blob: 22ad491fe71b365c61c027b34acbea6d743f5f96 [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 Faulet4a28a532019-03-01 11:19:40 +010063static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010064static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010065static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010066
Christopher Faulete0768eb2018-10-03 16:38:02 +020067/* This stream analyser waits for a complete HTTP request. It returns 1 if the
68 * processing can continue on next analysers, or zero if it either needs more
69 * data or wants to immediately abort the request (eg: timeout, error, ...). It
70 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
71 * when it has nothing left to do, and may remove any analyser when it wants to
72 * abort.
73 */
74int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
75{
Christopher Faulet9768c262018-10-22 09:34:31 +020076
Christopher Faulete0768eb2018-10-03 16:38:02 +020077 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020078 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020079 *
Christopher Faulet9768c262018-10-22 09:34:31 +020080 * Once the start line and all headers are received, we may perform a
81 * capture of the error (if any), and we will set a few fields. We also
82 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020084 struct session *sess = s->sess;
85 struct http_txn *txn = s->txn;
86 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020087 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010088 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020089
90 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
91 now_ms, __FUNCTION__,
92 s,
93 req,
94 req->rex, req->wex,
95 req->flags,
96 ci_data(req),
97 req->analysers);
98
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010099 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +0200100
Willy Tarreau4236f032019-03-05 10:43:32 +0100101 /* Parsing errors are caught here */
102 if (htx->flags & HTX_FL_PARSING_ERROR) {
103 stream_inc_http_req_ctr(s);
104 stream_inc_http_err_ctr(s);
105 proxy_inc_fe_req_ctr(sess->fe);
106 goto return_bad_req;
107 }
108
Christopher Faulete0768eb2018-10-03 16:38:02 +0200109 /* we're speaking HTTP here, so let's speak HTTP to the client */
110 s->srv_error = http_return_srv_error;
111
112 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100113 if (c_data(req) && s->logs.t_idle == -1) {
114 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
115
116 s->logs.t_idle = ((csinfo)
117 ? csinfo->t_idle
118 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
119 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120
Christopher Faulete0768eb2018-10-03 16:38:02 +0200121 /*
122 * Now we quickly check if we have found a full valid request.
123 * If not so, we check the FD and buffer states before leaving.
124 * A full request is indicated by the fact that we have seen
125 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
126 * requests are checked first. When waiting for a second request
127 * on a keep-alive stream, if we encounter and error, close, t/o,
128 * we note the error in the stream flags but don't set any state.
129 * Since the error will be noted there, it will not be counted by
130 * process_stream() as a frontend error.
131 * Last, we may increase some tracked counters' http request errors on
132 * the cases that are deliberately the client's fault. For instance,
133 * a timeout or connection reset is not counted as an error. However
134 * a bad request is.
135 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200136 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100137 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100138 * First catch invalid request because only part of headers have
139 * been transfered. Multiplexers have the responsibility to emit
140 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100141 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100142 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100143 stream_inc_http_req_ctr(s);
144 stream_inc_http_err_ctr(s);
145 proxy_inc_fe_req_ctr(sess->fe);
146 goto return_bad_req;
147 }
148
Christopher Faulet9768c262018-10-22 09:34:31 +0200149 /* 1: have we encountered a read error ? */
150 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 if (!(s->flags & SF_ERR_MASK))
152 s->flags |= SF_ERR_CLICL;
153
154 if (txn->flags & TX_WAIT_NEXT_RQ)
155 goto failed_keep_alive;
156
157 if (sess->fe->options & PR_O_IGNORE_PRB)
158 goto failed_keep_alive;
159
Christopher Faulet9768c262018-10-22 09:34:31 +0200160 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200161 stream_inc_http_req_ctr(s);
162 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100163 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200164 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100165 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200166
Christopher Faulet9768c262018-10-22 09:34:31 +0200167 txn->status = 400;
168 msg->err_state = msg->msg_state;
169 msg->msg_state = HTTP_MSG_ERROR;
170 htx_reply_and_close(s, txn->status, NULL);
171 req->analysers &= AN_REQ_FLT_END;
172
Christopher Faulete0768eb2018-10-03 16:38:02 +0200173 if (!(s->flags & SF_FINST_MASK))
174 s->flags |= SF_FINST_R;
175 return 0;
176 }
177
Christopher Faulet9768c262018-10-22 09:34:31 +0200178 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200179 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
180 if (!(s->flags & SF_ERR_MASK))
181 s->flags |= SF_ERR_CLITO;
182
183 if (txn->flags & TX_WAIT_NEXT_RQ)
184 goto failed_keep_alive;
185
186 if (sess->fe->options & PR_O_IGNORE_PRB)
187 goto failed_keep_alive;
188
Christopher Faulet9768c262018-10-22 09:34:31 +0200189 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200190 stream_inc_http_req_ctr(s);
191 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100192 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200193 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100194 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200195
Christopher Faulet9768c262018-10-22 09:34:31 +0200196 txn->status = 408;
197 msg->err_state = msg->msg_state;
198 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100199 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200200 req->analysers &= AN_REQ_FLT_END;
201
Christopher Faulete0768eb2018-10-03 16:38:02 +0200202 if (!(s->flags & SF_FINST_MASK))
203 s->flags |= SF_FINST_R;
204 return 0;
205 }
206
Christopher Faulet9768c262018-10-22 09:34:31 +0200207 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 else if (req->flags & CF_SHUTR) {
209 if (!(s->flags & SF_ERR_MASK))
210 s->flags |= SF_ERR_CLICL;
211
212 if (txn->flags & TX_WAIT_NEXT_RQ)
213 goto failed_keep_alive;
214
215 if (sess->fe->options & PR_O_IGNORE_PRB)
216 goto failed_keep_alive;
217
Christopher Faulete0768eb2018-10-03 16:38:02 +0200218 stream_inc_http_err_ctr(s);
219 stream_inc_http_req_ctr(s);
220 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100221 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200222 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100223 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200224
Christopher Faulet9768c262018-10-22 09:34:31 +0200225 txn->status = 400;
226 msg->err_state = msg->msg_state;
227 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100228 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200229 req->analysers &= AN_REQ_FLT_END;
230
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 if (!(s->flags & SF_FINST_MASK))
232 s->flags |= SF_FINST_R;
233 return 0;
234 }
235
236 channel_dont_connect(req);
237 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
238 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100239
Christopher Faulet9768c262018-10-22 09:34:31 +0200240 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200241 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
242 /* We need more data, we have to re-enable quick-ack in case we
243 * previously disabled it, otherwise we might cause the client
244 * to delay next data.
245 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100246 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200247 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100248
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 /* If the client starts to talk, let's fall back to
251 * request timeout processing.
252 */
253 txn->flags &= ~TX_WAIT_NEXT_RQ;
254 req->analyse_exp = TICK_ETERNITY;
255 }
256
257 /* just set the request timeout once at the beginning of the request */
258 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100259 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200260 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
261 else
262 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
263 }
264
265 /* we're not ready yet */
266 return 0;
267
268 failed_keep_alive:
269 /* Here we process low-level errors for keep-alive requests. In
270 * short, if the request is not the first one and it experiences
271 * a timeout, read error or shutdown, we just silently close so
272 * that the client can try again.
273 */
274 txn->status = 0;
275 msg->msg_state = HTTP_MSG_RQBEFORE;
276 req->analysers &= AN_REQ_FLT_END;
277 s->logs.logwait = 0;
278 s->logs.level = 0;
279 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200280 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281 return 0;
282 }
283
Christopher Faulet9768c262018-10-22 09:34:31 +0200284 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200285 stream_inc_http_req_ctr(s);
286 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
287
Christopher Faulet9768c262018-10-22 09:34:31 +0200288 /* kill the pending keep-alive timeout */
289 txn->flags &= ~TX_WAIT_NEXT_RQ;
290 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200291
Christopher Faulet03599112018-11-27 11:21:21 +0100292 sl = http_find_stline(htx);
293
Christopher Faulet9768c262018-10-22 09:34:31 +0200294 /* 0: we might have to print this header in debug mode */
295 if (unlikely((global.mode & MODE_DEBUG) &&
296 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
297 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200298
Christopher Faulet03599112018-11-27 11:21:21 +0100299 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200300
301 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
302 struct htx_blk *blk = htx_get_blk(htx, pos);
303 enum htx_blk_type type = htx_get_blk_type(blk);
304
305 if (type == HTX_BLK_EOH)
306 break;
307 if (type != HTX_BLK_HDR)
308 continue;
309
310 htx_debug_hdr("clihdr", s,
311 htx_get_blk_name(htx, blk),
312 htx_get_blk_value(htx, blk));
313 }
314 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200315
316 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100317 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200318 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100319 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100320 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200321 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100322 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100323 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100324 if (sl->flags & HTX_SL_F_BODYLESS)
325 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200326
327 /* we can make use of server redirect on GET and HEAD */
328 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
329 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100330 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200332 goto return_bad_req;
333 }
334
335 /*
336 * 2: check if the URI matches the monitor_uri.
337 * We have to do this for every request which gets in, because
338 * the monitor-uri is defined by the frontend.
339 */
340 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100341 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200342 /*
343 * We have found the monitor URI
344 */
345 struct acl_cond *cond;
346
347 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100348 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200349
350 /* Check if we want to fail this monitor request or not */
351 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
352 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
353
354 ret = acl_pass(ret);
355 if (cond->pol == ACL_COND_UNLESS)
356 ret = !ret;
357
358 if (ret) {
359 /* we fail this request, let's return 503 service unavail */
360 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366 }
367
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800368 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200369 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100370 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200371 if (!(s->flags & SF_ERR_MASK))
372 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
373 goto return_prx_cond;
374 }
375
376 /*
377 * 3: Maybe we have to copy the original REQURI for the logs ?
378 * Note: we cannot log anymore if the request has been
379 * classified as invalid.
380 */
381 if (unlikely(s->logs.logwait & LW_REQ)) {
382 /* we have a complete HTTP request that we must log */
383 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200384 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385
Christopher Faulet9768c262018-10-22 09:34:31 +0200386 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
387 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200388
389 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
390 s->do_log(s);
391 } else {
392 ha_alert("HTTP logging : out of memory.\n");
393 }
394 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395
Christopher Faulete0768eb2018-10-03 16:38:02 +0200396 /* if the frontend has "option http-use-proxy-header", we'll check if
397 * we have what looks like a proxied connection instead of a connection,
398 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
399 * Note that this is *not* RFC-compliant, however browsers and proxies
400 * happen to do that despite being non-standard :-(
401 * We consider that a request not beginning with either '/' or '*' is
402 * a proxied connection, which covers both "scheme://location" and
403 * CONNECT ip:port.
404 */
405 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100406 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200407 txn->flags |= TX_USE_PX_CONN;
408
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 /* 5: we may need to capture headers */
410 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200411 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200412
413 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
414 * only change if both the request and the config reference something else.
415 * Option httpclose by itself sets tunnel mode where headers are mangled.
416 * However, if another mode is set, it will affect it (eg: server-close/
417 * keep-alive + httpclose = close). Note that we avoid to redo the same work
418 * if FE and BE have the same settings (common). The method consists in
419 * checking if options changed between the two calls (implying that either
420 * one is non-null, or one of them is non-null and we are there for the first
421 * time.
422 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200423 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200424 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200425
426 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200427 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200428 req->analysers |= AN_REQ_HTTP_BODY;
429
430 /*
431 * RFC7234#4:
432 * A cache MUST write through requests with methods
433 * that are unsafe (Section 4.2.1 of [RFC7231]) to
434 * the origin server; i.e., a cache is not allowed
435 * to generate a reply to such a request before
436 * having forwarded the request and having received
437 * a corresponding response.
438 *
439 * RFC7231#4.2.1:
440 * Of the request methods defined by this
441 * specification, the GET, HEAD, OPTIONS, and TRACE
442 * methods are defined to be safe.
443 */
444 if (likely(txn->meth == HTTP_METH_GET ||
445 txn->meth == HTTP_METH_HEAD ||
446 txn->meth == HTTP_METH_OPTIONS ||
447 txn->meth == HTTP_METH_TRACE))
448 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
449
450 /* end of job, return OK */
451 req->analysers &= ~an_bit;
452 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200453
Christopher Faulete0768eb2018-10-03 16:38:02 +0200454 return 1;
455
456 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200457 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200458 txn->req.err_state = txn->req.msg_state;
459 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100460 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100461 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200462 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100463 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200464
465 return_prx_cond:
466 if (!(s->flags & SF_ERR_MASK))
467 s->flags |= SF_ERR_PRXCOND;
468 if (!(s->flags & SF_FINST_MASK))
469 s->flags |= SF_FINST_R;
470
471 req->analysers &= AN_REQ_FLT_END;
472 req->analyse_exp = TICK_ETERNITY;
473 return 0;
474}
475
476
477/* This stream analyser runs all HTTP request processing which is common to
478 * frontends and backends, which means blocking ACLs, filters, connection-close,
479 * reqadd, stats and redirects. This is performed for the designated proxy.
480 * It returns 1 if the processing can continue on next analysers, or zero if it
481 * either needs more data or wants to immediately abort the request (eg: deny,
482 * error, ...).
483 */
484int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
485{
486 struct session *sess = s->sess;
487 struct http_txn *txn = s->txn;
488 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200489 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200490 struct redirect_rule *rule;
491 struct cond_wordlist *wl;
492 enum rule_result verdict;
493 int deny_status = HTTP_ERR_403;
494 struct connection *conn = objt_conn(sess->origin);
495
496 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
497 /* we need more data */
498 goto return_prx_yield;
499 }
500
501 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
502 now_ms, __FUNCTION__,
503 s,
504 req,
505 req->rex, req->wex,
506 req->flags,
507 ci_data(req),
508 req->analysers);
509
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100510 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200511
Christopher Faulete0768eb2018-10-03 16:38:02 +0200512 /* just in case we have some per-backend tracking */
513 stream_inc_be_http_req_ctr(s);
514
515 /* evaluate http-request rules */
516 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200517 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200518
519 switch (verdict) {
520 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
521 goto return_prx_yield;
522
523 case HTTP_RULE_RES_CONT:
524 case HTTP_RULE_RES_STOP: /* nothing to do */
525 break;
526
527 case HTTP_RULE_RES_DENY: /* deny or tarpit */
528 if (txn->flags & TX_CLTARPIT)
529 goto tarpit;
530 goto deny;
531
532 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
533 goto return_prx_cond;
534
535 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
536 goto done;
537
538 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
539 goto return_bad_req;
540 }
541 }
542
543 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
544 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200545 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546
Christopher Fauletff2759f2018-10-24 11:13:16 +0200547 ctx.blk = NULL;
548 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
549 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200552 }
553
554 /* OK at this stage, we know that the request was accepted according to
555 * the http-request rules, we can check for the stats. Note that the
556 * URI is detected *before* the req* rules in order not to be affected
557 * by a possible reqrep, while they are processed *after* so that a
558 * reqdeny can still block them. This clearly needs to change in 1.6!
559 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200560 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200561 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100562 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200563 txn->status = 500;
564 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100565 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200566
567 if (!(s->flags & SF_ERR_MASK))
568 s->flags |= SF_ERR_RESOURCE;
569 goto return_prx_cond;
570 }
571
572 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200573 htx_handle_stats(s, req);
574 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200575 /* not all actions implemented: deny, allow, auth */
576
577 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
578 goto deny;
579
580 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
581 goto return_prx_cond;
582 }
583
584 /* evaluate the req* rules except reqadd */
585 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200586 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200587 goto return_bad_req;
588
589 if (txn->flags & TX_CLDENY)
590 goto deny;
591
592 if (txn->flags & TX_CLTARPIT) {
593 deny_status = HTTP_ERR_500;
594 goto tarpit;
595 }
596 }
597
598 /* add request headers from the rule sets in the same order */
599 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200600 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601 if (wl->cond) {
602 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
603 ret = acl_pass(ret);
604 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
605 ret = !ret;
606 if (!ret)
607 continue;
608 }
609
Christopher Fauletff2759f2018-10-24 11:13:16 +0200610 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
611 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200612 goto return_bad_req;
613 }
614
Christopher Faulete0768eb2018-10-03 16:38:02 +0200615 /* Proceed with the stats now. */
616 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
617 unlikely(objt_applet(s->target) == &http_cache_applet)) {
618 /* process the stats request now */
619 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100620 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200621
622 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
623 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
624 if (!(s->flags & SF_FINST_MASK))
625 s->flags |= SF_FINST_R;
626
627 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
628 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
629 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
630 req->analysers |= AN_REQ_HTTP_XFER_BODY;
631 goto done;
632 }
633
634 /* check whether we have some ACLs set to redirect this request */
635 list_for_each_entry(rule, &px->redirect_rules, list) {
636 if (rule->cond) {
637 int ret;
638
639 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
640 ret = acl_pass(ret);
641 if (rule->cond->pol == ACL_COND_UNLESS)
642 ret = !ret;
643 if (!ret)
644 continue;
645 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200646 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200647 goto return_bad_req;
648 goto done;
649 }
650
651 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
652 * If this happens, then the data will not come immediately, so we must
653 * send all what we have without waiting. Note that due to the small gain
654 * in waiting for the body of the request, it's easier to simply put the
655 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
656 * itself once used.
657 */
658 req->flags |= CF_SEND_DONTWAIT;
659
660 done: /* done with this analyser, continue with next ones that the calling
661 * points will have set, if any.
662 */
663 req->analyse_exp = TICK_ETERNITY;
664 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
665 req->analysers &= ~an_bit;
666 return 1;
667
668 tarpit:
669 /* Allow cookie logging
670 */
671 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200672 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200673
674 /* When a connection is tarpitted, we use the tarpit timeout,
675 * which may be the same as the connect timeout if unspecified.
676 * If unset, then set it to zero because we really want it to
677 * eventually expire. We build the tarpit as an analyser.
678 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100679 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200680
681 /* wipe the request out so that we can drop the connection early
682 * if the client closes first.
683 */
684 channel_dont_connect(req);
685
686 txn->status = http_err_codes[deny_status];
687
688 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
689 req->analysers |= AN_REQ_HTTP_TARPIT;
690 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
691 if (!req->analyse_exp)
692 req->analyse_exp = tick_add(now_ms, 0);
693 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100694 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200695 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100696 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200697 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100698 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 goto done_without_exp;
700
701 deny: /* this request was blocked (denied) */
702
703 /* Allow cookie logging
704 */
705 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200706 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707
708 txn->flags |= TX_CLDENY;
709 txn->status = http_err_codes[deny_status];
710 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100717 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200718 goto return_prx_cond;
719
720 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200721 txn->req.err_state = txn->req.msg_state;
722 txn->req.msg_state = HTTP_MSG_ERROR;
723 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100724 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200725
Olivier Houcharda798bf52019-03-08 18:52:00 +0100726 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200727 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100728 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200729
730 return_prx_cond:
731 if (!(s->flags & SF_ERR_MASK))
732 s->flags |= SF_ERR_PRXCOND;
733 if (!(s->flags & SF_FINST_MASK))
734 s->flags |= SF_FINST_R;
735
736 req->analysers &= AN_REQ_FLT_END;
737 req->analyse_exp = TICK_ETERNITY;
738 return 0;
739
740 return_prx_yield:
741 channel_dont_connect(req);
742 return 0;
743}
744
745/* This function performs all the processing enabled for the current request.
746 * It returns 1 if the processing can continue on next analysers, or zero if it
747 * needs more data, encounters an error, or wants to immediately abort the
748 * request. It relies on buffers flags, and updates s->req.analysers.
749 */
750int htx_process_request(struct stream *s, struct channel *req, int an_bit)
751{
752 struct session *sess = s->sess;
753 struct http_txn *txn = s->txn;
754 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200755 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200756 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
757
758 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
759 /* we need more data */
760 channel_dont_connect(req);
761 return 0;
762 }
763
764 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
765 now_ms, __FUNCTION__,
766 s,
767 req,
768 req->rex, req->wex,
769 req->flags,
770 ci_data(req),
771 req->analysers);
772
773 /*
774 * Right now, we know that we have processed the entire headers
775 * and that unwanted requests have been filtered out. We can do
776 * whatever we want with the remaining request. Also, now we
777 * may have separate values for ->fe, ->be.
778 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100779 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200780
781 /*
782 * If HTTP PROXY is set we simply get remote server address parsing
783 * incoming request. Note that this requires that a connection is
784 * allocated on the server side.
785 */
786 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
787 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100788 struct htx_sl *sl;
789 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200790
791 /* Note that for now we don't reuse existing proxy connections */
792 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
793 txn->req.err_state = txn->req.msg_state;
794 txn->req.msg_state = HTTP_MSG_ERROR;
795 txn->status = 500;
796 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100797 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200798
799 if (!(s->flags & SF_ERR_MASK))
800 s->flags |= SF_ERR_RESOURCE;
801 if (!(s->flags & SF_FINST_MASK))
802 s->flags |= SF_FINST_R;
803
804 return 0;
805 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200806 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 uri = htx_sl_req_uri(sl);
808 path = http_get_path(uri);
809 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200810 goto return_bad_req;
811
812 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200813 * uri.ptr and path.ptr (excluded). If it was not found, we need
814 * to replace from all the uri by a single "/".
815 *
816 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100817 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200818 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100820 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200821 }
822
823 /*
824 * 7: Now we can work with the cookies.
825 * Note that doing so might move headers in the request, but
826 * the fields will stay coherent and the URI will not move.
827 * This should only be performed in the backend.
828 */
829 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100830 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200831
832 /* add unique-id if "header-unique-id" is specified */
833
834 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
835 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
836 goto return_bad_req;
837 s->unique_id[0] = '\0';
838 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
839 }
840
841 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200842 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
843 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
844
845 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 }
848
849 /*
850 * 9: add X-Forwarded-For if either the frontend or the backend
851 * asks for it.
852 */
853 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200854 struct http_hdr_ctx ctx = { .blk = NULL };
855 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
856 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
857
Christopher Faulete0768eb2018-10-03 16:38:02 +0200858 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200859 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200860 /* The header is set to be added only if none is present
861 * and we found it, so don't do anything.
862 */
863 }
864 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
865 /* Add an X-Forwarded-For header unless the source IP is
866 * in the 'except' network range.
867 */
868 if ((!sess->fe->except_mask.s_addr ||
869 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
870 != sess->fe->except_net.s_addr) &&
871 (!s->be->except_mask.s_addr ||
872 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
873 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200874 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200875
876 /* Note: we rely on the backend to get the header name to be used for
877 * x-forwarded-for, because the header is really meant for the backends.
878 * However, if the backend did not specify any option, we have to rely
879 * on the frontend's header name.
880 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200881 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
882 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200883 goto return_bad_req;
884 }
885 }
886 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
887 /* FIXME: for the sake of completeness, we should also support
888 * 'except' here, although it is mostly useless in this case.
889 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200891
Christopher Faulete0768eb2018-10-03 16:38:02 +0200892 inet_ntop(AF_INET6,
893 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
894 pn, sizeof(pn));
895
896 /* Note: we rely on the backend to get the header name to be used for
897 * x-forwarded-for, because the header is really meant for the backends.
898 * However, if the backend did not specify any option, we have to rely
899 * on the frontend's header name.
900 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200901 chunk_printf(&trash, "%s", pn);
902 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200903 goto return_bad_req;
904 }
905 }
906
907 /*
908 * 10: add X-Original-To if either the frontend or the backend
909 * asks for it.
910 */
911 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
912
913 /* FIXME: don't know if IPv6 can handle that case too. */
914 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
915 /* Add an X-Original-To header unless the destination IP is
916 * in the 'except' network range.
917 */
918 conn_get_to_addr(cli_conn);
919
920 if (cli_conn->addr.to.ss_family == AF_INET &&
921 ((!sess->fe->except_mask_to.s_addr ||
922 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
923 != sess->fe->except_to.s_addr) &&
924 (!s->be->except_mask_to.s_addr ||
925 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
926 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200927 struct ist hdr;
928 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200929
930 /* Note: we rely on the backend to get the header name to be used for
931 * x-original-to, because the header is really meant for the backends.
932 * However, if the backend did not specify any option, we have to rely
933 * on the frontend's header name.
934 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200935 if (s->be->orgto_hdr_len)
936 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
937 else
938 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200939
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200940 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
941 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 goto return_bad_req;
943 }
944 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 }
946
Christopher Faulete0768eb2018-10-03 16:38:02 +0200947 /* If we have no server assigned yet and we're balancing on url_param
948 * with a POST request, we may be interested in checking the body for
949 * that parameter. This will be done in another analyser.
950 */
951 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100952 s->txn->meth == HTTP_METH_POST &&
953 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200954 channel_dont_connect(req);
955 req->analysers |= AN_REQ_HTTP_BODY;
956 }
957
958 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
959 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100960
Christopher Faulete0768eb2018-10-03 16:38:02 +0200961 /* We expect some data from the client. Unless we know for sure
962 * we already have a full request, we have to re-enable quick-ack
963 * in case we previously disabled it, otherwise we might cause
964 * the client to delay further data.
965 */
966 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200967 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100968 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200969
970 /*************************************************************
971 * OK, that's finished for the headers. We have done what we *
972 * could. Let's switch to the DATA state. *
973 ************************************************************/
974 req->analyse_exp = TICK_ETERNITY;
975 req->analysers &= ~an_bit;
976
977 s->logs.tv_request = now;
978 /* OK let's go on with the BODY now */
979 return 1;
980
981 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200982 txn->req.err_state = txn->req.msg_state;
983 txn->req.msg_state = HTTP_MSG_ERROR;
984 txn->status = 400;
985 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100986 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200987
Olivier Houcharda798bf52019-03-08 18:52:00 +0100988 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200989 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100990 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200991
992 if (!(s->flags & SF_ERR_MASK))
993 s->flags |= SF_ERR_PRXCOND;
994 if (!(s->flags & SF_FINST_MASK))
995 s->flags |= SF_FINST_R;
996 return 0;
997}
998
999/* This function is an analyser which processes the HTTP tarpit. It always
1000 * returns zero, at the beginning because it prevents any other processing
1001 * from occurring, and at the end because it terminates the request.
1002 */
1003int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1004{
1005 struct http_txn *txn = s->txn;
1006
1007 /* This connection is being tarpitted. The CLIENT side has
1008 * already set the connect expiration date to the right
1009 * timeout. We just have to check that the client is still
1010 * there and that the timeout has not expired.
1011 */
1012 channel_dont_connect(req);
1013 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1014 !tick_is_expired(req->analyse_exp, now_ms))
1015 return 0;
1016
1017 /* We will set the queue timer to the time spent, just for
1018 * logging purposes. We fake a 500 server error, so that the
1019 * attacker will not suspect his connection has been tarpitted.
1020 * It will not cause trouble to the logs because we can exclude
1021 * the tarpitted connections by filtering on the 'PT' status flags.
1022 */
1023 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1024
1025 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001026 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001027
1028 req->analysers &= AN_REQ_FLT_END;
1029 req->analyse_exp = TICK_ETERNITY;
1030
1031 if (!(s->flags & SF_ERR_MASK))
1032 s->flags |= SF_ERR_PRXCOND;
1033 if (!(s->flags & SF_FINST_MASK))
1034 s->flags |= SF_FINST_T;
1035 return 0;
1036}
1037
1038/* This function is an analyser which waits for the HTTP request body. It waits
1039 * for either the buffer to be full, or the full advertised contents to have
1040 * reached the buffer. It must only be called after the standard HTTP request
1041 * processing has occurred, because it expects the request to be parsed and will
1042 * look for the Expect header. It may send a 100-Continue interim response. It
1043 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1044 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1045 * needs to read more data, or 1 once it has completed its analysis.
1046 */
1047int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1048{
1049 struct session *sess = s->sess;
1050 struct http_txn *txn = s->txn;
1051 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001053
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001054
1055 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1056 now_ms, __FUNCTION__,
1057 s,
1058 req,
1059 req->rex, req->wex,
1060 req->flags,
1061 ci_data(req),
1062 req->analysers);
1063
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001064 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065
Willy Tarreau4236f032019-03-05 10:43:32 +01001066 if (htx->flags & HTX_FL_PARSING_ERROR)
1067 goto return_bad_req;
1068
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 if (msg->msg_state < HTTP_MSG_BODY)
1070 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001071
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072 /* We have to parse the HTTP request body to find any required data.
1073 * "balance url_param check_post" should have been the only way to get
1074 * into this. We were brought here after HTTP header analysis, so all
1075 * related structures are ready.
1076 */
1077
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001078 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001079 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1080 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001081 }
1082
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001083 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1086 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001089 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 goto http_end;
1091
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001092 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1094 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001095 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096
1097 if (!(s->flags & SF_ERR_MASK))
1098 s->flags |= SF_ERR_CLITO;
1099 if (!(s->flags & SF_FINST_MASK))
1100 s->flags |= SF_FINST_D;
1101 goto return_err_msg;
1102 }
1103
1104 /* we get here if we need to wait for more data */
1105 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1106 /* Not enough data. We'll re-use the http-request
1107 * timeout here. Ideally, we should set the timeout
1108 * relative to the accept() date. We just set the
1109 * request timeout once at the beginning of the
1110 * request.
1111 */
1112 channel_dont_connect(req);
1113 if (!tick_isset(req->analyse_exp))
1114 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1115 return 0;
1116 }
1117
1118 http_end:
1119 /* The situation will not evolve, so let's give up on the analysis. */
1120 s->logs.tv_request = now; /* update the request timer to reflect full request */
1121 req->analysers &= ~an_bit;
1122 req->analyse_exp = TICK_ETERNITY;
1123 return 1;
1124
1125 return_bad_req: /* let's centralize all bad requests */
1126 txn->req.err_state = txn->req.msg_state;
1127 txn->req.msg_state = HTTP_MSG_ERROR;
1128 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001129 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001130
1131 if (!(s->flags & SF_ERR_MASK))
1132 s->flags |= SF_ERR_PRXCOND;
1133 if (!(s->flags & SF_FINST_MASK))
1134 s->flags |= SF_FINST_R;
1135
1136 return_err_msg:
1137 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001138 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001139 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001140 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001141 return 0;
1142}
1143
1144/* This function is an analyser which forwards request body (including chunk
1145 * sizes if any). It is called as soon as we must forward, even if we forward
1146 * zero byte. The only situation where it must not be called is when we're in
1147 * tunnel mode and we want to forward till the close. It's used both to forward
1148 * remaining data and to resync after end of body. It expects the msg_state to
1149 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1150 * read more data, or 1 once we can go on with next request or end the stream.
1151 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1152 * bytes of pending data + the headers if not already done.
1153 */
1154int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1155{
1156 struct session *sess = s->sess;
1157 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001158 struct http_msg *msg = &txn->req;
1159 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001160 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001161 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001162
1163 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1164 now_ms, __FUNCTION__,
1165 s,
1166 req,
1167 req->rex, req->wex,
1168 req->flags,
1169 ci_data(req),
1170 req->analysers);
1171
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001172 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001173
1174 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1175 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1176 /* Output closed while we were sending data. We must abort and
1177 * wake the other side up.
1178 */
1179 msg->err_state = msg->msg_state;
1180 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001181 htx_end_request(s);
1182 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001183 return 1;
1184 }
1185
1186 /* Note that we don't have to send 100-continue back because we don't
1187 * need the data to complete our job, and it's up to the server to
1188 * decide whether to return 100, 417 or anything else in return of
1189 * an "Expect: 100-continue" header.
1190 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001191 if (msg->msg_state == HTTP_MSG_BODY)
1192 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001193
1194 /* Some post-connect processing might want us to refrain from starting to
1195 * forward data. Currently, the only reason for this is "balance url_param"
1196 * whichs need to parse/process the request after we've enabled forwarding.
1197 */
1198 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1199 if (!(s->res.flags & CF_READ_ATTACHED)) {
1200 channel_auto_connect(req);
1201 req->flags |= CF_WAKE_CONNECT;
1202 channel_dont_close(req); /* don't fail on early shutr */
1203 goto waiting;
1204 }
1205 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1206 }
1207
1208 /* in most states, we should abort in case of early close */
1209 channel_auto_close(req);
1210
1211 if (req->to_forward) {
Christopher Fauletf52170d2019-03-08 15:45:26 +01001212 if (req->to_forward == CHN_INFINITE_FORWARD) {
1213 if (req->flags & CF_SHUTR) {
1214 msg->msg_state = HTTP_MSG_DONE;
1215 req->to_forward = 0;
1216 goto done;
1217 }
1218 }
1219 else {
1220 /* We can't process the buffer's contents yet */
1221 req->flags |= CF_WAKE_WRITE;
1222 goto missing_data_or_waiting;
1223 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001224 }
1225
Christopher Faulet9768c262018-10-22 09:34:31 +02001226 if (msg->msg_state >= HTTP_MSG_DONE)
1227 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 /* Forward input data. We get it by removing all outgoing data not
1229 * forwarded yet from HTX data size. If there are some data filters, we
1230 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001231 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001232 if (HAS_REQ_DATA_FILTERS(s)) {
1233 ret = flt_http_payload(s, msg, htx->data);
1234 if (ret < 0)
1235 goto return_bad_req;
1236 c_adv(req, ret);
1237 if (htx->data != co_data(req) || htx->extra)
1238 goto missing_data_or_waiting;
1239 }
1240 else {
1241 c_adv(req, htx->data - co_data(req));
Christopher Fauletf52170d2019-03-08 15:45:26 +01001242 if (msg->flags & HTTP_MSGF_XFER_LEN)
1243 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001244 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001245
Christopher Faulet9768c262018-10-22 09:34:31 +02001246 /* Check if the end-of-message is reached and if so, switch the message
1247 * in HTTP_MSG_DONE state.
1248 */
1249 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1250 goto missing_data_or_waiting;
1251
1252 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01001253 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001254
1255 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001256 /* other states, DONE...TUNNEL */
1257 /* we don't want to forward closes on DONE except in tunnel mode. */
1258 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1259 channel_dont_close(req);
1260
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001261 if (HAS_REQ_DATA_FILTERS(s)) {
1262 ret = flt_http_end(s, msg);
1263 if (ret <= 0) {
1264 if (!ret)
1265 goto missing_data_or_waiting;
1266 goto return_bad_req;
1267 }
1268 }
1269
Christopher Fauletf2824e62018-10-01 12:12:37 +02001270 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001272 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001273 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1274 if (req->flags & CF_SHUTW) {
1275 /* request errors are most likely due to the
1276 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001277 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001279 goto return_bad_req;
1280 }
1281 return 1;
1282 }
1283
1284 /* If "option abortonclose" is set on the backend, we want to monitor
1285 * the client's connection and forward any shutdown notification to the
1286 * server, which will decide whether to close or to go on processing the
1287 * request. We only do that in tunnel mode, and not in other modes since
1288 * it can be abused to exhaust source ports. */
1289 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1290 channel_auto_read(req);
1291 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1292 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1293 s->si[1].flags |= SI_FL_NOLINGER;
1294 channel_auto_close(req);
1295 }
1296 else if (s->txn->meth == HTTP_METH_POST) {
1297 /* POST requests may require to read extra CRLF sent by broken
1298 * browsers and which could cause an RST to be sent upon close
1299 * on some systems (eg: Linux). */
1300 channel_auto_read(req);
1301 }
1302 return 0;
1303
1304 missing_data_or_waiting:
1305 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001306 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1307 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001308
1309 waiting:
1310 /* waiting for the last bits to leave the buffer */
1311 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001312 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001313
Christopher Faulet47365272018-10-31 17:40:50 +01001314 if (htx->flags & HTX_FL_PARSING_ERROR)
1315 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001316
Christopher Faulete0768eb2018-10-03 16:38:02 +02001317 /* When TE: chunked is used, we need to get there again to parse remaining
1318 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1319 * And when content-length is used, we never want to let the possible
1320 * shutdown be forwarded to the other side, as the state machine will
1321 * take care of it once the client responds. It's also important to
1322 * prevent TIME_WAITs from accumulating on the backend side, and for
1323 * HTTP/2 where the last frame comes with a shutdown.
1324 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001325 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001326 channel_dont_close(req);
1327
1328 /* We know that more data are expected, but we couldn't send more that
1329 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1330 * system knows it must not set a PUSH on this first part. Interactive
1331 * modes are already handled by the stream sock layer. We must not do
1332 * this in content-length mode because it could present the MSG_MORE
1333 * flag with the last block of forwarded data, which would cause an
1334 * additional delay to be observed by the receiver.
1335 */
1336 if (msg->flags & HTTP_MSGF_TE_CHNK)
1337 req->flags |= CF_EXPECT_MORE;
1338
1339 return 0;
1340
Christopher Faulet93e02d82019-03-08 14:18:50 +01001341 return_cli_abort:
1342 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1343 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1344 if (objt_server(s->target))
1345 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1346 if (!(s->flags & SF_ERR_MASK))
1347 s->flags |= SF_ERR_CLICL;
1348 status = 400;
1349 goto return_error;
1350
1351 return_srv_abort:
1352 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1353 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1354 if (objt_server(s->target))
1355 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1356 if (!(s->flags & SF_ERR_MASK))
1357 s->flags |= SF_ERR_SRVCL;
1358 status = 502;
1359 goto return_error;
1360
1361 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001362 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001364 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001366 s->flags |= SF_ERR_CLICL;
1367 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368
Christopher Faulet93e02d82019-03-08 14:18:50 +01001369 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 txn->req.err_state = txn->req.msg_state;
1371 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001372 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001374 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001376 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001377 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 }
1379 req->analysers &= AN_REQ_FLT_END;
1380 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 +01001381 if (!(s->flags & SF_FINST_MASK))
1382 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 return 0;
1384}
1385
1386/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1387 * processing can continue on next analysers, or zero if it either needs more
1388 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1389 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1390 * when it has nothing left to do, and may remove any analyser when it wants to
1391 * abort.
1392 */
1393int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1394{
Christopher Faulet9768c262018-10-22 09:34:31 +02001395 /*
1396 * We will analyze a complete HTTP response to check the its syntax.
1397 *
1398 * Once the start line and all headers are received, we may perform a
1399 * capture of the error (if any), and we will set a few fields. We also
1400 * logging and finally headers capture.
1401 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001402 struct session *sess = s->sess;
1403 struct http_txn *txn = s->txn;
1404 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001405 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001406 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001407 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001408 int n;
1409
1410 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1411 now_ms, __FUNCTION__,
1412 s,
1413 rep,
1414 rep->rex, rep->wex,
1415 rep->flags,
1416 ci_data(rep),
1417 rep->analysers);
1418
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001419 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001420
Willy Tarreau4236f032019-03-05 10:43:32 +01001421 /* Parsing errors are caught here */
1422 if (htx->flags & HTX_FL_PARSING_ERROR)
1423 goto return_bad_res;
1424
Christopher Faulete0768eb2018-10-03 16:38:02 +02001425 /*
1426 * Now we quickly check if we have found a full valid response.
1427 * If not so, we check the FD and buffer states before leaving.
1428 * A full response is indicated by the fact that we have seen
1429 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1430 * responses are checked first.
1431 *
1432 * Depending on whether the client is still there or not, we
1433 * may send an error response back or not. Note that normally
1434 * we should only check for HTTP status there, and check I/O
1435 * errors somewhere else.
1436 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001437 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001438 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001439 * First catch invalid response because of a parsing error or
1440 * because only part of headers have been transfered.
1441 * Multiplexers have the responsibility to emit all headers at
1442 * once. We must be sure to have forwarded all outgoing data
1443 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001444 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001445 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001446 goto return_bad_res;
1447
Christopher Faulet9768c262018-10-22 09:34:31 +02001448 /* 1: have we encountered a read error ? */
1449 if (rep->flags & CF_READ_ERROR) {
1450 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001451 goto abort_keep_alive;
1452
Olivier Houcharda798bf52019-03-08 18:52:00 +01001453 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001455 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001456 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 }
1458
Christopher Faulete0768eb2018-10-03 16:38:02 +02001459 rep->analysers &= AN_RES_FLT_END;
1460 txn->status = 502;
1461
1462 /* Check to see if the server refused the early data.
1463 * If so, just send a 425
1464 */
1465 if (objt_cs(s->si[1].end)) {
1466 struct connection *conn = objt_cs(s->si[1].end)->conn;
1467
1468 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1469 txn->status = 425;
1470 }
1471
1472 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001473 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001474
1475 if (!(s->flags & SF_ERR_MASK))
1476 s->flags |= SF_ERR_SRVCL;
1477 if (!(s->flags & SF_FINST_MASK))
1478 s->flags |= SF_FINST_H;
1479 return 0;
1480 }
1481
Christopher Faulet9768c262018-10-22 09:34:31 +02001482 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001484 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001486 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001487 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001488 }
1489
Christopher Faulete0768eb2018-10-03 16:38:02 +02001490 rep->analysers &= AN_RES_FLT_END;
1491 txn->status = 504;
1492 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001493 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494
1495 if (!(s->flags & SF_ERR_MASK))
1496 s->flags |= SF_ERR_SRVTO;
1497 if (!(s->flags & SF_FINST_MASK))
1498 s->flags |= SF_FINST_H;
1499 return 0;
1500 }
1501
Christopher Faulet9768c262018-10-22 09:34:31 +02001502 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001504 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1505 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001507 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508
1509 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001511 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512
1513 if (!(s->flags & SF_ERR_MASK))
1514 s->flags |= SF_ERR_CLICL;
1515 if (!(s->flags & SF_FINST_MASK))
1516 s->flags |= SF_FINST_H;
1517
1518 /* process_stream() will take care of the error */
1519 return 0;
1520 }
1521
Christopher Faulet9768c262018-10-22 09:34:31 +02001522 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001524 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 goto abort_keep_alive;
1526
Olivier Houcharda798bf52019-03-08 18:52:00 +01001527 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001529 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001530 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 }
1532
Christopher Faulete0768eb2018-10-03 16:38:02 +02001533 rep->analysers &= AN_RES_FLT_END;
1534 txn->status = 502;
1535 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001536 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537
1538 if (!(s->flags & SF_ERR_MASK))
1539 s->flags |= SF_ERR_SRVCL;
1540 if (!(s->flags & SF_FINST_MASK))
1541 s->flags |= SF_FINST_H;
1542 return 0;
1543 }
1544
Christopher Faulet9768c262018-10-22 09:34:31 +02001545 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001546 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 goto abort_keep_alive;
1549
Olivier Houcharda798bf52019-03-08 18:52:00 +01001550 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001552
1553 if (!(s->flags & SF_ERR_MASK))
1554 s->flags |= SF_ERR_CLICL;
1555 if (!(s->flags & SF_FINST_MASK))
1556 s->flags |= SF_FINST_H;
1557
1558 /* process_stream() will take care of the error */
1559 return 0;
1560 }
1561
1562 channel_dont_close(rep);
1563 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1564 return 0;
1565 }
1566
1567 /* More interesting part now : we know that we have a complete
1568 * response which at least looks like HTTP. We have an indicator
1569 * of each header's length, so we can parse them quickly.
1570 */
1571
Christopher Faulet9768c262018-10-22 09:34:31 +02001572 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001573 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 /* 0: we might have to print this header in debug mode */
1576 if (unlikely((global.mode & MODE_DEBUG) &&
1577 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1578 int32_t pos;
1579
Christopher Faulet03599112018-11-27 11:21:21 +01001580 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001581
1582 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1583 struct htx_blk *blk = htx_get_blk(htx, pos);
1584 enum htx_blk_type type = htx_get_blk_type(blk);
1585
1586 if (type == HTX_BLK_EOH)
1587 break;
1588 if (type != HTX_BLK_HDR)
1589 continue;
1590
1591 htx_debug_hdr("srvhdr", s,
1592 htx_get_blk_name(htx, blk),
1593 htx_get_blk_value(htx, blk));
1594 }
1595 }
1596
Christopher Faulet03599112018-11-27 11:21:21 +01001597 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001598 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001599 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001600 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001601 if (sl->flags & HTX_SL_F_XFER_LEN) {
1602 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001603 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001604 if (sl->flags & HTX_SL_F_BODYLESS)
1605 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001606 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001607
1608 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001609 if (n < 1 || n > 5)
1610 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001611
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 /* when the client triggers a 4xx from the server, it's most often due
1613 * to a missing object or permission. These events should be tracked
1614 * because if they happen often, it may indicate a brute force or a
1615 * vulnerability scan.
1616 */
1617 if (n == 4)
1618 stream_inc_http_err_ctr(s);
1619
1620 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001621 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 /* Adjust server's health based on status code. Note: status codes 501
1624 * and 505 are triggered on demand by client request, so we must not
1625 * count them as server failures.
1626 */
1627 if (objt_server(s->target)) {
1628 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001629 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001630 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001631 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001632 }
1633
1634 /*
1635 * We may be facing a 100-continue response, or any other informational
1636 * 1xx response which is non-final, in which case this is not the right
1637 * response, and we're waiting for the next one. Let's allow this response
1638 * to go to the client and wait for the next one. There's an exception for
1639 * 101 which is used later in the code to switch protocols.
1640 */
1641 if (txn->status < 200 &&
1642 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001643 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001644 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001645 msg->msg_state = HTTP_MSG_RPBEFORE;
1646 txn->status = 0;
1647 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001648 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001649 }
1650
1651 /*
1652 * 2: check for cacheability.
1653 */
1654
1655 switch (txn->status) {
1656 case 200:
1657 case 203:
1658 case 204:
1659 case 206:
1660 case 300:
1661 case 301:
1662 case 404:
1663 case 405:
1664 case 410:
1665 case 414:
1666 case 501:
1667 break;
1668 default:
1669 /* RFC7231#6.1:
1670 * Responses with status codes that are defined as
1671 * cacheable by default (e.g., 200, 203, 204, 206,
1672 * 300, 301, 404, 405, 410, 414, and 501 in this
1673 * specification) can be reused by a cache with
1674 * heuristic expiration unless otherwise indicated
1675 * by the method definition or explicit cache
1676 * controls [RFC7234]; all other status codes are
1677 * not cacheable by default.
1678 */
1679 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1680 break;
1681 }
1682
1683 /*
1684 * 3: we may need to capture headers
1685 */
1686 s->logs.logwait &= ~LW_RESP;
1687 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001688 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001689
Christopher Faulet9768c262018-10-22 09:34:31 +02001690 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001691 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1692 txn->status == 101)) {
1693 /* Either we've established an explicit tunnel, or we're
1694 * switching the protocol. In both cases, we're very unlikely
1695 * to understand the next protocols. We have to switch to tunnel
1696 * mode, so that we transfer the request and responses then let
1697 * this protocol pass unmodified. When we later implement specific
1698 * parsers for such protocols, we'll want to check the Upgrade
1699 * header which contains information about that protocol for
1700 * responses with status 101 (eg: see RFC2817 about TLS).
1701 */
1702 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001703 }
1704
Christopher Faulet61608322018-11-23 16:23:45 +01001705 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1706 * 407 (Proxy-Authenticate) responses and set the connection to private
1707 */
1708 srv_conn = cs_conn(objt_cs(s->si[1].end));
1709 if (srv_conn) {
1710 struct ist hdr;
1711 struct http_hdr_ctx ctx;
1712
1713 if (txn->status == 401)
1714 hdr = ist("WWW-Authenticate");
1715 else if (txn->status == 407)
1716 hdr = ist("Proxy-Authenticate");
1717 else
1718 goto end;
1719
1720 ctx.blk = NULL;
1721 while (http_find_header(htx, hdr, &ctx, 0)) {
1722 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1723 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1724 srv_conn->flags |= CO_FL_PRIVATE;
1725 }
1726 }
1727
1728 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001729 /* we want to have the response time before we start processing it */
1730 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1731
1732 /* end of job, return OK */
1733 rep->analysers &= ~an_bit;
1734 rep->analyse_exp = TICK_ETERNITY;
1735 channel_auto_close(rep);
1736 return 1;
1737
Christopher Faulet47365272018-10-31 17:40:50 +01001738 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001739 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001740 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001741 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001742 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001743 }
1744 txn->status = 502;
1745 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001746 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001747 rep->analysers &= AN_RES_FLT_END;
1748
1749 if (!(s->flags & SF_ERR_MASK))
1750 s->flags |= SF_ERR_PRXCOND;
1751 if (!(s->flags & SF_FINST_MASK))
1752 s->flags |= SF_FINST_H;
1753 return 0;
1754
Christopher Faulete0768eb2018-10-03 16:38:02 +02001755 abort_keep_alive:
1756 /* A keep-alive request to the server failed on a network error.
1757 * The client is required to retry. We need to close without returning
1758 * any other information so that the client retries.
1759 */
1760 txn->status = 0;
1761 rep->analysers &= AN_RES_FLT_END;
1762 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001763 s->logs.logwait = 0;
1764 s->logs.level = 0;
1765 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001766 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001767 return 0;
1768}
1769
1770/* This function performs all the processing enabled for the current response.
1771 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1772 * and updates s->res.analysers. It might make sense to explode it into several
1773 * other functions. It works like process_request (see indications above).
1774 */
1775int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1776{
1777 struct session *sess = s->sess;
1778 struct http_txn *txn = s->txn;
1779 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001780 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001781 struct proxy *cur_proxy;
1782 struct cond_wordlist *wl;
1783 enum rule_result ret = HTTP_RULE_RES_CONT;
1784
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001785 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1786 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001787
Christopher Faulete0768eb2018-10-03 16:38:02 +02001788 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1789 now_ms, __FUNCTION__,
1790 s,
1791 rep,
1792 rep->rex, rep->wex,
1793 rep->flags,
1794 ci_data(rep),
1795 rep->analysers);
1796
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001797 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001798
1799 /* The stats applet needs to adjust the Connection header but we don't
1800 * apply any filter there.
1801 */
1802 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1803 rep->analysers &= ~an_bit;
1804 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001805 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001806 }
1807
1808 /*
1809 * We will have to evaluate the filters.
1810 * As opposed to version 1.2, now they will be evaluated in the
1811 * filters order and not in the header order. This means that
1812 * each filter has to be validated among all headers.
1813 *
1814 * Filters are tried with ->be first, then with ->fe if it is
1815 * different from ->be.
1816 *
1817 * Maybe we are in resume condiion. In this case I choose the
1818 * "struct proxy" which contains the rule list matching the resume
1819 * pointer. If none of theses "struct proxy" match, I initialise
1820 * the process with the first one.
1821 *
1822 * In fact, I check only correspondance betwwen the current list
1823 * pointer and the ->fe rule list. If it doesn't match, I initialize
1824 * the loop with the ->be.
1825 */
1826 if (s->current_rule_list == &sess->fe->http_res_rules)
1827 cur_proxy = sess->fe;
1828 else
1829 cur_proxy = s->be;
1830 while (1) {
1831 struct proxy *rule_set = cur_proxy;
1832
1833 /* evaluate http-response rules */
1834 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001835 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001836
1837 if (ret == HTTP_RULE_RES_BADREQ)
1838 goto return_srv_prx_502;
1839
1840 if (ret == HTTP_RULE_RES_DONE) {
1841 rep->analysers &= ~an_bit;
1842 rep->analyse_exp = TICK_ETERNITY;
1843 return 1;
1844 }
1845 }
1846
1847 /* we need to be called again. */
1848 if (ret == HTTP_RULE_RES_YIELD) {
1849 channel_dont_close(rep);
1850 return 0;
1851 }
1852
1853 /* try headers filters */
1854 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001855 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1856 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001857 }
1858
1859 /* has the response been denied ? */
1860 if (txn->flags & TX_SVDENY) {
1861 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001862 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001863
Olivier Houcharda798bf52019-03-08 18:52:00 +01001864 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1865 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001867 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001868 goto return_srv_prx_502;
1869 }
1870
1871 /* add response headers from the rule sets in the same order */
1872 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001873 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001874 if (txn->status < 200 && txn->status != 101)
1875 break;
1876 if (wl->cond) {
1877 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1878 ret = acl_pass(ret);
1879 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1880 ret = !ret;
1881 if (!ret)
1882 continue;
1883 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001884
1885 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1886 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001887 goto return_bad_resp;
1888 }
1889
1890 /* check whether we're already working on the frontend */
1891 if (cur_proxy == sess->fe)
1892 break;
1893 cur_proxy = sess->fe;
1894 }
1895
1896 /* After this point, this anayzer can't return yield, so we can
1897 * remove the bit corresponding to this analyzer from the list.
1898 *
1899 * Note that the intermediate returns and goto found previously
1900 * reset the analyzers.
1901 */
1902 rep->analysers &= ~an_bit;
1903 rep->analyse_exp = TICK_ETERNITY;
1904
1905 /* OK that's all we can do for 1xx responses */
1906 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001907 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001908
1909 /*
1910 * Now check for a server cookie.
1911 */
1912 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001913 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001914
1915 /*
1916 * Check for cache-control or pragma headers if required.
1917 */
1918 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1919 check_response_for_cacheability(s, rep);
1920
1921 /*
1922 * Add server cookie in the response if needed
1923 */
1924 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1925 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1926 (!(s->flags & SF_DIRECT) ||
1927 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1928 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1929 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1930 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1931 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1932 !(s->flags & SF_IGNORE_PRST)) {
1933 /* the server is known, it's not the one the client requested, or the
1934 * cookie's last seen date needs to be refreshed. We have to
1935 * insert a set-cookie here, except if we want to insert only on POST
1936 * requests and this one isn't. Note that servers which don't have cookies
1937 * (eg: some backup servers) will return a full cookie removal request.
1938 */
1939 if (!objt_server(s->target)->cookie) {
1940 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001941 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001942 s->be->cookie_name);
1943 }
1944 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001945 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946
1947 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1948 /* emit last_date, which is mandatory */
1949 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1950 s30tob64((date.tv_sec+3) >> 2,
1951 trash.area + trash.data);
1952 trash.data += 5;
1953
1954 if (s->be->cookie_maxlife) {
1955 /* emit first_date, which is either the original one or
1956 * the current date.
1957 */
1958 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1959 s30tob64(txn->cookie_first_date ?
1960 txn->cookie_first_date >> 2 :
1961 (date.tv_sec+3) >> 2,
1962 trash.area + trash.data);
1963 trash.data += 5;
1964 }
1965 }
1966 chunk_appendf(&trash, "; path=/");
1967 }
1968
1969 if (s->be->cookie_domain)
1970 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1971
1972 if (s->be->ck_opts & PR_CK_HTTPONLY)
1973 chunk_appendf(&trash, "; HttpOnly");
1974
1975 if (s->be->ck_opts & PR_CK_SECURE)
1976 chunk_appendf(&trash, "; Secure");
1977
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001978 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001979 goto return_bad_resp;
1980
1981 txn->flags &= ~TX_SCK_MASK;
1982 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1983 /* the server did not change, only the date was updated */
1984 txn->flags |= TX_SCK_UPDATED;
1985 else
1986 txn->flags |= TX_SCK_INSERTED;
1987
1988 /* Here, we will tell an eventual cache on the client side that we don't
1989 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1990 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1991 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1992 */
1993 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1994
1995 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1996
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001997 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001998 goto return_bad_resp;
1999 }
2000 }
2001
2002 /*
2003 * Check if result will be cacheable with a cookie.
2004 * We'll block the response if security checks have caught
2005 * nasty things such as a cacheable cookie.
2006 */
2007 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2008 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2009 (s->be->options & PR_O_CHK_CACHE)) {
2010 /* we're in presence of a cacheable response containing
2011 * a set-cookie header. We'll block it as requested by
2012 * the 'checkcache' option, and send an alert.
2013 */
2014 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002015 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002016
Olivier Houcharda798bf52019-03-08 18:52:00 +01002017 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2018 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002020 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002021
2022 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2023 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2024 send_log(s->be, LOG_ALERT,
2025 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2026 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2027 goto return_srv_prx_502;
2028 }
2029
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002030 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002031 /* Always enter in the body analyzer */
2032 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2033 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2034
2035 /* if the user wants to log as soon as possible, without counting
2036 * bytes from the server, then this is the right moment. We have
2037 * to temporarily assign bytes_out to log what we currently have.
2038 */
2039 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2040 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002041 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002042 s->do_log(s);
2043 s->logs.bytes_out = 0;
2044 }
2045 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002046
2047 return_bad_resp:
2048 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002049 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002050 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002051 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002052 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002053
2054 return_srv_prx_502:
2055 rep->analysers &= AN_RES_FLT_END;
2056 txn->status = 502;
2057 s->logs.t_data = -1; /* was not a valid response */
2058 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002059 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002060 if (!(s->flags & SF_ERR_MASK))
2061 s->flags |= SF_ERR_PRXCOND;
2062 if (!(s->flags & SF_FINST_MASK))
2063 s->flags |= SF_FINST_H;
2064 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002065}
2066
2067/* This function is an analyser which forwards response body (including chunk
2068 * sizes if any). It is called as soon as we must forward, even if we forward
2069 * zero byte. The only situation where it must not be called is when we're in
2070 * tunnel mode and we want to forward till the close. It's used both to forward
2071 * remaining data and to resync after end of body. It expects the msg_state to
2072 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2073 * read more data, or 1 once we can go on with next request or end the stream.
2074 *
2075 * It is capable of compressing response data both in content-length mode and
2076 * in chunked mode. The state machines follows different flows depending on
2077 * whether content-length and chunked modes are used, since there are no
2078 * trailers in content-length :
2079 *
2080 * chk-mode cl-mode
2081 * ,----- BODY -----.
2082 * / \
2083 * V size > 0 V chk-mode
2084 * .--> SIZE -------------> DATA -------------> CRLF
2085 * | | size == 0 | last byte |
2086 * | v final crlf v inspected |
2087 * | TRAILERS -----------> DONE |
2088 * | |
2089 * `----------------------------------------------'
2090 *
2091 * Compression only happens in the DATA state, and must be flushed in final
2092 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2093 * is performed at once on final states for all bytes parsed, or when leaving
2094 * on missing data.
2095 */
2096int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2097{
2098 struct session *sess = s->sess;
2099 struct http_txn *txn = s->txn;
2100 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002101 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002102 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002103
2104 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2105 now_ms, __FUNCTION__,
2106 s,
2107 res,
2108 res->rex, res->wex,
2109 res->flags,
2110 ci_data(res),
2111 res->analysers);
2112
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002113 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002114
2115 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002116 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002117 /* Output closed while we were sending data. We must abort and
2118 * wake the other side up.
2119 */
2120 msg->err_state = msg->msg_state;
2121 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002122 htx_end_response(s);
2123 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124 return 1;
2125 }
2126
Christopher Faulet9768c262018-10-22 09:34:31 +02002127 if (msg->msg_state == HTTP_MSG_BODY)
2128 msg->msg_state = HTTP_MSG_DATA;
2129
Christopher Faulete0768eb2018-10-03 16:38:02 +02002130 /* in most states, we should abort in case of early close */
2131 channel_auto_close(res);
2132
Christopher Faulete0768eb2018-10-03 16:38:02 +02002133 if (res->to_forward) {
Christopher Fauletf52170d2019-03-08 15:45:26 +01002134 if (res->to_forward == CHN_INFINITE_FORWARD) {
2135 if (res->flags & CF_SHUTR) {
2136 msg->msg_state = HTTP_MSG_DONE;
2137 res->to_forward = 0;
2138 goto done;
2139 }
2140 }
2141 else {
2142 /* We can't process the buffer's contents yet */
2143 res->flags |= CF_WAKE_WRITE;
2144 goto missing_data_or_waiting;
2145 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002146 }
2147
Christopher Faulet9768c262018-10-22 09:34:31 +02002148 if (msg->msg_state >= HTTP_MSG_DONE)
2149 goto done;
2150
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002151 /* Forward input data. We get it by removing all outgoing data not
2152 * forwarded yet from HTX data size. If there are some data filters, we
2153 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002154 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002155 if (HAS_RSP_DATA_FILTERS(s)) {
2156 ret = flt_http_payload(s, msg, htx->data);
2157 if (ret < 0)
2158 goto return_bad_res;
2159 c_adv(res, ret);
2160 if (htx->data != co_data(res) || htx->extra)
2161 goto missing_data_or_waiting;
2162 }
2163 else {
2164 c_adv(res, htx->data - co_data(res));
Christopher Fauletf52170d2019-03-08 15:45:26 +01002165 if (msg->flags & HTTP_MSGF_XFER_LEN)
2166 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002167 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002168
2169 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2170 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002171 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002172 msg->msg_state = HTTP_MSG_TUNNEL;
2173 goto done;
2174 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002175 }
2176
Christopher Faulet9768c262018-10-22 09:34:31 +02002177 /* Check if the end-of-message is reached and if so, switch the message
2178 * in HTTP_MSG_DONE state.
2179 */
2180 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2181 goto missing_data_or_waiting;
2182
2183 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01002184 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002185
2186 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002188 channel_dont_close(res);
2189
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002190 if (HAS_RSP_DATA_FILTERS(s)) {
2191 ret = flt_http_end(s, msg);
2192 if (ret <= 0) {
2193 if (!ret)
2194 goto missing_data_or_waiting;
2195 goto return_bad_res;
2196 }
2197 }
2198
Christopher Fauletf2824e62018-10-01 12:12:37 +02002199 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002201 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002202 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2203 if (res->flags & CF_SHUTW) {
2204 /* response errors are most likely due to the
2205 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002206 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002208 goto return_bad_res;
2209 }
2210 return 1;
2211 }
2212 return 0;
2213
2214 missing_data_or_waiting:
2215 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002216 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217
Christopher Faulet47365272018-10-31 17:40:50 +01002218 if (htx->flags & HTX_FL_PARSING_ERROR)
2219 goto return_bad_res;
2220
Christopher Faulete0768eb2018-10-03 16:38:02 +02002221 /* stop waiting for data if the input is closed before the end. If the
2222 * client side was already closed, it means that the client has aborted,
2223 * so we don't want to count this as a server abort. Otherwise it's a
2224 * server abort.
2225 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002226 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002228 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002229 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002230 if (htx_is_empty(htx))
2231 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 }
2233
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 /* When TE: chunked is used, we need to get there again to parse
2235 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002236 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2237 * are filters registered on the stream, we don't want to forward a
2238 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002239 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002240 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 channel_dont_close(res);
2242
2243 /* We know that more data are expected, but we couldn't send more that
2244 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2245 * system knows it must not set a PUSH on this first part. Interactive
2246 * modes are already handled by the stream sock layer. We must not do
2247 * this in content-length mode because it could present the MSG_MORE
2248 * flag with the last block of forwarded data, which would cause an
2249 * additional delay to be observed by the receiver.
2250 */
2251 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2252 res->flags |= CF_EXPECT_MORE;
2253
2254 /* the stream handler will take care of timeouts and errors */
2255 return 0;
2256
Christopher Faulet93e02d82019-03-08 14:18:50 +01002257 return_srv_abort:
2258 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2259 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002261 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2262 if (!(s->flags & SF_ERR_MASK))
2263 s->flags |= SF_ERR_SRVCL;
2264 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265
Christopher Faulet93e02d82019-03-08 14:18:50 +01002266 return_cli_abort:
2267 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2268 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002270 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2271 if (!(s->flags & SF_ERR_MASK))
2272 s->flags |= SF_ERR_CLICL;
2273 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 return_bad_res:
2276 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2277 if (objt_server(s->target)) {
2278 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2279 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2280 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002281 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002282 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283
Christopher Faulet93e02d82019-03-08 14:18:50 +01002284 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 txn->rsp.err_state = txn->rsp.msg_state;
2286 txn->rsp.msg_state = HTTP_MSG_ERROR;
2287 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002288 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002289 res->analysers &= AN_RES_FLT_END;
2290 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 +02002291 if (!(s->flags & SF_FINST_MASK))
2292 s->flags |= SF_FINST_D;
2293 return 0;
2294}
2295
Christopher Faulet0f226952018-10-22 09:29:56 +02002296void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002297{
2298 struct proxy *fe = strm_fe(s);
2299 int tmp = TX_CON_WANT_CLO;
2300
2301 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2302 tmp = TX_CON_WANT_TUN;
2303
2304 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002305 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002306}
2307
2308/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002309 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002310 * as too large a request to build a valid response.
2311 */
2312int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2313{
Christopher Faulet99daf282018-11-28 22:58:13 +01002314 struct channel *req = &s->req;
2315 struct channel *res = &s->res;
2316 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002317 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002318 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002319 struct ist status, reason, location;
2320 unsigned int flags;
2321 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002322
2323 chunk = alloc_trash_chunk();
2324 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002325 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002326
Christopher Faulet99daf282018-11-28 22:58:13 +01002327 /*
2328 * Create the location
2329 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002330 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002331 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002332 case REDIRECT_TYPE_SCHEME: {
2333 struct http_hdr_ctx ctx;
2334 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002335
Christopher Faulet99daf282018-11-28 22:58:13 +01002336 host = ist("");
2337 ctx.blk = NULL;
2338 if (http_find_header(htx, ist("Host"), &ctx, 0))
2339 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002340
Christopher Faulet99daf282018-11-28 22:58:13 +01002341 sl = http_find_stline(htx);
2342 path = http_get_path(htx_sl_req_uri(sl));
2343 /* build message using path */
2344 if (path.ptr) {
2345 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2346 int qs = 0;
2347 while (qs < path.len) {
2348 if (*(path.ptr + qs) == '?') {
2349 path.len = qs;
2350 break;
2351 }
2352 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354 }
2355 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 else
2357 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358
Christopher Faulet99daf282018-11-28 22:58:13 +01002359 if (rule->rdr_str) { /* this is an old "redirect" rule */
2360 /* add scheme */
2361 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2362 goto fail;
2363 }
2364 else {
2365 /* add scheme with executing log format */
2366 chunk->data += build_logline(s, chunk->area + chunk->data,
2367 chunk->size - chunk->data,
2368 &rule->rdr_fmt);
2369 }
2370 /* add "://" + host + path */
2371 if (!chunk_memcat(chunk, "://", 3) ||
2372 !chunk_memcat(chunk, host.ptr, host.len) ||
2373 !chunk_memcat(chunk, path.ptr, path.len))
2374 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002375
Christopher Faulet99daf282018-11-28 22:58:13 +01002376 /* append a slash at the end of the location if needed and missing */
2377 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2378 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2379 if (chunk->data + 1 >= chunk->size)
2380 goto fail;
2381 chunk->area[chunk->data++] = '/';
2382 }
2383 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002384 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385
Christopher Faulet99daf282018-11-28 22:58:13 +01002386 case REDIRECT_TYPE_PREFIX: {
2387 struct ist path;
2388
2389 sl = http_find_stline(htx);
2390 path = http_get_path(htx_sl_req_uri(sl));
2391 /* build message using path */
2392 if (path.ptr) {
2393 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2394 int qs = 0;
2395 while (qs < path.len) {
2396 if (*(path.ptr + qs) == '?') {
2397 path.len = qs;
2398 break;
2399 }
2400 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402 }
2403 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 else
2405 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 if (rule->rdr_str) { /* this is an old "redirect" rule */
2408 /* add prefix. Note that if prefix == "/", we don't want to
2409 * add anything, otherwise it makes it hard for the user to
2410 * configure a self-redirection.
2411 */
2412 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2413 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2414 goto fail;
2415 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002417 else {
2418 /* add prefix with executing log format */
2419 chunk->data += build_logline(s, chunk->area + chunk->data,
2420 chunk->size - chunk->data,
2421 &rule->rdr_fmt);
2422 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 /* add path */
2425 if (!chunk_memcat(chunk, path.ptr, path.len))
2426 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427
Christopher Faulet99daf282018-11-28 22:58:13 +01002428 /* append a slash at the end of the location if needed and missing */
2429 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2430 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2431 if (chunk->data + 1 >= chunk->size)
2432 goto fail;
2433 chunk->area[chunk->data++] = '/';
2434 }
2435 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002436 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 case REDIRECT_TYPE_LOCATION:
2438 default:
2439 if (rule->rdr_str) { /* this is an old "redirect" rule */
2440 /* add location */
2441 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2442 goto fail;
2443 }
2444 else {
2445 /* add location with executing log format */
2446 chunk->data += build_logline(s, chunk->area + chunk->data,
2447 chunk->size - chunk->data,
2448 &rule->rdr_fmt);
2449 }
2450 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 location = ist2(chunk->area, chunk->data);
2453
2454 /*
2455 * Create the 30x response
2456 */
2457 switch (rule->code) {
2458 case 308:
2459 status = ist("308");
2460 reason = ist("Permanent Redirect");
2461 break;
2462 case 307:
2463 status = ist("307");
2464 reason = ist("Temporary Redirect");
2465 break;
2466 case 303:
2467 status = ist("303");
2468 reason = ist("See Other");
2469 break;
2470 case 301:
2471 status = ist("301");
2472 reason = ist("Moved Permanently");
2473 break;
2474 case 302:
2475 default:
2476 status = ist("302");
2477 reason = ist("Found");
2478 break;
2479 }
2480
2481 htx = htx_from_buf(&res->buf);
2482 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2483 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2484 if (!sl)
2485 goto fail;
2486 sl->info.res.status = rule->code;
2487 s->txn->status = rule->code;
2488
2489 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2490 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2491 !htx_add_header(htx, ist("Location"), location))
2492 goto fail;
2493
2494 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2495 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2496 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002497 }
2498
2499 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002500 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2501 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 }
2503
Christopher Faulet99daf282018-11-28 22:58:13 +01002504 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2505 goto fail;
2506
Christopher Fauletf2824e62018-10-01 12:12:37 +02002507 /* let's log the request time */
2508 s->logs.tv_request = now;
2509
Christopher Faulet99daf282018-11-28 22:58:13 +01002510 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002511 c_adv(res, data);
2512 res->total += data;
2513
2514 channel_auto_read(req);
2515 channel_abort(req);
2516 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002517 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002518
2519 res->wex = tick_add_ifset(now_ms, res->wto);
2520 channel_auto_read(res);
2521 channel_auto_close(res);
2522 channel_shutr_now(res);
2523
2524 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002525
2526 if (!(s->flags & SF_ERR_MASK))
2527 s->flags |= SF_ERR_LOCAL;
2528 if (!(s->flags & SF_FINST_MASK))
2529 s->flags |= SF_FINST_R;
2530
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 free_trash_chunk(chunk);
2532 return 1;
2533
2534 fail:
2535 /* If an error occurred, remove the incomplete HTTP response from the
2536 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002537 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002538 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002540}
2541
Christopher Faulet72333522018-10-24 11:25:02 +02002542int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2543 struct ist name, const char *str, struct my_regex *re, int action)
2544{
2545 struct http_hdr_ctx ctx;
2546 struct buffer *output = get_trash_chunk();
2547
2548 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2549 ctx.blk = NULL;
2550 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2551 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2552 continue;
2553
2554 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2555 if (output->data == -1)
2556 return -1;
2557 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2558 return -1;
2559 }
2560 return 0;
2561}
2562
2563static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2564 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2565{
2566 struct buffer *replace;
2567 int ret = -1;
2568
2569 replace = alloc_trash_chunk();
2570 if (!replace)
2571 goto leave;
2572
2573 replace->data = build_logline(s, replace->area, replace->size, fmt);
2574 if (replace->data >= replace->size - 1)
2575 goto leave;
2576
2577 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2578
2579 leave:
2580 free_trash_chunk(replace);
2581 return ret;
2582}
2583
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002584
2585/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2586 * on success and -1 on error. The response channel is updated accordingly.
2587 */
2588static int htx_reply_103_early_hints(struct channel *res)
2589{
2590 struct htx *htx = htx_from_buf(&res->buf);
2591 size_t data;
2592
2593 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2594 /* If an error occurred during an Early-hint rule,
2595 * remove the incomplete HTTP 103 response from the
2596 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002597 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002598 return -1;
2599 }
2600
2601 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002602 c_adv(res, data);
2603 res->total += data;
2604 return 0;
2605}
2606
Christopher Faulet6eb92892018-11-15 16:39:29 +01002607/*
2608 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2609 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002610 * If <early_hints> is 0, it is starts a new response by adding the start
2611 * line. If an error occurred -1 is returned. On success 0 is returned. The
2612 * channel is not updated here. It must be done calling the function
2613 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002614 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002615static 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 +01002616{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002617 struct channel *res = &s->res;
2618 struct htx *htx = htx_from_buf(&res->buf);
2619 struct buffer *value = alloc_trash_chunk();
2620
Christopher Faulet6eb92892018-11-15 16:39:29 +01002621 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 struct htx_sl *sl;
2623 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2624 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2625
2626 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2627 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2628 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002629 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002630 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002631 }
2632
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002633 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2634 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002635 goto fail;
2636
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002639
2640 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002641 /* If an error occurred during an Early-hint rule, remove the incomplete
2642 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002643 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002644 free_trash_chunk(value);
2645 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002646}
2647
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002648/* This function executes one of the set-{method,path,query,uri} actions. It
2649 * takes the string from the variable 'replace' with length 'len', then modifies
2650 * the relevant part of the request line accordingly. Then it updates various
2651 * pointers to the next elements which were moved, and the total buffer length.
2652 * It finds the action to be performed in p[2], previously filled by function
2653 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2654 * error, though this can be revisited when this code is finally exploited.
2655 *
2656 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2657 * query string and 3 to replace uri.
2658 *
2659 * In query string case, the mark question '?' must be set at the start of the
2660 * string by the caller, event if the replacement query string is empty.
2661 */
2662int htx_req_replace_stline(int action, const char *replace, int len,
2663 struct proxy *px, struct stream *s)
2664{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002665 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002666
2667 switch (action) {
2668 case 0: // method
2669 if (!http_replace_req_meth(htx, ist2(replace, len)))
2670 return -1;
2671 break;
2672
2673 case 1: // path
2674 if (!http_replace_req_path(htx, ist2(replace, len)))
2675 return -1;
2676 break;
2677
2678 case 2: // query
2679 if (!http_replace_req_query(htx, ist2(replace, len)))
2680 return -1;
2681 break;
2682
2683 case 3: // uri
2684 if (!http_replace_req_uri(htx, ist2(replace, len)))
2685 return -1;
2686 break;
2687
2688 default:
2689 return -1;
2690 }
2691 return 0;
2692}
2693
2694/* This function replace the HTTP status code and the associated message. The
2695 * variable <status> contains the new status code. This function never fails.
2696 */
2697void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2698{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002699 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002700 char *res;
2701
2702 chunk_reset(&trash);
2703 res = ultoa_o(status, trash.area, trash.size);
2704 trash.data = res - trash.area;
2705
2706 /* Do we have a custom reason format string? */
2707 if (reason == NULL)
2708 reason = http_get_reason(status);
2709
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002710 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002711 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2712}
2713
Christopher Faulet3e964192018-10-24 11:39:23 +02002714/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2715 * transaction <txn>. Returns the verdict of the first rule that prevents
2716 * further processing of the request (auth, deny, ...), and defaults to
2717 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2718 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2719 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2720 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2721 * status.
2722 */
2723static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2724 struct stream *s, int *deny_status)
2725{
2726 struct session *sess = strm_sess(s);
2727 struct http_txn *txn = s->txn;
2728 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002729 struct act_rule *rule;
2730 struct http_hdr_ctx ctx;
2731 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002732 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2733 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002734 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002735
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002736 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002737
2738 /* If "the current_rule_list" match the executed rule list, we are in
2739 * resume condition. If a resume is needed it is always in the action
2740 * and never in the ACL or converters. In this case, we initialise the
2741 * current rule, and go to the action execution point.
2742 */
2743 if (s->current_rule) {
2744 rule = s->current_rule;
2745 s->current_rule = NULL;
2746 if (s->current_rule_list == rules)
2747 goto resume_execution;
2748 }
2749 s->current_rule_list = rules;
2750
2751 list_for_each_entry(rule, rules, list) {
2752 /* check optional condition */
2753 if (rule->cond) {
2754 int ret;
2755
2756 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2757 ret = acl_pass(ret);
2758
2759 if (rule->cond->pol == ACL_COND_UNLESS)
2760 ret = !ret;
2761
2762 if (!ret) /* condition not matched */
2763 continue;
2764 }
2765
2766 act_flags |= ACT_FLAG_FIRST;
2767 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002768 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2769 early_hints = 0;
2770 if (htx_reply_103_early_hints(&s->res) == -1) {
2771 rule_ret = HTTP_RULE_RES_BADREQ;
2772 goto end;
2773 }
2774 }
2775
Christopher Faulet3e964192018-10-24 11:39:23 +02002776 switch (rule->action) {
2777 case ACT_ACTION_ALLOW:
2778 rule_ret = HTTP_RULE_RES_STOP;
2779 goto end;
2780
2781 case ACT_ACTION_DENY:
2782 if (deny_status)
2783 *deny_status = rule->deny_status;
2784 rule_ret = HTTP_RULE_RES_DENY;
2785 goto end;
2786
2787 case ACT_HTTP_REQ_TARPIT:
2788 txn->flags |= TX_CLTARPIT;
2789 if (deny_status)
2790 *deny_status = rule->deny_status;
2791 rule_ret = HTTP_RULE_RES_DENY;
2792 goto end;
2793
2794 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002795 /* Auth might be performed on regular http-req rules as well as on stats */
2796 auth_realm = rule->arg.auth.realm;
2797 if (!auth_realm) {
2798 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2799 auth_realm = STATS_DEFAULT_REALM;
2800 else
2801 auth_realm = px->id;
2802 }
2803 /* send 401/407 depending on whether we use a proxy or not. We still
2804 * count one error, because normal browsing won't significantly
2805 * increase the counter but brute force attempts will.
2806 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002807 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002808 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2809 rule_ret = HTTP_RULE_RES_BADREQ;
2810 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002811 goto end;
2812
2813 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002814 rule_ret = HTTP_RULE_RES_DONE;
2815 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2816 rule_ret = HTTP_RULE_RES_BADREQ;
2817 goto end;
2818
2819 case ACT_HTTP_SET_NICE:
2820 s->task->nice = rule->arg.nice;
2821 break;
2822
2823 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002824 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002825 break;
2826
2827 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002828 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002829 break;
2830
2831 case ACT_HTTP_SET_LOGL:
2832 s->logs.level = rule->arg.loglevel;
2833 break;
2834
2835 case ACT_HTTP_REPLACE_HDR:
2836 case ACT_HTTP_REPLACE_VAL:
2837 if (htx_transform_header(s, &s->req, htx,
2838 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2839 &rule->arg.hdr_add.fmt,
2840 &rule->arg.hdr_add.re, rule->action)) {
2841 rule_ret = HTTP_RULE_RES_BADREQ;
2842 goto end;
2843 }
2844 break;
2845
2846 case ACT_HTTP_DEL_HDR:
2847 /* remove all occurrences of the header */
2848 ctx.blk = NULL;
2849 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2850 http_remove_header(htx, &ctx);
2851 break;
2852
2853 case ACT_HTTP_SET_HDR:
2854 case ACT_HTTP_ADD_HDR: {
2855 /* The scope of the trash buffer must be limited to this function. The
2856 * build_logline() function can execute a lot of other function which
2857 * can use the trash buffer. So for limiting the scope of this global
2858 * buffer, we build first the header value using build_logline, and
2859 * after we store the header name.
2860 */
2861 struct buffer *replace;
2862 struct ist n, v;
2863
2864 replace = alloc_trash_chunk();
2865 if (!replace) {
2866 rule_ret = HTTP_RULE_RES_BADREQ;
2867 goto end;
2868 }
2869
2870 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2871 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2872 v = ist2(replace->area, replace->data);
2873
2874 if (rule->action == ACT_HTTP_SET_HDR) {
2875 /* remove all occurrences of the header */
2876 ctx.blk = NULL;
2877 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2878 http_remove_header(htx, &ctx);
2879 }
2880
2881 if (!http_add_header(htx, n, v)) {
2882 static unsigned char rate_limit = 0;
2883
2884 if ((rate_limit++ & 255) == 0) {
2885 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);
2886 }
2887
Olivier Houcharda798bf52019-03-08 18:52:00 +01002888 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002889 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002890 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002891 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002892 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002893 }
2894 free_trash_chunk(replace);
2895 break;
2896 }
2897
2898 case ACT_HTTP_DEL_ACL:
2899 case ACT_HTTP_DEL_MAP: {
2900 struct pat_ref *ref;
2901 struct buffer *key;
2902
2903 /* collect reference */
2904 ref = pat_ref_lookup(rule->arg.map.ref);
2905 if (!ref)
2906 continue;
2907
2908 /* allocate key */
2909 key = alloc_trash_chunk();
2910 if (!key) {
2911 rule_ret = HTTP_RULE_RES_BADREQ;
2912 goto end;
2913 }
2914
2915 /* collect key */
2916 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2917 key->area[key->data] = '\0';
2918
2919 /* perform update */
2920 /* returned code: 1=ok, 0=ko */
2921 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2922 pat_ref_delete(ref, key->area);
2923 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2924
2925 free_trash_chunk(key);
2926 break;
2927 }
2928
2929 case ACT_HTTP_ADD_ACL: {
2930 struct pat_ref *ref;
2931 struct buffer *key;
2932
2933 /* collect reference */
2934 ref = pat_ref_lookup(rule->arg.map.ref);
2935 if (!ref)
2936 continue;
2937
2938 /* allocate key */
2939 key = alloc_trash_chunk();
2940 if (!key) {
2941 rule_ret = HTTP_RULE_RES_BADREQ;
2942 goto end;
2943 }
2944
2945 /* collect key */
2946 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2947 key->area[key->data] = '\0';
2948
2949 /* perform update */
2950 /* add entry only if it does not already exist */
2951 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2952 if (pat_ref_find_elt(ref, key->area) == NULL)
2953 pat_ref_add(ref, key->area, NULL, NULL);
2954 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2955
2956 free_trash_chunk(key);
2957 break;
2958 }
2959
2960 case ACT_HTTP_SET_MAP: {
2961 struct pat_ref *ref;
2962 struct buffer *key, *value;
2963
2964 /* collect reference */
2965 ref = pat_ref_lookup(rule->arg.map.ref);
2966 if (!ref)
2967 continue;
2968
2969 /* allocate key */
2970 key = alloc_trash_chunk();
2971 if (!key) {
2972 rule_ret = HTTP_RULE_RES_BADREQ;
2973 goto end;
2974 }
2975
2976 /* allocate value */
2977 value = alloc_trash_chunk();
2978 if (!value) {
2979 free_trash_chunk(key);
2980 rule_ret = HTTP_RULE_RES_BADREQ;
2981 goto end;
2982 }
2983
2984 /* collect key */
2985 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2986 key->area[key->data] = '\0';
2987
2988 /* collect value */
2989 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2990 value->area[value->data] = '\0';
2991
2992 /* perform update */
2993 if (pat_ref_find_elt(ref, key->area) != NULL)
2994 /* update entry if it exists */
2995 pat_ref_set(ref, key->area, value->area, NULL);
2996 else
2997 /* insert a new entry */
2998 pat_ref_add(ref, key->area, value->area, NULL);
2999
3000 free_trash_chunk(key);
3001 free_trash_chunk(value);
3002 break;
3003 }
3004
3005 case ACT_HTTP_EARLY_HINT:
3006 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3007 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003008 early_hints = htx_add_early_hint_header(s, early_hints,
3009 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003010 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003011 if (early_hints == -1) {
3012 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003013 goto end;
3014 }
3015 break;
3016
3017 case ACT_CUSTOM:
3018 if ((s->req.flags & CF_READ_ERROR) ||
3019 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3020 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3021 (px->options & PR_O_ABRT_CLOSE)))
3022 act_flags |= ACT_FLAG_FINAL;
3023
3024 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3025 case ACT_RET_ERR:
3026 case ACT_RET_CONT:
3027 break;
3028 case ACT_RET_STOP:
3029 rule_ret = HTTP_RULE_RES_DONE;
3030 goto end;
3031 case ACT_RET_YIELD:
3032 s->current_rule = rule;
3033 rule_ret = HTTP_RULE_RES_YIELD;
3034 goto end;
3035 }
3036 break;
3037
3038 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3039 /* Note: only the first valid tracking parameter of each
3040 * applies.
3041 */
3042
3043 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3044 struct stktable *t;
3045 struct stksess *ts;
3046 struct stktable_key *key;
3047 void *ptr1, *ptr2;
3048
3049 t = rule->arg.trk_ctr.table.t;
3050 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3051 rule->arg.trk_ctr.expr, NULL);
3052
3053 if (key && (ts = stktable_get_entry(t, key))) {
3054 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3055
3056 /* let's count a new HTTP request as it's the first time we do it */
3057 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3058 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3059 if (ptr1 || ptr2) {
3060 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3061
3062 if (ptr1)
3063 stktable_data_cast(ptr1, http_req_cnt)++;
3064
3065 if (ptr2)
3066 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3067 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3068
3069 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3070
3071 /* If data was modified, we need to touch to re-schedule sync */
3072 stktable_touch_local(t, ts, 0);
3073 }
3074
3075 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3076 if (sess->fe != s->be)
3077 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3078 }
3079 }
3080 break;
3081
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003082 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003083 default:
3084 break;
3085 }
3086 }
3087
3088 end:
3089 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003090 if (htx_reply_103_early_hints(&s->res) == -1)
3091 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003092 }
3093
3094 /* we reached the end of the rules, nothing to report */
3095 return rule_ret;
3096}
3097
3098/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3099 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3100 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3101 * is returned, the process can continue the evaluation of next rule list. If
3102 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3103 * is returned, it means the operation could not be processed and a server error
3104 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3105 * deny rule. If *YIELD is returned, the caller must call again the function
3106 * with the same context.
3107 */
3108static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3109 struct stream *s)
3110{
3111 struct session *sess = strm_sess(s);
3112 struct http_txn *txn = s->txn;
3113 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003114 struct act_rule *rule;
3115 struct http_hdr_ctx ctx;
3116 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3117 int act_flags = 0;
3118
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003119 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003120
3121 /* If "the current_rule_list" match the executed rule list, we are in
3122 * resume condition. If a resume is needed it is always in the action
3123 * and never in the ACL or converters. In this case, we initialise the
3124 * current rule, and go to the action execution point.
3125 */
3126 if (s->current_rule) {
3127 rule = s->current_rule;
3128 s->current_rule = NULL;
3129 if (s->current_rule_list == rules)
3130 goto resume_execution;
3131 }
3132 s->current_rule_list = rules;
3133
3134 list_for_each_entry(rule, rules, list) {
3135 /* check optional condition */
3136 if (rule->cond) {
3137 int ret;
3138
3139 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3140 ret = acl_pass(ret);
3141
3142 if (rule->cond->pol == ACL_COND_UNLESS)
3143 ret = !ret;
3144
3145 if (!ret) /* condition not matched */
3146 continue;
3147 }
3148
3149 act_flags |= ACT_FLAG_FIRST;
3150resume_execution:
3151 switch (rule->action) {
3152 case ACT_ACTION_ALLOW:
3153 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3154 goto end;
3155
3156 case ACT_ACTION_DENY:
3157 txn->flags |= TX_SVDENY;
3158 rule_ret = HTTP_RULE_RES_STOP;
3159 goto end;
3160
3161 case ACT_HTTP_SET_NICE:
3162 s->task->nice = rule->arg.nice;
3163 break;
3164
3165 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003166 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003167 break;
3168
3169 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003170 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003171 break;
3172
3173 case ACT_HTTP_SET_LOGL:
3174 s->logs.level = rule->arg.loglevel;
3175 break;
3176
3177 case ACT_HTTP_REPLACE_HDR:
3178 case ACT_HTTP_REPLACE_VAL:
3179 if (htx_transform_header(s, &s->res, htx,
3180 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3181 &rule->arg.hdr_add.fmt,
3182 &rule->arg.hdr_add.re, rule->action)) {
3183 rule_ret = HTTP_RULE_RES_BADREQ;
3184 goto end;
3185 }
3186 break;
3187
3188 case ACT_HTTP_DEL_HDR:
3189 /* remove all occurrences of the header */
3190 ctx.blk = NULL;
3191 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3192 http_remove_header(htx, &ctx);
3193 break;
3194
3195 case ACT_HTTP_SET_HDR:
3196 case ACT_HTTP_ADD_HDR: {
3197 struct buffer *replace;
3198 struct ist n, v;
3199
3200 replace = alloc_trash_chunk();
3201 if (!replace) {
3202 rule_ret = HTTP_RULE_RES_BADREQ;
3203 goto end;
3204 }
3205
3206 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3207 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3208 v = ist2(replace->area, replace->data);
3209
3210 if (rule->action == ACT_HTTP_SET_HDR) {
3211 /* remove all occurrences of the header */
3212 ctx.blk = NULL;
3213 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3214 http_remove_header(htx, &ctx);
3215 }
3216
3217 if (!http_add_header(htx, n, v)) {
3218 static unsigned char rate_limit = 0;
3219
3220 if ((rate_limit++ & 255) == 0) {
3221 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);
3222 }
3223
Olivier Houcharda798bf52019-03-08 18:52:00 +01003224 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003225 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003226 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003227 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003228 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003229 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003230 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003231 }
3232 free_trash_chunk(replace);
3233 break;
3234 }
3235
3236 case ACT_HTTP_DEL_ACL:
3237 case ACT_HTTP_DEL_MAP: {
3238 struct pat_ref *ref;
3239 struct buffer *key;
3240
3241 /* collect reference */
3242 ref = pat_ref_lookup(rule->arg.map.ref);
3243 if (!ref)
3244 continue;
3245
3246 /* allocate key */
3247 key = alloc_trash_chunk();
3248 if (!key) {
3249 rule_ret = HTTP_RULE_RES_BADREQ;
3250 goto end;
3251 }
3252
3253 /* collect key */
3254 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3255 key->area[key->data] = '\0';
3256
3257 /* perform update */
3258 /* returned code: 1=ok, 0=ko */
3259 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3260 pat_ref_delete(ref, key->area);
3261 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3262
3263 free_trash_chunk(key);
3264 break;
3265 }
3266
3267 case ACT_HTTP_ADD_ACL: {
3268 struct pat_ref *ref;
3269 struct buffer *key;
3270
3271 /* collect reference */
3272 ref = pat_ref_lookup(rule->arg.map.ref);
3273 if (!ref)
3274 continue;
3275
3276 /* allocate key */
3277 key = alloc_trash_chunk();
3278 if (!key) {
3279 rule_ret = HTTP_RULE_RES_BADREQ;
3280 goto end;
3281 }
3282
3283 /* collect key */
3284 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3285 key->area[key->data] = '\0';
3286
3287 /* perform update */
3288 /* check if the entry already exists */
3289 if (pat_ref_find_elt(ref, key->area) == NULL)
3290 pat_ref_add(ref, key->area, NULL, NULL);
3291
3292 free_trash_chunk(key);
3293 break;
3294 }
3295
3296 case ACT_HTTP_SET_MAP: {
3297 struct pat_ref *ref;
3298 struct buffer *key, *value;
3299
3300 /* collect reference */
3301 ref = pat_ref_lookup(rule->arg.map.ref);
3302 if (!ref)
3303 continue;
3304
3305 /* allocate key */
3306 key = alloc_trash_chunk();
3307 if (!key) {
3308 rule_ret = HTTP_RULE_RES_BADREQ;
3309 goto end;
3310 }
3311
3312 /* allocate value */
3313 value = alloc_trash_chunk();
3314 if (!value) {
3315 free_trash_chunk(key);
3316 rule_ret = HTTP_RULE_RES_BADREQ;
3317 goto end;
3318 }
3319
3320 /* collect key */
3321 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3322 key->area[key->data] = '\0';
3323
3324 /* collect value */
3325 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3326 value->area[value->data] = '\0';
3327
3328 /* perform update */
3329 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3330 if (pat_ref_find_elt(ref, key->area) != NULL)
3331 /* update entry if it exists */
3332 pat_ref_set(ref, key->area, value->area, NULL);
3333 else
3334 /* insert a new entry */
3335 pat_ref_add(ref, key->area, value->area, NULL);
3336 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3337 free_trash_chunk(key);
3338 free_trash_chunk(value);
3339 break;
3340 }
3341
3342 case ACT_HTTP_REDIR:
3343 rule_ret = HTTP_RULE_RES_DONE;
3344 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3345 rule_ret = HTTP_RULE_RES_BADREQ;
3346 goto end;
3347
3348 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3349 /* Note: only the first valid tracking parameter of each
3350 * applies.
3351 */
3352 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3353 struct stktable *t;
3354 struct stksess *ts;
3355 struct stktable_key *key;
3356 void *ptr;
3357
3358 t = rule->arg.trk_ctr.table.t;
3359 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3360 rule->arg.trk_ctr.expr, NULL);
3361
3362 if (key && (ts = stktable_get_entry(t, key))) {
3363 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3364
3365 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3366
3367 /* let's count a new HTTP request as it's the first time we do it */
3368 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3369 if (ptr)
3370 stktable_data_cast(ptr, http_req_cnt)++;
3371
3372 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3373 if (ptr)
3374 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3375 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3376
3377 /* When the client triggers a 4xx from the server, it's most often due
3378 * to a missing object or permission. These events should be tracked
3379 * because if they happen often, it may indicate a brute force or a
3380 * vulnerability scan. Normally this is done when receiving the response
3381 * but here we're tracking after this ought to have been done so we have
3382 * to do it on purpose.
3383 */
3384 if ((unsigned)(txn->status - 400) < 100) {
3385 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3386 if (ptr)
3387 stktable_data_cast(ptr, http_err_cnt)++;
3388
3389 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3390 if (ptr)
3391 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3392 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3393 }
3394
3395 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3396
3397 /* If data was modified, we need to touch to re-schedule sync */
3398 stktable_touch_local(t, ts, 0);
3399
3400 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3401 if (sess->fe != s->be)
3402 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3403 }
3404 }
3405 break;
3406
3407 case ACT_CUSTOM:
3408 if ((s->req.flags & CF_READ_ERROR) ||
3409 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3410 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3411 (px->options & PR_O_ABRT_CLOSE)))
3412 act_flags |= ACT_FLAG_FINAL;
3413
3414 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3415 case ACT_RET_ERR:
3416 case ACT_RET_CONT:
3417 break;
3418 case ACT_RET_STOP:
3419 rule_ret = HTTP_RULE_RES_STOP;
3420 goto end;
3421 case ACT_RET_YIELD:
3422 s->current_rule = rule;
3423 rule_ret = HTTP_RULE_RES_YIELD;
3424 goto end;
3425 }
3426 break;
3427
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003428 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003429 default:
3430 break;
3431 }
3432 }
3433
3434 end:
3435 /* we reached the end of the rules, nothing to report */
3436 return rule_ret;
3437}
3438
Christopher Faulet33640082018-10-24 11:53:01 +02003439/* Iterate the same filter through all request headers.
3440 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3441 * Since it can manage the switch to another backend, it updates the per-proxy
3442 * DENY stats.
3443 */
3444static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3445{
3446 struct http_txn *txn = s->txn;
3447 struct htx *htx;
3448 struct buffer *hdr = get_trash_chunk();
3449 int32_t pos;
3450
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003451 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003452
3453 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3454 struct htx_blk *blk = htx_get_blk(htx, pos);
3455 enum htx_blk_type type;
3456 struct ist n, v;
3457
3458 next_hdr:
3459 type = htx_get_blk_type(blk);
3460 if (type == HTX_BLK_EOH)
3461 break;
3462 if (type != HTX_BLK_HDR)
3463 continue;
3464
3465 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3466 return 1;
3467 else if (unlikely(txn->flags & TX_CLALLOW) &&
3468 (exp->action == ACT_ALLOW ||
3469 exp->action == ACT_DENY ||
3470 exp->action == ACT_TARPIT))
3471 return 0;
3472
3473 n = htx_get_blk_name(htx, blk);
3474 v = htx_get_blk_value(htx, blk);
3475
Christopher Faulet02e771a2019-02-26 15:36:05 +01003476 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003477 hdr->area[hdr->data++] = ':';
3478 hdr->area[hdr->data++] = ' ';
3479 chunk_memcat(hdr, v.ptr, v.len);
3480
3481 /* Now we have one header in <hdr> */
3482
3483 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3484 struct http_hdr_ctx ctx;
3485 int len;
3486
3487 switch (exp->action) {
3488 case ACT_ALLOW:
3489 txn->flags |= TX_CLALLOW;
3490 goto end;
3491
3492 case ACT_DENY:
3493 txn->flags |= TX_CLDENY;
3494 goto end;
3495
3496 case ACT_TARPIT:
3497 txn->flags |= TX_CLTARPIT;
3498 goto end;
3499
3500 case ACT_REPLACE:
3501 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3502 if (len < 0)
3503 return -1;
3504
3505 http_parse_header(ist2(trash.area, len), &n, &v);
3506 ctx.blk = blk;
3507 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003508 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003509 if (!http_replace_header(htx, &ctx, n, v))
3510 return -1;
3511 if (!ctx.blk)
3512 goto end;
3513 pos = htx_get_blk_pos(htx, blk);
3514 break;
3515
3516 case ACT_REMOVE:
3517 ctx.blk = blk;
3518 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003519 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003520 if (!http_remove_header(htx, &ctx))
3521 return -1;
3522 if (!ctx.blk)
3523 goto end;
3524 pos = htx_get_blk_pos(htx, blk);
3525 goto next_hdr;
3526
3527 }
3528 }
3529 }
3530 end:
3531 return 0;
3532}
3533
3534/* Apply the filter to the request line.
3535 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3536 * or -1 if a replacement resulted in an invalid request line.
3537 * Since it can manage the switch to another backend, it updates the per-proxy
3538 * DENY stats.
3539 */
3540static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3541{
3542 struct http_txn *txn = s->txn;
3543 struct htx *htx;
3544 struct buffer *reqline = get_trash_chunk();
3545 int done;
3546
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003547 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003548
3549 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3550 return 1;
3551 else if (unlikely(txn->flags & TX_CLALLOW) &&
3552 (exp->action == ACT_ALLOW ||
3553 exp->action == ACT_DENY ||
3554 exp->action == ACT_TARPIT))
3555 return 0;
3556 else if (exp->action == ACT_REMOVE)
3557 return 0;
3558
3559 done = 0;
3560
3561 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3562
3563 /* Now we have the request line between cur_ptr and cur_end */
3564 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003565 struct htx_sl *sl = http_find_stline(htx);
3566 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003567 int len;
3568
3569 switch (exp->action) {
3570 case ACT_ALLOW:
3571 txn->flags |= TX_CLALLOW;
3572 done = 1;
3573 break;
3574
3575 case ACT_DENY:
3576 txn->flags |= TX_CLDENY;
3577 done = 1;
3578 break;
3579
3580 case ACT_TARPIT:
3581 txn->flags |= TX_CLTARPIT;
3582 done = 1;
3583 break;
3584
3585 case ACT_REPLACE:
3586 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3587 if (len < 0)
3588 return -1;
3589
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003590 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3591 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3592 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003593 return -1;
3594 done = 1;
3595 break;
3596 }
3597 }
3598 return done;
3599}
3600
3601/*
3602 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3603 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3604 * unparsable request. Since it can manage the switch to another backend, it
3605 * updates the per-proxy DENY stats.
3606 */
3607static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3608{
3609 struct session *sess = s->sess;
3610 struct http_txn *txn = s->txn;
3611 struct hdr_exp *exp;
3612
3613 for (exp = px->req_exp; exp; exp = exp->next) {
3614 int ret;
3615
3616 /*
3617 * The interleaving of transformations and verdicts
3618 * makes it difficult to decide to continue or stop
3619 * the evaluation.
3620 */
3621
3622 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3623 break;
3624
3625 if ((txn->flags & TX_CLALLOW) &&
3626 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3627 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3628 continue;
3629
3630 /* if this filter had a condition, evaluate it now and skip to
3631 * next filter if the condition does not match.
3632 */
3633 if (exp->cond) {
3634 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3635 ret = acl_pass(ret);
3636 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3637 ret = !ret;
3638
3639 if (!ret)
3640 continue;
3641 }
3642
3643 /* Apply the filter to the request line. */
3644 ret = htx_apply_filter_to_req_line(s, req, exp);
3645 if (unlikely(ret < 0))
3646 return -1;
3647
3648 if (likely(ret == 0)) {
3649 /* The filter did not match the request, it can be
3650 * iterated through all headers.
3651 */
3652 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3653 return -1;
3654 }
3655 }
3656 return 0;
3657}
3658
3659/* Iterate the same filter through all response headers contained in <res>.
3660 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3661 */
3662static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3663{
3664 struct http_txn *txn = s->txn;
3665 struct htx *htx;
3666 struct buffer *hdr = get_trash_chunk();
3667 int32_t pos;
3668
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003669 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003670
3671 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3672 struct htx_blk *blk = htx_get_blk(htx, pos);
3673 enum htx_blk_type type;
3674 struct ist n, v;
3675
3676 next_hdr:
3677 type = htx_get_blk_type(blk);
3678 if (type == HTX_BLK_EOH)
3679 break;
3680 if (type != HTX_BLK_HDR)
3681 continue;
3682
3683 if (unlikely(txn->flags & TX_SVDENY))
3684 return 1;
3685 else if (unlikely(txn->flags & TX_SVALLOW) &&
3686 (exp->action == ACT_ALLOW ||
3687 exp->action == ACT_DENY))
3688 return 0;
3689
3690 n = htx_get_blk_name(htx, blk);
3691 v = htx_get_blk_value(htx, blk);
3692
Christopher Faulet02e771a2019-02-26 15:36:05 +01003693 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003694 hdr->area[hdr->data++] = ':';
3695 hdr->area[hdr->data++] = ' ';
3696 chunk_memcat(hdr, v.ptr, v.len);
3697
3698 /* Now we have one header in <hdr> */
3699
3700 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3701 struct http_hdr_ctx ctx;
3702 int len;
3703
3704 switch (exp->action) {
3705 case ACT_ALLOW:
3706 txn->flags |= TX_SVALLOW;
3707 goto end;
3708 break;
3709
3710 case ACT_DENY:
3711 txn->flags |= TX_SVDENY;
3712 goto end;
3713 break;
3714
3715 case ACT_REPLACE:
3716 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3717 if (len < 0)
3718 return -1;
3719
3720 http_parse_header(ist2(trash.area, len), &n, &v);
3721 ctx.blk = blk;
3722 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003723 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003724 if (!http_replace_header(htx, &ctx, n, v))
3725 return -1;
3726 if (!ctx.blk)
3727 goto end;
3728 pos = htx_get_blk_pos(htx, blk);
3729 break;
3730
3731 case ACT_REMOVE:
3732 ctx.blk = blk;
3733 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003734 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003735 if (!http_remove_header(htx, &ctx))
3736 return -1;
3737 if (!ctx.blk)
3738 goto end;
3739 pos = htx_get_blk_pos(htx, blk);
3740 goto next_hdr;
3741 }
3742 }
3743
3744 }
3745 end:
3746 return 0;
3747}
3748
3749/* Apply the filter to the status line in the response buffer <res>.
3750 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3751 * or -1 if a replacement resulted in an invalid status line.
3752 */
3753static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3754{
3755 struct http_txn *txn = s->txn;
3756 struct htx *htx;
3757 struct buffer *resline = get_trash_chunk();
3758 int done;
3759
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003760 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003761
3762 if (unlikely(txn->flags & TX_SVDENY))
3763 return 1;
3764 else if (unlikely(txn->flags & TX_SVALLOW) &&
3765 (exp->action == ACT_ALLOW ||
3766 exp->action == ACT_DENY))
3767 return 0;
3768 else if (exp->action == ACT_REMOVE)
3769 return 0;
3770
3771 done = 0;
3772 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3773
3774 /* Now we have the status line between cur_ptr and cur_end */
3775 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003776 struct htx_sl *sl = http_find_stline(htx);
3777 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003778 int len;
3779
3780 switch (exp->action) {
3781 case ACT_ALLOW:
3782 txn->flags |= TX_SVALLOW;
3783 done = 1;
3784 break;
3785
3786 case ACT_DENY:
3787 txn->flags |= TX_SVDENY;
3788 done = 1;
3789 break;
3790
3791 case ACT_REPLACE:
3792 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3793 if (len < 0)
3794 return -1;
3795
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003796 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3797 sl->info.res.status = strl2ui(code.ptr, code.len);
3798 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003799 return -1;
3800
3801 done = 1;
3802 return 1;
3803 }
3804 }
3805 return done;
3806}
3807
3808/*
3809 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3810 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3811 * unparsable response.
3812 */
3813static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3814{
3815 struct session *sess = s->sess;
3816 struct http_txn *txn = s->txn;
3817 struct hdr_exp *exp;
3818
3819 for (exp = px->rsp_exp; exp; exp = exp->next) {
3820 int ret;
3821
3822 /*
3823 * The interleaving of transformations and verdicts
3824 * makes it difficult to decide to continue or stop
3825 * the evaluation.
3826 */
3827
3828 if (txn->flags & TX_SVDENY)
3829 break;
3830
3831 if ((txn->flags & TX_SVALLOW) &&
3832 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3833 exp->action == ACT_PASS)) {
3834 exp = exp->next;
3835 continue;
3836 }
3837
3838 /* if this filter had a condition, evaluate it now and skip to
3839 * next filter if the condition does not match.
3840 */
3841 if (exp->cond) {
3842 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3843 ret = acl_pass(ret);
3844 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3845 ret = !ret;
3846 if (!ret)
3847 continue;
3848 }
3849
3850 /* Apply the filter to the status line. */
3851 ret = htx_apply_filter_to_sts_line(s, res, exp);
3852 if (unlikely(ret < 0))
3853 return -1;
3854
3855 if (likely(ret == 0)) {
3856 /* The filter did not match the response, it can be
3857 * iterated through all headers.
3858 */
3859 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3860 return -1;
3861 }
3862 }
3863 return 0;
3864}
3865
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003866/*
3867 * Manage client-side cookie. It can impact performance by about 2% so it is
3868 * desirable to call it only when needed. This code is quite complex because
3869 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3870 * highly recommended not to touch this part without a good reason !
3871 */
3872static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3873{
3874 struct session *sess = s->sess;
3875 struct http_txn *txn = s->txn;
3876 struct htx *htx;
3877 struct http_hdr_ctx ctx;
3878 char *hdr_beg, *hdr_end, *del_from;
3879 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3880 int preserve_hdr;
3881
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003882 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003883 ctx.blk = NULL;
3884 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3885 del_from = NULL; /* nothing to be deleted */
3886 preserve_hdr = 0; /* assume we may kill the whole header */
3887
3888 /* Now look for cookies. Conforming to RFC2109, we have to support
3889 * attributes whose name begin with a '$', and associate them with
3890 * the right cookie, if we want to delete this cookie.
3891 * So there are 3 cases for each cookie read :
3892 * 1) it's a special attribute, beginning with a '$' : ignore it.
3893 * 2) it's a server id cookie that we *MAY* want to delete : save
3894 * some pointers on it (last semi-colon, beginning of cookie...)
3895 * 3) it's an application cookie : we *MAY* have to delete a previous
3896 * "special" cookie.
3897 * At the end of loop, if a "special" cookie remains, we may have to
3898 * remove it. If no application cookie persists in the header, we
3899 * *MUST* delete it.
3900 *
3901 * Note: RFC2965 is unclear about the processing of spaces around
3902 * the equal sign in the ATTR=VALUE form. A careful inspection of
3903 * the RFC explicitly allows spaces before it, and not within the
3904 * tokens (attrs or values). An inspection of RFC2109 allows that
3905 * too but section 10.1.3 lets one think that spaces may be allowed
3906 * after the equal sign too, resulting in some (rare) buggy
3907 * implementations trying to do that. So let's do what servers do.
3908 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3909 * allowed quoted strings in values, with any possible character
3910 * after a backslash, including control chars and delimitors, which
3911 * causes parsing to become ambiguous. Browsers also allow spaces
3912 * within values even without quotes.
3913 *
3914 * We have to keep multiple pointers in order to support cookie
3915 * removal at the beginning, middle or end of header without
3916 * corrupting the header. All of these headers are valid :
3917 *
3918 * hdr_beg hdr_end
3919 * | |
3920 * v |
3921 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3922 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3923 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3924 * | | | | | | |
3925 * | | | | | | |
3926 * | | | | | | +--> next
3927 * | | | | | +----> val_end
3928 * | | | | +-----------> val_beg
3929 * | | | +--------------> equal
3930 * | | +----------------> att_end
3931 * | +---------------------> att_beg
3932 * +--------------------------> prev
3933 *
3934 */
3935 hdr_beg = ctx.value.ptr;
3936 hdr_end = hdr_beg + ctx.value.len;
3937 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3938 /* Iterate through all cookies on this line */
3939
3940 /* find att_beg */
3941 att_beg = prev;
3942 if (prev > hdr_beg)
3943 att_beg++;
3944
3945 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3946 att_beg++;
3947
3948 /* find att_end : this is the first character after the last non
3949 * space before the equal. It may be equal to hdr_end.
3950 */
3951 equal = att_end = att_beg;
3952 while (equal < hdr_end) {
3953 if (*equal == '=' || *equal == ',' || *equal == ';')
3954 break;
3955 if (HTTP_IS_SPHT(*equal++))
3956 continue;
3957 att_end = equal;
3958 }
3959
3960 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3961 * is between <att_beg> and <equal>, both may be identical.
3962 */
3963 /* look for end of cookie if there is an equal sign */
3964 if (equal < hdr_end && *equal == '=') {
3965 /* look for the beginning of the value */
3966 val_beg = equal + 1;
3967 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3968 val_beg++;
3969
3970 /* find the end of the value, respecting quotes */
3971 next = http_find_cookie_value_end(val_beg, hdr_end);
3972
3973 /* make val_end point to the first white space or delimitor after the value */
3974 val_end = next;
3975 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3976 val_end--;
3977 }
3978 else
3979 val_beg = val_end = next = equal;
3980
3981 /* We have nothing to do with attributes beginning with
3982 * '$'. However, they will automatically be removed if a
3983 * header before them is removed, since they're supposed
3984 * to be linked together.
3985 */
3986 if (*att_beg == '$')
3987 continue;
3988
3989 /* Ignore cookies with no equal sign */
3990 if (equal == next) {
3991 /* This is not our cookie, so we must preserve it. But if we already
3992 * scheduled another cookie for removal, we cannot remove the
3993 * complete header, but we can remove the previous block itself.
3994 */
3995 preserve_hdr = 1;
3996 if (del_from != NULL) {
3997 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3998 val_end += delta;
3999 next += delta;
4000 hdr_end += delta;
4001 prev = del_from;
4002 del_from = NULL;
4003 }
4004 continue;
4005 }
4006
4007 /* if there are spaces around the equal sign, we need to
4008 * strip them otherwise we'll get trouble for cookie captures,
4009 * or even for rewrites. Since this happens extremely rarely,
4010 * it does not hurt performance.
4011 */
4012 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4013 int stripped_before = 0;
4014 int stripped_after = 0;
4015
4016 if (att_end != equal) {
4017 memmove(att_end, equal, hdr_end - equal);
4018 stripped_before = (att_end - equal);
4019 equal += stripped_before;
4020 val_beg += stripped_before;
4021 }
4022
4023 if (val_beg > equal + 1) {
4024 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4025 stripped_after = (equal + 1) - val_beg;
4026 val_beg += stripped_after;
4027 stripped_before += stripped_after;
4028 }
4029
4030 val_end += stripped_before;
4031 next += stripped_before;
4032 hdr_end += stripped_before;
4033 }
4034 /* now everything is as on the diagram above */
4035
4036 /* First, let's see if we want to capture this cookie. We check
4037 * that we don't already have a client side cookie, because we
4038 * can only capture one. Also as an optimisation, we ignore
4039 * cookies shorter than the declared name.
4040 */
4041 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4042 (val_end - att_beg >= sess->fe->capture_namelen) &&
4043 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4044 int log_len = val_end - att_beg;
4045
4046 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4047 ha_alert("HTTP logging : out of memory.\n");
4048 } else {
4049 if (log_len > sess->fe->capture_len)
4050 log_len = sess->fe->capture_len;
4051 memcpy(txn->cli_cookie, att_beg, log_len);
4052 txn->cli_cookie[log_len] = 0;
4053 }
4054 }
4055
4056 /* Persistence cookies in passive, rewrite or insert mode have the
4057 * following form :
4058 *
4059 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4060 *
4061 * For cookies in prefix mode, the form is :
4062 *
4063 * Cookie: NAME=SRV~VALUE
4064 */
4065 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4066 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4067 struct server *srv = s->be->srv;
4068 char *delim;
4069
4070 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4071 * have the server ID between val_beg and delim, and the original cookie between
4072 * delim+1 and val_end. Otherwise, delim==val_end :
4073 *
4074 * hdr_beg
4075 * |
4076 * v
4077 * NAME=SRV; # in all but prefix modes
4078 * NAME=SRV~OPAQUE ; # in prefix mode
4079 * || || | |+-> next
4080 * || || | +--> val_end
4081 * || || +---------> delim
4082 * || |+------------> val_beg
4083 * || +-------------> att_end = equal
4084 * |+-----------------> att_beg
4085 * +------------------> prev
4086 *
4087 */
4088 if (s->be->ck_opts & PR_CK_PFX) {
4089 for (delim = val_beg; delim < val_end; delim++)
4090 if (*delim == COOKIE_DELIM)
4091 break;
4092 }
4093 else {
4094 char *vbar1;
4095 delim = val_end;
4096 /* Now check if the cookie contains a date field, which would
4097 * appear after a vertical bar ('|') just after the server name
4098 * and before the delimiter.
4099 */
4100 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4101 if (vbar1) {
4102 /* OK, so left of the bar is the server's cookie and
4103 * right is the last seen date. It is a base64 encoded
4104 * 30-bit value representing the UNIX date since the
4105 * epoch in 4-second quantities.
4106 */
4107 int val;
4108 delim = vbar1++;
4109 if (val_end - vbar1 >= 5) {
4110 val = b64tos30(vbar1);
4111 if (val > 0)
4112 txn->cookie_last_date = val << 2;
4113 }
4114 /* look for a second vertical bar */
4115 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4116 if (vbar1 && (val_end - vbar1 > 5)) {
4117 val = b64tos30(vbar1 + 1);
4118 if (val > 0)
4119 txn->cookie_first_date = val << 2;
4120 }
4121 }
4122 }
4123
4124 /* if the cookie has an expiration date and the proxy wants to check
4125 * it, then we do that now. We first check if the cookie is too old,
4126 * then only if it has expired. We detect strict overflow because the
4127 * time resolution here is not great (4 seconds). Cookies with dates
4128 * in the future are ignored if their offset is beyond one day. This
4129 * allows an admin to fix timezone issues without expiring everyone
4130 * and at the same time avoids keeping unwanted side effects for too
4131 * long.
4132 */
4133 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4134 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4135 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4136 txn->flags &= ~TX_CK_MASK;
4137 txn->flags |= TX_CK_OLD;
4138 delim = val_beg; // let's pretend we have not found the cookie
4139 txn->cookie_first_date = 0;
4140 txn->cookie_last_date = 0;
4141 }
4142 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4143 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4144 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4145 txn->flags &= ~TX_CK_MASK;
4146 txn->flags |= TX_CK_EXPIRED;
4147 delim = val_beg; // let's pretend we have not found the cookie
4148 txn->cookie_first_date = 0;
4149 txn->cookie_last_date = 0;
4150 }
4151
4152 /* Here, we'll look for the first running server which supports the cookie.
4153 * This allows to share a same cookie between several servers, for example
4154 * to dedicate backup servers to specific servers only.
4155 * However, to prevent clients from sticking to cookie-less backup server
4156 * when they have incidentely learned an empty cookie, we simply ignore
4157 * empty cookies and mark them as invalid.
4158 * The same behaviour is applied when persistence must be ignored.
4159 */
4160 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4161 srv = NULL;
4162
4163 while (srv) {
4164 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4165 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4166 if ((srv->cur_state != SRV_ST_STOPPED) ||
4167 (s->be->options & PR_O_PERSIST) ||
4168 (s->flags & SF_FORCE_PRST)) {
4169 /* we found the server and we can use it */
4170 txn->flags &= ~TX_CK_MASK;
4171 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4172 s->flags |= SF_DIRECT | SF_ASSIGNED;
4173 s->target = &srv->obj_type;
4174 break;
4175 } else {
4176 /* we found a server, but it's down,
4177 * mark it as such and go on in case
4178 * another one is available.
4179 */
4180 txn->flags &= ~TX_CK_MASK;
4181 txn->flags |= TX_CK_DOWN;
4182 }
4183 }
4184 srv = srv->next;
4185 }
4186
4187 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4188 /* no server matched this cookie or we deliberately skipped it */
4189 txn->flags &= ~TX_CK_MASK;
4190 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4191 txn->flags |= TX_CK_UNUSED;
4192 else
4193 txn->flags |= TX_CK_INVALID;
4194 }
4195
4196 /* depending on the cookie mode, we may have to either :
4197 * - delete the complete cookie if we're in insert+indirect mode, so that
4198 * the server never sees it ;
4199 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004200 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004201 * if we're in cookie prefix mode
4202 */
4203 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4204 int delta; /* negative */
4205
4206 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4207 delta = val_beg - (delim + 1);
4208 val_end += delta;
4209 next += delta;
4210 hdr_end += delta;
4211 del_from = NULL;
4212 preserve_hdr = 1; /* we want to keep this cookie */
4213 }
4214 else if (del_from == NULL &&
4215 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4216 del_from = prev;
4217 }
4218 }
4219 else {
4220 /* This is not our cookie, so we must preserve it. But if we already
4221 * scheduled another cookie for removal, we cannot remove the
4222 * complete header, but we can remove the previous block itself.
4223 */
4224 preserve_hdr = 1;
4225
4226 if (del_from != NULL) {
4227 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4228 if (att_beg >= del_from)
4229 att_beg += delta;
4230 if (att_end >= del_from)
4231 att_end += delta;
4232 val_beg += delta;
4233 val_end += delta;
4234 next += delta;
4235 hdr_end += delta;
4236 prev = del_from;
4237 del_from = NULL;
4238 }
4239 }
4240
4241 /* continue with next cookie on this header line */
4242 att_beg = next;
4243 } /* for each cookie */
4244
4245
4246 /* There are no more cookies on this line.
4247 * We may still have one (or several) marked for deletion at the
4248 * end of the line. We must do this now in two ways :
4249 * - if some cookies must be preserved, we only delete from the
4250 * mark to the end of line ;
4251 * - if nothing needs to be preserved, simply delete the whole header
4252 */
4253 if (del_from) {
4254 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4255 }
4256 if ((hdr_end - hdr_beg) != ctx.value.len) {
4257 if (hdr_beg != hdr_end) {
4258 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004259 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004260 }
4261 else
4262 http_remove_header(htx, &ctx);
4263 }
4264 } /* for each "Cookie header */
4265}
4266
4267/*
4268 * Manage server-side cookies. It can impact performance by about 2% so it is
4269 * desirable to call it only when needed. This function is also used when we
4270 * just need to know if there is a cookie (eg: for check-cache).
4271 */
4272static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4273{
4274 struct session *sess = s->sess;
4275 struct http_txn *txn = s->txn;
4276 struct htx *htx;
4277 struct http_hdr_ctx ctx;
4278 struct server *srv;
4279 char *hdr_beg, *hdr_end;
4280 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4281 int is_cookie2;
4282
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004283 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004284
4285 ctx.blk = NULL;
4286 while (1) {
4287 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4288 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4289 break;
4290 is_cookie2 = 1;
4291 }
4292
4293 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4294 * <prev> points to the colon.
4295 */
4296 txn->flags |= TX_SCK_PRESENT;
4297
4298 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4299 * check-cache is enabled) and we are not interested in checking
4300 * them. Warning, the cookie capture is declared in the frontend.
4301 */
4302 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4303 break;
4304
4305 /* OK so now we know we have to process this response cookie.
4306 * The format of the Set-Cookie header is slightly different
4307 * from the format of the Cookie header in that it does not
4308 * support the comma as a cookie delimiter (thus the header
4309 * cannot be folded) because the Expires attribute described in
4310 * the original Netscape's spec may contain an unquoted date
4311 * with a comma inside. We have to live with this because
4312 * many browsers don't support Max-Age and some browsers don't
4313 * support quoted strings. However the Set-Cookie2 header is
4314 * clean.
4315 *
4316 * We have to keep multiple pointers in order to support cookie
4317 * removal at the beginning, middle or end of header without
4318 * corrupting the header (in case of set-cookie2). A special
4319 * pointer, <scav> points to the beginning of the set-cookie-av
4320 * fields after the first semi-colon. The <next> pointer points
4321 * either to the end of line (set-cookie) or next unquoted comma
4322 * (set-cookie2). All of these headers are valid :
4323 *
4324 * hdr_beg hdr_end
4325 * | |
4326 * v |
4327 * NAME1 = VALUE 1 ; Secure; Path="/" |
4328 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4329 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4330 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4331 * | | | | | | | |
4332 * | | | | | | | +-> next
4333 * | | | | | | +------------> scav
4334 * | | | | | +--------------> val_end
4335 * | | | | +--------------------> val_beg
4336 * | | | +----------------------> equal
4337 * | | +------------------------> att_end
4338 * | +----------------------------> att_beg
4339 * +------------------------------> prev
4340 * -------------------------------> hdr_beg
4341 */
4342 hdr_beg = ctx.value.ptr;
4343 hdr_end = hdr_beg + ctx.value.len;
4344 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4345
4346 /* Iterate through all cookies on this line */
4347
4348 /* find att_beg */
4349 att_beg = prev;
4350 if (prev > hdr_beg)
4351 att_beg++;
4352
4353 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4354 att_beg++;
4355
4356 /* find att_end : this is the first character after the last non
4357 * space before the equal. It may be equal to hdr_end.
4358 */
4359 equal = att_end = att_beg;
4360
4361 while (equal < hdr_end) {
4362 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4363 break;
4364 if (HTTP_IS_SPHT(*equal++))
4365 continue;
4366 att_end = equal;
4367 }
4368
4369 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4370 * is between <att_beg> and <equal>, both may be identical.
4371 */
4372
4373 /* look for end of cookie if there is an equal sign */
4374 if (equal < hdr_end && *equal == '=') {
4375 /* look for the beginning of the value */
4376 val_beg = equal + 1;
4377 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4378 val_beg++;
4379
4380 /* find the end of the value, respecting quotes */
4381 next = http_find_cookie_value_end(val_beg, hdr_end);
4382
4383 /* make val_end point to the first white space or delimitor after the value */
4384 val_end = next;
4385 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4386 val_end--;
4387 }
4388 else {
4389 /* <equal> points to next comma, semi-colon or EOL */
4390 val_beg = val_end = next = equal;
4391 }
4392
4393 if (next < hdr_end) {
4394 /* Set-Cookie2 supports multiple cookies, and <next> points to
4395 * a colon or semi-colon before the end. So skip all attr-value
4396 * pairs and look for the next comma. For Set-Cookie, since
4397 * commas are permitted in values, skip to the end.
4398 */
4399 if (is_cookie2)
4400 next = http_find_hdr_value_end(next, hdr_end);
4401 else
4402 next = hdr_end;
4403 }
4404
4405 /* Now everything is as on the diagram above */
4406
4407 /* Ignore cookies with no equal sign */
4408 if (equal == val_end)
4409 continue;
4410
4411 /* If there are spaces around the equal sign, we need to
4412 * strip them otherwise we'll get trouble for cookie captures,
4413 * or even for rewrites. Since this happens extremely rarely,
4414 * it does not hurt performance.
4415 */
4416 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4417 int stripped_before = 0;
4418 int stripped_after = 0;
4419
4420 if (att_end != equal) {
4421 memmove(att_end, equal, hdr_end - equal);
4422 stripped_before = (att_end - equal);
4423 equal += stripped_before;
4424 val_beg += stripped_before;
4425 }
4426
4427 if (val_beg > equal + 1) {
4428 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4429 stripped_after = (equal + 1) - val_beg;
4430 val_beg += stripped_after;
4431 stripped_before += stripped_after;
4432 }
4433
4434 val_end += stripped_before;
4435 next += stripped_before;
4436 hdr_end += stripped_before;
4437
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004438 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4439 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004440 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004441 }
4442
4443 /* First, let's see if we want to capture this cookie. We check
4444 * that we don't already have a server side cookie, because we
4445 * can only capture one. Also as an optimisation, we ignore
4446 * cookies shorter than the declared name.
4447 */
4448 if (sess->fe->capture_name != NULL &&
4449 txn->srv_cookie == NULL &&
4450 (val_end - att_beg >= sess->fe->capture_namelen) &&
4451 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4452 int log_len = val_end - att_beg;
4453 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4454 ha_alert("HTTP logging : out of memory.\n");
4455 }
4456 else {
4457 if (log_len > sess->fe->capture_len)
4458 log_len = sess->fe->capture_len;
4459 memcpy(txn->srv_cookie, att_beg, log_len);
4460 txn->srv_cookie[log_len] = 0;
4461 }
4462 }
4463
4464 srv = objt_server(s->target);
4465 /* now check if we need to process it for persistence */
4466 if (!(s->flags & SF_IGNORE_PRST) &&
4467 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4468 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4469 /* assume passive cookie by default */
4470 txn->flags &= ~TX_SCK_MASK;
4471 txn->flags |= TX_SCK_FOUND;
4472
4473 /* If the cookie is in insert mode on a known server, we'll delete
4474 * this occurrence because we'll insert another one later.
4475 * We'll delete it too if the "indirect" option is set and we're in
4476 * a direct access.
4477 */
4478 if (s->be->ck_opts & PR_CK_PSV) {
4479 /* The "preserve" flag was set, we don't want to touch the
4480 * server's cookie.
4481 */
4482 }
4483 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4484 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4485 /* this cookie must be deleted */
4486 if (prev == hdr_beg && next == hdr_end) {
4487 /* whole header */
4488 http_remove_header(htx, &ctx);
4489 /* note: while both invalid now, <next> and <hdr_end>
4490 * are still equal, so the for() will stop as expected.
4491 */
4492 } else {
4493 /* just remove the value */
4494 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4495 next = prev;
4496 hdr_end += delta;
4497 }
4498 txn->flags &= ~TX_SCK_MASK;
4499 txn->flags |= TX_SCK_DELETED;
4500 /* and go on with next cookie */
4501 }
4502 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4503 /* replace bytes val_beg->val_end with the cookie name associated
4504 * with this server since we know it.
4505 */
4506 int sliding, delta;
4507
4508 ctx.value = ist2(val_beg, val_end - val_beg);
4509 ctx.lws_before = ctx.lws_after = 0;
4510 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4511 delta = srv->cklen - (val_end - val_beg);
4512 sliding = (ctx.value.ptr - val_beg);
4513 hdr_beg += sliding;
4514 val_beg += sliding;
4515 next += sliding + delta;
4516 hdr_end += sliding + delta;
4517
4518 txn->flags &= ~TX_SCK_MASK;
4519 txn->flags |= TX_SCK_REPLACED;
4520 }
4521 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4522 /* insert the cookie name associated with this server
4523 * before existing cookie, and insert a delimiter between them..
4524 */
4525 int sliding, delta;
4526 ctx.value = ist2(val_beg, 0);
4527 ctx.lws_before = ctx.lws_after = 0;
4528 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4529 delta = srv->cklen + 1;
4530 sliding = (ctx.value.ptr - val_beg);
4531 hdr_beg += sliding;
4532 val_beg += sliding;
4533 next += sliding + delta;
4534 hdr_end += sliding + delta;
4535
4536 val_beg[srv->cklen] = COOKIE_DELIM;
4537 txn->flags &= ~TX_SCK_MASK;
4538 txn->flags |= TX_SCK_REPLACED;
4539 }
4540 }
4541 /* that's done for this cookie, check the next one on the same
4542 * line when next != hdr_end (only if is_cookie2).
4543 */
4544 }
4545 }
4546}
4547
Christopher Faulet25a02f62018-10-24 12:00:25 +02004548/*
4549 * Parses the Cache-Control and Pragma request header fields to determine if
4550 * the request may be served from the cache and/or if it is cacheable. Updates
4551 * s->txn->flags.
4552 */
4553void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4554{
4555 struct http_txn *txn = s->txn;
4556 struct htx *htx;
4557 int32_t pos;
4558 int pragma_found, cc_found, i;
4559
4560 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4561 return; /* nothing more to do here */
4562
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004563 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004564 pragma_found = cc_found = 0;
4565 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4566 struct htx_blk *blk = htx_get_blk(htx, pos);
4567 enum htx_blk_type type = htx_get_blk_type(blk);
4568 struct ist n, v;
4569
4570 if (type == HTX_BLK_EOH)
4571 break;
4572 if (type != HTX_BLK_HDR)
4573 continue;
4574
4575 n = htx_get_blk_name(htx, blk);
4576 v = htx_get_blk_value(htx, blk);
4577
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004578 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004579 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4580 pragma_found = 1;
4581 continue;
4582 }
4583 }
4584
4585 /* Don't use the cache and don't try to store if we found the
4586 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004587 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004588 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4589 txn->flags |= TX_CACHE_IGNORE;
4590 continue;
4591 }
4592
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004593 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004594 continue;
4595
4596 /* OK, right now we know we have a cache-control header */
4597 cc_found = 1;
4598 if (!v.len) /* no info */
4599 continue;
4600
4601 i = 0;
4602 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4603 !isspace((unsigned char)*(v.ptr+i)))
4604 i++;
4605
4606 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4607 * values after max-age, max-stale nor min-fresh, we simply don't
4608 * use the cache when they're specified.
4609 */
4610 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4611 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4612 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4613 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4614 txn->flags |= TX_CACHE_IGNORE;
4615 continue;
4616 }
4617
4618 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4619 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4620 continue;
4621 }
4622 }
4623
4624 /* RFC7234#5.4:
4625 * When the Cache-Control header field is also present and
4626 * understood in a request, Pragma is ignored.
4627 * When the Cache-Control header field is not present in a
4628 * request, caches MUST consider the no-cache request
4629 * pragma-directive as having the same effect as if
4630 * "Cache-Control: no-cache" were present.
4631 */
4632 if (!cc_found && pragma_found)
4633 txn->flags |= TX_CACHE_IGNORE;
4634}
4635
4636/*
4637 * Check if response is cacheable or not. Updates s->txn->flags.
4638 */
4639void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4640{
4641 struct http_txn *txn = s->txn;
4642 struct htx *htx;
4643 int32_t pos;
4644 int i;
4645
4646 if (txn->status < 200) {
4647 /* do not try to cache interim responses! */
4648 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4649 return;
4650 }
4651
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004652 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004653 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4654 struct htx_blk *blk = htx_get_blk(htx, pos);
4655 enum htx_blk_type type = htx_get_blk_type(blk);
4656 struct ist n, v;
4657
4658 if (type == HTX_BLK_EOH)
4659 break;
4660 if (type != HTX_BLK_HDR)
4661 continue;
4662
4663 n = htx_get_blk_name(htx, blk);
4664 v = htx_get_blk_value(htx, blk);
4665
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004666 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004667 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4668 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4669 return;
4670 }
4671 }
4672
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004673 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004674 continue;
4675
4676 /* OK, right now we know we have a cache-control header */
4677 if (!v.len) /* no info */
4678 continue;
4679
4680 i = 0;
4681 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4682 !isspace((unsigned char)*(v.ptr+i)))
4683 i++;
4684
4685 /* we have a complete value between v.ptr and (v.ptr+i) */
4686 if (i < v.len && *(v.ptr + i) == '=') {
4687 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4688 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4689 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4690 continue;
4691 }
4692
4693 /* we have something of the form no-cache="set-cookie" */
4694 if ((v.len >= 21) &&
4695 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4696 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4697 txn->flags &= ~TX_CACHE_COOK;
4698 continue;
4699 }
4700
4701 /* OK, so we know that either p2 points to the end of string or to a comma */
4702 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4703 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4704 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4705 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4706 return;
4707 }
4708
4709 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4710 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4711 continue;
4712 }
4713 }
4714}
4715
Christopher Faulet64159df2018-10-24 21:15:35 +02004716/* send a server's name with an outgoing request over an established connection.
4717 * Note: this function is designed to be called once the request has been
4718 * scheduled for being forwarded. This is the reason why the number of forwarded
4719 * bytes have to be adjusted.
4720 */
4721int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4722{
4723 struct htx *htx;
4724 struct http_hdr_ctx ctx;
4725 struct ist hdr;
4726 uint32_t data;
4727
4728 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004729 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004730 data = htx->data;
4731
4732 ctx.blk = NULL;
4733 while (http_find_header(htx, hdr, &ctx, 1))
4734 http_remove_header(htx, &ctx);
4735 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4736
4737 if (co_data(&s->req)) {
4738 if (data >= htx->data)
4739 c_rew(&s->req, data - htx->data);
4740 else
4741 c_adv(&s->req, htx->data - data);
4742 }
4743 return 0;
4744}
4745
Christopher Faulet377c5a52018-10-24 21:21:30 +02004746/*
4747 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4748 * for the current backend.
4749 *
4750 * It is assumed that the request is either a HEAD, GET, or POST and that the
4751 * uri_auth field is valid.
4752 *
4753 * Returns 1 if stats should be provided, otherwise 0.
4754 */
4755static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4756{
4757 struct uri_auth *uri_auth = backend->uri_auth;
4758 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004759 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004760 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004761
4762 if (!uri_auth)
4763 return 0;
4764
4765 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4766 return 0;
4767
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004768 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004769 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004770 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004771
4772 /* check URI size */
4773 if (uri_auth->uri_len > uri.len)
4774 return 0;
4775
4776 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4777 return 0;
4778
4779 return 1;
4780}
4781
4782/* This function prepares an applet to handle the stats. It can deal with the
4783 * "100-continue" expectation, check that admin rules are met for POST requests,
4784 * and program a response message if something was unexpected. It cannot fail
4785 * and always relies on the stats applet to complete the job. It does not touch
4786 * analysers nor counters, which are left to the caller. It does not touch
4787 * s->target which is supposed to already point to the stats applet. The caller
4788 * is expected to have already assigned an appctx to the stream.
4789 */
4790static int htx_handle_stats(struct stream *s, struct channel *req)
4791{
4792 struct stats_admin_rule *stats_admin_rule;
4793 struct stream_interface *si = &s->si[1];
4794 struct session *sess = s->sess;
4795 struct http_txn *txn = s->txn;
4796 struct http_msg *msg = &txn->req;
4797 struct uri_auth *uri_auth = s->be->uri_auth;
4798 const char *h, *lookup, *end;
4799 struct appctx *appctx;
4800 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004801 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004802
4803 appctx = si_appctx(si);
4804 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4805 appctx->st1 = appctx->st2 = 0;
4806 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4807 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4808 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4809 appctx->ctx.stats.flags |= STAT_CHUNKED;
4810
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004811 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004813 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4814 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004815
4816 for (h = lookup; h <= end - 3; h++) {
4817 if (memcmp(h, ";up", 3) == 0) {
4818 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4819 break;
4820 }
4821 }
4822
4823 if (uri_auth->refresh) {
4824 for (h = lookup; h <= end - 10; h++) {
4825 if (memcmp(h, ";norefresh", 10) == 0) {
4826 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4827 break;
4828 }
4829 }
4830 }
4831
4832 for (h = lookup; h <= end - 4; h++) {
4833 if (memcmp(h, ";csv", 4) == 0) {
4834 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4835 break;
4836 }
4837 }
4838
4839 for (h = lookup; h <= end - 6; h++) {
4840 if (memcmp(h, ";typed", 6) == 0) {
4841 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4842 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4843 break;
4844 }
4845 }
4846
4847 for (h = lookup; h <= end - 8; h++) {
4848 if (memcmp(h, ";st=", 4) == 0) {
4849 int i;
4850 h += 4;
4851 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4852 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4853 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4854 appctx->ctx.stats.st_code = i;
4855 break;
4856 }
4857 }
4858 break;
4859 }
4860 }
4861
4862 appctx->ctx.stats.scope_str = 0;
4863 appctx->ctx.stats.scope_len = 0;
4864 for (h = lookup; h <= end - 8; h++) {
4865 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4866 int itx = 0;
4867 const char *h2;
4868 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4869 const char *err;
4870
4871 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4872 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004873 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4874 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004875 if (*h == ';' || *h == '&' || *h == ' ')
4876 break;
4877 itx++;
4878 h++;
4879 }
4880
4881 if (itx > STAT_SCOPE_TXT_MAXLEN)
4882 itx = STAT_SCOPE_TXT_MAXLEN;
4883 appctx->ctx.stats.scope_len = itx;
4884
4885 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4886 memcpy(scope_txt, h2, itx);
4887 scope_txt[itx] = '\0';
4888 err = invalid_char(scope_txt);
4889 if (err) {
4890 /* bad char in search text => clear scope */
4891 appctx->ctx.stats.scope_str = 0;
4892 appctx->ctx.stats.scope_len = 0;
4893 }
4894 break;
4895 }
4896 }
4897
4898 /* now check whether we have some admin rules for this request */
4899 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4900 int ret = 1;
4901
4902 if (stats_admin_rule->cond) {
4903 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4904 ret = acl_pass(ret);
4905 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4906 ret = !ret;
4907 }
4908
4909 if (ret) {
4910 /* no rule, or the rule matches */
4911 appctx->ctx.stats.flags |= STAT_ADMIN;
4912 break;
4913 }
4914 }
4915
Christopher Faulet5d45e382019-02-27 15:15:23 +01004916 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4917 appctx->st0 = STAT_HTTP_HEAD;
4918 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004919 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4920 /* we'll need the request body, possibly after sending 100-continue */
4921 if (msg->msg_state < HTTP_MSG_DATA)
4922 req->analysers |= AN_REQ_HTTP_BODY;
4923 appctx->st0 = STAT_HTTP_POST;
4924 }
4925 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004926 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004927 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4928 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4929 appctx->st0 = STAT_HTTP_LAST;
4930 }
4931 }
4932 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004933 /* Unsupported method */
4934 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4935 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4936 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004937 }
4938
4939 s->task->nice = -32; /* small boost for HTTP statistics */
4940 return 1;
4941}
4942
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004943void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4944{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004945 struct channel *req = &s->req;
4946 struct channel *res = &s->res;
4947 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004948 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004949 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004950 struct ist path, location;
4951 unsigned int flags;
4952 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004953
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004954 /*
4955 * Create the location
4956 */
4957 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004958
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004959 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004960 /* special prefix "/" means don't change URL */
4961 srv = __objt_server(s->target);
4962 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4963 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4964 return;
4965 }
4966
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004967 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004968 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004969 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004970 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004971 if (!path.ptr)
4972 return;
4973
4974 if (!chunk_memcat(&trash, path.ptr, path.len))
4975 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004976 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004977
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004978 /*
4979 * Create the 302 respone
4980 */
4981 htx = htx_from_buf(&res->buf);
4982 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4983 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4984 ist("HTTP/1.1"), ist("302"), ist("Found"));
4985 if (!sl)
4986 goto fail;
4987 sl->info.res.status = 302;
4988 s->txn->status = 302;
4989
4990 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4991 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4992 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4993 !htx_add_header(htx, ist("Location"), location))
4994 goto fail;
4995
4996 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4997 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004998
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004999 /*
5000 * Send the message
5001 */
5002 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 c_adv(res, data);
5004 res->total += data;
5005
5006 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007 si_shutr(si);
5008 si_shutw(si);
5009 si->err_type = SI_ET_NONE;
5010 si->state = SI_ST_CLO;
5011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 channel_auto_read(req);
5013 channel_abort(req);
5014 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005015 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005016 channel_auto_read(res);
5017 channel_auto_close(res);
5018
5019 if (!(s->flags & SF_ERR_MASK))
5020 s->flags |= SF_ERR_LOCAL;
5021 if (!(s->flags & SF_FINST_MASK))
5022 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005023
5024 /* FIXME: we should increase a counter of redirects per server and per backend. */
5025 srv_inc_sess_ctr(srv);
5026 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005027 return;
5028
5029 fail:
5030 /* If an error occurred, remove the incomplete HTTP response from the
5031 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005032 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005033}
5034
Christopher Fauletf2824e62018-10-01 12:12:37 +02005035/* This function terminates the request because it was completly analyzed or
5036 * because an error was triggered during the body forwarding.
5037 */
5038static void htx_end_request(struct stream *s)
5039{
5040 struct channel *chn = &s->req;
5041 struct http_txn *txn = s->txn;
5042
5043 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5044 now_ms, __FUNCTION__, s,
5045 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5046 s->req.analysers, s->res.analysers);
5047
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005048 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5049 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005050 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005051 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005052 goto end;
5053 }
5054
5055 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5056 return;
5057
5058 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005059 /* No need to read anymore, the request was completely parsed.
5060 * We can shut the read side unless we want to abort_on_close,
5061 * or we have a POST request. The issue with POST requests is
5062 * that some browsers still send a CRLF after the request, and
5063 * this CRLF must be read so that it does not remain in the kernel
5064 * buffers, otherwise a close could cause an RST on some systems
5065 * (eg: Linux).
5066 */
5067 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5068 txn->meth != HTTP_METH_POST)
5069 channel_dont_read(chn);
5070
5071 /* if the server closes the connection, we want to immediately react
5072 * and close the socket to save packets and syscalls.
5073 */
5074 s->si[1].flags |= SI_FL_NOHALF;
5075
5076 /* In any case we've finished parsing the request so we must
5077 * disable Nagle when sending data because 1) we're not going
5078 * to shut this side, and 2) the server is waiting for us to
5079 * send pending data.
5080 */
5081 chn->flags |= CF_NEVER_WAIT;
5082
Christopher Fauletd01ce402019-01-02 17:44:13 +01005083 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5084 /* The server has not finished to respond, so we
5085 * don't want to move in order not to upset it.
5086 */
5087 return;
5088 }
5089
Christopher Fauletf2824e62018-10-01 12:12:37 +02005090 /* When we get here, it means that both the request and the
5091 * response have finished receiving. Depending on the connection
5092 * mode, we'll have to wait for the last bytes to leave in either
5093 * direction, and sometimes for a close to be effective.
5094 */
5095 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5096 /* Tunnel mode will not have any analyser so it needs to
5097 * poll for reads.
5098 */
5099 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005100 if (b_data(&chn->buf))
5101 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005102 txn->req.msg_state = HTTP_MSG_TUNNEL;
5103 }
5104 else {
5105 /* we're not expecting any new data to come for this
5106 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005107 *
5108 * However, there is an exception if the response
5109 * length is undefined. In this case, we need to wait
5110 * the close from the server. The response will be
5111 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005112 */
5113 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5114 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005115 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005116
5117 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5118 channel_shutr_now(chn);
5119 channel_shutw_now(chn);
5120 }
5121 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005122 goto check_channel_flags;
5123 }
5124
5125 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5126 http_msg_closing:
5127 /* nothing else to forward, just waiting for the output buffer
5128 * to be empty and for the shutw_now to take effect.
5129 */
5130 if (channel_is_empty(chn)) {
5131 txn->req.msg_state = HTTP_MSG_CLOSED;
5132 goto http_msg_closed;
5133 }
5134 else if (chn->flags & CF_SHUTW) {
5135 txn->req.err_state = txn->req.msg_state;
5136 txn->req.msg_state = HTTP_MSG_ERROR;
5137 goto end;
5138 }
5139 return;
5140 }
5141
5142 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5143 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005144 /* if we don't know whether the server will close, we need to hard close */
5145 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5146 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005147 /* see above in MSG_DONE why we only do this in these states */
5148 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5149 channel_dont_read(chn);
5150 goto end;
5151 }
5152
5153 check_channel_flags:
5154 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5155 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5156 /* if we've just closed an output, let's switch */
5157 txn->req.msg_state = HTTP_MSG_CLOSING;
5158 goto http_msg_closing;
5159 }
5160
5161 end:
5162 chn->analysers &= AN_REQ_FLT_END;
5163 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5164 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5165 channel_auto_close(chn);
5166 channel_auto_read(chn);
5167}
5168
5169
5170/* This function terminates the response because it was completly analyzed or
5171 * because an error was triggered during the body forwarding.
5172 */
5173static void htx_end_response(struct stream *s)
5174{
5175 struct channel *chn = &s->res;
5176 struct http_txn *txn = s->txn;
5177
5178 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5179 now_ms, __FUNCTION__, s,
5180 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5181 s->req.analysers, s->res.analysers);
5182
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005183 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5184 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005185 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005186 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005187 goto end;
5188 }
5189
5190 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5191 return;
5192
5193 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5194 /* In theory, we don't need to read anymore, but we must
5195 * still monitor the server connection for a possible close
5196 * while the request is being uploaded, so we don't disable
5197 * reading.
5198 */
5199 /* channel_dont_read(chn); */
5200
5201 if (txn->req.msg_state < HTTP_MSG_DONE) {
5202 /* The client seems to still be sending data, probably
5203 * because we got an error response during an upload.
5204 * We have the choice of either breaking the connection
5205 * or letting it pass through. Let's do the later.
5206 */
5207 return;
5208 }
5209
5210 /* When we get here, it means that both the request and the
5211 * response have finished receiving. Depending on the connection
5212 * mode, we'll have to wait for the last bytes to leave in either
5213 * direction, and sometimes for a close to be effective.
5214 */
5215 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5216 channel_auto_read(chn);
5217 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005218 if (b_data(&chn->buf))
5219 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005220 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5221 }
5222 else {
5223 /* we're not expecting any new data to come for this
5224 * transaction, so we can close it.
5225 */
5226 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5227 channel_shutr_now(chn);
5228 channel_shutw_now(chn);
5229 }
5230 }
5231 goto check_channel_flags;
5232 }
5233
5234 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5235 http_msg_closing:
5236 /* nothing else to forward, just waiting for the output buffer
5237 * to be empty and for the shutw_now to take effect.
5238 */
5239 if (channel_is_empty(chn)) {
5240 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5241 goto http_msg_closed;
5242 }
5243 else if (chn->flags & CF_SHUTW) {
5244 txn->rsp.err_state = txn->rsp.msg_state;
5245 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005246 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005247 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005248 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005249 goto end;
5250 }
5251 return;
5252 }
5253
5254 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5255 http_msg_closed:
5256 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005257 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005258 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005259 goto end;
5260 }
5261
5262 check_channel_flags:
5263 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5264 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5265 /* if we've just closed an output, let's switch */
5266 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5267 goto http_msg_closing;
5268 }
5269
5270 end:
5271 chn->analysers &= AN_RES_FLT_END;
5272 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5273 chn->analysers |= AN_RES_FLT_XFER_DATA;
5274 channel_auto_close(chn);
5275 channel_auto_read(chn);
5276}
5277
Christopher Faulet0f226952018-10-22 09:29:56 +02005278void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5279 int finst, const struct buffer *msg)
5280{
5281 channel_auto_read(si_oc(si));
5282 channel_abort(si_oc(si));
5283 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005284 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005285 channel_auto_close(si_ic(si));
5286 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005287
5288 /* <msg> is an HTX structure. So we copy it in the response's
5289 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005290 if (msg) {
5291 struct channel *chn = si_ic(si);
5292 struct htx *htx;
5293
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005294 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005295 chn->buf.data = msg->data;
5296 memcpy(chn->buf.area, msg->area, msg->data);
5297 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005298 c_adv(chn, htx->data);
5299 chn->total += htx->data;
5300 }
5301 if (!(s->flags & SF_ERR_MASK))
5302 s->flags |= err;
5303 if (!(s->flags & SF_FINST_MASK))
5304 s->flags |= finst;
5305}
5306
5307void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5308{
5309 channel_auto_read(&s->req);
5310 channel_abort(&s->req);
5311 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005312 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5313 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005314
5315 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005316
5317 /* <msg> is an HTX structure. So we copy it in the response's
5318 * channel */
5319 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005320 if (msg) {
5321 struct channel *chn = &s->res;
5322 struct htx *htx;
5323
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005324 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005325 chn->buf.data = msg->data;
5326 memcpy(chn->buf.area, msg->area, msg->data);
5327 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005328 c_adv(chn, htx->data);
5329 chn->total += htx->data;
5330 }
5331
5332 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5333 channel_auto_read(&s->res);
5334 channel_auto_close(&s->res);
5335 channel_shutr_now(&s->res);
5336}
5337
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005338struct buffer *htx_error_message(struct stream *s)
5339{
5340 const int msgnum = http_get_status_idx(s->txn->status);
5341
5342 if (s->be->errmsg[msgnum].area)
5343 return &s->be->errmsg[msgnum];
5344 else if (strm_fe(s)->errmsg[msgnum].area)
5345 return &strm_fe(s)->errmsg[msgnum];
5346 else
5347 return &htx_err_chunks[msgnum];
5348}
5349
5350
Christopher Faulet4a28a532019-03-01 11:19:40 +01005351/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5352 * on success and -1 on error.
5353 */
5354static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5355{
5356 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5357 * then we must send an HTTP/1.1 100 Continue intermediate response.
5358 */
5359 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5360 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5361 struct ist hdr = { .ptr = "Expect", .len = 6 };
5362 struct http_hdr_ctx ctx;
5363
5364 ctx.blk = NULL;
5365 /* Expect is allowed in 1.1, look for it */
5366 if (http_find_header(htx, hdr, &ctx, 0) &&
5367 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5368 if (htx_reply_100_continue(s) == -1)
5369 return -1;
5370 http_remove_header(htx, &ctx);
5371 }
5372 }
5373 return 0;
5374}
5375
Christopher Faulet23a3c792018-11-28 10:01:23 +01005376/* Send a 100-Continue response to the client. It returns 0 on success and -1
5377 * on error. The response channel is updated accordingly.
5378 */
5379static int htx_reply_100_continue(struct stream *s)
5380{
5381 struct channel *res = &s->res;
5382 struct htx *htx = htx_from_buf(&res->buf);
5383 struct htx_sl *sl;
5384 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5385 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5386 size_t data;
5387
5388 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5389 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5390 if (!sl)
5391 goto fail;
5392 sl->info.res.status = 100;
5393
5394 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5395 goto fail;
5396
5397 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005398 c_adv(res, data);
5399 res->total += data;
5400 return 0;
5401
5402 fail:
5403 /* If an error occurred, remove the incomplete HTTP response from the
5404 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005405 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005406 return -1;
5407}
5408
Christopher Faulet12c51e22018-11-28 15:59:42 +01005409
5410/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5411 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5412 * error. The response channel is updated accordingly.
5413 */
5414static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5415{
5416 struct channel *res = &s->res;
5417 struct htx *htx = htx_from_buf(&res->buf);
5418 struct htx_sl *sl;
5419 struct ist code, body;
5420 int status;
5421 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5422 size_t data;
5423
5424 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5425 status = 401;
5426 code = ist("401");
5427 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5428 "You need a valid user and password to access this content.\n"
5429 "</body></html>\n");
5430 }
5431 else {
5432 status = 407;
5433 code = ist("407");
5434 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5435 "You need a valid user and password to access this content.\n"
5436 "</body></html>\n");
5437 }
5438
5439 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5440 ist("HTTP/1.1"), code, ist("Unauthorized"));
5441 if (!sl)
5442 goto fail;
5443 sl->info.res.status = status;
5444 s->txn->status = status;
5445
5446 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5447 goto fail;
5448
5449 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5450 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005451 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5452 goto fail;
5453 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5454 goto fail;
5455 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005457 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5458 goto fail;
5459
5460 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005461 c_adv(res, data);
5462 res->total += data;
5463
5464 channel_auto_read(&s->req);
5465 channel_abort(&s->req);
5466 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005467 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005468
5469 res->wex = tick_add_ifset(now_ms, res->wto);
5470 channel_auto_read(res);
5471 channel_auto_close(res);
5472 channel_shutr_now(res);
5473 return 0;
5474
5475 fail:
5476 /* If an error occurred, remove the incomplete HTTP response from the
5477 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005478 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005479 return -1;
5480}
5481
Christopher Faulet0f226952018-10-22 09:29:56 +02005482/*
5483 * Capture headers from message <htx> according to header list <cap_hdr>, and
5484 * fill the <cap> pointers appropriately.
5485 */
5486static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5487{
5488 struct cap_hdr *h;
5489 int32_t pos;
5490
5491 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5492 struct htx_blk *blk = htx_get_blk(htx, pos);
5493 enum htx_blk_type type = htx_get_blk_type(blk);
5494 struct ist n, v;
5495
5496 if (type == HTX_BLK_EOH)
5497 break;
5498 if (type != HTX_BLK_HDR)
5499 continue;
5500
5501 n = htx_get_blk_name(htx, blk);
5502
5503 for (h = cap_hdr; h; h = h->next) {
5504 if (h->namelen && (h->namelen == n.len) &&
5505 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5506 if (cap[h->index] == NULL)
5507 cap[h->index] =
5508 pool_alloc(h->pool);
5509
5510 if (cap[h->index] == NULL) {
5511 ha_alert("HTTP capture : out of memory.\n");
5512 break;
5513 }
5514
5515 v = htx_get_blk_value(htx, blk);
5516 if (v.len > h->len)
5517 v.len = h->len;
5518
5519 memcpy(cap[h->index], v.ptr, v.len);
5520 cap[h->index][v.len]=0;
5521 }
5522 }
5523 }
5524}
5525
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005526/* Delete a value in a header between delimiters <from> and <next>. The header
5527 * itself is delimited by <start> and <end> pointers. The number of characters
5528 * displaced is returned, and the pointer to the first delimiter is updated if
5529 * required. The function tries as much as possible to respect the following
5530 * principles :
5531 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5532 * in which case <next> is simply removed
5533 * - set exactly one space character after the new first delimiter, unless there
5534 * are not enough characters in the block being moved to do so.
5535 * - remove unneeded spaces before the previous delimiter and after the new
5536 * one.
5537 *
5538 * It is the caller's responsibility to ensure that :
5539 * - <from> points to a valid delimiter or <start> ;
5540 * - <next> points to a valid delimiter or <end> ;
5541 * - there are non-space chars before <from>.
5542 */
5543static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5544{
5545 char *prev = *from;
5546
5547 if (prev == start) {
5548 /* We're removing the first value. eat the semicolon, if <next>
5549 * is lower than <end> */
5550 if (next < end)
5551 next++;
5552
5553 while (next < end && HTTP_IS_SPHT(*next))
5554 next++;
5555 }
5556 else {
5557 /* Remove useless spaces before the old delimiter. */
5558 while (HTTP_IS_SPHT(*(prev-1)))
5559 prev--;
5560 *from = prev;
5561
5562 /* copy the delimiter and if possible a space if we're
5563 * not at the end of the line.
5564 */
5565 if (next < end) {
5566 *prev++ = *next++;
5567 if (prev + 1 < next)
5568 *prev++ = ' ';
5569 while (next < end && HTTP_IS_SPHT(*next))
5570 next++;
5571 }
5572 }
5573 memmove(prev, next, end - next);
5574 return (prev - next);
5575}
5576
Christopher Faulet0f226952018-10-22 09:29:56 +02005577
5578/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005579 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005580 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005581static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005582{
5583 struct ist dst = ist2(str, 0);
5584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005586 goto end;
5587 if (dst.len + 1 > len)
5588 goto end;
5589 dst.ptr[dst.len++] = ' ';
5590
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005591 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005592 goto end;
5593 if (dst.len + 1 > len)
5594 goto end;
5595 dst.ptr[dst.len++] = ' ';
5596
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005597 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005598 end:
5599 return dst.len;
5600}
5601
Christopher Fauletf0523542018-10-24 11:06:58 +02005602/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005603 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005604 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005605static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005606{
5607 struct ist dst = ist2(str, 0);
5608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005609 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005610 goto end;
5611 if (dst.len + 1 > len)
5612 goto end;
5613 dst.ptr[dst.len++] = ' ';
5614
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005615 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005616 goto end;
5617 if (dst.len + 1 > len)
5618 goto end;
5619 dst.ptr[dst.len++] = ' ';
5620
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005621 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005622 end:
5623 return dst.len;
5624}
5625
5626
Christopher Faulet0f226952018-10-22 09:29:56 +02005627/*
5628 * Print a debug line with a start line.
5629 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005631{
5632 struct session *sess = strm_sess(s);
5633 int max;
5634
5635 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5636 dir,
5637 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5638 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5639
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005643 trash.area[trash.data++] = ' ';
5644
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005645 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005646 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005647 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005648 trash.area[trash.data++] = ' ';
5649
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005650 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005651 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005652 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 trash.area[trash.data++] = '\n';
5654
5655 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5656}
5657
5658/*
5659 * Print a debug line with a header.
5660 */
5661static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5662{
5663 struct session *sess = strm_sess(s);
5664 int max;
5665
5666 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5667 dir,
5668 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5669 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5670
5671 max = n.len;
5672 UBOUND(max, trash.size - trash.data - 3);
5673 chunk_memcat(&trash, n.ptr, max);
5674 trash.area[trash.data++] = ':';
5675 trash.area[trash.data++] = ' ';
5676
5677 max = v.len;
5678 UBOUND(max, trash.size - trash.data - 1);
5679 chunk_memcat(&trash, v.ptr, max);
5680 trash.area[trash.data++] = '\n';
5681
5682 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5683}
5684
5685
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005686__attribute__((constructor))
5687static void __htx_protocol_init(void)
5688{
5689}
5690
5691
5692/*
5693 * Local variables:
5694 * c-indent-level: 8
5695 * c-basic-offset: 8
5696 * End:
5697 */