blob: 05a7fb19ec42f4897f3b32814322cd70a6a9830b [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
19#include <types/cache.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020020#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020021
22#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020023#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020024#include <proto/channel.h>
25#include <proto/checks.h>
26#include <proto/connection.h>
27#include <proto/filters.h>
28#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020029#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020030#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020031#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020032#include <proto/proto_http.h>
33#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020034#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020035#include <proto/stream.h>
36#include <proto/stream_interface.h>
37#include <proto/stats.h>
38
Christopher Faulet377c5a52018-10-24 21:21:30 +020039extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020040
41static void htx_end_request(struct stream *s);
42static void htx_end_response(struct stream *s);
43
Christopher Faulet0f226952018-10-22 09:29:56 +020044static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020045static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010046static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
47static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
48static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020049static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
50
Christopher Faulet3e964192018-10-24 11:39:23 +020051static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
52static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
53
Christopher Faulet33640082018-10-24 11:53:01 +020054static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
55static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
56
Christopher Fauletfcda7c62018-10-24 11:56:22 +020057static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
58static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
59
Christopher Faulet377c5a52018-10-24 21:21:30 +020060static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
61static int htx_handle_stats(struct stream *s, struct channel *req);
62
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
412 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
413 * only change if both the request and the config reference something else.
414 * Option httpclose by itself sets tunnel mode where headers are mangled.
415 * However, if another mode is set, it will affect it (eg: server-close/
416 * keep-alive + httpclose = close). Note that we avoid to redo the same work
417 * if FE and BE have the same settings (common). The method consists in
418 * checking if options changed between the two calls (implying that either
419 * one is non-null, or one of them is non-null and we are there for the first
420 * time.
421 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200422 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200423 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200424
425 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200426 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 req->analysers |= AN_REQ_HTTP_BODY;
428
429 /*
430 * RFC7234#4:
431 * A cache MUST write through requests with methods
432 * that are unsafe (Section 4.2.1 of [RFC7231]) to
433 * the origin server; i.e., a cache is not allowed
434 * to generate a reply to such a request before
435 * having forwarded the request and having received
436 * a corresponding response.
437 *
438 * RFC7231#4.2.1:
439 * Of the request methods defined by this
440 * specification, the GET, HEAD, OPTIONS, and TRACE
441 * methods are defined to be safe.
442 */
443 if (likely(txn->meth == HTTP_METH_GET ||
444 txn->meth == HTTP_METH_HEAD ||
445 txn->meth == HTTP_METH_OPTIONS ||
446 txn->meth == HTTP_METH_TRACE))
447 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
448
449 /* end of job, return OK */
450 req->analysers &= ~an_bit;
451 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200452
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 return 1;
454
455 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200456 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200457 txn->req.err_state = txn->req.msg_state;
458 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100459 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100460 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200461 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100462 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200463
464 return_prx_cond:
465 if (!(s->flags & SF_ERR_MASK))
466 s->flags |= SF_ERR_PRXCOND;
467 if (!(s->flags & SF_FINST_MASK))
468 s->flags |= SF_FINST_R;
469
470 req->analysers &= AN_REQ_FLT_END;
471 req->analyse_exp = TICK_ETERNITY;
472 return 0;
473}
474
475
476/* This stream analyser runs all HTTP request processing which is common to
477 * frontends and backends, which means blocking ACLs, filters, connection-close,
478 * reqadd, stats and redirects. This is performed for the designated proxy.
479 * It returns 1 if the processing can continue on next analysers, or zero if it
480 * either needs more data or wants to immediately abort the request (eg: deny,
481 * error, ...).
482 */
483int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
484{
485 struct session *sess = s->sess;
486 struct http_txn *txn = s->txn;
487 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200489 struct redirect_rule *rule;
490 struct cond_wordlist *wl;
491 enum rule_result verdict;
492 int deny_status = HTTP_ERR_403;
493 struct connection *conn = objt_conn(sess->origin);
494
495 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
496 /* we need more data */
497 goto return_prx_yield;
498 }
499
500 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
501 now_ms, __FUNCTION__,
502 s,
503 req,
504 req->rex, req->wex,
505 req->flags,
506 ci_data(req),
507 req->analysers);
508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100509 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200510
Christopher Faulete0768eb2018-10-03 16:38:02 +0200511 /* just in case we have some per-backend tracking */
512 stream_inc_be_http_req_ctr(s);
513
514 /* evaluate http-request rules */
515 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200516 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200517
518 switch (verdict) {
519 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
520 goto return_prx_yield;
521
522 case HTTP_RULE_RES_CONT:
523 case HTTP_RULE_RES_STOP: /* nothing to do */
524 break;
525
526 case HTTP_RULE_RES_DENY: /* deny or tarpit */
527 if (txn->flags & TX_CLTARPIT)
528 goto tarpit;
529 goto deny;
530
531 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
532 goto return_prx_cond;
533
534 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
535 goto done;
536
537 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
538 goto return_bad_req;
539 }
540 }
541
542 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
543 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200544 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 ctx.blk = NULL;
547 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
548 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
552
553 /* OK at this stage, we know that the request was accepted according to
554 * the http-request rules, we can check for the stats. Note that the
555 * URI is detected *before* the req* rules in order not to be affected
556 * by a possible reqrep, while they are processed *after* so that a
557 * reqdeny can still block them. This clearly needs to change in 1.6!
558 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200559 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100561 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200562 txn->status = 500;
563 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200565
566 if (!(s->flags & SF_ERR_MASK))
567 s->flags |= SF_ERR_RESOURCE;
568 goto return_prx_cond;
569 }
570
571 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200572 htx_handle_stats(s, req);
573 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200574 /* not all actions implemented: deny, allow, auth */
575
576 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
577 goto deny;
578
579 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
580 goto return_prx_cond;
581 }
582
583 /* evaluate the req* rules except reqadd */
584 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200585 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200586 goto return_bad_req;
587
588 if (txn->flags & TX_CLDENY)
589 goto deny;
590
591 if (txn->flags & TX_CLTARPIT) {
592 deny_status = HTTP_ERR_500;
593 goto tarpit;
594 }
595 }
596
597 /* add request headers from the rule sets in the same order */
598 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (wl->cond) {
601 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
602 ret = acl_pass(ret);
603 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
604 ret = !ret;
605 if (!ret)
606 continue;
607 }
608
Christopher Fauletff2759f2018-10-24 11:13:16 +0200609 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
610 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 goto return_bad_req;
612 }
613
Christopher Faulete0768eb2018-10-03 16:38:02 +0200614 /* Proceed with the stats now. */
615 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
616 unlikely(objt_applet(s->target) == &http_cache_applet)) {
617 /* process the stats request now */
618 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100619 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200620
621 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
622 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
623 if (!(s->flags & SF_FINST_MASK))
624 s->flags |= SF_FINST_R;
625
626 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
627 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
628 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
629 req->analysers |= AN_REQ_HTTP_XFER_BODY;
630 goto done;
631 }
632
633 /* check whether we have some ACLs set to redirect this request */
634 list_for_each_entry(rule, &px->redirect_rules, list) {
635 if (rule->cond) {
636 int ret;
637
638 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
639 ret = acl_pass(ret);
640 if (rule->cond->pol == ACL_COND_UNLESS)
641 ret = !ret;
642 if (!ret)
643 continue;
644 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200645 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200646 goto return_bad_req;
647 goto done;
648 }
649
650 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
651 * If this happens, then the data will not come immediately, so we must
652 * send all what we have without waiting. Note that due to the small gain
653 * in waiting for the body of the request, it's easier to simply put the
654 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
655 * itself once used.
656 */
657 req->flags |= CF_SEND_DONTWAIT;
658
659 done: /* done with this analyser, continue with next ones that the calling
660 * points will have set, if any.
661 */
662 req->analyse_exp = TICK_ETERNITY;
663 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
664 req->analysers &= ~an_bit;
665 return 1;
666
667 tarpit:
668 /* Allow cookie logging
669 */
670 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200671 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200672
673 /* When a connection is tarpitted, we use the tarpit timeout,
674 * which may be the same as the connect timeout if unspecified.
675 * If unset, then set it to zero because we really want it to
676 * eventually expire. We build the tarpit as an analyser.
677 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100678 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200679
680 /* wipe the request out so that we can drop the connection early
681 * if the client closes first.
682 */
683 channel_dont_connect(req);
684
685 txn->status = http_err_codes[deny_status];
686
687 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
688 req->analysers |= AN_REQ_HTTP_TARPIT;
689 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
690 if (!req->analyse_exp)
691 req->analyse_exp = tick_add(now_ms, 0);
692 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100693 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100695 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200696 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100697 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 goto done_without_exp;
699
700 deny: /* this request was blocked (denied) */
701
702 /* Allow cookie logging
703 */
704 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200705 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200706
707 txn->flags |= TX_CLDENY;
708 txn->status = http_err_codes[deny_status];
709 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100710 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100712 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200713 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100714 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100716 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 goto return_prx_cond;
718
719 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720 txn->req.err_state = txn->req.msg_state;
721 txn->req.msg_state = HTTP_MSG_ERROR;
722 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100723 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200724
Olivier Houcharda798bf52019-03-08 18:52:00 +0100725 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200726 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100727 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200728
729 return_prx_cond:
730 if (!(s->flags & SF_ERR_MASK))
731 s->flags |= SF_ERR_PRXCOND;
732 if (!(s->flags & SF_FINST_MASK))
733 s->flags |= SF_FINST_R;
734
735 req->analysers &= AN_REQ_FLT_END;
736 req->analyse_exp = TICK_ETERNITY;
737 return 0;
738
739 return_prx_yield:
740 channel_dont_connect(req);
741 return 0;
742}
743
744/* This function performs all the processing enabled for the current request.
745 * It returns 1 if the processing can continue on next analysers, or zero if it
746 * needs more data, encounters an error, or wants to immediately abort the
747 * request. It relies on buffers flags, and updates s->req.analysers.
748 */
749int htx_process_request(struct stream *s, struct channel *req, int an_bit)
750{
751 struct session *sess = s->sess;
752 struct http_txn *txn = s->txn;
753 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200754 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200755 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
756
757 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
758 /* we need more data */
759 channel_dont_connect(req);
760 return 0;
761 }
762
763 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
764 now_ms, __FUNCTION__,
765 s,
766 req,
767 req->rex, req->wex,
768 req->flags,
769 ci_data(req),
770 req->analysers);
771
772 /*
773 * Right now, we know that we have processed the entire headers
774 * and that unwanted requests have been filtered out. We can do
775 * whatever we want with the remaining request. Also, now we
776 * may have separate values for ->fe, ->be.
777 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100778 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200779
780 /*
781 * If HTTP PROXY is set we simply get remote server address parsing
782 * incoming request. Note that this requires that a connection is
783 * allocated on the server side.
784 */
785 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
786 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100787 struct htx_sl *sl;
788 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200789
790 /* Note that for now we don't reuse existing proxy connections */
791 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
792 txn->req.err_state = txn->req.msg_state;
793 txn->req.msg_state = HTTP_MSG_ERROR;
794 txn->status = 500;
795 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100796 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797
798 if (!(s->flags & SF_ERR_MASK))
799 s->flags |= SF_ERR_RESOURCE;
800 if (!(s->flags & SF_FINST_MASK))
801 s->flags |= SF_FINST_R;
802
803 return 0;
804 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100806 uri = htx_sl_req_uri(sl);
807 path = http_get_path(uri);
808 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 goto return_bad_req;
810
811 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200812 * uri.ptr and path.ptr (excluded). If it was not found, we need
813 * to replace from all the uri by a single "/".
814 *
815 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100816 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200817 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100819 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200820 }
821
822 /*
823 * 7: Now we can work with the cookies.
824 * Note that doing so might move headers in the request, but
825 * the fields will stay coherent and the URI will not move.
826 * This should only be performed in the backend.
827 */
828 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100829 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200830
831 /* add unique-id if "header-unique-id" is specified */
832
833 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
834 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
835 goto return_bad_req;
836 s->unique_id[0] = '\0';
837 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
838 }
839
840 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200841 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
842 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
843
844 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 }
847
848 /*
849 * 9: add X-Forwarded-For if either the frontend or the backend
850 * asks for it.
851 */
852 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200853 struct http_hdr_ctx ctx = { .blk = NULL };
854 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
855 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
856
Christopher Faulete0768eb2018-10-03 16:38:02 +0200857 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200858 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200859 /* The header is set to be added only if none is present
860 * and we found it, so don't do anything.
861 */
862 }
863 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
864 /* Add an X-Forwarded-For header unless the source IP is
865 * in the 'except' network range.
866 */
867 if ((!sess->fe->except_mask.s_addr ||
868 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
869 != sess->fe->except_net.s_addr) &&
870 (!s->be->except_mask.s_addr ||
871 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
872 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200873 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200874
875 /* Note: we rely on the backend to get the header name to be used for
876 * x-forwarded-for, because the header is really meant for the backends.
877 * However, if the backend did not specify any option, we have to rely
878 * on the frontend's header name.
879 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200880 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
881 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200882 goto return_bad_req;
883 }
884 }
885 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
886 /* FIXME: for the sake of completeness, we should also support
887 * 'except' here, although it is mostly useless in this case.
888 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200889 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200890
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 inet_ntop(AF_INET6,
892 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
893 pn, sizeof(pn));
894
895 /* Note: we rely on the backend to get the header name to be used for
896 * x-forwarded-for, because the header is really meant for the backends.
897 * However, if the backend did not specify any option, we have to rely
898 * on the frontend's header name.
899 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200900 chunk_printf(&trash, "%s", pn);
901 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200902 goto return_bad_req;
903 }
904 }
905
906 /*
907 * 10: add X-Original-To if either the frontend or the backend
908 * asks for it.
909 */
910 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
911
912 /* FIXME: don't know if IPv6 can handle that case too. */
913 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
914 /* Add an X-Original-To header unless the destination IP is
915 * in the 'except' network range.
916 */
917 conn_get_to_addr(cli_conn);
918
919 if (cli_conn->addr.to.ss_family == AF_INET &&
920 ((!sess->fe->except_mask_to.s_addr ||
921 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
922 != sess->fe->except_to.s_addr) &&
923 (!s->be->except_mask_to.s_addr ||
924 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
925 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200926 struct ist hdr;
927 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928
929 /* Note: we rely on the backend to get the header name to be used for
930 * x-original-to, because the header is really meant for the backends.
931 * However, if the backend did not specify any option, we have to rely
932 * on the frontend's header name.
933 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200934 if (s->be->orgto_hdr_len)
935 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
936 else
937 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200939 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
940 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 goto return_bad_req;
942 }
943 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200944 }
945
Christopher Faulete0768eb2018-10-03 16:38:02 +0200946 /* If we have no server assigned yet and we're balancing on url_param
947 * with a POST request, we may be interested in checking the body for
948 * that parameter. This will be done in another analyser.
949 */
950 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100951 s->txn->meth == HTTP_METH_POST &&
952 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200953 channel_dont_connect(req);
954 req->analysers |= AN_REQ_HTTP_BODY;
955 }
956
957 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
958 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100959
Christopher Faulete0768eb2018-10-03 16:38:02 +0200960 /* We expect some data from the client. Unless we know for sure
961 * we already have a full request, we have to re-enable quick-ack
962 * in case we previously disabled it, otherwise we might cause
963 * the client to delay further data.
964 */
965 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200966 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100967 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200968
969 /*************************************************************
970 * OK, that's finished for the headers. We have done what we *
971 * could. Let's switch to the DATA state. *
972 ************************************************************/
973 req->analyse_exp = TICK_ETERNITY;
974 req->analysers &= ~an_bit;
975
976 s->logs.tv_request = now;
977 /* OK let's go on with the BODY now */
978 return 1;
979
980 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200981 txn->req.err_state = txn->req.msg_state;
982 txn->req.msg_state = HTTP_MSG_ERROR;
983 txn->status = 400;
984 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100985 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200986
Olivier Houcharda798bf52019-03-08 18:52:00 +0100987 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200988 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100989 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200990
991 if (!(s->flags & SF_ERR_MASK))
992 s->flags |= SF_ERR_PRXCOND;
993 if (!(s->flags & SF_FINST_MASK))
994 s->flags |= SF_FINST_R;
995 return 0;
996}
997
998/* This function is an analyser which processes the HTTP tarpit. It always
999 * returns zero, at the beginning because it prevents any other processing
1000 * from occurring, and at the end because it terminates the request.
1001 */
1002int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1003{
1004 struct http_txn *txn = s->txn;
1005
1006 /* This connection is being tarpitted. The CLIENT side has
1007 * already set the connect expiration date to the right
1008 * timeout. We just have to check that the client is still
1009 * there and that the timeout has not expired.
1010 */
1011 channel_dont_connect(req);
1012 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1013 !tick_is_expired(req->analyse_exp, now_ms))
1014 return 0;
1015
1016 /* We will set the queue timer to the time spent, just for
1017 * logging purposes. We fake a 500 server error, so that the
1018 * attacker will not suspect his connection has been tarpitted.
1019 * It will not cause trouble to the logs because we can exclude
1020 * the tarpitted connections by filtering on the 'PT' status flags.
1021 */
1022 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1023
1024 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001025 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001026
1027 req->analysers &= AN_REQ_FLT_END;
1028 req->analyse_exp = TICK_ETERNITY;
1029
1030 if (!(s->flags & SF_ERR_MASK))
1031 s->flags |= SF_ERR_PRXCOND;
1032 if (!(s->flags & SF_FINST_MASK))
1033 s->flags |= SF_FINST_T;
1034 return 0;
1035}
1036
1037/* This function is an analyser which waits for the HTTP request body. It waits
1038 * for either the buffer to be full, or the full advertised contents to have
1039 * reached the buffer. It must only be called after the standard HTTP request
1040 * processing has occurred, because it expects the request to be parsed and will
1041 * look for the Expect header. It may send a 100-Continue interim response. It
1042 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1043 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1044 * needs to read more data, or 1 once it has completed its analysis.
1045 */
1046int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1047{
1048 struct session *sess = s->sess;
1049 struct http_txn *txn = s->txn;
1050 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001051 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001052
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053
1054 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1055 now_ms, __FUNCTION__,
1056 s,
1057 req,
1058 req->rex, req->wex,
1059 req->flags,
1060 ci_data(req),
1061 req->analysers);
1062
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001063 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001064
Willy Tarreau4236f032019-03-05 10:43:32 +01001065 if (htx->flags & HTX_FL_PARSING_ERROR)
1066 goto return_bad_req;
1067
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068 if (msg->msg_state < HTTP_MSG_BODY)
1069 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001070
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071 /* We have to parse the HTTP request body to find any required data.
1072 * "balance url_param check_post" should have been the only way to get
1073 * into this. We were brought here after HTTP header analysis, so all
1074 * related structures are ready.
1075 */
1076
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001077 if (msg->msg_state < HTTP_MSG_DATA) {
1078 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1079 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (msg->flags & HTTP_MSGF_VER_11) {
1082 struct ist hdr = { .ptr = "Expect", .len = 6 };
1083 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 ctx.blk = NULL;
1086 /* Expect is allowed in 1.1, look for it */
1087 if (http_find_header(htx, hdr, &ctx, 0) &&
1088 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001089 if (htx_reply_100_continue(s) == -1)
1090 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 http_remove_header(htx, &ctx);
1092 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001094 }
1095
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001096 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001097
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001098 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1099 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001100 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001101 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001102 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001103 goto http_end;
1104
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001105 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001106 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1107 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001108 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001109
1110 if (!(s->flags & SF_ERR_MASK))
1111 s->flags |= SF_ERR_CLITO;
1112 if (!(s->flags & SF_FINST_MASK))
1113 s->flags |= SF_FINST_D;
1114 goto return_err_msg;
1115 }
1116
1117 /* we get here if we need to wait for more data */
1118 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1119 /* Not enough data. We'll re-use the http-request
1120 * timeout here. Ideally, we should set the timeout
1121 * relative to the accept() date. We just set the
1122 * request timeout once at the beginning of the
1123 * request.
1124 */
1125 channel_dont_connect(req);
1126 if (!tick_isset(req->analyse_exp))
1127 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1128 return 0;
1129 }
1130
1131 http_end:
1132 /* The situation will not evolve, so let's give up on the analysis. */
1133 s->logs.tv_request = now; /* update the request timer to reflect full request */
1134 req->analysers &= ~an_bit;
1135 req->analyse_exp = TICK_ETERNITY;
1136 return 1;
1137
1138 return_bad_req: /* let's centralize all bad requests */
1139 txn->req.err_state = txn->req.msg_state;
1140 txn->req.msg_state = HTTP_MSG_ERROR;
1141 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001142 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001143
1144 if (!(s->flags & SF_ERR_MASK))
1145 s->flags |= SF_ERR_PRXCOND;
1146 if (!(s->flags & SF_FINST_MASK))
1147 s->flags |= SF_FINST_R;
1148
1149 return_err_msg:
1150 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001151 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001152 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001153 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001154 return 0;
1155}
1156
1157/* This function is an analyser which forwards request body (including chunk
1158 * sizes if any). It is called as soon as we must forward, even if we forward
1159 * zero byte. The only situation where it must not be called is when we're in
1160 * tunnel mode and we want to forward till the close. It's used both to forward
1161 * remaining data and to resync after end of body. It expects the msg_state to
1162 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1163 * read more data, or 1 once we can go on with next request or end the stream.
1164 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1165 * bytes of pending data + the headers if not already done.
1166 */
1167int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1168{
1169 struct session *sess = s->sess;
1170 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001171 struct http_msg *msg = &txn->req;
1172 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001173 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001174 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001175
1176 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1177 now_ms, __FUNCTION__,
1178 s,
1179 req,
1180 req->rex, req->wex,
1181 req->flags,
1182 ci_data(req),
1183 req->analysers);
1184
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001185 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1188 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1189 /* Output closed while we were sending data. We must abort and
1190 * wake the other side up.
1191 */
1192 msg->err_state = msg->msg_state;
1193 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001194 htx_end_request(s);
1195 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001196 return 1;
1197 }
1198
1199 /* Note that we don't have to send 100-continue back because we don't
1200 * need the data to complete our job, and it's up to the server to
1201 * decide whether to return 100, 417 or anything else in return of
1202 * an "Expect: 100-continue" header.
1203 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001204 if (msg->msg_state == HTTP_MSG_BODY)
1205 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001206
1207 /* Some post-connect processing might want us to refrain from starting to
1208 * forward data. Currently, the only reason for this is "balance url_param"
1209 * whichs need to parse/process the request after we've enabled forwarding.
1210 */
1211 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1212 if (!(s->res.flags & CF_READ_ATTACHED)) {
1213 channel_auto_connect(req);
1214 req->flags |= CF_WAKE_CONNECT;
1215 channel_dont_close(req); /* don't fail on early shutr */
1216 goto waiting;
1217 }
1218 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1219 }
1220
1221 /* in most states, we should abort in case of early close */
1222 channel_auto_close(req);
1223
1224 if (req->to_forward) {
Christopher Fauletf52170d2019-03-08 15:45:26 +01001225 if (req->to_forward == CHN_INFINITE_FORWARD) {
1226 if (req->flags & CF_SHUTR) {
1227 msg->msg_state = HTTP_MSG_DONE;
1228 req->to_forward = 0;
1229 goto done;
1230 }
1231 }
1232 else {
1233 /* We can't process the buffer's contents yet */
1234 req->flags |= CF_WAKE_WRITE;
1235 goto missing_data_or_waiting;
1236 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001237 }
1238
Christopher Faulet9768c262018-10-22 09:34:31 +02001239 if (msg->msg_state >= HTTP_MSG_DONE)
1240 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001241 /* Forward input data. We get it by removing all outgoing data not
1242 * forwarded yet from HTX data size. If there are some data filters, we
1243 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001244 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001245 if (HAS_REQ_DATA_FILTERS(s)) {
1246 ret = flt_http_payload(s, msg, htx->data);
1247 if (ret < 0)
1248 goto return_bad_req;
1249 c_adv(req, ret);
1250 if (htx->data != co_data(req) || htx->extra)
1251 goto missing_data_or_waiting;
1252 }
1253 else {
1254 c_adv(req, htx->data - co_data(req));
Christopher Fauletf52170d2019-03-08 15:45:26 +01001255 if (msg->flags & HTTP_MSGF_XFER_LEN)
1256 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001257 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258
Christopher Faulet9768c262018-10-22 09:34:31 +02001259 /* Check if the end-of-message is reached and if so, switch the message
1260 * in HTTP_MSG_DONE state.
1261 */
1262 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1263 goto missing_data_or_waiting;
1264
1265 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01001266 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001267
1268 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001269 /* other states, DONE...TUNNEL */
1270 /* we don't want to forward closes on DONE except in tunnel mode. */
1271 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1272 channel_dont_close(req);
1273
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001274 if (HAS_REQ_DATA_FILTERS(s)) {
1275 ret = flt_http_end(s, msg);
1276 if (ret <= 0) {
1277 if (!ret)
1278 goto missing_data_or_waiting;
1279 goto return_bad_req;
1280 }
1281 }
1282
Christopher Fauletf2824e62018-10-01 12:12:37 +02001283 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001284 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001285 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1287 if (req->flags & CF_SHUTW) {
1288 /* request errors are most likely due to the
1289 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001290 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001291 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001292 goto return_bad_req;
1293 }
1294 return 1;
1295 }
1296
1297 /* If "option abortonclose" is set on the backend, we want to monitor
1298 * the client's connection and forward any shutdown notification to the
1299 * server, which will decide whether to close or to go on processing the
1300 * request. We only do that in tunnel mode, and not in other modes since
1301 * it can be abused to exhaust source ports. */
1302 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1303 channel_auto_read(req);
1304 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1305 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1306 s->si[1].flags |= SI_FL_NOLINGER;
1307 channel_auto_close(req);
1308 }
1309 else if (s->txn->meth == HTTP_METH_POST) {
1310 /* POST requests may require to read extra CRLF sent by broken
1311 * browsers and which could cause an RST to be sent upon close
1312 * on some systems (eg: Linux). */
1313 channel_auto_read(req);
1314 }
1315 return 0;
1316
1317 missing_data_or_waiting:
1318 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001319 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1320 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321
1322 waiting:
1323 /* waiting for the last bits to leave the buffer */
1324 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001325 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001326
Christopher Faulet47365272018-10-31 17:40:50 +01001327 if (htx->flags & HTX_FL_PARSING_ERROR)
1328 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001329
Christopher Faulete0768eb2018-10-03 16:38:02 +02001330 /* When TE: chunked is used, we need to get there again to parse remaining
1331 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1332 * And when content-length is used, we never want to let the possible
1333 * shutdown be forwarded to the other side, as the state machine will
1334 * take care of it once the client responds. It's also important to
1335 * prevent TIME_WAITs from accumulating on the backend side, and for
1336 * HTTP/2 where the last frame comes with a shutdown.
1337 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001338 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001339 channel_dont_close(req);
1340
1341 /* We know that more data are expected, but we couldn't send more that
1342 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1343 * system knows it must not set a PUSH on this first part. Interactive
1344 * modes are already handled by the stream sock layer. We must not do
1345 * this in content-length mode because it could present the MSG_MORE
1346 * flag with the last block of forwarded data, which would cause an
1347 * additional delay to be observed by the receiver.
1348 */
1349 if (msg->flags & HTTP_MSGF_TE_CHNK)
1350 req->flags |= CF_EXPECT_MORE;
1351
1352 return 0;
1353
Christopher Faulet93e02d82019-03-08 14:18:50 +01001354 return_cli_abort:
1355 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1356 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1357 if (objt_server(s->target))
1358 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1359 if (!(s->flags & SF_ERR_MASK))
1360 s->flags |= SF_ERR_CLICL;
1361 status = 400;
1362 goto return_error;
1363
1364 return_srv_abort:
1365 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1366 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1367 if (objt_server(s->target))
1368 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1369 if (!(s->flags & SF_ERR_MASK))
1370 s->flags |= SF_ERR_SRVCL;
1371 status = 502;
1372 goto return_error;
1373
1374 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001375 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001377 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001379 s->flags |= SF_ERR_CLICL;
1380 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381
Christopher Faulet93e02d82019-03-08 14:18:50 +01001382 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 txn->req.err_state = txn->req.msg_state;
1384 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001385 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001387 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001388 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001389 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001390 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 }
1392 req->analysers &= AN_REQ_FLT_END;
1393 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001394 if (!(s->flags & SF_FINST_MASK))
1395 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001396 return 0;
1397}
1398
1399/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1400 * processing can continue on next analysers, or zero if it either needs more
1401 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1402 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1403 * when it has nothing left to do, and may remove any analyser when it wants to
1404 * abort.
1405 */
1406int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1407{
Christopher Faulet9768c262018-10-22 09:34:31 +02001408 /*
1409 * We will analyze a complete HTTP response to check the its syntax.
1410 *
1411 * Once the start line and all headers are received, we may perform a
1412 * capture of the error (if any), and we will set a few fields. We also
1413 * logging and finally headers capture.
1414 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001415 struct session *sess = s->sess;
1416 struct http_txn *txn = s->txn;
1417 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001418 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001419 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001420 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001421 int n;
1422
1423 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1424 now_ms, __FUNCTION__,
1425 s,
1426 rep,
1427 rep->rex, rep->wex,
1428 rep->flags,
1429 ci_data(rep),
1430 rep->analysers);
1431
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001432 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001433
Willy Tarreau4236f032019-03-05 10:43:32 +01001434 /* Parsing errors are caught here */
1435 if (htx->flags & HTX_FL_PARSING_ERROR)
1436 goto return_bad_res;
1437
Christopher Faulete0768eb2018-10-03 16:38:02 +02001438 /*
1439 * Now we quickly check if we have found a full valid response.
1440 * If not so, we check the FD and buffer states before leaving.
1441 * A full response is indicated by the fact that we have seen
1442 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1443 * responses are checked first.
1444 *
1445 * Depending on whether the client is still there or not, we
1446 * may send an error response back or not. Note that normally
1447 * we should only check for HTTP status there, and check I/O
1448 * errors somewhere else.
1449 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001450 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001451 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001452 * First catch invalid response because of a parsing error or
1453 * because only part of headers have been transfered.
1454 * Multiplexers have the responsibility to emit all headers at
1455 * once. We must be sure to have forwarded all outgoing data
1456 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001457 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001458 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001459 goto return_bad_res;
1460
Christopher Faulet9768c262018-10-22 09:34:31 +02001461 /* 1: have we encountered a read error ? */
1462 if (rep->flags & CF_READ_ERROR) {
1463 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001464 goto abort_keep_alive;
1465
Olivier Houcharda798bf52019-03-08 18:52:00 +01001466 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001467 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001468 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001469 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001470 }
1471
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472 rep->analysers &= AN_RES_FLT_END;
1473 txn->status = 502;
1474
1475 /* Check to see if the server refused the early data.
1476 * If so, just send a 425
1477 */
1478 if (objt_cs(s->si[1].end)) {
1479 struct connection *conn = objt_cs(s->si[1].end)->conn;
1480
1481 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1482 txn->status = 425;
1483 }
1484
1485 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001486 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001487
1488 if (!(s->flags & SF_ERR_MASK))
1489 s->flags |= SF_ERR_SRVCL;
1490 if (!(s->flags & SF_FINST_MASK))
1491 s->flags |= SF_FINST_H;
1492 return 0;
1493 }
1494
Christopher Faulet9768c262018-10-22 09:34:31 +02001495 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001497 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001498 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001499 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001500 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 }
1502
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503 rep->analysers &= AN_RES_FLT_END;
1504 txn->status = 504;
1505 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001506 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507
1508 if (!(s->flags & SF_ERR_MASK))
1509 s->flags |= SF_ERR_SRVTO;
1510 if (!(s->flags & SF_FINST_MASK))
1511 s->flags |= SF_FINST_H;
1512 return 0;
1513 }
1514
Christopher Faulet9768c262018-10-22 09:34:31 +02001515 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001517 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1518 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001520 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521
1522 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001524 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525
1526 if (!(s->flags & SF_ERR_MASK))
1527 s->flags |= SF_ERR_CLICL;
1528 if (!(s->flags & SF_FINST_MASK))
1529 s->flags |= SF_FINST_H;
1530
1531 /* process_stream() will take care of the error */
1532 return 0;
1533 }
1534
Christopher Faulet9768c262018-10-22 09:34:31 +02001535 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001537 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 goto abort_keep_alive;
1539
Olivier Houcharda798bf52019-03-08 18:52:00 +01001540 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001542 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001543 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 }
1545
Christopher Faulete0768eb2018-10-03 16:38:02 +02001546 rep->analysers &= AN_RES_FLT_END;
1547 txn->status = 502;
1548 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001549 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550
1551 if (!(s->flags & SF_ERR_MASK))
1552 s->flags |= SF_ERR_SRVCL;
1553 if (!(s->flags & SF_FINST_MASK))
1554 s->flags |= SF_FINST_H;
1555 return 0;
1556 }
1557
Christopher Faulet9768c262018-10-22 09:34:31 +02001558 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001560 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 goto abort_keep_alive;
1562
Olivier Houcharda798bf52019-03-08 18:52:00 +01001563 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565
1566 if (!(s->flags & SF_ERR_MASK))
1567 s->flags |= SF_ERR_CLICL;
1568 if (!(s->flags & SF_FINST_MASK))
1569 s->flags |= SF_FINST_H;
1570
1571 /* process_stream() will take care of the error */
1572 return 0;
1573 }
1574
1575 channel_dont_close(rep);
1576 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1577 return 0;
1578 }
1579
1580 /* More interesting part now : we know that we have a complete
1581 * response which at least looks like HTTP. We have an indicator
1582 * of each header's length, so we can parse them quickly.
1583 */
1584
Christopher Faulet9768c262018-10-22 09:34:31 +02001585 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001586 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587
Christopher Faulet9768c262018-10-22 09:34:31 +02001588 /* 0: we might have to print this header in debug mode */
1589 if (unlikely((global.mode & MODE_DEBUG) &&
1590 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1591 int32_t pos;
1592
Christopher Faulet03599112018-11-27 11:21:21 +01001593 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001594
1595 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1596 struct htx_blk *blk = htx_get_blk(htx, pos);
1597 enum htx_blk_type type = htx_get_blk_type(blk);
1598
1599 if (type == HTX_BLK_EOH)
1600 break;
1601 if (type != HTX_BLK_HDR)
1602 continue;
1603
1604 htx_debug_hdr("srvhdr", s,
1605 htx_get_blk_name(htx, blk),
1606 htx_get_blk_value(htx, blk));
1607 }
1608 }
1609
Christopher Faulet03599112018-11-27 11:21:21 +01001610 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001611 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001612 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001613 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001614 if (sl->flags & HTX_SL_F_XFER_LEN) {
1615 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001616 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001617 if (sl->flags & HTX_SL_F_BODYLESS)
1618 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001619 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001620
1621 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622 if (n < 1 || n > 5)
1623 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001624
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625 /* when the client triggers a 4xx from the server, it's most often due
1626 * to a missing object or permission. These events should be tracked
1627 * because if they happen often, it may indicate a brute force or a
1628 * vulnerability scan.
1629 */
1630 if (n == 4)
1631 stream_inc_http_err_ctr(s);
1632
1633 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001634 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635
Christopher Faulete0768eb2018-10-03 16:38:02 +02001636 /* Adjust server's health based on status code. Note: status codes 501
1637 * and 505 are triggered on demand by client request, so we must not
1638 * count them as server failures.
1639 */
1640 if (objt_server(s->target)) {
1641 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001642 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001643 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001644 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001645 }
1646
1647 /*
1648 * We may be facing a 100-continue response, or any other informational
1649 * 1xx response which is non-final, in which case this is not the right
1650 * response, and we're waiting for the next one. Let's allow this response
1651 * to go to the client and wait for the next one. There's an exception for
1652 * 101 which is used later in the code to switch protocols.
1653 */
1654 if (txn->status < 200 &&
1655 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001656 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001657 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001658 msg->msg_state = HTTP_MSG_RPBEFORE;
1659 txn->status = 0;
1660 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001661 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001662 }
1663
1664 /*
1665 * 2: check for cacheability.
1666 */
1667
1668 switch (txn->status) {
1669 case 200:
1670 case 203:
1671 case 204:
1672 case 206:
1673 case 300:
1674 case 301:
1675 case 404:
1676 case 405:
1677 case 410:
1678 case 414:
1679 case 501:
1680 break;
1681 default:
1682 /* RFC7231#6.1:
1683 * Responses with status codes that are defined as
1684 * cacheable by default (e.g., 200, 203, 204, 206,
1685 * 300, 301, 404, 405, 410, 414, and 501 in this
1686 * specification) can be reused by a cache with
1687 * heuristic expiration unless otherwise indicated
1688 * by the method definition or explicit cache
1689 * controls [RFC7234]; all other status codes are
1690 * not cacheable by default.
1691 */
1692 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1693 break;
1694 }
1695
1696 /*
1697 * 3: we may need to capture headers
1698 */
1699 s->logs.logwait &= ~LW_RESP;
1700 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001701 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702
Christopher Faulet9768c262018-10-22 09:34:31 +02001703 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001704 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1705 txn->status == 101)) {
1706 /* Either we've established an explicit tunnel, or we're
1707 * switching the protocol. In both cases, we're very unlikely
1708 * to understand the next protocols. We have to switch to tunnel
1709 * mode, so that we transfer the request and responses then let
1710 * this protocol pass unmodified. When we later implement specific
1711 * parsers for such protocols, we'll want to check the Upgrade
1712 * header which contains information about that protocol for
1713 * responses with status 101 (eg: see RFC2817 about TLS).
1714 */
1715 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001716 }
1717
Christopher Faulet61608322018-11-23 16:23:45 +01001718 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1719 * 407 (Proxy-Authenticate) responses and set the connection to private
1720 */
1721 srv_conn = cs_conn(objt_cs(s->si[1].end));
1722 if (srv_conn) {
1723 struct ist hdr;
1724 struct http_hdr_ctx ctx;
1725
1726 if (txn->status == 401)
1727 hdr = ist("WWW-Authenticate");
1728 else if (txn->status == 407)
1729 hdr = ist("Proxy-Authenticate");
1730 else
1731 goto end;
1732
1733 ctx.blk = NULL;
1734 while (http_find_header(htx, hdr, &ctx, 0)) {
1735 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1736 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1737 srv_conn->flags |= CO_FL_PRIVATE;
1738 }
1739 }
1740
1741 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001742 /* we want to have the response time before we start processing it */
1743 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1744
1745 /* end of job, return OK */
1746 rep->analysers &= ~an_bit;
1747 rep->analyse_exp = TICK_ETERNITY;
1748 channel_auto_close(rep);
1749 return 1;
1750
Christopher Faulet47365272018-10-31 17:40:50 +01001751 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001752 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001753 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001754 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001755 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001756 }
1757 txn->status = 502;
1758 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001759 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001760 rep->analysers &= AN_RES_FLT_END;
1761
1762 if (!(s->flags & SF_ERR_MASK))
1763 s->flags |= SF_ERR_PRXCOND;
1764 if (!(s->flags & SF_FINST_MASK))
1765 s->flags |= SF_FINST_H;
1766 return 0;
1767
Christopher Faulete0768eb2018-10-03 16:38:02 +02001768 abort_keep_alive:
1769 /* A keep-alive request to the server failed on a network error.
1770 * The client is required to retry. We need to close without returning
1771 * any other information so that the client retries.
1772 */
1773 txn->status = 0;
1774 rep->analysers &= AN_RES_FLT_END;
1775 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776 s->logs.logwait = 0;
1777 s->logs.level = 0;
1778 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001779 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001780 return 0;
1781}
1782
1783/* This function performs all the processing enabled for the current response.
1784 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1785 * and updates s->res.analysers. It might make sense to explode it into several
1786 * other functions. It works like process_request (see indications above).
1787 */
1788int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1789{
1790 struct session *sess = s->sess;
1791 struct http_txn *txn = s->txn;
1792 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001793 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001794 struct proxy *cur_proxy;
1795 struct cond_wordlist *wl;
1796 enum rule_result ret = HTTP_RULE_RES_CONT;
1797
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001798 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1799 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001800
Christopher Faulete0768eb2018-10-03 16:38:02 +02001801 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1802 now_ms, __FUNCTION__,
1803 s,
1804 rep,
1805 rep->rex, rep->wex,
1806 rep->flags,
1807 ci_data(rep),
1808 rep->analysers);
1809
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001810 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001811
1812 /* The stats applet needs to adjust the Connection header but we don't
1813 * apply any filter there.
1814 */
1815 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1816 rep->analysers &= ~an_bit;
1817 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001818 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001819 }
1820
1821 /*
1822 * We will have to evaluate the filters.
1823 * As opposed to version 1.2, now they will be evaluated in the
1824 * filters order and not in the header order. This means that
1825 * each filter has to be validated among all headers.
1826 *
1827 * Filters are tried with ->be first, then with ->fe if it is
1828 * different from ->be.
1829 *
1830 * Maybe we are in resume condiion. In this case I choose the
1831 * "struct proxy" which contains the rule list matching the resume
1832 * pointer. If none of theses "struct proxy" match, I initialise
1833 * the process with the first one.
1834 *
1835 * In fact, I check only correspondance betwwen the current list
1836 * pointer and the ->fe rule list. If it doesn't match, I initialize
1837 * the loop with the ->be.
1838 */
1839 if (s->current_rule_list == &sess->fe->http_res_rules)
1840 cur_proxy = sess->fe;
1841 else
1842 cur_proxy = s->be;
1843 while (1) {
1844 struct proxy *rule_set = cur_proxy;
1845
1846 /* evaluate http-response rules */
1847 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001848 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001849
1850 if (ret == HTTP_RULE_RES_BADREQ)
1851 goto return_srv_prx_502;
1852
1853 if (ret == HTTP_RULE_RES_DONE) {
1854 rep->analysers &= ~an_bit;
1855 rep->analyse_exp = TICK_ETERNITY;
1856 return 1;
1857 }
1858 }
1859
1860 /* we need to be called again. */
1861 if (ret == HTTP_RULE_RES_YIELD) {
1862 channel_dont_close(rep);
1863 return 0;
1864 }
1865
1866 /* try headers filters */
1867 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001868 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1869 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001870 }
1871
1872 /* has the response been denied ? */
1873 if (txn->flags & TX_SVDENY) {
1874 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001875 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001876
Olivier Houcharda798bf52019-03-08 18:52:00 +01001877 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1878 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001880 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001881 goto return_srv_prx_502;
1882 }
1883
1884 /* add response headers from the rule sets in the same order */
1885 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001886 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001887 if (txn->status < 200 && txn->status != 101)
1888 break;
1889 if (wl->cond) {
1890 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1891 ret = acl_pass(ret);
1892 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1893 ret = !ret;
1894 if (!ret)
1895 continue;
1896 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001897
1898 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1899 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001900 goto return_bad_resp;
1901 }
1902
1903 /* check whether we're already working on the frontend */
1904 if (cur_proxy == sess->fe)
1905 break;
1906 cur_proxy = sess->fe;
1907 }
1908
1909 /* After this point, this anayzer can't return yield, so we can
1910 * remove the bit corresponding to this analyzer from the list.
1911 *
1912 * Note that the intermediate returns and goto found previously
1913 * reset the analyzers.
1914 */
1915 rep->analysers &= ~an_bit;
1916 rep->analyse_exp = TICK_ETERNITY;
1917
1918 /* OK that's all we can do for 1xx responses */
1919 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001920 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001921
1922 /*
1923 * Now check for a server cookie.
1924 */
1925 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001926 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001927
1928 /*
1929 * Check for cache-control or pragma headers if required.
1930 */
1931 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1932 check_response_for_cacheability(s, rep);
1933
1934 /*
1935 * Add server cookie in the response if needed
1936 */
1937 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1938 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1939 (!(s->flags & SF_DIRECT) ||
1940 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1941 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1942 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1943 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1944 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1945 !(s->flags & SF_IGNORE_PRST)) {
1946 /* the server is known, it's not the one the client requested, or the
1947 * cookie's last seen date needs to be refreshed. We have to
1948 * insert a set-cookie here, except if we want to insert only on POST
1949 * requests and this one isn't. Note that servers which don't have cookies
1950 * (eg: some backup servers) will return a full cookie removal request.
1951 */
1952 if (!objt_server(s->target)->cookie) {
1953 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001954 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001955 s->be->cookie_name);
1956 }
1957 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001958 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001959
1960 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1961 /* emit last_date, which is mandatory */
1962 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1963 s30tob64((date.tv_sec+3) >> 2,
1964 trash.area + trash.data);
1965 trash.data += 5;
1966
1967 if (s->be->cookie_maxlife) {
1968 /* emit first_date, which is either the original one or
1969 * the current date.
1970 */
1971 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1972 s30tob64(txn->cookie_first_date ?
1973 txn->cookie_first_date >> 2 :
1974 (date.tv_sec+3) >> 2,
1975 trash.area + trash.data);
1976 trash.data += 5;
1977 }
1978 }
1979 chunk_appendf(&trash, "; path=/");
1980 }
1981
1982 if (s->be->cookie_domain)
1983 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1984
1985 if (s->be->ck_opts & PR_CK_HTTPONLY)
1986 chunk_appendf(&trash, "; HttpOnly");
1987
1988 if (s->be->ck_opts & PR_CK_SECURE)
1989 chunk_appendf(&trash, "; Secure");
1990
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001991 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001992 goto return_bad_resp;
1993
1994 txn->flags &= ~TX_SCK_MASK;
1995 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1996 /* the server did not change, only the date was updated */
1997 txn->flags |= TX_SCK_UPDATED;
1998 else
1999 txn->flags |= TX_SCK_INSERTED;
2000
2001 /* Here, we will tell an eventual cache on the client side that we don't
2002 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2003 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2004 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2005 */
2006 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2007
2008 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2009
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002010 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002011 goto return_bad_resp;
2012 }
2013 }
2014
2015 /*
2016 * Check if result will be cacheable with a cookie.
2017 * We'll block the response if security checks have caught
2018 * nasty things such as a cacheable cookie.
2019 */
2020 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2021 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2022 (s->be->options & PR_O_CHK_CACHE)) {
2023 /* we're in presence of a cacheable response containing
2024 * a set-cookie header. We'll block it as requested by
2025 * the 'checkcache' option, and send an alert.
2026 */
2027 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002028 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002029
Olivier Houcharda798bf52019-03-08 18:52:00 +01002030 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2031 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002032 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002033 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002034
2035 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2036 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2037 send_log(s->be, LOG_ALERT,
2038 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2039 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2040 goto return_srv_prx_502;
2041 }
2042
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002043 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002044 /* Always enter in the body analyzer */
2045 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2046 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2047
2048 /* if the user wants to log as soon as possible, without counting
2049 * bytes from the server, then this is the right moment. We have
2050 * to temporarily assign bytes_out to log what we currently have.
2051 */
2052 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2053 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002054 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002055 s->do_log(s);
2056 s->logs.bytes_out = 0;
2057 }
2058 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002059
2060 return_bad_resp:
2061 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002062 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002063 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002064 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002065 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002066
2067 return_srv_prx_502:
2068 rep->analysers &= AN_RES_FLT_END;
2069 txn->status = 502;
2070 s->logs.t_data = -1; /* was not a valid response */
2071 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002072 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002073 if (!(s->flags & SF_ERR_MASK))
2074 s->flags |= SF_ERR_PRXCOND;
2075 if (!(s->flags & SF_FINST_MASK))
2076 s->flags |= SF_FINST_H;
2077 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002078}
2079
2080/* This function is an analyser which forwards response body (including chunk
2081 * sizes if any). It is called as soon as we must forward, even if we forward
2082 * zero byte. The only situation where it must not be called is when we're in
2083 * tunnel mode and we want to forward till the close. It's used both to forward
2084 * remaining data and to resync after end of body. It expects the msg_state to
2085 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2086 * read more data, or 1 once we can go on with next request or end the stream.
2087 *
2088 * It is capable of compressing response data both in content-length mode and
2089 * in chunked mode. The state machines follows different flows depending on
2090 * whether content-length and chunked modes are used, since there are no
2091 * trailers in content-length :
2092 *
2093 * chk-mode cl-mode
2094 * ,----- BODY -----.
2095 * / \
2096 * V size > 0 V chk-mode
2097 * .--> SIZE -------------> DATA -------------> CRLF
2098 * | | size == 0 | last byte |
2099 * | v final crlf v inspected |
2100 * | TRAILERS -----------> DONE |
2101 * | |
2102 * `----------------------------------------------'
2103 *
2104 * Compression only happens in the DATA state, and must be flushed in final
2105 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2106 * is performed at once on final states for all bytes parsed, or when leaving
2107 * on missing data.
2108 */
2109int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2110{
2111 struct session *sess = s->sess;
2112 struct http_txn *txn = s->txn;
2113 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002114 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002115 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002116
2117 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2118 now_ms, __FUNCTION__,
2119 s,
2120 res,
2121 res->rex, res->wex,
2122 res->flags,
2123 ci_data(res),
2124 res->analysers);
2125
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002126 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002127
2128 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002129 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002130 /* Output closed while we were sending data. We must abort and
2131 * wake the other side up.
2132 */
2133 msg->err_state = msg->msg_state;
2134 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002135 htx_end_response(s);
2136 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002137 return 1;
2138 }
2139
Christopher Faulet9768c262018-10-22 09:34:31 +02002140 if (msg->msg_state == HTTP_MSG_BODY)
2141 msg->msg_state = HTTP_MSG_DATA;
2142
Christopher Faulete0768eb2018-10-03 16:38:02 +02002143 /* in most states, we should abort in case of early close */
2144 channel_auto_close(res);
2145
Christopher Faulete0768eb2018-10-03 16:38:02 +02002146 if (res->to_forward) {
Christopher Fauletf52170d2019-03-08 15:45:26 +01002147 if (res->to_forward == CHN_INFINITE_FORWARD) {
2148 if (res->flags & CF_SHUTR) {
2149 msg->msg_state = HTTP_MSG_DONE;
2150 res->to_forward = 0;
2151 goto done;
2152 }
2153 }
2154 else {
2155 /* We can't process the buffer's contents yet */
2156 res->flags |= CF_WAKE_WRITE;
2157 goto missing_data_or_waiting;
2158 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002159 }
2160
Christopher Faulet9768c262018-10-22 09:34:31 +02002161 if (msg->msg_state >= HTTP_MSG_DONE)
2162 goto done;
2163
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002164 /* Forward input data. We get it by removing all outgoing data not
2165 * forwarded yet from HTX data size. If there are some data filters, we
2166 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002167 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 if (HAS_RSP_DATA_FILTERS(s)) {
2169 ret = flt_http_payload(s, msg, htx->data);
2170 if (ret < 0)
2171 goto return_bad_res;
2172 c_adv(res, ret);
2173 if (htx->data != co_data(res) || htx->extra)
2174 goto missing_data_or_waiting;
2175 }
2176 else {
2177 c_adv(res, htx->data - co_data(res));
Christopher Fauletf52170d2019-03-08 15:45:26 +01002178 if (msg->flags & HTTP_MSGF_XFER_LEN)
2179 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002180 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002181
2182 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2183 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002184 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002185 msg->msg_state = HTTP_MSG_TUNNEL;
2186 goto done;
2187 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002188 }
2189
Christopher Faulet9768c262018-10-22 09:34:31 +02002190 /* Check if the end-of-message is reached and if so, switch the message
2191 * in HTTP_MSG_DONE state.
2192 */
2193 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2194 goto missing_data_or_waiting;
2195
2196 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01002197 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002198
2199 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002201 channel_dont_close(res);
2202
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002203 if (HAS_RSP_DATA_FILTERS(s)) {
2204 ret = flt_http_end(s, msg);
2205 if (ret <= 0) {
2206 if (!ret)
2207 goto missing_data_or_waiting;
2208 goto return_bad_res;
2209 }
2210 }
2211
Christopher Fauletf2824e62018-10-01 12:12:37 +02002212 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002214 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002215 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2216 if (res->flags & CF_SHUTW) {
2217 /* response errors are most likely due to the
2218 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002219 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002221 goto return_bad_res;
2222 }
2223 return 1;
2224 }
2225 return 0;
2226
2227 missing_data_or_waiting:
2228 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002229 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230
Christopher Faulet47365272018-10-31 17:40:50 +01002231 if (htx->flags & HTX_FL_PARSING_ERROR)
2232 goto return_bad_res;
2233
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 /* stop waiting for data if the input is closed before the end. If the
2235 * client side was already closed, it means that the client has aborted,
2236 * so we don't want to count this as a server abort. Otherwise it's a
2237 * server abort.
2238 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002240 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002241 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002243 if (htx_is_empty(htx))
2244 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002245 }
2246
Christopher Faulete0768eb2018-10-03 16:38:02 +02002247 /* When TE: chunked is used, we need to get there again to parse
2248 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002249 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2250 * are filters registered on the stream, we don't want to forward a
2251 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002252 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002253 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002254 channel_dont_close(res);
2255
2256 /* We know that more data are expected, but we couldn't send more that
2257 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2258 * system knows it must not set a PUSH on this first part. Interactive
2259 * modes are already handled by the stream sock layer. We must not do
2260 * this in content-length mode because it could present the MSG_MORE
2261 * flag with the last block of forwarded data, which would cause an
2262 * additional delay to be observed by the receiver.
2263 */
2264 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2265 res->flags |= CF_EXPECT_MORE;
2266
2267 /* the stream handler will take care of timeouts and errors */
2268 return 0;
2269
Christopher Faulet93e02d82019-03-08 14:18:50 +01002270 return_srv_abort:
2271 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2272 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002273 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002274 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2275 if (!(s->flags & SF_ERR_MASK))
2276 s->flags |= SF_ERR_SRVCL;
2277 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278
Christopher Faulet93e02d82019-03-08 14:18:50 +01002279 return_cli_abort:
2280 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2281 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002283 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2284 if (!(s->flags & SF_ERR_MASK))
2285 s->flags |= SF_ERR_CLICL;
2286 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002287
Christopher Faulet93e02d82019-03-08 14:18:50 +01002288 return_bad_res:
2289 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2290 if (objt_server(s->target)) {
2291 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2292 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2293 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002294 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002295 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296
Christopher Faulet93e02d82019-03-08 14:18:50 +01002297 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 txn->rsp.err_state = txn->rsp.msg_state;
2299 txn->rsp.msg_state = HTTP_MSG_ERROR;
2300 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002301 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 res->analysers &= AN_RES_FLT_END;
2303 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulete0768eb2018-10-03 16:38:02 +02002304 if (!(s->flags & SF_FINST_MASK))
2305 s->flags |= SF_FINST_D;
2306 return 0;
2307}
2308
Christopher Faulet0f226952018-10-22 09:29:56 +02002309void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002310{
2311 struct proxy *fe = strm_fe(s);
2312 int tmp = TX_CON_WANT_CLO;
2313
2314 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2315 tmp = TX_CON_WANT_TUN;
2316
2317 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002318 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002319}
2320
2321/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002322 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323 * as too large a request to build a valid response.
2324 */
2325int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2326{
Christopher Faulet99daf282018-11-28 22:58:13 +01002327 struct channel *req = &s->req;
2328 struct channel *res = &s->res;
2329 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002330 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002331 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002332 struct ist status, reason, location;
2333 unsigned int flags;
2334 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002335
2336 chunk = alloc_trash_chunk();
2337 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002338 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002339
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 /*
2341 * Create the location
2342 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002343 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002344 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002345 case REDIRECT_TYPE_SCHEME: {
2346 struct http_hdr_ctx ctx;
2347 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002348
Christopher Faulet99daf282018-11-28 22:58:13 +01002349 host = ist("");
2350 ctx.blk = NULL;
2351 if (http_find_header(htx, ist("Host"), &ctx, 0))
2352 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353
Christopher Faulet99daf282018-11-28 22:58:13 +01002354 sl = http_find_stline(htx);
2355 path = http_get_path(htx_sl_req_uri(sl));
2356 /* build message using path */
2357 if (path.ptr) {
2358 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2359 int qs = 0;
2360 while (qs < path.len) {
2361 if (*(path.ptr + qs) == '?') {
2362 path.len = qs;
2363 break;
2364 }
2365 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002367 }
2368 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002369 else
2370 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002371
Christopher Faulet99daf282018-11-28 22:58:13 +01002372 if (rule->rdr_str) { /* this is an old "redirect" rule */
2373 /* add scheme */
2374 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2375 goto fail;
2376 }
2377 else {
2378 /* add scheme with executing log format */
2379 chunk->data += build_logline(s, chunk->area + chunk->data,
2380 chunk->size - chunk->data,
2381 &rule->rdr_fmt);
2382 }
2383 /* add "://" + host + path */
2384 if (!chunk_memcat(chunk, "://", 3) ||
2385 !chunk_memcat(chunk, host.ptr, host.len) ||
2386 !chunk_memcat(chunk, path.ptr, path.len))
2387 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 /* append a slash at the end of the location if needed and missing */
2390 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2391 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2392 if (chunk->data + 1 >= chunk->size)
2393 goto fail;
2394 chunk->area[chunk->data++] = '/';
2395 }
2396 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002398
Christopher Faulet99daf282018-11-28 22:58:13 +01002399 case REDIRECT_TYPE_PREFIX: {
2400 struct ist path;
2401
2402 sl = http_find_stline(htx);
2403 path = http_get_path(htx_sl_req_uri(sl));
2404 /* build message using path */
2405 if (path.ptr) {
2406 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2407 int qs = 0;
2408 while (qs < path.len) {
2409 if (*(path.ptr + qs) == '?') {
2410 path.len = qs;
2411 break;
2412 }
2413 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415 }
2416 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002417 else
2418 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002419
Christopher Faulet99daf282018-11-28 22:58:13 +01002420 if (rule->rdr_str) { /* this is an old "redirect" rule */
2421 /* add prefix. Note that if prefix == "/", we don't want to
2422 * add anything, otherwise it makes it hard for the user to
2423 * configure a self-redirection.
2424 */
2425 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2426 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2427 goto fail;
2428 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002430 else {
2431 /* add prefix with executing log format */
2432 chunk->data += build_logline(s, chunk->area + chunk->data,
2433 chunk->size - chunk->data,
2434 &rule->rdr_fmt);
2435 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002436
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 /* add path */
2438 if (!chunk_memcat(chunk, path.ptr, path.len))
2439 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002440
Christopher Faulet99daf282018-11-28 22:58:13 +01002441 /* append a slash at the end of the location if needed and missing */
2442 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2443 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2444 if (chunk->data + 1 >= chunk->size)
2445 goto fail;
2446 chunk->area[chunk->data++] = '/';
2447 }
2448 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 case REDIRECT_TYPE_LOCATION:
2451 default:
2452 if (rule->rdr_str) { /* this is an old "redirect" rule */
2453 /* add location */
2454 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2455 goto fail;
2456 }
2457 else {
2458 /* add location with executing log format */
2459 chunk->data += build_logline(s, chunk->area + chunk->data,
2460 chunk->size - chunk->data,
2461 &rule->rdr_fmt);
2462 }
2463 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002465 location = ist2(chunk->area, chunk->data);
2466
2467 /*
2468 * Create the 30x response
2469 */
2470 switch (rule->code) {
2471 case 308:
2472 status = ist("308");
2473 reason = ist("Permanent Redirect");
2474 break;
2475 case 307:
2476 status = ist("307");
2477 reason = ist("Temporary Redirect");
2478 break;
2479 case 303:
2480 status = ist("303");
2481 reason = ist("See Other");
2482 break;
2483 case 301:
2484 status = ist("301");
2485 reason = ist("Moved Permanently");
2486 break;
2487 case 302:
2488 default:
2489 status = ist("302");
2490 reason = ist("Found");
2491 break;
2492 }
2493
2494 htx = htx_from_buf(&res->buf);
2495 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2496 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2497 if (!sl)
2498 goto fail;
2499 sl->info.res.status = rule->code;
2500 s->txn->status = rule->code;
2501
2502 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2503 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2504 !htx_add_header(htx, ist("Location"), location))
2505 goto fail;
2506
2507 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2508 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2509 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002510 }
2511
2512 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002513 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2514 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002515 }
2516
Christopher Faulet99daf282018-11-28 22:58:13 +01002517 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2518 goto fail;
2519
Christopher Fauletf2824e62018-10-01 12:12:37 +02002520 /* let's log the request time */
2521 s->logs.tv_request = now;
2522
Christopher Faulet99daf282018-11-28 22:58:13 +01002523 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002524 c_adv(res, data);
2525 res->total += data;
2526
2527 channel_auto_read(req);
2528 channel_abort(req);
2529 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002530 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002531
2532 res->wex = tick_add_ifset(now_ms, res->wto);
2533 channel_auto_read(res);
2534 channel_auto_close(res);
2535 channel_shutr_now(res);
2536
2537 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002538
2539 if (!(s->flags & SF_ERR_MASK))
2540 s->flags |= SF_ERR_LOCAL;
2541 if (!(s->flags & SF_FINST_MASK))
2542 s->flags |= SF_FINST_R;
2543
Christopher Faulet99daf282018-11-28 22:58:13 +01002544 free_trash_chunk(chunk);
2545 return 1;
2546
2547 fail:
2548 /* If an error occurred, remove the incomplete HTTP response from the
2549 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002550 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002551 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002553}
2554
Christopher Faulet72333522018-10-24 11:25:02 +02002555int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2556 struct ist name, const char *str, struct my_regex *re, int action)
2557{
2558 struct http_hdr_ctx ctx;
2559 struct buffer *output = get_trash_chunk();
2560
2561 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2562 ctx.blk = NULL;
2563 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2564 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2565 continue;
2566
2567 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2568 if (output->data == -1)
2569 return -1;
2570 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2571 return -1;
2572 }
2573 return 0;
2574}
2575
2576static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2577 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2578{
2579 struct buffer *replace;
2580 int ret = -1;
2581
2582 replace = alloc_trash_chunk();
2583 if (!replace)
2584 goto leave;
2585
2586 replace->data = build_logline(s, replace->area, replace->size, fmt);
2587 if (replace->data >= replace->size - 1)
2588 goto leave;
2589
2590 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2591
2592 leave:
2593 free_trash_chunk(replace);
2594 return ret;
2595}
2596
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002597
2598/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2599 * on success and -1 on error. The response channel is updated accordingly.
2600 */
2601static int htx_reply_103_early_hints(struct channel *res)
2602{
2603 struct htx *htx = htx_from_buf(&res->buf);
2604 size_t data;
2605
2606 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2607 /* If an error occurred during an Early-hint rule,
2608 * remove the incomplete HTTP 103 response from the
2609 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002610 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002611 return -1;
2612 }
2613
2614 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002615 c_adv(res, data);
2616 res->total += data;
2617 return 0;
2618}
2619
Christopher Faulet6eb92892018-11-15 16:39:29 +01002620/*
2621 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2622 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002623 * If <early_hints> is 0, it is starts a new response by adding the start
2624 * line. If an error occurred -1 is returned. On success 0 is returned. The
2625 * channel is not updated here. It must be done calling the function
2626 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002627 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002628static int htx_add_early_hint_header(struct stream *s, int early_hints, const struct ist name, struct list *fmt)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002629{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002630 struct channel *res = &s->res;
2631 struct htx *htx = htx_from_buf(&res->buf);
2632 struct buffer *value = alloc_trash_chunk();
2633
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002635 struct htx_sl *sl;
2636 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2637 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2638
2639 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2640 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2641 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002642 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002644 }
2645
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2647 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002648 goto fail;
2649
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002652
2653 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 /* If an error occurred during an Early-hint rule, remove the incomplete
2655 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002656 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002657 free_trash_chunk(value);
2658 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002659}
2660
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002661/* This function executes one of the set-{method,path,query,uri} actions. It
2662 * takes the string from the variable 'replace' with length 'len', then modifies
2663 * the relevant part of the request line accordingly. Then it updates various
2664 * pointers to the next elements which were moved, and the total buffer length.
2665 * It finds the action to be performed in p[2], previously filled by function
2666 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2667 * error, though this can be revisited when this code is finally exploited.
2668 *
2669 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2670 * query string and 3 to replace uri.
2671 *
2672 * In query string case, the mark question '?' must be set at the start of the
2673 * string by the caller, event if the replacement query string is empty.
2674 */
2675int htx_req_replace_stline(int action, const char *replace, int len,
2676 struct proxy *px, struct stream *s)
2677{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002678 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002679
2680 switch (action) {
2681 case 0: // method
2682 if (!http_replace_req_meth(htx, ist2(replace, len)))
2683 return -1;
2684 break;
2685
2686 case 1: // path
2687 if (!http_replace_req_path(htx, ist2(replace, len)))
2688 return -1;
2689 break;
2690
2691 case 2: // query
2692 if (!http_replace_req_query(htx, ist2(replace, len)))
2693 return -1;
2694 break;
2695
2696 case 3: // uri
2697 if (!http_replace_req_uri(htx, ist2(replace, len)))
2698 return -1;
2699 break;
2700
2701 default:
2702 return -1;
2703 }
2704 return 0;
2705}
2706
2707/* This function replace the HTTP status code and the associated message. The
2708 * variable <status> contains the new status code. This function never fails.
2709 */
2710void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2711{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002712 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002713 char *res;
2714
2715 chunk_reset(&trash);
2716 res = ultoa_o(status, trash.area, trash.size);
2717 trash.data = res - trash.area;
2718
2719 /* Do we have a custom reason format string? */
2720 if (reason == NULL)
2721 reason = http_get_reason(status);
2722
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002723 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002724 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2725}
2726
Christopher Faulet3e964192018-10-24 11:39:23 +02002727/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2728 * transaction <txn>. Returns the verdict of the first rule that prevents
2729 * further processing of the request (auth, deny, ...), and defaults to
2730 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2731 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2732 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2733 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2734 * status.
2735 */
2736static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2737 struct stream *s, int *deny_status)
2738{
2739 struct session *sess = strm_sess(s);
2740 struct http_txn *txn = s->txn;
2741 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002742 struct act_rule *rule;
2743 struct http_hdr_ctx ctx;
2744 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002745 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2746 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002747 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002748
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002749 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002750
2751 /* If "the current_rule_list" match the executed rule list, we are in
2752 * resume condition. If a resume is needed it is always in the action
2753 * and never in the ACL or converters. In this case, we initialise the
2754 * current rule, and go to the action execution point.
2755 */
2756 if (s->current_rule) {
2757 rule = s->current_rule;
2758 s->current_rule = NULL;
2759 if (s->current_rule_list == rules)
2760 goto resume_execution;
2761 }
2762 s->current_rule_list = rules;
2763
2764 list_for_each_entry(rule, rules, list) {
2765 /* check optional condition */
2766 if (rule->cond) {
2767 int ret;
2768
2769 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2770 ret = acl_pass(ret);
2771
2772 if (rule->cond->pol == ACL_COND_UNLESS)
2773 ret = !ret;
2774
2775 if (!ret) /* condition not matched */
2776 continue;
2777 }
2778
2779 act_flags |= ACT_FLAG_FIRST;
2780 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002781 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2782 early_hints = 0;
2783 if (htx_reply_103_early_hints(&s->res) == -1) {
2784 rule_ret = HTTP_RULE_RES_BADREQ;
2785 goto end;
2786 }
2787 }
2788
Christopher Faulet3e964192018-10-24 11:39:23 +02002789 switch (rule->action) {
2790 case ACT_ACTION_ALLOW:
2791 rule_ret = HTTP_RULE_RES_STOP;
2792 goto end;
2793
2794 case ACT_ACTION_DENY:
2795 if (deny_status)
2796 *deny_status = rule->deny_status;
2797 rule_ret = HTTP_RULE_RES_DENY;
2798 goto end;
2799
2800 case ACT_HTTP_REQ_TARPIT:
2801 txn->flags |= TX_CLTARPIT;
2802 if (deny_status)
2803 *deny_status = rule->deny_status;
2804 rule_ret = HTTP_RULE_RES_DENY;
2805 goto end;
2806
2807 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002808 /* Auth might be performed on regular http-req rules as well as on stats */
2809 auth_realm = rule->arg.auth.realm;
2810 if (!auth_realm) {
2811 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2812 auth_realm = STATS_DEFAULT_REALM;
2813 else
2814 auth_realm = px->id;
2815 }
2816 /* send 401/407 depending on whether we use a proxy or not. We still
2817 * count one error, because normal browsing won't significantly
2818 * increase the counter but brute force attempts will.
2819 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002820 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002821 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2822 rule_ret = HTTP_RULE_RES_BADREQ;
2823 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 goto end;
2825
2826 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002827 rule_ret = HTTP_RULE_RES_DONE;
2828 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2829 rule_ret = HTTP_RULE_RES_BADREQ;
2830 goto end;
2831
2832 case ACT_HTTP_SET_NICE:
2833 s->task->nice = rule->arg.nice;
2834 break;
2835
2836 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002837 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002838 break;
2839
2840 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002841 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002842 break;
2843
2844 case ACT_HTTP_SET_LOGL:
2845 s->logs.level = rule->arg.loglevel;
2846 break;
2847
2848 case ACT_HTTP_REPLACE_HDR:
2849 case ACT_HTTP_REPLACE_VAL:
2850 if (htx_transform_header(s, &s->req, htx,
2851 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2852 &rule->arg.hdr_add.fmt,
2853 &rule->arg.hdr_add.re, rule->action)) {
2854 rule_ret = HTTP_RULE_RES_BADREQ;
2855 goto end;
2856 }
2857 break;
2858
2859 case ACT_HTTP_DEL_HDR:
2860 /* remove all occurrences of the header */
2861 ctx.blk = NULL;
2862 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2863 http_remove_header(htx, &ctx);
2864 break;
2865
2866 case ACT_HTTP_SET_HDR:
2867 case ACT_HTTP_ADD_HDR: {
2868 /* The scope of the trash buffer must be limited to this function. The
2869 * build_logline() function can execute a lot of other function which
2870 * can use the trash buffer. So for limiting the scope of this global
2871 * buffer, we build first the header value using build_logline, and
2872 * after we store the header name.
2873 */
2874 struct buffer *replace;
2875 struct ist n, v;
2876
2877 replace = alloc_trash_chunk();
2878 if (!replace) {
2879 rule_ret = HTTP_RULE_RES_BADREQ;
2880 goto end;
2881 }
2882
2883 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2884 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2885 v = ist2(replace->area, replace->data);
2886
2887 if (rule->action == ACT_HTTP_SET_HDR) {
2888 /* remove all occurrences of the header */
2889 ctx.blk = NULL;
2890 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2891 http_remove_header(htx, &ctx);
2892 }
2893
2894 if (!http_add_header(htx, n, v)) {
2895 static unsigned char rate_limit = 0;
2896
2897 if ((rate_limit++ & 255) == 0) {
2898 send_log(px, LOG_WARNING, "Proxy %s failed to add or set the request header '%.*s' for request #%u. You might need to increase tune.maxrewrite.", px->id, (int)n.len, n.ptr, s->uniq_id);
2899 }
2900
Olivier Houcharda798bf52019-03-08 18:52:00 +01002901 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002902 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002903 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002904 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002905 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002906 }
2907 free_trash_chunk(replace);
2908 break;
2909 }
2910
2911 case ACT_HTTP_DEL_ACL:
2912 case ACT_HTTP_DEL_MAP: {
2913 struct pat_ref *ref;
2914 struct buffer *key;
2915
2916 /* collect reference */
2917 ref = pat_ref_lookup(rule->arg.map.ref);
2918 if (!ref)
2919 continue;
2920
2921 /* allocate key */
2922 key = alloc_trash_chunk();
2923 if (!key) {
2924 rule_ret = HTTP_RULE_RES_BADREQ;
2925 goto end;
2926 }
2927
2928 /* collect key */
2929 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2930 key->area[key->data] = '\0';
2931
2932 /* perform update */
2933 /* returned code: 1=ok, 0=ko */
2934 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2935 pat_ref_delete(ref, key->area);
2936 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2937
2938 free_trash_chunk(key);
2939 break;
2940 }
2941
2942 case ACT_HTTP_ADD_ACL: {
2943 struct pat_ref *ref;
2944 struct buffer *key;
2945
2946 /* collect reference */
2947 ref = pat_ref_lookup(rule->arg.map.ref);
2948 if (!ref)
2949 continue;
2950
2951 /* allocate key */
2952 key = alloc_trash_chunk();
2953 if (!key) {
2954 rule_ret = HTTP_RULE_RES_BADREQ;
2955 goto end;
2956 }
2957
2958 /* collect key */
2959 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2960 key->area[key->data] = '\0';
2961
2962 /* perform update */
2963 /* add entry only if it does not already exist */
2964 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2965 if (pat_ref_find_elt(ref, key->area) == NULL)
2966 pat_ref_add(ref, key->area, NULL, NULL);
2967 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2968
2969 free_trash_chunk(key);
2970 break;
2971 }
2972
2973 case ACT_HTTP_SET_MAP: {
2974 struct pat_ref *ref;
2975 struct buffer *key, *value;
2976
2977 /* collect reference */
2978 ref = pat_ref_lookup(rule->arg.map.ref);
2979 if (!ref)
2980 continue;
2981
2982 /* allocate key */
2983 key = alloc_trash_chunk();
2984 if (!key) {
2985 rule_ret = HTTP_RULE_RES_BADREQ;
2986 goto end;
2987 }
2988
2989 /* allocate value */
2990 value = alloc_trash_chunk();
2991 if (!value) {
2992 free_trash_chunk(key);
2993 rule_ret = HTTP_RULE_RES_BADREQ;
2994 goto end;
2995 }
2996
2997 /* collect key */
2998 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2999 key->area[key->data] = '\0';
3000
3001 /* collect value */
3002 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3003 value->area[value->data] = '\0';
3004
3005 /* perform update */
3006 if (pat_ref_find_elt(ref, key->area) != NULL)
3007 /* update entry if it exists */
3008 pat_ref_set(ref, key->area, value->area, NULL);
3009 else
3010 /* insert a new entry */
3011 pat_ref_add(ref, key->area, value->area, NULL);
3012
3013 free_trash_chunk(key);
3014 free_trash_chunk(value);
3015 break;
3016 }
3017
3018 case ACT_HTTP_EARLY_HINT:
3019 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3020 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003021 early_hints = htx_add_early_hint_header(s, early_hints,
3022 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003023 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003024 if (early_hints == -1) {
3025 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003026 goto end;
3027 }
3028 break;
3029
3030 case ACT_CUSTOM:
3031 if ((s->req.flags & CF_READ_ERROR) ||
3032 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3033 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3034 (px->options & PR_O_ABRT_CLOSE)))
3035 act_flags |= ACT_FLAG_FINAL;
3036
3037 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3038 case ACT_RET_ERR:
3039 case ACT_RET_CONT:
3040 break;
3041 case ACT_RET_STOP:
3042 rule_ret = HTTP_RULE_RES_DONE;
3043 goto end;
3044 case ACT_RET_YIELD:
3045 s->current_rule = rule;
3046 rule_ret = HTTP_RULE_RES_YIELD;
3047 goto end;
3048 }
3049 break;
3050
3051 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3052 /* Note: only the first valid tracking parameter of each
3053 * applies.
3054 */
3055
3056 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3057 struct stktable *t;
3058 struct stksess *ts;
3059 struct stktable_key *key;
3060 void *ptr1, *ptr2;
3061
3062 t = rule->arg.trk_ctr.table.t;
3063 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3064 rule->arg.trk_ctr.expr, NULL);
3065
3066 if (key && (ts = stktable_get_entry(t, key))) {
3067 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3068
3069 /* let's count a new HTTP request as it's the first time we do it */
3070 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3071 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3072 if (ptr1 || ptr2) {
3073 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3074
3075 if (ptr1)
3076 stktable_data_cast(ptr1, http_req_cnt)++;
3077
3078 if (ptr2)
3079 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3080 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3081
3082 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3083
3084 /* If data was modified, we need to touch to re-schedule sync */
3085 stktable_touch_local(t, ts, 0);
3086 }
3087
3088 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3089 if (sess->fe != s->be)
3090 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3091 }
3092 }
3093 break;
3094
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003095 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003096 default:
3097 break;
3098 }
3099 }
3100
3101 end:
3102 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003103 if (htx_reply_103_early_hints(&s->res) == -1)
3104 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003105 }
3106
3107 /* we reached the end of the rules, nothing to report */
3108 return rule_ret;
3109}
3110
3111/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3112 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3113 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3114 * is returned, the process can continue the evaluation of next rule list. If
3115 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3116 * is returned, it means the operation could not be processed and a server error
3117 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3118 * deny rule. If *YIELD is returned, the caller must call again the function
3119 * with the same context.
3120 */
3121static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3122 struct stream *s)
3123{
3124 struct session *sess = strm_sess(s);
3125 struct http_txn *txn = s->txn;
3126 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003127 struct act_rule *rule;
3128 struct http_hdr_ctx ctx;
3129 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3130 int act_flags = 0;
3131
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003132 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003133
3134 /* If "the current_rule_list" match the executed rule list, we are in
3135 * resume condition. If a resume is needed it is always in the action
3136 * and never in the ACL or converters. In this case, we initialise the
3137 * current rule, and go to the action execution point.
3138 */
3139 if (s->current_rule) {
3140 rule = s->current_rule;
3141 s->current_rule = NULL;
3142 if (s->current_rule_list == rules)
3143 goto resume_execution;
3144 }
3145 s->current_rule_list = rules;
3146
3147 list_for_each_entry(rule, rules, list) {
3148 /* check optional condition */
3149 if (rule->cond) {
3150 int ret;
3151
3152 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3153 ret = acl_pass(ret);
3154
3155 if (rule->cond->pol == ACL_COND_UNLESS)
3156 ret = !ret;
3157
3158 if (!ret) /* condition not matched */
3159 continue;
3160 }
3161
3162 act_flags |= ACT_FLAG_FIRST;
3163resume_execution:
3164 switch (rule->action) {
3165 case ACT_ACTION_ALLOW:
3166 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3167 goto end;
3168
3169 case ACT_ACTION_DENY:
3170 txn->flags |= TX_SVDENY;
3171 rule_ret = HTTP_RULE_RES_STOP;
3172 goto end;
3173
3174 case ACT_HTTP_SET_NICE:
3175 s->task->nice = rule->arg.nice;
3176 break;
3177
3178 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003179 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003180 break;
3181
3182 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003183 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003184 break;
3185
3186 case ACT_HTTP_SET_LOGL:
3187 s->logs.level = rule->arg.loglevel;
3188 break;
3189
3190 case ACT_HTTP_REPLACE_HDR:
3191 case ACT_HTTP_REPLACE_VAL:
3192 if (htx_transform_header(s, &s->res, htx,
3193 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3194 &rule->arg.hdr_add.fmt,
3195 &rule->arg.hdr_add.re, rule->action)) {
3196 rule_ret = HTTP_RULE_RES_BADREQ;
3197 goto end;
3198 }
3199 break;
3200
3201 case ACT_HTTP_DEL_HDR:
3202 /* remove all occurrences of the header */
3203 ctx.blk = NULL;
3204 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3205 http_remove_header(htx, &ctx);
3206 break;
3207
3208 case ACT_HTTP_SET_HDR:
3209 case ACT_HTTP_ADD_HDR: {
3210 struct buffer *replace;
3211 struct ist n, v;
3212
3213 replace = alloc_trash_chunk();
3214 if (!replace) {
3215 rule_ret = HTTP_RULE_RES_BADREQ;
3216 goto end;
3217 }
3218
3219 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3220 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3221 v = ist2(replace->area, replace->data);
3222
3223 if (rule->action == ACT_HTTP_SET_HDR) {
3224 /* remove all occurrences of the header */
3225 ctx.blk = NULL;
3226 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3227 http_remove_header(htx, &ctx);
3228 }
3229
3230 if (!http_add_header(htx, n, v)) {
3231 static unsigned char rate_limit = 0;
3232
3233 if ((rate_limit++ & 255) == 0) {
3234 send_log(px, LOG_WARNING, "Proxy %s failed to add or set the response header '%.*s' for request #%u. You might need to increase tune.maxrewrite.", px->id, (int)n.len, n.ptr, s->uniq_id);
3235 }
3236
Olivier Houcharda798bf52019-03-08 18:52:00 +01003237 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003238 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003239 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003240 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003241 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003242 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003243 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003244 }
3245 free_trash_chunk(replace);
3246 break;
3247 }
3248
3249 case ACT_HTTP_DEL_ACL:
3250 case ACT_HTTP_DEL_MAP: {
3251 struct pat_ref *ref;
3252 struct buffer *key;
3253
3254 /* collect reference */
3255 ref = pat_ref_lookup(rule->arg.map.ref);
3256 if (!ref)
3257 continue;
3258
3259 /* allocate key */
3260 key = alloc_trash_chunk();
3261 if (!key) {
3262 rule_ret = HTTP_RULE_RES_BADREQ;
3263 goto end;
3264 }
3265
3266 /* collect key */
3267 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3268 key->area[key->data] = '\0';
3269
3270 /* perform update */
3271 /* returned code: 1=ok, 0=ko */
3272 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3273 pat_ref_delete(ref, key->area);
3274 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3275
3276 free_trash_chunk(key);
3277 break;
3278 }
3279
3280 case ACT_HTTP_ADD_ACL: {
3281 struct pat_ref *ref;
3282 struct buffer *key;
3283
3284 /* collect reference */
3285 ref = pat_ref_lookup(rule->arg.map.ref);
3286 if (!ref)
3287 continue;
3288
3289 /* allocate key */
3290 key = alloc_trash_chunk();
3291 if (!key) {
3292 rule_ret = HTTP_RULE_RES_BADREQ;
3293 goto end;
3294 }
3295
3296 /* collect key */
3297 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3298 key->area[key->data] = '\0';
3299
3300 /* perform update */
3301 /* check if the entry already exists */
3302 if (pat_ref_find_elt(ref, key->area) == NULL)
3303 pat_ref_add(ref, key->area, NULL, NULL);
3304
3305 free_trash_chunk(key);
3306 break;
3307 }
3308
3309 case ACT_HTTP_SET_MAP: {
3310 struct pat_ref *ref;
3311 struct buffer *key, *value;
3312
3313 /* collect reference */
3314 ref = pat_ref_lookup(rule->arg.map.ref);
3315 if (!ref)
3316 continue;
3317
3318 /* allocate key */
3319 key = alloc_trash_chunk();
3320 if (!key) {
3321 rule_ret = HTTP_RULE_RES_BADREQ;
3322 goto end;
3323 }
3324
3325 /* allocate value */
3326 value = alloc_trash_chunk();
3327 if (!value) {
3328 free_trash_chunk(key);
3329 rule_ret = HTTP_RULE_RES_BADREQ;
3330 goto end;
3331 }
3332
3333 /* collect key */
3334 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3335 key->area[key->data] = '\0';
3336
3337 /* collect value */
3338 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3339 value->area[value->data] = '\0';
3340
3341 /* perform update */
3342 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3343 if (pat_ref_find_elt(ref, key->area) != NULL)
3344 /* update entry if it exists */
3345 pat_ref_set(ref, key->area, value->area, NULL);
3346 else
3347 /* insert a new entry */
3348 pat_ref_add(ref, key->area, value->area, NULL);
3349 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3350 free_trash_chunk(key);
3351 free_trash_chunk(value);
3352 break;
3353 }
3354
3355 case ACT_HTTP_REDIR:
3356 rule_ret = HTTP_RULE_RES_DONE;
3357 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3358 rule_ret = HTTP_RULE_RES_BADREQ;
3359 goto end;
3360
3361 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3362 /* Note: only the first valid tracking parameter of each
3363 * applies.
3364 */
3365 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3366 struct stktable *t;
3367 struct stksess *ts;
3368 struct stktable_key *key;
3369 void *ptr;
3370
3371 t = rule->arg.trk_ctr.table.t;
3372 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3373 rule->arg.trk_ctr.expr, NULL);
3374
3375 if (key && (ts = stktable_get_entry(t, key))) {
3376 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3377
3378 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3379
3380 /* let's count a new HTTP request as it's the first time we do it */
3381 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3382 if (ptr)
3383 stktable_data_cast(ptr, http_req_cnt)++;
3384
3385 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3386 if (ptr)
3387 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3388 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3389
3390 /* When the client triggers a 4xx from the server, it's most often due
3391 * to a missing object or permission. These events should be tracked
3392 * because if they happen often, it may indicate a brute force or a
3393 * vulnerability scan. Normally this is done when receiving the response
3394 * but here we're tracking after this ought to have been done so we have
3395 * to do it on purpose.
3396 */
3397 if ((unsigned)(txn->status - 400) < 100) {
3398 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3399 if (ptr)
3400 stktable_data_cast(ptr, http_err_cnt)++;
3401
3402 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3403 if (ptr)
3404 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3405 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3406 }
3407
3408 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3409
3410 /* If data was modified, we need to touch to re-schedule sync */
3411 stktable_touch_local(t, ts, 0);
3412
3413 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3414 if (sess->fe != s->be)
3415 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3416 }
3417 }
3418 break;
3419
3420 case ACT_CUSTOM:
3421 if ((s->req.flags & CF_READ_ERROR) ||
3422 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3423 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3424 (px->options & PR_O_ABRT_CLOSE)))
3425 act_flags |= ACT_FLAG_FINAL;
3426
3427 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3428 case ACT_RET_ERR:
3429 case ACT_RET_CONT:
3430 break;
3431 case ACT_RET_STOP:
3432 rule_ret = HTTP_RULE_RES_STOP;
3433 goto end;
3434 case ACT_RET_YIELD:
3435 s->current_rule = rule;
3436 rule_ret = HTTP_RULE_RES_YIELD;
3437 goto end;
3438 }
3439 break;
3440
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003441 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003442 default:
3443 break;
3444 }
3445 }
3446
3447 end:
3448 /* we reached the end of the rules, nothing to report */
3449 return rule_ret;
3450}
3451
Christopher Faulet33640082018-10-24 11:53:01 +02003452/* Iterate the same filter through all request headers.
3453 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3454 * Since it can manage the switch to another backend, it updates the per-proxy
3455 * DENY stats.
3456 */
3457static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3458{
3459 struct http_txn *txn = s->txn;
3460 struct htx *htx;
3461 struct buffer *hdr = get_trash_chunk();
3462 int32_t pos;
3463
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003464 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003465
3466 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3467 struct htx_blk *blk = htx_get_blk(htx, pos);
3468 enum htx_blk_type type;
3469 struct ist n, v;
3470
3471 next_hdr:
3472 type = htx_get_blk_type(blk);
3473 if (type == HTX_BLK_EOH)
3474 break;
3475 if (type != HTX_BLK_HDR)
3476 continue;
3477
3478 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3479 return 1;
3480 else if (unlikely(txn->flags & TX_CLALLOW) &&
3481 (exp->action == ACT_ALLOW ||
3482 exp->action == ACT_DENY ||
3483 exp->action == ACT_TARPIT))
3484 return 0;
3485
3486 n = htx_get_blk_name(htx, blk);
3487 v = htx_get_blk_value(htx, blk);
3488
Christopher Faulet02e771a2019-02-26 15:36:05 +01003489 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003490 hdr->area[hdr->data++] = ':';
3491 hdr->area[hdr->data++] = ' ';
3492 chunk_memcat(hdr, v.ptr, v.len);
3493
3494 /* Now we have one header in <hdr> */
3495
3496 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3497 struct http_hdr_ctx ctx;
3498 int len;
3499
3500 switch (exp->action) {
3501 case ACT_ALLOW:
3502 txn->flags |= TX_CLALLOW;
3503 goto end;
3504
3505 case ACT_DENY:
3506 txn->flags |= TX_CLDENY;
3507 goto end;
3508
3509 case ACT_TARPIT:
3510 txn->flags |= TX_CLTARPIT;
3511 goto end;
3512
3513 case ACT_REPLACE:
3514 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3515 if (len < 0)
3516 return -1;
3517
3518 http_parse_header(ist2(trash.area, len), &n, &v);
3519 ctx.blk = blk;
3520 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003521 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003522 if (!http_replace_header(htx, &ctx, n, v))
3523 return -1;
3524 if (!ctx.blk)
3525 goto end;
3526 pos = htx_get_blk_pos(htx, blk);
3527 break;
3528
3529 case ACT_REMOVE:
3530 ctx.blk = blk;
3531 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003532 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003533 if (!http_remove_header(htx, &ctx))
3534 return -1;
3535 if (!ctx.blk)
3536 goto end;
3537 pos = htx_get_blk_pos(htx, blk);
3538 goto next_hdr;
3539
3540 }
3541 }
3542 }
3543 end:
3544 return 0;
3545}
3546
3547/* Apply the filter to the request line.
3548 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3549 * or -1 if a replacement resulted in an invalid request line.
3550 * Since it can manage the switch to another backend, it updates the per-proxy
3551 * DENY stats.
3552 */
3553static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3554{
3555 struct http_txn *txn = s->txn;
3556 struct htx *htx;
3557 struct buffer *reqline = get_trash_chunk();
3558 int done;
3559
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003560 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003561
3562 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3563 return 1;
3564 else if (unlikely(txn->flags & TX_CLALLOW) &&
3565 (exp->action == ACT_ALLOW ||
3566 exp->action == ACT_DENY ||
3567 exp->action == ACT_TARPIT))
3568 return 0;
3569 else if (exp->action == ACT_REMOVE)
3570 return 0;
3571
3572 done = 0;
3573
3574 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3575
3576 /* Now we have the request line between cur_ptr and cur_end */
3577 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003578 struct htx_sl *sl = http_find_stline(htx);
3579 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003580 int len;
3581
3582 switch (exp->action) {
3583 case ACT_ALLOW:
3584 txn->flags |= TX_CLALLOW;
3585 done = 1;
3586 break;
3587
3588 case ACT_DENY:
3589 txn->flags |= TX_CLDENY;
3590 done = 1;
3591 break;
3592
3593 case ACT_TARPIT:
3594 txn->flags |= TX_CLTARPIT;
3595 done = 1;
3596 break;
3597
3598 case ACT_REPLACE:
3599 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3600 if (len < 0)
3601 return -1;
3602
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003603 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3604 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3605 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003606 return -1;
3607 done = 1;
3608 break;
3609 }
3610 }
3611 return done;
3612}
3613
3614/*
3615 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3616 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3617 * unparsable request. Since it can manage the switch to another backend, it
3618 * updates the per-proxy DENY stats.
3619 */
3620static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3621{
3622 struct session *sess = s->sess;
3623 struct http_txn *txn = s->txn;
3624 struct hdr_exp *exp;
3625
3626 for (exp = px->req_exp; exp; exp = exp->next) {
3627 int ret;
3628
3629 /*
3630 * The interleaving of transformations and verdicts
3631 * makes it difficult to decide to continue or stop
3632 * the evaluation.
3633 */
3634
3635 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3636 break;
3637
3638 if ((txn->flags & TX_CLALLOW) &&
3639 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3640 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3641 continue;
3642
3643 /* if this filter had a condition, evaluate it now and skip to
3644 * next filter if the condition does not match.
3645 */
3646 if (exp->cond) {
3647 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3648 ret = acl_pass(ret);
3649 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3650 ret = !ret;
3651
3652 if (!ret)
3653 continue;
3654 }
3655
3656 /* Apply the filter to the request line. */
3657 ret = htx_apply_filter_to_req_line(s, req, exp);
3658 if (unlikely(ret < 0))
3659 return -1;
3660
3661 if (likely(ret == 0)) {
3662 /* The filter did not match the request, it can be
3663 * iterated through all headers.
3664 */
3665 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3666 return -1;
3667 }
3668 }
3669 return 0;
3670}
3671
3672/* Iterate the same filter through all response headers contained in <res>.
3673 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3674 */
3675static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3676{
3677 struct http_txn *txn = s->txn;
3678 struct htx *htx;
3679 struct buffer *hdr = get_trash_chunk();
3680 int32_t pos;
3681
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003682 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003683
3684 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3685 struct htx_blk *blk = htx_get_blk(htx, pos);
3686 enum htx_blk_type type;
3687 struct ist n, v;
3688
3689 next_hdr:
3690 type = htx_get_blk_type(blk);
3691 if (type == HTX_BLK_EOH)
3692 break;
3693 if (type != HTX_BLK_HDR)
3694 continue;
3695
3696 if (unlikely(txn->flags & TX_SVDENY))
3697 return 1;
3698 else if (unlikely(txn->flags & TX_SVALLOW) &&
3699 (exp->action == ACT_ALLOW ||
3700 exp->action == ACT_DENY))
3701 return 0;
3702
3703 n = htx_get_blk_name(htx, blk);
3704 v = htx_get_blk_value(htx, blk);
3705
Christopher Faulet02e771a2019-02-26 15:36:05 +01003706 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003707 hdr->area[hdr->data++] = ':';
3708 hdr->area[hdr->data++] = ' ';
3709 chunk_memcat(hdr, v.ptr, v.len);
3710
3711 /* Now we have one header in <hdr> */
3712
3713 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3714 struct http_hdr_ctx ctx;
3715 int len;
3716
3717 switch (exp->action) {
3718 case ACT_ALLOW:
3719 txn->flags |= TX_SVALLOW;
3720 goto end;
3721 break;
3722
3723 case ACT_DENY:
3724 txn->flags |= TX_SVDENY;
3725 goto end;
3726 break;
3727
3728 case ACT_REPLACE:
3729 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3730 if (len < 0)
3731 return -1;
3732
3733 http_parse_header(ist2(trash.area, len), &n, &v);
3734 ctx.blk = blk;
3735 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003736 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003737 if (!http_replace_header(htx, &ctx, n, v))
3738 return -1;
3739 if (!ctx.blk)
3740 goto end;
3741 pos = htx_get_blk_pos(htx, blk);
3742 break;
3743
3744 case ACT_REMOVE:
3745 ctx.blk = blk;
3746 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003747 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003748 if (!http_remove_header(htx, &ctx))
3749 return -1;
3750 if (!ctx.blk)
3751 goto end;
3752 pos = htx_get_blk_pos(htx, blk);
3753 goto next_hdr;
3754 }
3755 }
3756
3757 }
3758 end:
3759 return 0;
3760}
3761
3762/* Apply the filter to the status line in the response buffer <res>.
3763 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3764 * or -1 if a replacement resulted in an invalid status line.
3765 */
3766static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3767{
3768 struct http_txn *txn = s->txn;
3769 struct htx *htx;
3770 struct buffer *resline = get_trash_chunk();
3771 int done;
3772
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003773 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003774
3775 if (unlikely(txn->flags & TX_SVDENY))
3776 return 1;
3777 else if (unlikely(txn->flags & TX_SVALLOW) &&
3778 (exp->action == ACT_ALLOW ||
3779 exp->action == ACT_DENY))
3780 return 0;
3781 else if (exp->action == ACT_REMOVE)
3782 return 0;
3783
3784 done = 0;
3785 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3786
3787 /* Now we have the status line between cur_ptr and cur_end */
3788 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003789 struct htx_sl *sl = http_find_stline(htx);
3790 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003791 int len;
3792
3793 switch (exp->action) {
3794 case ACT_ALLOW:
3795 txn->flags |= TX_SVALLOW;
3796 done = 1;
3797 break;
3798
3799 case ACT_DENY:
3800 txn->flags |= TX_SVDENY;
3801 done = 1;
3802 break;
3803
3804 case ACT_REPLACE:
3805 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3806 if (len < 0)
3807 return -1;
3808
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003809 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3810 sl->info.res.status = strl2ui(code.ptr, code.len);
3811 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003812 return -1;
3813
3814 done = 1;
3815 return 1;
3816 }
3817 }
3818 return done;
3819}
3820
3821/*
3822 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3823 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3824 * unparsable response.
3825 */
3826static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3827{
3828 struct session *sess = s->sess;
3829 struct http_txn *txn = s->txn;
3830 struct hdr_exp *exp;
3831
3832 for (exp = px->rsp_exp; exp; exp = exp->next) {
3833 int ret;
3834
3835 /*
3836 * The interleaving of transformations and verdicts
3837 * makes it difficult to decide to continue or stop
3838 * the evaluation.
3839 */
3840
3841 if (txn->flags & TX_SVDENY)
3842 break;
3843
3844 if ((txn->flags & TX_SVALLOW) &&
3845 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3846 exp->action == ACT_PASS)) {
3847 exp = exp->next;
3848 continue;
3849 }
3850
3851 /* if this filter had a condition, evaluate it now and skip to
3852 * next filter if the condition does not match.
3853 */
3854 if (exp->cond) {
3855 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3856 ret = acl_pass(ret);
3857 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3858 ret = !ret;
3859 if (!ret)
3860 continue;
3861 }
3862
3863 /* Apply the filter to the status line. */
3864 ret = htx_apply_filter_to_sts_line(s, res, exp);
3865 if (unlikely(ret < 0))
3866 return -1;
3867
3868 if (likely(ret == 0)) {
3869 /* The filter did not match the response, it can be
3870 * iterated through all headers.
3871 */
3872 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3873 return -1;
3874 }
3875 }
3876 return 0;
3877}
3878
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003879/*
3880 * Manage client-side cookie. It can impact performance by about 2% so it is
3881 * desirable to call it only when needed. This code is quite complex because
3882 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3883 * highly recommended not to touch this part without a good reason !
3884 */
3885static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3886{
3887 struct session *sess = s->sess;
3888 struct http_txn *txn = s->txn;
3889 struct htx *htx;
3890 struct http_hdr_ctx ctx;
3891 char *hdr_beg, *hdr_end, *del_from;
3892 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3893 int preserve_hdr;
3894
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003895 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003896 ctx.blk = NULL;
3897 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3898 del_from = NULL; /* nothing to be deleted */
3899 preserve_hdr = 0; /* assume we may kill the whole header */
3900
3901 /* Now look for cookies. Conforming to RFC2109, we have to support
3902 * attributes whose name begin with a '$', and associate them with
3903 * the right cookie, if we want to delete this cookie.
3904 * So there are 3 cases for each cookie read :
3905 * 1) it's a special attribute, beginning with a '$' : ignore it.
3906 * 2) it's a server id cookie that we *MAY* want to delete : save
3907 * some pointers on it (last semi-colon, beginning of cookie...)
3908 * 3) it's an application cookie : we *MAY* have to delete a previous
3909 * "special" cookie.
3910 * At the end of loop, if a "special" cookie remains, we may have to
3911 * remove it. If no application cookie persists in the header, we
3912 * *MUST* delete it.
3913 *
3914 * Note: RFC2965 is unclear about the processing of spaces around
3915 * the equal sign in the ATTR=VALUE form. A careful inspection of
3916 * the RFC explicitly allows spaces before it, and not within the
3917 * tokens (attrs or values). An inspection of RFC2109 allows that
3918 * too but section 10.1.3 lets one think that spaces may be allowed
3919 * after the equal sign too, resulting in some (rare) buggy
3920 * implementations trying to do that. So let's do what servers do.
3921 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3922 * allowed quoted strings in values, with any possible character
3923 * after a backslash, including control chars and delimitors, which
3924 * causes parsing to become ambiguous. Browsers also allow spaces
3925 * within values even without quotes.
3926 *
3927 * We have to keep multiple pointers in order to support cookie
3928 * removal at the beginning, middle or end of header without
3929 * corrupting the header. All of these headers are valid :
3930 *
3931 * hdr_beg hdr_end
3932 * | |
3933 * v |
3934 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3935 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3936 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3937 * | | | | | | |
3938 * | | | | | | |
3939 * | | | | | | +--> next
3940 * | | | | | +----> val_end
3941 * | | | | +-----------> val_beg
3942 * | | | +--------------> equal
3943 * | | +----------------> att_end
3944 * | +---------------------> att_beg
3945 * +--------------------------> prev
3946 *
3947 */
3948 hdr_beg = ctx.value.ptr;
3949 hdr_end = hdr_beg + ctx.value.len;
3950 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3951 /* Iterate through all cookies on this line */
3952
3953 /* find att_beg */
3954 att_beg = prev;
3955 if (prev > hdr_beg)
3956 att_beg++;
3957
3958 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3959 att_beg++;
3960
3961 /* find att_end : this is the first character after the last non
3962 * space before the equal. It may be equal to hdr_end.
3963 */
3964 equal = att_end = att_beg;
3965 while (equal < hdr_end) {
3966 if (*equal == '=' || *equal == ',' || *equal == ';')
3967 break;
3968 if (HTTP_IS_SPHT(*equal++))
3969 continue;
3970 att_end = equal;
3971 }
3972
3973 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3974 * is between <att_beg> and <equal>, both may be identical.
3975 */
3976 /* look for end of cookie if there is an equal sign */
3977 if (equal < hdr_end && *equal == '=') {
3978 /* look for the beginning of the value */
3979 val_beg = equal + 1;
3980 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3981 val_beg++;
3982
3983 /* find the end of the value, respecting quotes */
3984 next = http_find_cookie_value_end(val_beg, hdr_end);
3985
3986 /* make val_end point to the first white space or delimitor after the value */
3987 val_end = next;
3988 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3989 val_end--;
3990 }
3991 else
3992 val_beg = val_end = next = equal;
3993
3994 /* We have nothing to do with attributes beginning with
3995 * '$'. However, they will automatically be removed if a
3996 * header before them is removed, since they're supposed
3997 * to be linked together.
3998 */
3999 if (*att_beg == '$')
4000 continue;
4001
4002 /* Ignore cookies with no equal sign */
4003 if (equal == next) {
4004 /* This is not our cookie, so we must preserve it. But if we already
4005 * scheduled another cookie for removal, we cannot remove the
4006 * complete header, but we can remove the previous block itself.
4007 */
4008 preserve_hdr = 1;
4009 if (del_from != NULL) {
4010 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4011 val_end += delta;
4012 next += delta;
4013 hdr_end += delta;
4014 prev = del_from;
4015 del_from = NULL;
4016 }
4017 continue;
4018 }
4019
4020 /* if there are spaces around the equal sign, we need to
4021 * strip them otherwise we'll get trouble for cookie captures,
4022 * or even for rewrites. Since this happens extremely rarely,
4023 * it does not hurt performance.
4024 */
4025 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4026 int stripped_before = 0;
4027 int stripped_after = 0;
4028
4029 if (att_end != equal) {
4030 memmove(att_end, equal, hdr_end - equal);
4031 stripped_before = (att_end - equal);
4032 equal += stripped_before;
4033 val_beg += stripped_before;
4034 }
4035
4036 if (val_beg > equal + 1) {
4037 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4038 stripped_after = (equal + 1) - val_beg;
4039 val_beg += stripped_after;
4040 stripped_before += stripped_after;
4041 }
4042
4043 val_end += stripped_before;
4044 next += stripped_before;
4045 hdr_end += stripped_before;
4046 }
4047 /* now everything is as on the diagram above */
4048
4049 /* First, let's see if we want to capture this cookie. We check
4050 * that we don't already have a client side cookie, because we
4051 * can only capture one. Also as an optimisation, we ignore
4052 * cookies shorter than the declared name.
4053 */
4054 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4055 (val_end - att_beg >= sess->fe->capture_namelen) &&
4056 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4057 int log_len = val_end - att_beg;
4058
4059 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4060 ha_alert("HTTP logging : out of memory.\n");
4061 } else {
4062 if (log_len > sess->fe->capture_len)
4063 log_len = sess->fe->capture_len;
4064 memcpy(txn->cli_cookie, att_beg, log_len);
4065 txn->cli_cookie[log_len] = 0;
4066 }
4067 }
4068
4069 /* Persistence cookies in passive, rewrite or insert mode have the
4070 * following form :
4071 *
4072 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4073 *
4074 * For cookies in prefix mode, the form is :
4075 *
4076 * Cookie: NAME=SRV~VALUE
4077 */
4078 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4079 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4080 struct server *srv = s->be->srv;
4081 char *delim;
4082
4083 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4084 * have the server ID between val_beg and delim, and the original cookie between
4085 * delim+1 and val_end. Otherwise, delim==val_end :
4086 *
4087 * hdr_beg
4088 * |
4089 * v
4090 * NAME=SRV; # in all but prefix modes
4091 * NAME=SRV~OPAQUE ; # in prefix mode
4092 * || || | |+-> next
4093 * || || | +--> val_end
4094 * || || +---------> delim
4095 * || |+------------> val_beg
4096 * || +-------------> att_end = equal
4097 * |+-----------------> att_beg
4098 * +------------------> prev
4099 *
4100 */
4101 if (s->be->ck_opts & PR_CK_PFX) {
4102 for (delim = val_beg; delim < val_end; delim++)
4103 if (*delim == COOKIE_DELIM)
4104 break;
4105 }
4106 else {
4107 char *vbar1;
4108 delim = val_end;
4109 /* Now check if the cookie contains a date field, which would
4110 * appear after a vertical bar ('|') just after the server name
4111 * and before the delimiter.
4112 */
4113 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4114 if (vbar1) {
4115 /* OK, so left of the bar is the server's cookie and
4116 * right is the last seen date. It is a base64 encoded
4117 * 30-bit value representing the UNIX date since the
4118 * epoch in 4-second quantities.
4119 */
4120 int val;
4121 delim = vbar1++;
4122 if (val_end - vbar1 >= 5) {
4123 val = b64tos30(vbar1);
4124 if (val > 0)
4125 txn->cookie_last_date = val << 2;
4126 }
4127 /* look for a second vertical bar */
4128 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4129 if (vbar1 && (val_end - vbar1 > 5)) {
4130 val = b64tos30(vbar1 + 1);
4131 if (val > 0)
4132 txn->cookie_first_date = val << 2;
4133 }
4134 }
4135 }
4136
4137 /* if the cookie has an expiration date and the proxy wants to check
4138 * it, then we do that now. We first check if the cookie is too old,
4139 * then only if it has expired. We detect strict overflow because the
4140 * time resolution here is not great (4 seconds). Cookies with dates
4141 * in the future are ignored if their offset is beyond one day. This
4142 * allows an admin to fix timezone issues without expiring everyone
4143 * and at the same time avoids keeping unwanted side effects for too
4144 * long.
4145 */
4146 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4147 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4148 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4149 txn->flags &= ~TX_CK_MASK;
4150 txn->flags |= TX_CK_OLD;
4151 delim = val_beg; // let's pretend we have not found the cookie
4152 txn->cookie_first_date = 0;
4153 txn->cookie_last_date = 0;
4154 }
4155 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4156 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4157 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4158 txn->flags &= ~TX_CK_MASK;
4159 txn->flags |= TX_CK_EXPIRED;
4160 delim = val_beg; // let's pretend we have not found the cookie
4161 txn->cookie_first_date = 0;
4162 txn->cookie_last_date = 0;
4163 }
4164
4165 /* Here, we'll look for the first running server which supports the cookie.
4166 * This allows to share a same cookie between several servers, for example
4167 * to dedicate backup servers to specific servers only.
4168 * However, to prevent clients from sticking to cookie-less backup server
4169 * when they have incidentely learned an empty cookie, we simply ignore
4170 * empty cookies and mark them as invalid.
4171 * The same behaviour is applied when persistence must be ignored.
4172 */
4173 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4174 srv = NULL;
4175
4176 while (srv) {
4177 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4178 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4179 if ((srv->cur_state != SRV_ST_STOPPED) ||
4180 (s->be->options & PR_O_PERSIST) ||
4181 (s->flags & SF_FORCE_PRST)) {
4182 /* we found the server and we can use it */
4183 txn->flags &= ~TX_CK_MASK;
4184 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4185 s->flags |= SF_DIRECT | SF_ASSIGNED;
4186 s->target = &srv->obj_type;
4187 break;
4188 } else {
4189 /* we found a server, but it's down,
4190 * mark it as such and go on in case
4191 * another one is available.
4192 */
4193 txn->flags &= ~TX_CK_MASK;
4194 txn->flags |= TX_CK_DOWN;
4195 }
4196 }
4197 srv = srv->next;
4198 }
4199
4200 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4201 /* no server matched this cookie or we deliberately skipped it */
4202 txn->flags &= ~TX_CK_MASK;
4203 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4204 txn->flags |= TX_CK_UNUSED;
4205 else
4206 txn->flags |= TX_CK_INVALID;
4207 }
4208
4209 /* depending on the cookie mode, we may have to either :
4210 * - delete the complete cookie if we're in insert+indirect mode, so that
4211 * the server never sees it ;
4212 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004213 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004214 * if we're in cookie prefix mode
4215 */
4216 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4217 int delta; /* negative */
4218
4219 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4220 delta = val_beg - (delim + 1);
4221 val_end += delta;
4222 next += delta;
4223 hdr_end += delta;
4224 del_from = NULL;
4225 preserve_hdr = 1; /* we want to keep this cookie */
4226 }
4227 else if (del_from == NULL &&
4228 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4229 del_from = prev;
4230 }
4231 }
4232 else {
4233 /* This is not our cookie, so we must preserve it. But if we already
4234 * scheduled another cookie for removal, we cannot remove the
4235 * complete header, but we can remove the previous block itself.
4236 */
4237 preserve_hdr = 1;
4238
4239 if (del_from != NULL) {
4240 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4241 if (att_beg >= del_from)
4242 att_beg += delta;
4243 if (att_end >= del_from)
4244 att_end += delta;
4245 val_beg += delta;
4246 val_end += delta;
4247 next += delta;
4248 hdr_end += delta;
4249 prev = del_from;
4250 del_from = NULL;
4251 }
4252 }
4253
4254 /* continue with next cookie on this header line */
4255 att_beg = next;
4256 } /* for each cookie */
4257
4258
4259 /* There are no more cookies on this line.
4260 * We may still have one (or several) marked for deletion at the
4261 * end of the line. We must do this now in two ways :
4262 * - if some cookies must be preserved, we only delete from the
4263 * mark to the end of line ;
4264 * - if nothing needs to be preserved, simply delete the whole header
4265 */
4266 if (del_from) {
4267 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4268 }
4269 if ((hdr_end - hdr_beg) != ctx.value.len) {
4270 if (hdr_beg != hdr_end) {
4271 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004272 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004273 }
4274 else
4275 http_remove_header(htx, &ctx);
4276 }
4277 } /* for each "Cookie header */
4278}
4279
4280/*
4281 * Manage server-side cookies. It can impact performance by about 2% so it is
4282 * desirable to call it only when needed. This function is also used when we
4283 * just need to know if there is a cookie (eg: for check-cache).
4284 */
4285static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4286{
4287 struct session *sess = s->sess;
4288 struct http_txn *txn = s->txn;
4289 struct htx *htx;
4290 struct http_hdr_ctx ctx;
4291 struct server *srv;
4292 char *hdr_beg, *hdr_end;
4293 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4294 int is_cookie2;
4295
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004296 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004297
4298 ctx.blk = NULL;
4299 while (1) {
4300 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4301 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4302 break;
4303 is_cookie2 = 1;
4304 }
4305
4306 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4307 * <prev> points to the colon.
4308 */
4309 txn->flags |= TX_SCK_PRESENT;
4310
4311 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4312 * check-cache is enabled) and we are not interested in checking
4313 * them. Warning, the cookie capture is declared in the frontend.
4314 */
4315 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4316 break;
4317
4318 /* OK so now we know we have to process this response cookie.
4319 * The format of the Set-Cookie header is slightly different
4320 * from the format of the Cookie header in that it does not
4321 * support the comma as a cookie delimiter (thus the header
4322 * cannot be folded) because the Expires attribute described in
4323 * the original Netscape's spec may contain an unquoted date
4324 * with a comma inside. We have to live with this because
4325 * many browsers don't support Max-Age and some browsers don't
4326 * support quoted strings. However the Set-Cookie2 header is
4327 * clean.
4328 *
4329 * We have to keep multiple pointers in order to support cookie
4330 * removal at the beginning, middle or end of header without
4331 * corrupting the header (in case of set-cookie2). A special
4332 * pointer, <scav> points to the beginning of the set-cookie-av
4333 * fields after the first semi-colon. The <next> pointer points
4334 * either to the end of line (set-cookie) or next unquoted comma
4335 * (set-cookie2). All of these headers are valid :
4336 *
4337 * hdr_beg hdr_end
4338 * | |
4339 * v |
4340 * NAME1 = VALUE 1 ; Secure; Path="/" |
4341 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4342 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4343 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4344 * | | | | | | | |
4345 * | | | | | | | +-> next
4346 * | | | | | | +------------> scav
4347 * | | | | | +--------------> val_end
4348 * | | | | +--------------------> val_beg
4349 * | | | +----------------------> equal
4350 * | | +------------------------> att_end
4351 * | +----------------------------> att_beg
4352 * +------------------------------> prev
4353 * -------------------------------> hdr_beg
4354 */
4355 hdr_beg = ctx.value.ptr;
4356 hdr_end = hdr_beg + ctx.value.len;
4357 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4358
4359 /* Iterate through all cookies on this line */
4360
4361 /* find att_beg */
4362 att_beg = prev;
4363 if (prev > hdr_beg)
4364 att_beg++;
4365
4366 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4367 att_beg++;
4368
4369 /* find att_end : this is the first character after the last non
4370 * space before the equal. It may be equal to hdr_end.
4371 */
4372 equal = att_end = att_beg;
4373
4374 while (equal < hdr_end) {
4375 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4376 break;
4377 if (HTTP_IS_SPHT(*equal++))
4378 continue;
4379 att_end = equal;
4380 }
4381
4382 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4383 * is between <att_beg> and <equal>, both may be identical.
4384 */
4385
4386 /* look for end of cookie if there is an equal sign */
4387 if (equal < hdr_end && *equal == '=') {
4388 /* look for the beginning of the value */
4389 val_beg = equal + 1;
4390 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4391 val_beg++;
4392
4393 /* find the end of the value, respecting quotes */
4394 next = http_find_cookie_value_end(val_beg, hdr_end);
4395
4396 /* make val_end point to the first white space or delimitor after the value */
4397 val_end = next;
4398 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4399 val_end--;
4400 }
4401 else {
4402 /* <equal> points to next comma, semi-colon or EOL */
4403 val_beg = val_end = next = equal;
4404 }
4405
4406 if (next < hdr_end) {
4407 /* Set-Cookie2 supports multiple cookies, and <next> points to
4408 * a colon or semi-colon before the end. So skip all attr-value
4409 * pairs and look for the next comma. For Set-Cookie, since
4410 * commas are permitted in values, skip to the end.
4411 */
4412 if (is_cookie2)
4413 next = http_find_hdr_value_end(next, hdr_end);
4414 else
4415 next = hdr_end;
4416 }
4417
4418 /* Now everything is as on the diagram above */
4419
4420 /* Ignore cookies with no equal sign */
4421 if (equal == val_end)
4422 continue;
4423
4424 /* If there are spaces around the equal sign, we need to
4425 * strip them otherwise we'll get trouble for cookie captures,
4426 * or even for rewrites. Since this happens extremely rarely,
4427 * it does not hurt performance.
4428 */
4429 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4430 int stripped_before = 0;
4431 int stripped_after = 0;
4432
4433 if (att_end != equal) {
4434 memmove(att_end, equal, hdr_end - equal);
4435 stripped_before = (att_end - equal);
4436 equal += stripped_before;
4437 val_beg += stripped_before;
4438 }
4439
4440 if (val_beg > equal + 1) {
4441 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4442 stripped_after = (equal + 1) - val_beg;
4443 val_beg += stripped_after;
4444 stripped_before += stripped_after;
4445 }
4446
4447 val_end += stripped_before;
4448 next += stripped_before;
4449 hdr_end += stripped_before;
4450
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004451 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4452 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004453 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004454 }
4455
4456 /* First, let's see if we want to capture this cookie. We check
4457 * that we don't already have a server side cookie, because we
4458 * can only capture one. Also as an optimisation, we ignore
4459 * cookies shorter than the declared name.
4460 */
4461 if (sess->fe->capture_name != NULL &&
4462 txn->srv_cookie == NULL &&
4463 (val_end - att_beg >= sess->fe->capture_namelen) &&
4464 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4465 int log_len = val_end - att_beg;
4466 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4467 ha_alert("HTTP logging : out of memory.\n");
4468 }
4469 else {
4470 if (log_len > sess->fe->capture_len)
4471 log_len = sess->fe->capture_len;
4472 memcpy(txn->srv_cookie, att_beg, log_len);
4473 txn->srv_cookie[log_len] = 0;
4474 }
4475 }
4476
4477 srv = objt_server(s->target);
4478 /* now check if we need to process it for persistence */
4479 if (!(s->flags & SF_IGNORE_PRST) &&
4480 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4481 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4482 /* assume passive cookie by default */
4483 txn->flags &= ~TX_SCK_MASK;
4484 txn->flags |= TX_SCK_FOUND;
4485
4486 /* If the cookie is in insert mode on a known server, we'll delete
4487 * this occurrence because we'll insert another one later.
4488 * We'll delete it too if the "indirect" option is set and we're in
4489 * a direct access.
4490 */
4491 if (s->be->ck_opts & PR_CK_PSV) {
4492 /* The "preserve" flag was set, we don't want to touch the
4493 * server's cookie.
4494 */
4495 }
4496 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4497 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4498 /* this cookie must be deleted */
4499 if (prev == hdr_beg && next == hdr_end) {
4500 /* whole header */
4501 http_remove_header(htx, &ctx);
4502 /* note: while both invalid now, <next> and <hdr_end>
4503 * are still equal, so the for() will stop as expected.
4504 */
4505 } else {
4506 /* just remove the value */
4507 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4508 next = prev;
4509 hdr_end += delta;
4510 }
4511 txn->flags &= ~TX_SCK_MASK;
4512 txn->flags |= TX_SCK_DELETED;
4513 /* and go on with next cookie */
4514 }
4515 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4516 /* replace bytes val_beg->val_end with the cookie name associated
4517 * with this server since we know it.
4518 */
4519 int sliding, delta;
4520
4521 ctx.value = ist2(val_beg, val_end - val_beg);
4522 ctx.lws_before = ctx.lws_after = 0;
4523 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4524 delta = srv->cklen - (val_end - val_beg);
4525 sliding = (ctx.value.ptr - val_beg);
4526 hdr_beg += sliding;
4527 val_beg += sliding;
4528 next += sliding + delta;
4529 hdr_end += sliding + delta;
4530
4531 txn->flags &= ~TX_SCK_MASK;
4532 txn->flags |= TX_SCK_REPLACED;
4533 }
4534 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4535 /* insert the cookie name associated with this server
4536 * before existing cookie, and insert a delimiter between them..
4537 */
4538 int sliding, delta;
4539 ctx.value = ist2(val_beg, 0);
4540 ctx.lws_before = ctx.lws_after = 0;
4541 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4542 delta = srv->cklen + 1;
4543 sliding = (ctx.value.ptr - val_beg);
4544 hdr_beg += sliding;
4545 val_beg += sliding;
4546 next += sliding + delta;
4547 hdr_end += sliding + delta;
4548
4549 val_beg[srv->cklen] = COOKIE_DELIM;
4550 txn->flags &= ~TX_SCK_MASK;
4551 txn->flags |= TX_SCK_REPLACED;
4552 }
4553 }
4554 /* that's done for this cookie, check the next one on the same
4555 * line when next != hdr_end (only if is_cookie2).
4556 */
4557 }
4558 }
4559}
4560
Christopher Faulet25a02f62018-10-24 12:00:25 +02004561/*
4562 * Parses the Cache-Control and Pragma request header fields to determine if
4563 * the request may be served from the cache and/or if it is cacheable. Updates
4564 * s->txn->flags.
4565 */
4566void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4567{
4568 struct http_txn *txn = s->txn;
4569 struct htx *htx;
4570 int32_t pos;
4571 int pragma_found, cc_found, i;
4572
4573 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4574 return; /* nothing more to do here */
4575
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004576 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004577 pragma_found = cc_found = 0;
4578 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4579 struct htx_blk *blk = htx_get_blk(htx, pos);
4580 enum htx_blk_type type = htx_get_blk_type(blk);
4581 struct ist n, v;
4582
4583 if (type == HTX_BLK_EOH)
4584 break;
4585 if (type != HTX_BLK_HDR)
4586 continue;
4587
4588 n = htx_get_blk_name(htx, blk);
4589 v = htx_get_blk_value(htx, blk);
4590
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004591 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004592 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4593 pragma_found = 1;
4594 continue;
4595 }
4596 }
4597
4598 /* Don't use the cache and don't try to store if we found the
4599 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004600 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004601 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4602 txn->flags |= TX_CACHE_IGNORE;
4603 continue;
4604 }
4605
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004606 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004607 continue;
4608
4609 /* OK, right now we know we have a cache-control header */
4610 cc_found = 1;
4611 if (!v.len) /* no info */
4612 continue;
4613
4614 i = 0;
4615 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4616 !isspace((unsigned char)*(v.ptr+i)))
4617 i++;
4618
4619 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4620 * values after max-age, max-stale nor min-fresh, we simply don't
4621 * use the cache when they're specified.
4622 */
4623 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4624 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4625 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4626 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4627 txn->flags |= TX_CACHE_IGNORE;
4628 continue;
4629 }
4630
4631 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4632 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4633 continue;
4634 }
4635 }
4636
4637 /* RFC7234#5.4:
4638 * When the Cache-Control header field is also present and
4639 * understood in a request, Pragma is ignored.
4640 * When the Cache-Control header field is not present in a
4641 * request, caches MUST consider the no-cache request
4642 * pragma-directive as having the same effect as if
4643 * "Cache-Control: no-cache" were present.
4644 */
4645 if (!cc_found && pragma_found)
4646 txn->flags |= TX_CACHE_IGNORE;
4647}
4648
4649/*
4650 * Check if response is cacheable or not. Updates s->txn->flags.
4651 */
4652void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4653{
4654 struct http_txn *txn = s->txn;
4655 struct htx *htx;
4656 int32_t pos;
4657 int i;
4658
4659 if (txn->status < 200) {
4660 /* do not try to cache interim responses! */
4661 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4662 return;
4663 }
4664
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004665 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004666 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4667 struct htx_blk *blk = htx_get_blk(htx, pos);
4668 enum htx_blk_type type = htx_get_blk_type(blk);
4669 struct ist n, v;
4670
4671 if (type == HTX_BLK_EOH)
4672 break;
4673 if (type != HTX_BLK_HDR)
4674 continue;
4675
4676 n = htx_get_blk_name(htx, blk);
4677 v = htx_get_blk_value(htx, blk);
4678
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004679 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004680 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4681 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4682 return;
4683 }
4684 }
4685
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004686 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004687 continue;
4688
4689 /* OK, right now we know we have a cache-control header */
4690 if (!v.len) /* no info */
4691 continue;
4692
4693 i = 0;
4694 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4695 !isspace((unsigned char)*(v.ptr+i)))
4696 i++;
4697
4698 /* we have a complete value between v.ptr and (v.ptr+i) */
4699 if (i < v.len && *(v.ptr + i) == '=') {
4700 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4701 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4702 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4703 continue;
4704 }
4705
4706 /* we have something of the form no-cache="set-cookie" */
4707 if ((v.len >= 21) &&
4708 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4709 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4710 txn->flags &= ~TX_CACHE_COOK;
4711 continue;
4712 }
4713
4714 /* OK, so we know that either p2 points to the end of string or to a comma */
4715 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4716 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4717 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4718 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4719 return;
4720 }
4721
4722 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4723 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4724 continue;
4725 }
4726 }
4727}
4728
Christopher Faulet64159df2018-10-24 21:15:35 +02004729/* send a server's name with an outgoing request over an established connection.
4730 * Note: this function is designed to be called once the request has been
4731 * scheduled for being forwarded. This is the reason why the number of forwarded
4732 * bytes have to be adjusted.
4733 */
4734int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4735{
4736 struct htx *htx;
4737 struct http_hdr_ctx ctx;
4738 struct ist hdr;
4739 uint32_t data;
4740
4741 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004742 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004743 data = htx->data;
4744
4745 ctx.blk = NULL;
4746 while (http_find_header(htx, hdr, &ctx, 1))
4747 http_remove_header(htx, &ctx);
4748 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4749
4750 if (co_data(&s->req)) {
4751 if (data >= htx->data)
4752 c_rew(&s->req, data - htx->data);
4753 else
4754 c_adv(&s->req, htx->data - data);
4755 }
4756 return 0;
4757}
4758
Christopher Faulet377c5a52018-10-24 21:21:30 +02004759/*
4760 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4761 * for the current backend.
4762 *
4763 * It is assumed that the request is either a HEAD, GET, or POST and that the
4764 * uri_auth field is valid.
4765 *
4766 * Returns 1 if stats should be provided, otherwise 0.
4767 */
4768static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4769{
4770 struct uri_auth *uri_auth = backend->uri_auth;
4771 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004772 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004773 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004774
4775 if (!uri_auth)
4776 return 0;
4777
4778 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4779 return 0;
4780
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004781 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004782 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004783 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004784
4785 /* check URI size */
4786 if (uri_auth->uri_len > uri.len)
4787 return 0;
4788
4789 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4790 return 0;
4791
4792 return 1;
4793}
4794
4795/* This function prepares an applet to handle the stats. It can deal with the
4796 * "100-continue" expectation, check that admin rules are met for POST requests,
4797 * and program a response message if something was unexpected. It cannot fail
4798 * and always relies on the stats applet to complete the job. It does not touch
4799 * analysers nor counters, which are left to the caller. It does not touch
4800 * s->target which is supposed to already point to the stats applet. The caller
4801 * is expected to have already assigned an appctx to the stream.
4802 */
4803static int htx_handle_stats(struct stream *s, struct channel *req)
4804{
4805 struct stats_admin_rule *stats_admin_rule;
4806 struct stream_interface *si = &s->si[1];
4807 struct session *sess = s->sess;
4808 struct http_txn *txn = s->txn;
4809 struct http_msg *msg = &txn->req;
4810 struct uri_auth *uri_auth = s->be->uri_auth;
4811 const char *h, *lookup, *end;
4812 struct appctx *appctx;
4813 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004814 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004815
4816 appctx = si_appctx(si);
4817 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4818 appctx->st1 = appctx->st2 = 0;
4819 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4820 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4821 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4822 appctx->ctx.stats.flags |= STAT_CHUNKED;
4823
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004824 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004825 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004826 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4827 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004828
4829 for (h = lookup; h <= end - 3; h++) {
4830 if (memcmp(h, ";up", 3) == 0) {
4831 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4832 break;
4833 }
4834 }
4835
4836 if (uri_auth->refresh) {
4837 for (h = lookup; h <= end - 10; h++) {
4838 if (memcmp(h, ";norefresh", 10) == 0) {
4839 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4840 break;
4841 }
4842 }
4843 }
4844
4845 for (h = lookup; h <= end - 4; h++) {
4846 if (memcmp(h, ";csv", 4) == 0) {
4847 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4848 break;
4849 }
4850 }
4851
4852 for (h = lookup; h <= end - 6; h++) {
4853 if (memcmp(h, ";typed", 6) == 0) {
4854 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4855 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4856 break;
4857 }
4858 }
4859
4860 for (h = lookup; h <= end - 8; h++) {
4861 if (memcmp(h, ";st=", 4) == 0) {
4862 int i;
4863 h += 4;
4864 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4865 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4866 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4867 appctx->ctx.stats.st_code = i;
4868 break;
4869 }
4870 }
4871 break;
4872 }
4873 }
4874
4875 appctx->ctx.stats.scope_str = 0;
4876 appctx->ctx.stats.scope_len = 0;
4877 for (h = lookup; h <= end - 8; h++) {
4878 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4879 int itx = 0;
4880 const char *h2;
4881 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4882 const char *err;
4883
4884 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4885 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004886 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4887 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004888 if (*h == ';' || *h == '&' || *h == ' ')
4889 break;
4890 itx++;
4891 h++;
4892 }
4893
4894 if (itx > STAT_SCOPE_TXT_MAXLEN)
4895 itx = STAT_SCOPE_TXT_MAXLEN;
4896 appctx->ctx.stats.scope_len = itx;
4897
4898 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4899 memcpy(scope_txt, h2, itx);
4900 scope_txt[itx] = '\0';
4901 err = invalid_char(scope_txt);
4902 if (err) {
4903 /* bad char in search text => clear scope */
4904 appctx->ctx.stats.scope_str = 0;
4905 appctx->ctx.stats.scope_len = 0;
4906 }
4907 break;
4908 }
4909 }
4910
4911 /* now check whether we have some admin rules for this request */
4912 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4913 int ret = 1;
4914
4915 if (stats_admin_rule->cond) {
4916 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4917 ret = acl_pass(ret);
4918 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4919 ret = !ret;
4920 }
4921
4922 if (ret) {
4923 /* no rule, or the rule matches */
4924 appctx->ctx.stats.flags |= STAT_ADMIN;
4925 break;
4926 }
4927 }
4928
Christopher Faulet5d45e382019-02-27 15:15:23 +01004929 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4930 appctx->st0 = STAT_HTTP_HEAD;
4931 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004932 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4933 /* we'll need the request body, possibly after sending 100-continue */
4934 if (msg->msg_state < HTTP_MSG_DATA)
4935 req->analysers |= AN_REQ_HTTP_BODY;
4936 appctx->st0 = STAT_HTTP_POST;
4937 }
4938 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004939 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004940 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4941 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4942 appctx->st0 = STAT_HTTP_LAST;
4943 }
4944 }
4945 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004946 /* Unsupported method */
4947 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4948 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4949 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004950 }
4951
4952 s->task->nice = -32; /* small boost for HTTP statistics */
4953 return 1;
4954}
4955
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004956void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4957{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004958 struct channel *req = &s->req;
4959 struct channel *res = &s->res;
4960 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004961 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004962 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004963 struct ist path, location;
4964 unsigned int flags;
4965 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004966
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004967 /*
4968 * Create the location
4969 */
4970 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004971
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004972 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004973 /* special prefix "/" means don't change URL */
4974 srv = __objt_server(s->target);
4975 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4976 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4977 return;
4978 }
4979
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004980 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004981 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004982 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004983 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004984 if (!path.ptr)
4985 return;
4986
4987 if (!chunk_memcat(&trash, path.ptr, path.len))
4988 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004989 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004991 /*
4992 * Create the 302 respone
4993 */
4994 htx = htx_from_buf(&res->buf);
4995 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4996 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4997 ist("HTTP/1.1"), ist("302"), ist("Found"));
4998 if (!sl)
4999 goto fail;
5000 sl->info.res.status = 302;
5001 s->txn->status = 302;
5002
5003 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5004 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5005 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5006 !htx_add_header(htx, ist("Location"), location))
5007 goto fail;
5008
5009 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5010 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /*
5013 * Send the message
5014 */
5015 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005016 c_adv(res, data);
5017 res->total += data;
5018
5019 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005020 si_shutr(si);
5021 si_shutw(si);
5022 si->err_type = SI_ET_NONE;
5023 si->state = SI_ST_CLO;
5024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 channel_auto_read(req);
5026 channel_abort(req);
5027 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005028 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 channel_auto_read(res);
5030 channel_auto_close(res);
5031
5032 if (!(s->flags & SF_ERR_MASK))
5033 s->flags |= SF_ERR_LOCAL;
5034 if (!(s->flags & SF_FINST_MASK))
5035 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005036
5037 /* FIXME: we should increase a counter of redirects per server and per backend. */
5038 srv_inc_sess_ctr(srv);
5039 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005040 return;
5041
5042 fail:
5043 /* If an error occurred, remove the incomplete HTTP response from the
5044 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005045 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005046}
5047
Christopher Fauletf2824e62018-10-01 12:12:37 +02005048/* This function terminates the request because it was completly analyzed or
5049 * because an error was triggered during the body forwarding.
5050 */
5051static void htx_end_request(struct stream *s)
5052{
5053 struct channel *chn = &s->req;
5054 struct http_txn *txn = s->txn;
5055
5056 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5057 now_ms, __FUNCTION__, s,
5058 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5059 s->req.analysers, s->res.analysers);
5060
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005061 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5062 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005063 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005064 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005065 goto end;
5066 }
5067
5068 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5069 return;
5070
5071 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005072 /* No need to read anymore, the request was completely parsed.
5073 * We can shut the read side unless we want to abort_on_close,
5074 * or we have a POST request. The issue with POST requests is
5075 * that some browsers still send a CRLF after the request, and
5076 * this CRLF must be read so that it does not remain in the kernel
5077 * buffers, otherwise a close could cause an RST on some systems
5078 * (eg: Linux).
5079 */
5080 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5081 txn->meth != HTTP_METH_POST)
5082 channel_dont_read(chn);
5083
5084 /* if the server closes the connection, we want to immediately react
5085 * and close the socket to save packets and syscalls.
5086 */
5087 s->si[1].flags |= SI_FL_NOHALF;
5088
5089 /* In any case we've finished parsing the request so we must
5090 * disable Nagle when sending data because 1) we're not going
5091 * to shut this side, and 2) the server is waiting for us to
5092 * send pending data.
5093 */
5094 chn->flags |= CF_NEVER_WAIT;
5095
Christopher Fauletd01ce402019-01-02 17:44:13 +01005096 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5097 /* The server has not finished to respond, so we
5098 * don't want to move in order not to upset it.
5099 */
5100 return;
5101 }
5102
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 /* When we get here, it means that both the request and the
5104 * response have finished receiving. Depending on the connection
5105 * mode, we'll have to wait for the last bytes to leave in either
5106 * direction, and sometimes for a close to be effective.
5107 */
5108 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5109 /* Tunnel mode will not have any analyser so it needs to
5110 * poll for reads.
5111 */
5112 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005113 if (b_data(&chn->buf))
5114 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 txn->req.msg_state = HTTP_MSG_TUNNEL;
5116 }
5117 else {
5118 /* we're not expecting any new data to come for this
5119 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005120 *
5121 * However, there is an exception if the response
5122 * length is undefined. In this case, we need to wait
5123 * the close from the server. The response will be
5124 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005125 */
5126 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5127 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005128 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005129
5130 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5131 channel_shutr_now(chn);
5132 channel_shutw_now(chn);
5133 }
5134 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005135 goto check_channel_flags;
5136 }
5137
5138 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5139 http_msg_closing:
5140 /* nothing else to forward, just waiting for the output buffer
5141 * to be empty and for the shutw_now to take effect.
5142 */
5143 if (channel_is_empty(chn)) {
5144 txn->req.msg_state = HTTP_MSG_CLOSED;
5145 goto http_msg_closed;
5146 }
5147 else if (chn->flags & CF_SHUTW) {
5148 txn->req.err_state = txn->req.msg_state;
5149 txn->req.msg_state = HTTP_MSG_ERROR;
5150 goto end;
5151 }
5152 return;
5153 }
5154
5155 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5156 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005157 /* if we don't know whether the server will close, we need to hard close */
5158 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5159 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 /* see above in MSG_DONE why we only do this in these states */
5161 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5162 channel_dont_read(chn);
5163 goto end;
5164 }
5165
5166 check_channel_flags:
5167 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5168 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5169 /* if we've just closed an output, let's switch */
5170 txn->req.msg_state = HTTP_MSG_CLOSING;
5171 goto http_msg_closing;
5172 }
5173
5174 end:
5175 chn->analysers &= AN_REQ_FLT_END;
5176 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5177 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5178 channel_auto_close(chn);
5179 channel_auto_read(chn);
5180}
5181
5182
5183/* This function terminates the response because it was completly analyzed or
5184 * because an error was triggered during the body forwarding.
5185 */
5186static void htx_end_response(struct stream *s)
5187{
5188 struct channel *chn = &s->res;
5189 struct http_txn *txn = s->txn;
5190
5191 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5192 now_ms, __FUNCTION__, s,
5193 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5194 s->req.analysers, s->res.analysers);
5195
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005196 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5197 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005198 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005199 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005200 goto end;
5201 }
5202
5203 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5204 return;
5205
5206 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5207 /* In theory, we don't need to read anymore, but we must
5208 * still monitor the server connection for a possible close
5209 * while the request is being uploaded, so we don't disable
5210 * reading.
5211 */
5212 /* channel_dont_read(chn); */
5213
5214 if (txn->req.msg_state < HTTP_MSG_DONE) {
5215 /* The client seems to still be sending data, probably
5216 * because we got an error response during an upload.
5217 * We have the choice of either breaking the connection
5218 * or letting it pass through. Let's do the later.
5219 */
5220 return;
5221 }
5222
5223 /* When we get here, it means that both the request and the
5224 * response have finished receiving. Depending on the connection
5225 * mode, we'll have to wait for the last bytes to leave in either
5226 * direction, and sometimes for a close to be effective.
5227 */
5228 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5229 channel_auto_read(chn);
5230 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005231 if (b_data(&chn->buf))
5232 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5234 }
5235 else {
5236 /* we're not expecting any new data to come for this
5237 * transaction, so we can close it.
5238 */
5239 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5240 channel_shutr_now(chn);
5241 channel_shutw_now(chn);
5242 }
5243 }
5244 goto check_channel_flags;
5245 }
5246
5247 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5248 http_msg_closing:
5249 /* nothing else to forward, just waiting for the output buffer
5250 * to be empty and for the shutw_now to take effect.
5251 */
5252 if (channel_is_empty(chn)) {
5253 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5254 goto http_msg_closed;
5255 }
5256 else if (chn->flags & CF_SHUTW) {
5257 txn->rsp.err_state = txn->rsp.msg_state;
5258 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005259 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005260 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005261 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005262 goto end;
5263 }
5264 return;
5265 }
5266
5267 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5268 http_msg_closed:
5269 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005270 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005271 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005272 goto end;
5273 }
5274
5275 check_channel_flags:
5276 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5277 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5278 /* if we've just closed an output, let's switch */
5279 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5280 goto http_msg_closing;
5281 }
5282
5283 end:
5284 chn->analysers &= AN_RES_FLT_END;
5285 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5286 chn->analysers |= AN_RES_FLT_XFER_DATA;
5287 channel_auto_close(chn);
5288 channel_auto_read(chn);
5289}
5290
Christopher Faulet0f226952018-10-22 09:29:56 +02005291void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5292 int finst, const struct buffer *msg)
5293{
5294 channel_auto_read(si_oc(si));
5295 channel_abort(si_oc(si));
5296 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005297 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005298 channel_auto_close(si_ic(si));
5299 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005300
5301 /* <msg> is an HTX structure. So we copy it in the response's
5302 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005303 if (msg) {
5304 struct channel *chn = si_ic(si);
5305 struct htx *htx;
5306
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005307 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005308 chn->buf.data = msg->data;
5309 memcpy(chn->buf.area, msg->area, msg->data);
5310 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005311 c_adv(chn, htx->data);
5312 chn->total += htx->data;
5313 }
5314 if (!(s->flags & SF_ERR_MASK))
5315 s->flags |= err;
5316 if (!(s->flags & SF_FINST_MASK))
5317 s->flags |= finst;
5318}
5319
5320void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5321{
5322 channel_auto_read(&s->req);
5323 channel_abort(&s->req);
5324 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005325 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5326 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005327
5328 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005329
5330 /* <msg> is an HTX structure. So we copy it in the response's
5331 * channel */
5332 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005333 if (msg) {
5334 struct channel *chn = &s->res;
5335 struct htx *htx;
5336
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005337 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005338 chn->buf.data = msg->data;
5339 memcpy(chn->buf.area, msg->area, msg->data);
5340 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005341 c_adv(chn, htx->data);
5342 chn->total += htx->data;
5343 }
5344
5345 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5346 channel_auto_read(&s->res);
5347 channel_auto_close(&s->res);
5348 channel_shutr_now(&s->res);
5349}
5350
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005351struct buffer *htx_error_message(struct stream *s)
5352{
5353 const int msgnum = http_get_status_idx(s->txn->status);
5354
5355 if (s->be->errmsg[msgnum].area)
5356 return &s->be->errmsg[msgnum];
5357 else if (strm_fe(s)->errmsg[msgnum].area)
5358 return &strm_fe(s)->errmsg[msgnum];
5359 else
5360 return &htx_err_chunks[msgnum];
5361}
5362
5363
Christopher Faulet23a3c792018-11-28 10:01:23 +01005364/* Send a 100-Continue response to the client. It returns 0 on success and -1
5365 * on error. The response channel is updated accordingly.
5366 */
5367static int htx_reply_100_continue(struct stream *s)
5368{
5369 struct channel *res = &s->res;
5370 struct htx *htx = htx_from_buf(&res->buf);
5371 struct htx_sl *sl;
5372 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5373 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5374 size_t data;
5375
5376 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5377 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5378 if (!sl)
5379 goto fail;
5380 sl->info.res.status = 100;
5381
5382 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5383 goto fail;
5384
5385 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005386 c_adv(res, data);
5387 res->total += data;
5388 return 0;
5389
5390 fail:
5391 /* If an error occurred, remove the incomplete HTTP response from the
5392 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005393 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005394 return -1;
5395}
5396
Christopher Faulet12c51e22018-11-28 15:59:42 +01005397
5398/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5399 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5400 * error. The response channel is updated accordingly.
5401 */
5402static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5403{
5404 struct channel *res = &s->res;
5405 struct htx *htx = htx_from_buf(&res->buf);
5406 struct htx_sl *sl;
5407 struct ist code, body;
5408 int status;
5409 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5410 size_t data;
5411
5412 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5413 status = 401;
5414 code = ist("401");
5415 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5416 "You need a valid user and password to access this content.\n"
5417 "</body></html>\n");
5418 }
5419 else {
5420 status = 407;
5421 code = ist("407");
5422 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5423 "You need a valid user and password to access this content.\n"
5424 "</body></html>\n");
5425 }
5426
5427 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5428 ist("HTTP/1.1"), code, ist("Unauthorized"));
5429 if (!sl)
5430 goto fail;
5431 sl->info.res.status = status;
5432 s->txn->status = status;
5433
5434 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5435 goto fail;
5436
5437 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5438 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005439 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5440 goto fail;
5441 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5442 goto fail;
5443 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005444 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005445 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5446 goto fail;
5447
5448 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005449 c_adv(res, data);
5450 res->total += data;
5451
5452 channel_auto_read(&s->req);
5453 channel_abort(&s->req);
5454 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005455 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456
5457 res->wex = tick_add_ifset(now_ms, res->wto);
5458 channel_auto_read(res);
5459 channel_auto_close(res);
5460 channel_shutr_now(res);
5461 return 0;
5462
5463 fail:
5464 /* If an error occurred, remove the incomplete HTTP response from the
5465 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005466 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005467 return -1;
5468}
5469
Christopher Faulet0f226952018-10-22 09:29:56 +02005470/*
5471 * Capture headers from message <htx> according to header list <cap_hdr>, and
5472 * fill the <cap> pointers appropriately.
5473 */
5474static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5475{
5476 struct cap_hdr *h;
5477 int32_t pos;
5478
5479 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5480 struct htx_blk *blk = htx_get_blk(htx, pos);
5481 enum htx_blk_type type = htx_get_blk_type(blk);
5482 struct ist n, v;
5483
5484 if (type == HTX_BLK_EOH)
5485 break;
5486 if (type != HTX_BLK_HDR)
5487 continue;
5488
5489 n = htx_get_blk_name(htx, blk);
5490
5491 for (h = cap_hdr; h; h = h->next) {
5492 if (h->namelen && (h->namelen == n.len) &&
5493 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5494 if (cap[h->index] == NULL)
5495 cap[h->index] =
5496 pool_alloc(h->pool);
5497
5498 if (cap[h->index] == NULL) {
5499 ha_alert("HTTP capture : out of memory.\n");
5500 break;
5501 }
5502
5503 v = htx_get_blk_value(htx, blk);
5504 if (v.len > h->len)
5505 v.len = h->len;
5506
5507 memcpy(cap[h->index], v.ptr, v.len);
5508 cap[h->index][v.len]=0;
5509 }
5510 }
5511 }
5512}
5513
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005514/* Delete a value in a header between delimiters <from> and <next>. The header
5515 * itself is delimited by <start> and <end> pointers. The number of characters
5516 * displaced is returned, and the pointer to the first delimiter is updated if
5517 * required. The function tries as much as possible to respect the following
5518 * principles :
5519 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5520 * in which case <next> is simply removed
5521 * - set exactly one space character after the new first delimiter, unless there
5522 * are not enough characters in the block being moved to do so.
5523 * - remove unneeded spaces before the previous delimiter and after the new
5524 * one.
5525 *
5526 * It is the caller's responsibility to ensure that :
5527 * - <from> points to a valid delimiter or <start> ;
5528 * - <next> points to a valid delimiter or <end> ;
5529 * - there are non-space chars before <from>.
5530 */
5531static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5532{
5533 char *prev = *from;
5534
5535 if (prev == start) {
5536 /* We're removing the first value. eat the semicolon, if <next>
5537 * is lower than <end> */
5538 if (next < end)
5539 next++;
5540
5541 while (next < end && HTTP_IS_SPHT(*next))
5542 next++;
5543 }
5544 else {
5545 /* Remove useless spaces before the old delimiter. */
5546 while (HTTP_IS_SPHT(*(prev-1)))
5547 prev--;
5548 *from = prev;
5549
5550 /* copy the delimiter and if possible a space if we're
5551 * not at the end of the line.
5552 */
5553 if (next < end) {
5554 *prev++ = *next++;
5555 if (prev + 1 < next)
5556 *prev++ = ' ';
5557 while (next < end && HTTP_IS_SPHT(*next))
5558 next++;
5559 }
5560 }
5561 memmove(prev, next, end - next);
5562 return (prev - next);
5563}
5564
Christopher Faulet0f226952018-10-22 09:29:56 +02005565
5566/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005567 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005568 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005569static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005570{
5571 struct ist dst = ist2(str, 0);
5572
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005573 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005574 goto end;
5575 if (dst.len + 1 > len)
5576 goto end;
5577 dst.ptr[dst.len++] = ' ';
5578
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005579 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005580 goto end;
5581 if (dst.len + 1 > len)
5582 goto end;
5583 dst.ptr[dst.len++] = ' ';
5584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005586 end:
5587 return dst.len;
5588}
5589
Christopher Fauletf0523542018-10-24 11:06:58 +02005590/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005591 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005592 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005593static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005594{
5595 struct ist dst = ist2(str, 0);
5596
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005597 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005598 goto end;
5599 if (dst.len + 1 > len)
5600 goto end;
5601 dst.ptr[dst.len++] = ' ';
5602
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005603 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005604 goto end;
5605 if (dst.len + 1 > len)
5606 goto end;
5607 dst.ptr[dst.len++] = ' ';
5608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005609 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005610 end:
5611 return dst.len;
5612}
5613
5614
Christopher Faulet0f226952018-10-22 09:29:56 +02005615/*
5616 * Print a debug line with a start line.
5617 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005618static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005619{
5620 struct session *sess = strm_sess(s);
5621 int max;
5622
5623 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5624 dir,
5625 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5626 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5627
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005628 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005629 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005631 trash.area[trash.data++] = ' ';
5632
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005634 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005635 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005636 trash.area[trash.data++] = ' ';
5637
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 trash.area[trash.data++] = '\n';
5642
5643 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5644}
5645
5646/*
5647 * Print a debug line with a header.
5648 */
5649static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5650{
5651 struct session *sess = strm_sess(s);
5652 int max;
5653
5654 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5655 dir,
5656 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5657 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5658
5659 max = n.len;
5660 UBOUND(max, trash.size - trash.data - 3);
5661 chunk_memcat(&trash, n.ptr, max);
5662 trash.area[trash.data++] = ':';
5663 trash.area[trash.data++] = ' ';
5664
5665 max = v.len;
5666 UBOUND(max, trash.size - trash.data - 1);
5667 chunk_memcat(&trash, v.ptr, max);
5668 trash.area[trash.data++] = '\n';
5669
5670 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5671}
5672
5673
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005674__attribute__((constructor))
5675static void __htx_protocol_init(void)
5676{
5677}
5678
5679
5680/*
5681 * Local variables:
5682 * c-indent-level: 8
5683 * c-basic-offset: 8
5684 * End:
5685 */