blob: add9a102c5bb6341cba1e12d60cd059f1630922c [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
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 stream_inc_http_req_ctr(s);
151 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100152 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Fauletc549b562021-03-12 11:26:15 +0100153 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100154 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200155
Christopher Faulet9768c262018-10-22 09:34:31 +0200156 txn->status = 400;
157 msg->err_state = msg->msg_state;
158 msg->msg_state = HTTP_MSG_ERROR;
159 htx_reply_and_close(s, txn->status, NULL);
160 req->analysers &= AN_REQ_FLT_END;
161
Christopher Faulete0768eb2018-10-03 16:38:02 +0200162 if (!(s->flags & SF_FINST_MASK))
163 s->flags |= SF_FINST_R;
164 return 0;
165 }
166
Christopher Faulet9768c262018-10-22 09:34:31 +0200167 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
169 if (!(s->flags & SF_ERR_MASK))
170 s->flags |= SF_ERR_CLITO;
171
172 if (txn->flags & TX_WAIT_NEXT_RQ)
173 goto failed_keep_alive;
174
175 if (sess->fe->options & PR_O_IGNORE_PRB)
176 goto failed_keep_alive;
177
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 stream_inc_http_req_ctr(s);
179 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100180 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Fauletc549b562021-03-12 11:26:15 +0100181 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183
Christopher Faulet9768c262018-10-22 09:34:31 +0200184 txn->status = 408;
185 msg->err_state = msg->msg_state;
186 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100187 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 req->analysers &= AN_REQ_FLT_END;
189
Christopher Faulete0768eb2018-10-03 16:38:02 +0200190 if (!(s->flags & SF_FINST_MASK))
191 s->flags |= SF_FINST_R;
192 return 0;
193 }
194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200196 else if (req->flags & CF_SHUTR) {
197 if (!(s->flags & SF_ERR_MASK))
198 s->flags |= SF_ERR_CLICL;
199
200 if (txn->flags & TX_WAIT_NEXT_RQ)
201 goto failed_keep_alive;
202
203 if (sess->fe->options & PR_O_IGNORE_PRB)
204 goto failed_keep_alive;
205
Christopher Faulete0768eb2018-10-03 16:38:02 +0200206 stream_inc_http_err_ctr(s);
207 stream_inc_http_req_ctr(s);
208 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100209 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Fauletc549b562021-03-12 11:26:15 +0100210 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212
Christopher Faulet9768c262018-10-22 09:34:31 +0200213 txn->status = 400;
214 msg->err_state = msg->msg_state;
215 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100216 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200217 req->analysers &= AN_REQ_FLT_END;
218
Christopher Faulete0768eb2018-10-03 16:38:02 +0200219 if (!(s->flags & SF_FINST_MASK))
220 s->flags |= SF_FINST_R;
221 return 0;
222 }
223
224 channel_dont_connect(req);
225 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
226 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100227
Christopher Fauletc549b562021-03-12 11:26:15 +0100228 if (sess->listener && (sess->listener->options & LI_O_NOQUICKACK) && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200229 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
230 /* We need more data, we have to re-enable quick-ack in case we
231 * previously disabled it, otherwise we might cause the client
232 * to delay next data.
233 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100234 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200235 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236
Christopher Faulet47365272018-10-31 17:40:50 +0100237 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200238 /* If the client starts to talk, let's fall back to
239 * request timeout processing.
240 */
241 txn->flags &= ~TX_WAIT_NEXT_RQ;
242 req->analyse_exp = TICK_ETERNITY;
243 }
244
245 /* just set the request timeout once at the beginning of the request */
246 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100247 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200248 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
249 else
250 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
251 }
252
253 /* we're not ready yet */
254 return 0;
255
256 failed_keep_alive:
257 /* Here we process low-level errors for keep-alive requests. In
258 * short, if the request is not the first one and it experiences
259 * a timeout, read error or shutdown, we just silently close so
260 * that the client can try again.
261 */
262 txn->status = 0;
263 msg->msg_state = HTTP_MSG_RQBEFORE;
264 req->analysers &= AN_REQ_FLT_END;
265 s->logs.logwait = 0;
266 s->logs.level = 0;
267 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200268 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200269 return 0;
270 }
271
Christopher Faulet9768c262018-10-22 09:34:31 +0200272 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200273 stream_inc_http_req_ctr(s);
274 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
275
Christopher Faulet9768c262018-10-22 09:34:31 +0200276 /* kill the pending keep-alive timeout */
277 txn->flags &= ~TX_WAIT_NEXT_RQ;
278 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200279
Christopher Faulet29f17582019-05-23 11:03:26 +0200280 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200281 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 /* 0: we might have to print this header in debug mode */
284 if (unlikely((global.mode & MODE_DEBUG) &&
285 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
286 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200287
Christopher Faulet03599112018-11-27 11:21:21 +0100288 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200289
Christopher Fauleta3f15502019-05-13 15:27:23 +0200290 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200291 struct htx_blk *blk = htx_get_blk(htx, pos);
292 enum htx_blk_type type = htx_get_blk_type(blk);
293
294 if (type == HTX_BLK_EOH)
295 break;
296 if (type != HTX_BLK_HDR)
297 continue;
298
299 htx_debug_hdr("clihdr", s,
300 htx_get_blk_name(htx, blk),
301 htx_get_blk_value(htx, blk));
302 }
303 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200304
305 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100306 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100308 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100309 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200310 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100312 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100313 if (sl->flags & HTX_SL_F_BODYLESS)
314 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200315
316 /* we can make use of server redirect on GET and HEAD */
317 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
318 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100319 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200321 goto return_bad_req;
322 }
323
324 /*
325 * 2: check if the URI matches the monitor_uri.
326 * We have to do this for every request which gets in, because
327 * the monitor-uri is defined by the frontend.
328 */
329 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet943ab4d2020-02-18 14:51:51 +0100330 isteq(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 /*
332 * We have found the monitor URI
333 */
334 struct acl_cond *cond;
335
336 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100337 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200338
339 /* Check if we want to fail this monitor request or not */
340 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
341 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
342
343 ret = acl_pass(ret);
344 if (cond->pol == ACL_COND_UNLESS)
345 ret = !ret;
346
347 if (ret) {
348 /* we fail this request, let's return 503 service unavail */
349 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100350 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200351 if (!(s->flags & SF_ERR_MASK))
352 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
353 goto return_prx_cond;
354 }
355 }
356
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800357 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200358 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100359 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 if (!(s->flags & SF_ERR_MASK))
361 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
362 goto return_prx_cond;
363 }
364
365 /*
366 * 3: Maybe we have to copy the original REQURI for the logs ?
367 * Note: we cannot log anymore if the request has been
368 * classified as invalid.
369 */
370 if (unlikely(s->logs.logwait & LW_REQ)) {
371 /* we have a complete HTTP request that we must log */
372 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200373 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200374
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
376 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377
378 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
379 s->do_log(s);
380 } else {
381 ha_alert("HTTP logging : out of memory.\n");
382 }
383 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385 /* if the frontend has "option http-use-proxy-header", we'll check if
386 * we have what looks like a proxied connection instead of a connection,
387 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
388 * Note that this is *not* RFC-compliant, however browsers and proxies
389 * happen to do that despite being non-standard :-(
390 * We consider that a request not beginning with either '/' or '*' is
391 * a proxied connection, which covers both "scheme://location" and
392 * CONNECT ip:port.
393 */
394 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100395 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200396 txn->flags |= TX_USE_PX_CONN;
397
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 /* 5: we may need to capture headers */
399 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200400 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200401
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100402 /* by default, close the stream at the end of the transaction. */
403 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200404
405 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200406 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200407 req->analysers |= AN_REQ_HTTP_BODY;
408
409 /*
410 * RFC7234#4:
411 * A cache MUST write through requests with methods
412 * that are unsafe (Section 4.2.1 of [RFC7231]) to
413 * the origin server; i.e., a cache is not allowed
414 * to generate a reply to such a request before
415 * having forwarded the request and having received
416 * a corresponding response.
417 *
418 * RFC7231#4.2.1:
419 * Of the request methods defined by this
420 * specification, the GET, HEAD, OPTIONS, and TRACE
421 * methods are defined to be safe.
422 */
423 if (likely(txn->meth == HTTP_METH_GET ||
424 txn->meth == HTTP_METH_HEAD ||
425 txn->meth == HTTP_METH_OPTIONS ||
426 txn->meth == HTTP_METH_TRACE))
427 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
428
429 /* end of job, return OK */
430 req->analysers &= ~an_bit;
431 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200432
Christopher Faulete0768eb2018-10-03 16:38:02 +0200433 return 1;
434
435 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200436 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200437 txn->req.err_state = txn->req.msg_state;
438 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100439 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100440 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +0100441 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443
444 return_prx_cond:
445 if (!(s->flags & SF_ERR_MASK))
446 s->flags |= SF_ERR_PRXCOND;
447 if (!(s->flags & SF_FINST_MASK))
448 s->flags |= SF_FINST_R;
449
450 req->analysers &= AN_REQ_FLT_END;
451 req->analyse_exp = TICK_ETERNITY;
452 return 0;
453}
454
455
456/* This stream analyser runs all HTTP request processing which is common to
457 * frontends and backends, which means blocking ACLs, filters, connection-close,
458 * reqadd, stats and redirects. This is performed for the designated proxy.
459 * It returns 1 if the processing can continue on next analysers, or zero if it
460 * either needs more data or wants to immediately abort the request (eg: deny,
461 * error, ...).
462 */
463int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
464{
465 struct session *sess = s->sess;
466 struct http_txn *txn = s->txn;
467 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200468 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200469 struct redirect_rule *rule;
470 struct cond_wordlist *wl;
471 enum rule_result verdict;
472 int deny_status = HTTP_ERR_403;
473 struct connection *conn = objt_conn(sess->origin);
474
475 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
476 /* we need more data */
477 goto return_prx_yield;
478 }
479
480 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
481 now_ms, __FUNCTION__,
482 s,
483 req,
484 req->rex, req->wex,
485 req->flags,
486 ci_data(req),
487 req->analysers);
488
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100489 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200490
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200491 /* just in case we have some per-backend tracking. Only called the first
492 * execution of the analyser. */
493 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
494 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200495
496 /* evaluate http-request rules */
497 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200498 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200499
500 switch (verdict) {
501 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
502 goto return_prx_yield;
503
504 case HTTP_RULE_RES_CONT:
505 case HTTP_RULE_RES_STOP: /* nothing to do */
506 break;
507
508 case HTTP_RULE_RES_DENY: /* deny or tarpit */
509 if (txn->flags & TX_CLTARPIT)
510 goto tarpit;
511 goto deny;
512
513 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
514 goto return_prx_cond;
515
516 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
517 goto done;
518
519 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
520 goto return_bad_req;
521 }
522 }
523
524 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
Olivier Houchard629693f2020-01-23 14:57:36 +0100525 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200526 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200527
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 ctx.blk = NULL;
529 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
530 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200531 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200532 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 }
534
535 /* OK at this stage, we know that the request was accepted according to
536 * the http-request rules, we can check for the stats. Note that the
537 * URI is detected *before* the req* rules in order not to be affected
538 * by a possible reqrep, while they are processed *after* so that a
539 * reqdeny can still block them. This clearly needs to change in 1.6!
540 */
Christopher Faulet4629d082019-07-04 11:27:15 +0200541 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100543 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 txn->status = 500;
545 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100546 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200547
548 if (!(s->flags & SF_ERR_MASK))
549 s->flags |= SF_ERR_RESOURCE;
550 goto return_prx_cond;
551 }
552
553 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200554 htx_handle_stats(s, req);
555 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200556 /* not all actions implemented: deny, allow, auth */
557
558 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
559 goto deny;
560
561 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
562 goto return_prx_cond;
563 }
564
565 /* evaluate the req* rules except reqadd */
566 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200567 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200568 goto return_bad_req;
569
570 if (txn->flags & TX_CLDENY)
571 goto deny;
572
573 if (txn->flags & TX_CLTARPIT) {
574 deny_status = HTTP_ERR_500;
575 goto tarpit;
576 }
577 }
578
579 /* add request headers from the rule sets in the same order */
580 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200581 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200582 if (wl->cond) {
583 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
584 ret = acl_pass(ret);
585 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
586 ret = !ret;
587 if (!ret)
588 continue;
589 }
590
Christopher Fauletff2759f2018-10-24 11:13:16 +0200591 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
592 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200593 goto return_bad_req;
594 }
595
Christopher Faulet2571bc62019-03-01 11:44:26 +0100596 /* Proceed with the applets now. */
597 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200598 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100599 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100601 if (htx_handle_expect_hdr(s, htx, msg) == -1)
602 goto return_bad_req;
603
Christopher Faulete0768eb2018-10-03 16:38:02 +0200604 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
605 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
606 if (!(s->flags & SF_FINST_MASK))
607 s->flags |= SF_FINST_R;
608
609 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
610 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
611 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
612 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100613
614 req->flags |= CF_SEND_DONTWAIT;
615 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200616 goto done;
617 }
618
619 /* check whether we have some ACLs set to redirect this request */
620 list_for_each_entry(rule, &px->redirect_rules, list) {
621 if (rule->cond) {
622 int ret;
623
624 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
625 ret = acl_pass(ret);
626 if (rule->cond->pol == ACL_COND_UNLESS)
627 ret = !ret;
628 if (!ret)
629 continue;
630 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200631 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200632 goto return_bad_req;
633 goto done;
634 }
635
636 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
637 * If this happens, then the data will not come immediately, so we must
638 * send all what we have without waiting. Note that due to the small gain
639 * in waiting for the body of the request, it's easier to simply put the
640 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
641 * itself once used.
642 */
643 req->flags |= CF_SEND_DONTWAIT;
644
645 done: /* done with this analyser, continue with next ones that the calling
646 * points will have set, if any.
647 */
648 req->analyse_exp = TICK_ETERNITY;
649 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
650 req->analysers &= ~an_bit;
651 return 1;
652
653 tarpit:
654 /* Allow cookie logging
655 */
656 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200657 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200658
659 /* When a connection is tarpitted, we use the tarpit timeout,
660 * which may be the same as the connect timeout if unspecified.
661 * If unset, then set it to zero because we really want it to
662 * eventually expire. We build the tarpit as an analyser.
663 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100664 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200665
666 /* wipe the request out so that we can drop the connection early
667 * if the client closes first.
668 */
669 channel_dont_connect(req);
670
671 txn->status = http_err_codes[deny_status];
672
673 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
674 req->analysers |= AN_REQ_HTTP_TARPIT;
675 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
676 if (!req->analyse_exp)
677 req->analyse_exp = tick_add(now_ms, 0);
678 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100679 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200680 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +0100682 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 goto done_without_exp;
685
686 deny: /* this request was blocked (denied) */
687
688 /* Allow cookie logging
689 */
690 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200691 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200692
693 txn->flags |= TX_CLDENY;
694 txn->status = http_err_codes[deny_status];
695 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100696 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200697 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100698 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +0100701 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 goto return_prx_cond;
704
705 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200706 txn->req.err_state = txn->req.msg_state;
707 txn->req.msg_state = HTTP_MSG_ERROR;
708 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100709 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710
Olivier Houcharda798bf52019-03-08 18:52:00 +0100711 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +0100712 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714
715 return_prx_cond:
716 if (!(s->flags & SF_ERR_MASK))
717 s->flags |= SF_ERR_PRXCOND;
718 if (!(s->flags & SF_FINST_MASK))
719 s->flags |= SF_FINST_R;
720
721 req->analysers &= AN_REQ_FLT_END;
722 req->analyse_exp = TICK_ETERNITY;
723 return 0;
724
725 return_prx_yield:
726 channel_dont_connect(req);
727 return 0;
728}
729
730/* This function performs all the processing enabled for the current request.
731 * It returns 1 if the processing can continue on next analysers, or zero if it
732 * needs more data, encounters an error, or wants to immediately abort the
733 * request. It relies on buffers flags, and updates s->req.analysers.
734 */
735int htx_process_request(struct stream *s, struct channel *req, int an_bit)
736{
737 struct session *sess = s->sess;
738 struct http_txn *txn = s->txn;
739 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200740 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200741 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
742
743 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
744 /* we need more data */
745 channel_dont_connect(req);
746 return 0;
747 }
748
749 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
750 now_ms, __FUNCTION__,
751 s,
752 req,
753 req->rex, req->wex,
754 req->flags,
755 ci_data(req),
756 req->analysers);
757
758 /*
759 * Right now, we know that we have processed the entire headers
760 * and that unwanted requests have been filtered out. We can do
761 * whatever we want with the remaining request. Also, now we
762 * may have separate values for ->fe, ->be.
763 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100764 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200765
766 /*
767 * If HTTP PROXY is set we simply get remote server address parsing
768 * incoming request. Note that this requires that a connection is
769 * allocated on the server side.
770 */
771 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
772 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100773 struct htx_sl *sl;
774 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200775
776 /* Note that for now we don't reuse existing proxy connections */
777 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
778 txn->req.err_state = txn->req.msg_state;
779 txn->req.msg_state = HTTP_MSG_ERROR;
780 txn->status = 500;
781 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100782 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 if (!(s->flags & SF_ERR_MASK))
785 s->flags |= SF_ERR_RESOURCE;
786 if (!(s->flags & SF_FINST_MASK))
787 s->flags |= SF_FINST_R;
788
789 return 0;
790 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200791 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100792 uri = htx_sl_req_uri(sl);
793 path = http_get_path(uri);
794 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200795 goto return_bad_req;
796
797 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200798 * uri.ptr and path.ptr (excluded). If it was not found, we need
799 * to replace from all the uri by a single "/".
800 *
801 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100802 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200803 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200804 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100805 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau3284dd22019-07-18 16:17:15 +0200806 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200807 }
808
809 /*
810 * 7: Now we can work with the cookies.
811 * Note that doing so might move headers in the request, but
812 * the fields will stay coherent and the URI will not move.
813 * This should only be performed in the backend.
814 */
815 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100816 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200817
818 /* add unique-id if "header-unique-id" is specified */
819
820 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
821 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
822 goto return_bad_req;
823 s->unique_id[0] = '\0';
824 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
825 }
826
827 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200828 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
829 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
830
831 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200832 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200833 }
834
835 /*
836 * 9: add X-Forwarded-For if either the frontend or the backend
837 * asks for it.
838 */
839 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200840 struct http_hdr_ctx ctx = { .blk = NULL };
841 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
842 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
843
Christopher Faulete0768eb2018-10-03 16:38:02 +0200844 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200845 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 /* The header is set to be added only if none is present
847 * and we found it, so don't do anything.
848 */
849 }
850 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
851 /* Add an X-Forwarded-For header unless the source IP is
852 * in the 'except' network range.
853 */
854 if ((!sess->fe->except_mask.s_addr ||
855 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
856 != sess->fe->except_net.s_addr) &&
857 (!s->be->except_mask.s_addr ||
858 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
859 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200860 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200861
862 /* Note: we rely on the backend to get the header name to be used for
863 * x-forwarded-for, because the header is really meant for the backends.
864 * However, if the backend did not specify any option, we have to rely
865 * on the frontend's header name.
866 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200867 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
868 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200869 goto return_bad_req;
870 }
871 }
872 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
873 /* FIXME: for the sake of completeness, we should also support
874 * 'except' here, although it is mostly useless in this case.
875 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200876 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 inet_ntop(AF_INET6,
879 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
880 pn, sizeof(pn));
881
882 /* Note: we rely on the backend to get the header name to be used for
883 * x-forwarded-for, because the header is really meant for the backends.
884 * However, if the backend did not specify any option, we have to rely
885 * on the frontend's header name.
886 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200887 chunk_printf(&trash, "%s", pn);
888 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200889 goto return_bad_req;
890 }
891 }
892
893 /*
894 * 10: add X-Original-To if either the frontend or the backend
895 * asks for it.
896 */
897 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
898
899 /* FIXME: don't know if IPv6 can handle that case too. */
Christopher Faulet8fc16fb2021-02-26 12:45:56 +0100900 if (cli_conn && cli_conn->addr.to.ss_family == AF_INET) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200901 /* Add an X-Original-To header unless the destination IP is
902 * in the 'except' network range.
903 */
904 conn_get_to_addr(cli_conn);
905
906 if (cli_conn->addr.to.ss_family == AF_INET &&
907 ((!sess->fe->except_mask_to.s_addr ||
908 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
909 != sess->fe->except_to.s_addr) &&
910 (!s->be->except_mask_to.s_addr ||
911 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
912 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200913 struct ist hdr;
914 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200915
916 /* Note: we rely on the backend to get the header name to be used for
917 * x-original-to, because the header is really meant for the backends.
918 * However, if the backend did not specify any option, we have to rely
919 * on the frontend's header name.
920 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200921 if (s->be->orgto_hdr_len)
922 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
923 else
924 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200925
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200926 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
927 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928 goto return_bad_req;
929 }
930 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 }
932
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 /* If we have no server assigned yet and we're balancing on url_param
934 * with a POST request, we may be interested in checking the body for
935 * that parameter. This will be done in another analyser.
936 */
937 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100938 s->txn->meth == HTTP_METH_POST &&
939 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 channel_dont_connect(req);
941 req->analysers |= AN_REQ_HTTP_BODY;
942 }
943
944 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
945 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100946
Christopher Faulete0768eb2018-10-03 16:38:02 +0200947 /* We expect some data from the client. Unless we know for sure
948 * we already have a full request, we have to re-enable quick-ack
949 * in case we previously disabled it, otherwise we might cause
950 * the client to delay further data.
951 */
William Lallemanddb9fd042021-03-08 15:26:48 +0100952 if (sess->listener && (sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200953 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100954 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200955
956 /*************************************************************
957 * OK, that's finished for the headers. We have done what we *
958 * could. Let's switch to the DATA state. *
959 ************************************************************/
960 req->analyse_exp = TICK_ETERNITY;
961 req->analysers &= ~an_bit;
962
963 s->logs.tv_request = now;
964 /* OK let's go on with the BODY now */
965 return 1;
966
967 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200968 txn->req.err_state = txn->req.msg_state;
969 txn->req.msg_state = HTTP_MSG_ERROR;
970 txn->status = 400;
971 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100972 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200973
Olivier Houcharda798bf52019-03-08 18:52:00 +0100974 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +0100975 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977
978 if (!(s->flags & SF_ERR_MASK))
979 s->flags |= SF_ERR_PRXCOND;
980 if (!(s->flags & SF_FINST_MASK))
981 s->flags |= SF_FINST_R;
982 return 0;
983}
984
985/* This function is an analyser which processes the HTTP tarpit. It always
986 * returns zero, at the beginning because it prevents any other processing
987 * from occurring, and at the end because it terminates the request.
988 */
989int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
990{
991 struct http_txn *txn = s->txn;
992
993 /* This connection is being tarpitted. The CLIENT side has
994 * already set the connect expiration date to the right
995 * timeout. We just have to check that the client is still
996 * there and that the timeout has not expired.
997 */
998 channel_dont_connect(req);
999 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1000 !tick_is_expired(req->analyse_exp, now_ms))
1001 return 0;
1002
1003 /* We will set the queue timer to the time spent, just for
1004 * logging purposes. We fake a 500 server error, so that the
1005 * attacker will not suspect his connection has been tarpitted.
1006 * It will not cause trouble to the logs because we can exclude
1007 * the tarpitted connections by filtering on the 'PT' status flags.
1008 */
1009 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1010
Christopher Fauletef9a1692020-02-21 10:20:46 +01001011 htx_reply_and_close(s, txn->status, (!(req->flags & CF_READ_ERROR) ? htx_error_message(s) : NULL));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001012
1013 req->analysers &= AN_REQ_FLT_END;
1014 req->analyse_exp = TICK_ETERNITY;
1015
1016 if (!(s->flags & SF_ERR_MASK))
1017 s->flags |= SF_ERR_PRXCOND;
1018 if (!(s->flags & SF_FINST_MASK))
1019 s->flags |= SF_FINST_T;
1020 return 0;
1021}
1022
1023/* This function is an analyser which waits for the HTTP request body. It waits
1024 * for either the buffer to be full, or the full advertised contents to have
1025 * reached the buffer. It must only be called after the standard HTTP request
1026 * processing has occurred, because it expects the request to be parsed and will
1027 * look for the Expect header. It may send a 100-Continue interim response. It
1028 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1029 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1030 * needs to read more data, or 1 once it has completed its analysis.
1031 */
1032int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1033{
1034 struct session *sess = s->sess;
1035 struct http_txn *txn = s->txn;
1036 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001037 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001038
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039
1040 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1041 now_ms, __FUNCTION__,
1042 s,
1043 req,
1044 req->rex, req->wex,
1045 req->flags,
1046 ci_data(req),
1047 req->analysers);
1048
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001049 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001050
Willy Tarreau4236f032019-03-05 10:43:32 +01001051 if (htx->flags & HTX_FL_PARSING_ERROR)
1052 goto return_bad_req;
1053
Christopher Faulet1c8288d2020-11-16 16:03:35 +01001054 /* CONNECT requests have no body */
1055 if (txn->meth == HTTP_METH_CONNECT)
1056 goto http_end;
1057
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001058 if (msg->msg_state < HTTP_MSG_BODY)
1059 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001060
Christopher Faulete0768eb2018-10-03 16:38:02 +02001061 /* We have to parse the HTTP request body to find any required data.
1062 * "balance url_param check_post" should have been the only way to get
1063 * into this. We were brought here after HTTP header analysis, so all
1064 * related structures are ready.
1065 */
1066
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001067 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001068 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1069 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001070 }
1071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001073
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001074 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1075 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001076 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001077 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001078 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079 goto http_end;
1080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001082 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1083 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001084 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001085
1086 if (!(s->flags & SF_ERR_MASK))
1087 s->flags |= SF_ERR_CLITO;
1088 if (!(s->flags & SF_FINST_MASK))
1089 s->flags |= SF_FINST_D;
1090 goto return_err_msg;
1091 }
1092
1093 /* we get here if we need to wait for more data */
1094 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1095 /* Not enough data. We'll re-use the http-request
1096 * timeout here. Ideally, we should set the timeout
1097 * relative to the accept() date. We just set the
1098 * request timeout once at the beginning of the
1099 * request.
1100 */
1101 channel_dont_connect(req);
1102 if (!tick_isset(req->analyse_exp))
1103 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1104 return 0;
1105 }
1106
1107 http_end:
1108 /* The situation will not evolve, so let's give up on the analysis. */
1109 s->logs.tv_request = now; /* update the request timer to reflect full request */
1110 req->analysers &= ~an_bit;
1111 req->analyse_exp = TICK_ETERNITY;
1112 return 1;
1113
1114 return_bad_req: /* let's centralize all bad requests */
1115 txn->req.err_state = txn->req.msg_state;
1116 txn->req.msg_state = HTTP_MSG_ERROR;
1117 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001118 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001119
1120 if (!(s->flags & SF_ERR_MASK))
1121 s->flags |= SF_ERR_PRXCOND;
1122 if (!(s->flags & SF_FINST_MASK))
1123 s->flags |= SF_FINST_R;
1124
1125 return_err_msg:
1126 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01001128 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001129 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001130 return 0;
1131}
1132
1133/* This function is an analyser which forwards request body (including chunk
1134 * sizes if any). It is called as soon as we must forward, even if we forward
1135 * zero byte. The only situation where it must not be called is when we're in
1136 * tunnel mode and we want to forward till the close. It's used both to forward
1137 * remaining data and to resync after end of body. It expects the msg_state to
1138 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1139 * read more data, or 1 once we can go on with next request or end the stream.
1140 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1141 * bytes of pending data + the headers if not already done.
1142 */
1143int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1144{
1145 struct session *sess = s->sess;
1146 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001147 struct http_msg *msg = &txn->req;
1148 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001149 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001150 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001151
1152 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1153 now_ms, __FUNCTION__,
1154 s,
1155 req,
1156 req->rex, req->wex,
1157 req->flags,
1158 ci_data(req),
1159 req->analysers);
1160
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001161 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001162
1163 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1164 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1165 /* Output closed while we were sending data. We must abort and
1166 * wake the other side up.
1167 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001168 /* Don't abort yet if we had L7 retries activated and it
1169 * was a write error, we may recover.
1170 */
1171 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1172 (s->si[1].flags & SI_FL_L7_RETRY))
1173 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001174 msg->err_state = msg->msg_state;
1175 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001176 htx_end_request(s);
1177 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001178 return 1;
1179 }
1180
1181 /* Note that we don't have to send 100-continue back because we don't
1182 * need the data to complete our job, and it's up to the server to
1183 * decide whether to return 100, 417 or anything else in return of
1184 * an "Expect: 100-continue" header.
1185 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001186 if (msg->msg_state == HTTP_MSG_BODY)
1187 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001188
1189 /* Some post-connect processing might want us to refrain from starting to
1190 * forward data. Currently, the only reason for this is "balance url_param"
1191 * whichs need to parse/process the request after we've enabled forwarding.
1192 */
1193 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1194 if (!(s->res.flags & CF_READ_ATTACHED)) {
1195 channel_auto_connect(req);
1196 req->flags |= CF_WAKE_CONNECT;
1197 channel_dont_close(req); /* don't fail on early shutr */
1198 goto waiting;
1199 }
1200 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1201 }
1202
1203 /* in most states, we should abort in case of early close */
1204 channel_auto_close(req);
1205
1206 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001207 if (req->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001208 if (req->flags & CF_EOI)
1209 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01001210 }
1211 else {
1212 /* We can't process the buffer's contents yet */
1213 req->flags |= CF_WAKE_WRITE;
1214 goto missing_data_or_waiting;
1215 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001216 }
1217
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001218 if (msg->msg_state >= HTTP_MSG_ENDING)
1219 goto ending;
1220
1221 if (txn->meth == HTTP_METH_CONNECT) {
1222 msg->msg_state = HTTP_MSG_ENDING;
1223 goto ending;
1224 }
1225
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001226 /* Forward input data. We get it by removing all outgoing data not
1227 * forwarded yet from HTX data size. If there are some data filters, we
1228 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001230 if (HAS_REQ_DATA_FILTERS(s)) {
1231 ret = flt_http_payload(s, msg, htx->data);
1232 if (ret < 0)
1233 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001234 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001235 }
1236 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001237 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001238 if (msg->flags & HTTP_MSGF_XFER_LEN)
1239 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001240 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001241
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001242 if (htx->data != co_data(req))
1243 goto missing_data_or_waiting;
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001244
Christopher Faulet9768c262018-10-22 09:34:31 +02001245 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001246 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1247 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001248 */
1249 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1250 goto missing_data_or_waiting;
1251
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001252 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02001253
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001254 ending:
1255 /* other states, ENDING...TUNNEL */
1256 if (msg->msg_state >= HTTP_MSG_DONE)
1257 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001259 if (HAS_REQ_DATA_FILTERS(s)) {
1260 ret = flt_http_end(s, msg);
1261 if (ret <= 0) {
1262 if (!ret)
1263 goto missing_data_or_waiting;
1264 goto return_bad_req;
1265 }
1266 }
1267
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001268 if (txn->meth == HTTP_METH_CONNECT)
1269 msg->msg_state = HTTP_MSG_TUNNEL;
1270 else {
1271 msg->msg_state = HTTP_MSG_DONE;
1272 req->to_forward = 0;
1273 }
1274
1275 done:
1276 /* we don't want to forward closes on DONE except in tunnel mode. */
1277 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1278 channel_dont_close(req);
1279
Christopher Fauletf2824e62018-10-01 12:12:37 +02001280 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001282 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001283 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1284 if (req->flags & CF_SHUTW) {
1285 /* request errors are most likely due to the
1286 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001287 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001288 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001289 goto return_bad_req;
1290 }
1291 return 1;
1292 }
1293
1294 /* If "option abortonclose" is set on the backend, we want to monitor
1295 * the client's connection and forward any shutdown notification to the
1296 * server, which will decide whether to close or to go on processing the
1297 * request. We only do that in tunnel mode, and not in other modes since
1298 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001299 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001300 channel_auto_read(req);
1301 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1302 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1303 s->si[1].flags |= SI_FL_NOLINGER;
1304 channel_auto_close(req);
1305 }
1306 else if (s->txn->meth == HTTP_METH_POST) {
1307 /* POST requests may require to read extra CRLF sent by broken
1308 * browsers and which could cause an RST to be sent upon close
1309 * on some systems (eg: Linux). */
1310 channel_auto_read(req);
1311 }
1312 return 0;
1313
1314 missing_data_or_waiting:
1315 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001316 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001317 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001318
1319 waiting:
1320 /* waiting for the last bits to leave the buffer */
1321 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001322 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001323
Christopher Faulet47365272018-10-31 17:40:50 +01001324 if (htx->flags & HTX_FL_PARSING_ERROR)
1325 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001326
Christopher Faulete0768eb2018-10-03 16:38:02 +02001327 /* When TE: chunked is used, we need to get there again to parse remaining
1328 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1329 * And when content-length is used, we never want to let the possible
1330 * shutdown be forwarded to the other side, as the state machine will
1331 * take care of it once the client responds. It's also important to
1332 * prevent TIME_WAITs from accumulating on the backend side, and for
1333 * HTTP/2 where the last frame comes with a shutdown.
1334 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001335 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001336 channel_dont_close(req);
1337
1338 /* We know that more data are expected, but we couldn't send more that
1339 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1340 * system knows it must not set a PUSH on this first part. Interactive
1341 * modes are already handled by the stream sock layer. We must not do
1342 * this in content-length mode because it could present the MSG_MORE
1343 * flag with the last block of forwarded data, which would cause an
1344 * additional delay to be observed by the receiver.
1345 */
1346 if (msg->flags & HTTP_MSGF_TE_CHNK)
1347 req->flags |= CF_EXPECT_MORE;
1348
1349 return 0;
1350
Christopher Faulet93e02d82019-03-08 14:18:50 +01001351 return_cli_abort:
1352 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1353 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1354 if (objt_server(s->target))
1355 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1356 if (!(s->flags & SF_ERR_MASK))
1357 s->flags |= SF_ERR_CLICL;
1358 status = 400;
1359 goto return_error;
1360
1361 return_srv_abort:
1362 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1363 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1364 if (objt_server(s->target))
1365 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1366 if (!(s->flags & SF_ERR_MASK))
1367 s->flags |= SF_ERR_SRVCL;
1368 status = 502;
1369 goto return_error;
1370
1371 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001372 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01001373 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001374 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001376 s->flags |= SF_ERR_CLICL;
1377 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378
Christopher Faulet93e02d82019-03-08 14:18:50 +01001379 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001380 txn->req.err_state = txn->req.msg_state;
1381 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001382 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001384 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001385 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001386 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001387 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001388 }
1389 req->analysers &= AN_REQ_FLT_END;
1390 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 +01001391 if (!(s->flags & SF_FINST_MASK))
1392 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001393 return 0;
1394}
1395
Olivier Houcharda254a372019-04-05 15:30:12 +02001396/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1397/* Returns 0 if we can attempt to retry, -1 otherwise */
1398static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1399{
1400 struct channel *req, *res;
1401 int co_data;
1402
1403 si->conn_retries--;
1404 if (si->conn_retries < 0)
1405 return -1;
1406
Willy Tarreau223995e2019-05-04 10:38:31 +02001407 if (objt_server(s->target))
1408 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1409 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1410
Olivier Houcharda254a372019-04-05 15:30:12 +02001411 req = &s->req;
1412 res = &s->res;
1413 /* Remove any write error from the request, and read error from the response */
1414 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1415 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1416 res->analysers = 0;
1417 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchardc86a9662020-05-12 22:18:14 +02001418 s->flags &= ~SF_ADDR_SET;
Olivier Houchard530249c2019-07-12 16:16:59 +02001419 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001420 si->exp = TICK_ETERNITY;
1421 res->rex = TICK_ETERNITY;
1422 res->to_forward = 0;
1423 res->analyse_exp = TICK_ETERNITY;
1424 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001425 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001426 si_release_endpoint(&s->si[1]);
1427 b_free(&req->buf);
1428 /* Swap the L7 buffer with the channel buffer */
1429 /* We know we stored the co_data as b_data, so get it there */
1430 co_data = b_data(&si->l7_buffer);
1431 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1432 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1433
1434 co_set_data(req, co_data);
1435 b_reset(&res->buf);
1436 co_set_data(res, 0);
1437 return 0;
1438}
1439
Christopher Faulete0768eb2018-10-03 16:38:02 +02001440/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1441 * processing can continue on next analysers, or zero if it either needs more
1442 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1443 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1444 * when it has nothing left to do, and may remove any analyser when it wants to
1445 * abort.
1446 */
1447int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1448{
Christopher Faulet9768c262018-10-22 09:34:31 +02001449 /*
1450 * We will analyze a complete HTTP response to check the its syntax.
1451 *
1452 * Once the start line and all headers are received, we may perform a
1453 * capture of the error (if any), and we will set a few fields. We also
1454 * logging and finally headers capture.
1455 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456 struct session *sess = s->sess;
1457 struct http_txn *txn = s->txn;
1458 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001459 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001460 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001461 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001462 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001463 int n;
1464
1465 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1466 now_ms, __FUNCTION__,
1467 s,
1468 rep,
1469 rep->rex, rep->wex,
1470 rep->flags,
1471 ci_data(rep),
1472 rep->analysers);
1473
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001474 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001475
Willy Tarreau4236f032019-03-05 10:43:32 +01001476 /* Parsing errors are caught here */
1477 if (htx->flags & HTX_FL_PARSING_ERROR)
1478 goto return_bad_res;
1479
Christopher Faulete0768eb2018-10-03 16:38:02 +02001480 /*
1481 * Now we quickly check if we have found a full valid response.
1482 * If not so, we check the FD and buffer states before leaving.
1483 * A full response is indicated by the fact that we have seen
1484 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1485 * responses are checked first.
1486 *
1487 * Depending on whether the client is still there or not, we
1488 * may send an error response back or not. Note that normally
1489 * we should only check for HTTP status there, and check I/O
1490 * errors somewhere else.
1491 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001492 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001493 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001494 /* 1: have we encountered a read error ? */
1495 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001496 struct connection *conn = NULL;
1497
Olivier Houchard865d8392019-05-03 22:46:27 +02001498 if (objt_cs(s->si[1].end))
1499 conn = objt_cs(s->si[1].end)->conn;
1500
1501 if (si_b->flags & SI_FL_L7_RETRY &&
1502 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001503 /* If we arrive here, then CF_READ_ERROR was
1504 * set by si_cs_recv() because we matched a
1505 * status, overwise it would have removed
1506 * the SI_FL_L7_RETRY flag, so it's ok not
1507 * to check s->be->retry_type.
1508 */
1509 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1510 return 0;
1511 }
1512
Olivier Houchard6db16992019-05-17 15:40:49 +02001513 if (txn->flags & TX_NOT_FIRST)
1514 goto abort_keep_alive;
1515
Olivier Houcharda798bf52019-03-08 18:52:00 +01001516 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001517 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001518 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001519 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520 }
1521
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001523 s->req.analysers &= AN_REQ_FLT_END;
1524 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 txn->status = 502;
1526
1527 /* Check to see if the server refused the early data.
1528 * If so, just send a 425
1529 */
Willy Tarreau1b4cc2e2020-06-23 05:58:20 +02001530 if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001531 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001532 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001533 do_l7_retry(s, si_b) == 0)
1534 return 0;
1535 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 }
1537
1538 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001539 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540
1541 if (!(s->flags & SF_ERR_MASK))
1542 s->flags |= SF_ERR_SRVCL;
1543 if (!(s->flags & SF_FINST_MASK))
1544 s->flags |= SF_FINST_H;
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001550 if ((si_b->flags & SI_FL_L7_RETRY) &&
1551 (s->be->retry_type & PR_RE_TIMEOUT)) {
1552 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1553 return 0;
1554 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001555 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001558 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 }
1560
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001562 s->req.analysers &= AN_REQ_FLT_END;
1563 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564 txn->status = 504;
1565 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001566 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001567
1568 if (!(s->flags & SF_ERR_MASK))
1569 s->flags |= SF_ERR_SRVTO;
1570 if (!(s->flags & SF_FINST_MASK))
1571 s->flags |= SF_FINST_H;
1572 return 0;
1573 }
1574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001577 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1578 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001580 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001581
1582 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001583 s->req.analysers &= AN_REQ_FLT_END;
1584 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001586 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587
1588 if (!(s->flags & SF_ERR_MASK))
1589 s->flags |= SF_ERR_CLICL;
1590 if (!(s->flags & SF_FINST_MASK))
1591 s->flags |= SF_FINST_H;
1592
1593 /* process_stream() will take care of the error */
1594 return 0;
1595 }
1596
Christopher Faulet9768c262018-10-22 09:34:31 +02001597 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001598 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001599 if ((si_b->flags & SI_FL_L7_RETRY) &&
1600 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1601 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1602 return 0;
1603 }
1604
Olivier Houchard6db16992019-05-17 15:40:49 +02001605 if (txn->flags & TX_NOT_FIRST)
1606 goto abort_keep_alive;
1607
Olivier Houcharda798bf52019-03-08 18:52:00 +01001608 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001609 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001610 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001611 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 }
1613
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001615 s->req.analysers &= AN_REQ_FLT_END;
1616 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001617 txn->status = 502;
1618 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001619 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620
1621 if (!(s->flags & SF_ERR_MASK))
1622 s->flags |= SF_ERR_SRVCL;
1623 if (!(s->flags & SF_FINST_MASK))
1624 s->flags |= SF_FINST_H;
1625 return 0;
1626 }
1627
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001630 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631 goto abort_keep_alive;
1632
Olivier Houcharda798bf52019-03-08 18:52:00 +01001633 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001635 s->req.analysers &= AN_REQ_FLT_END;
1636 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001637
1638 if (!(s->flags & SF_ERR_MASK))
1639 s->flags |= SF_ERR_CLICL;
1640 if (!(s->flags & SF_FINST_MASK))
1641 s->flags |= SF_FINST_H;
1642
1643 /* process_stream() will take care of the error */
1644 return 0;
1645 }
1646
1647 channel_dont_close(rep);
1648 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1649 return 0;
1650 }
1651
1652 /* More interesting part now : we know that we have a complete
1653 * response which at least looks like HTTP. We have an indicator
1654 * of each header's length, so we can parse them quickly.
1655 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001656 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001657 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001658 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001659
Christopher Faulet9768c262018-10-22 09:34:31 +02001660 /* 0: we might have to print this header in debug mode */
1661 if (unlikely((global.mode & MODE_DEBUG) &&
1662 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1663 int32_t pos;
1664
Christopher Faulet03599112018-11-27 11:21:21 +01001665 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001666
Christopher Fauleta3f15502019-05-13 15:27:23 +02001667 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001668 struct htx_blk *blk = htx_get_blk(htx, pos);
1669 enum htx_blk_type type = htx_get_blk_type(blk);
1670
1671 if (type == HTX_BLK_EOH)
1672 break;
1673 if (type != HTX_BLK_HDR)
1674 continue;
1675
1676 htx_debug_hdr("srvhdr", s,
1677 htx_get_blk_name(htx, blk),
1678 htx_get_blk_value(htx, blk));
1679 }
1680 }
1681
Christopher Faulet03599112018-11-27 11:21:21 +01001682 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001683 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001684 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001685 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001686 if (sl->flags & HTX_SL_F_XFER_LEN) {
1687 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001688 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001689 if (sl->flags & HTX_SL_F_BODYLESS)
1690 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001691 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001692
1693 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694 if (n < 1 || n > 5)
1695 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001696
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697 /* when the client triggers a 4xx from the server, it's most often due
1698 * to a missing object or permission. These events should be tracked
1699 * because if they happen often, it may indicate a brute force or a
1700 * vulnerability scan.
1701 */
1702 if (n == 4)
1703 stream_inc_http_err_ctr(s);
1704
1705 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001706 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001707
Christopher Faulete0768eb2018-10-03 16:38:02 +02001708 /* Adjust server's health based on status code. Note: status codes 501
1709 * and 505 are triggered on demand by client request, so we must not
1710 * count them as server failures.
1711 */
1712 if (objt_server(s->target)) {
1713 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001714 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001716 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 }
1718
1719 /*
1720 * We may be facing a 100-continue response, or any other informational
1721 * 1xx response which is non-final, in which case this is not the right
1722 * response, and we're waiting for the next one. Let's allow this response
1723 * to go to the client and wait for the next one. There's an exception for
1724 * 101 which is used later in the code to switch protocols.
1725 */
1726 if (txn->status < 200 &&
1727 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001728 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001729 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001730 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001731 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001732 txn->status = 0;
1733 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet5761e7d2020-08-31 11:07:07 +02001734 rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001735 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001736 }
1737
1738 /*
1739 * 2: check for cacheability.
1740 */
1741
1742 switch (txn->status) {
1743 case 200:
1744 case 203:
1745 case 204:
1746 case 206:
1747 case 300:
1748 case 301:
1749 case 404:
1750 case 405:
1751 case 410:
1752 case 414:
1753 case 501:
1754 break;
1755 default:
1756 /* RFC7231#6.1:
1757 * Responses with status codes that are defined as
1758 * cacheable by default (e.g., 200, 203, 204, 206,
1759 * 300, 301, 404, 405, 410, 414, and 501 in this
1760 * specification) can be reused by a cache with
1761 * heuristic expiration unless otherwise indicated
1762 * by the method definition or explicit cache
1763 * controls [RFC7234]; all other status codes are
1764 * not cacheable by default.
1765 */
1766 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1767 break;
1768 }
1769
1770 /*
1771 * 3: we may need to capture headers
1772 */
1773 s->logs.logwait &= ~LW_RESP;
1774 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001775 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776
Christopher Faulet9768c262018-10-22 09:34:31 +02001777 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001778 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1779 txn->status == 101)) {
1780 /* Either we've established an explicit tunnel, or we're
1781 * switching the protocol. In both cases, we're very unlikely
1782 * to understand the next protocols. We have to switch to tunnel
1783 * mode, so that we transfer the request and responses then let
1784 * this protocol pass unmodified. When we later implement specific
1785 * parsers for such protocols, we'll want to check the Upgrade
1786 * header which contains information about that protocol for
1787 * responses with status 101 (eg: see RFC2817 about TLS).
1788 */
1789 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001790 }
1791
Christopher Faulet61608322018-11-23 16:23:45 +01001792 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1793 * 407 (Proxy-Authenticate) responses and set the connection to private
1794 */
1795 srv_conn = cs_conn(objt_cs(s->si[1].end));
1796 if (srv_conn) {
1797 struct ist hdr;
1798 struct http_hdr_ctx ctx;
1799
1800 if (txn->status == 401)
1801 hdr = ist("WWW-Authenticate");
1802 else if (txn->status == 407)
1803 hdr = ist("Proxy-Authenticate");
1804 else
1805 goto end;
1806
1807 ctx.blk = NULL;
1808 while (http_find_header(htx, hdr, &ctx, 0)) {
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001809 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1810 * possibly followed by blanks and a base64 string, the connection
1811 * is private. Since it's a mess to deal with, we only check for
1812 * values starting with "NTLM" or "Nego". Note that often multiple
1813 * headers are sent by the server there.
1814 */
1815 if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
Willy Tarreaud3be89b2020-05-07 19:10:15 +02001816 (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001817 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001818 srv_conn->flags |= CO_FL_PRIVATE;
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001819 break;
Olivier Houchard250031e2019-05-29 15:01:50 +02001820 }
Christopher Faulet61608322018-11-23 16:23:45 +01001821 }
1822 }
1823
1824 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001825 /* we want to have the response time before we start processing it */
1826 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1827
1828 /* end of job, return OK */
1829 rep->analysers &= ~an_bit;
1830 rep->analyse_exp = TICK_ETERNITY;
1831 channel_auto_close(rep);
1832 return 1;
1833
Christopher Faulet47365272018-10-31 17:40:50 +01001834 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001835 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001836 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001837 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001838 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001839 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001840 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001841 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001842 do_l7_retry(s, si_b) == 0)
1843 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001844 txn->status = 502;
1845 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001846 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001847 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001848 s->req.analysers &= AN_REQ_FLT_END;
1849 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001850
1851 if (!(s->flags & SF_ERR_MASK))
1852 s->flags |= SF_ERR_PRXCOND;
1853 if (!(s->flags & SF_FINST_MASK))
1854 s->flags |= SF_FINST_H;
1855 return 0;
1856
Christopher Faulete0768eb2018-10-03 16:38:02 +02001857 abort_keep_alive:
1858 /* A keep-alive request to the server failed on a network error.
1859 * The client is required to retry. We need to close without returning
1860 * any other information so that the client retries.
1861 */
1862 txn->status = 0;
1863 rep->analysers &= AN_RES_FLT_END;
1864 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001865 s->logs.logwait = 0;
1866 s->logs.level = 0;
1867 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001868 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 return 0;
1870}
1871
1872/* This function performs all the processing enabled for the current response.
1873 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1874 * and updates s->res.analysers. It might make sense to explode it into several
1875 * other functions. It works like process_request (see indications above).
1876 */
1877int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1878{
1879 struct session *sess = s->sess;
1880 struct http_txn *txn = s->txn;
1881 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001882 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001883 struct proxy *cur_proxy;
1884 struct cond_wordlist *wl;
1885 enum rule_result ret = HTTP_RULE_RES_CONT;
1886
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001887 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1888 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001889
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1891 now_ms, __FUNCTION__,
1892 s,
1893 rep,
1894 rep->rex, rep->wex,
1895 rep->flags,
1896 ci_data(rep),
1897 rep->analysers);
1898
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001899 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001900
1901 /* The stats applet needs to adjust the Connection header but we don't
1902 * apply any filter there.
1903 */
1904 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1905 rep->analysers &= ~an_bit;
1906 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001907 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001908 }
1909
1910 /*
1911 * We will have to evaluate the filters.
1912 * As opposed to version 1.2, now they will be evaluated in the
1913 * filters order and not in the header order. This means that
1914 * each filter has to be validated among all headers.
1915 *
1916 * Filters are tried with ->be first, then with ->fe if it is
1917 * different from ->be.
1918 *
1919 * Maybe we are in resume condiion. In this case I choose the
1920 * "struct proxy" which contains the rule list matching the resume
1921 * pointer. If none of theses "struct proxy" match, I initialise
1922 * the process with the first one.
1923 *
1924 * In fact, I check only correspondance betwwen the current list
1925 * pointer and the ->fe rule list. If it doesn't match, I initialize
1926 * the loop with the ->be.
1927 */
1928 if (s->current_rule_list == &sess->fe->http_res_rules)
1929 cur_proxy = sess->fe;
1930 else
1931 cur_proxy = s->be;
1932 while (1) {
1933 struct proxy *rule_set = cur_proxy;
1934
1935 /* evaluate http-response rules */
1936 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001937 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001938
1939 if (ret == HTTP_RULE_RES_BADREQ)
1940 goto return_srv_prx_502;
1941
1942 if (ret == HTTP_RULE_RES_DONE) {
1943 rep->analysers &= ~an_bit;
1944 rep->analyse_exp = TICK_ETERNITY;
1945 return 1;
1946 }
1947 }
1948
1949 /* we need to be called again. */
1950 if (ret == HTTP_RULE_RES_YIELD) {
1951 channel_dont_close(rep);
1952 return 0;
1953 }
1954
1955 /* try headers filters */
1956 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001957 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1958 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001959 }
1960
1961 /* has the response been denied ? */
1962 if (txn->flags & TX_SVDENY) {
1963 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001964 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001965
Olivier Houcharda798bf52019-03-08 18:52:00 +01001966 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1967 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01001968 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001969 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001970 goto return_srv_prx_502;
1971 }
1972
1973 /* add response headers from the rule sets in the same order */
1974 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001975 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001976 if (txn->status < 200 && txn->status != 101)
1977 break;
1978 if (wl->cond) {
1979 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1980 ret = acl_pass(ret);
1981 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1982 ret = !ret;
1983 if (!ret)
1984 continue;
1985 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001986
1987 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1988 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001989 goto return_bad_resp;
1990 }
1991
1992 /* check whether we're already working on the frontend */
1993 if (cur_proxy == sess->fe)
1994 break;
1995 cur_proxy = sess->fe;
1996 }
1997
1998 /* After this point, this anayzer can't return yield, so we can
1999 * remove the bit corresponding to this analyzer from the list.
2000 *
2001 * Note that the intermediate returns and goto found previously
2002 * reset the analyzers.
2003 */
2004 rep->analysers &= ~an_bit;
2005 rep->analyse_exp = TICK_ETERNITY;
2006
2007 /* OK that's all we can do for 1xx responses */
2008 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002009 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002010
2011 /*
2012 * Now check for a server cookie.
2013 */
2014 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002015 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002016
2017 /*
2018 * Check for cache-control or pragma headers if required.
2019 */
2020 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2021 check_response_for_cacheability(s, rep);
2022
2023 /*
2024 * Add server cookie in the response if needed
2025 */
2026 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2027 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2028 (!(s->flags & SF_DIRECT) ||
2029 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2030 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2031 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2032 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2033 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2034 !(s->flags & SF_IGNORE_PRST)) {
2035 /* the server is known, it's not the one the client requested, or the
2036 * cookie's last seen date needs to be refreshed. We have to
2037 * insert a set-cookie here, except if we want to insert only on POST
2038 * requests and this one isn't. Note that servers which don't have cookies
2039 * (eg: some backup servers) will return a full cookie removal request.
2040 */
2041 if (!objt_server(s->target)->cookie) {
2042 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002043 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002044 s->be->cookie_name);
2045 }
2046 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002047 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002048
2049 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2050 /* emit last_date, which is mandatory */
2051 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2052 s30tob64((date.tv_sec+3) >> 2,
2053 trash.area + trash.data);
2054 trash.data += 5;
2055
2056 if (s->be->cookie_maxlife) {
2057 /* emit first_date, which is either the original one or
2058 * the current date.
2059 */
2060 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2061 s30tob64(txn->cookie_first_date ?
2062 txn->cookie_first_date >> 2 :
2063 (date.tv_sec+3) >> 2,
2064 trash.area + trash.data);
2065 trash.data += 5;
2066 }
2067 }
2068 chunk_appendf(&trash, "; path=/");
2069 }
2070
2071 if (s->be->cookie_domain)
2072 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2073
2074 if (s->be->ck_opts & PR_CK_HTTPONLY)
2075 chunk_appendf(&trash, "; HttpOnly");
2076
2077 if (s->be->ck_opts & PR_CK_SECURE)
2078 chunk_appendf(&trash, "; Secure");
2079
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002080 if (s->be->cookie_attrs)
2081 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2082
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002083 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002084 goto return_bad_resp;
2085
2086 txn->flags &= ~TX_SCK_MASK;
2087 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2088 /* the server did not change, only the date was updated */
2089 txn->flags |= TX_SCK_UPDATED;
2090 else
2091 txn->flags |= TX_SCK_INSERTED;
2092
2093 /* Here, we will tell an eventual cache on the client side that we don't
2094 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2095 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2096 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2097 */
2098 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2099
2100 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2101
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002102 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002103 goto return_bad_resp;
2104 }
2105 }
2106
2107 /*
2108 * Check if result will be cacheable with a cookie.
2109 * We'll block the response if security checks have caught
2110 * nasty things such as a cacheable cookie.
2111 */
2112 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2113 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2114 (s->be->options & PR_O_CHK_CACHE)) {
2115 /* we're in presence of a cacheable response containing
2116 * a set-cookie header. We'll block it as requested by
2117 * the 'checkcache' option, and send an alert.
2118 */
2119 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002120 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002121
Olivier Houcharda798bf52019-03-08 18:52:00 +01002122 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2123 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01002124 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002125 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126
2127 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2128 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2129 send_log(s->be, LOG_ALERT,
2130 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2131 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2132 goto return_srv_prx_502;
2133 }
2134
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002135 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 /* Always enter in the body analyzer */
2137 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2138 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2139
2140 /* if the user wants to log as soon as possible, without counting
2141 * bytes from the server, then this is the right moment. We have
2142 * to temporarily assign bytes_out to log what we currently have.
2143 */
2144 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2145 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002146 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002147 s->do_log(s);
2148 s->logs.bytes_out = 0;
2149 }
2150 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002151
2152 return_bad_resp:
2153 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002154 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002155 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002156 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002157 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002158
2159 return_srv_prx_502:
2160 rep->analysers &= AN_RES_FLT_END;
2161 txn->status = 502;
2162 s->logs.t_data = -1; /* was not a valid response */
2163 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002164 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002165 if (!(s->flags & SF_ERR_MASK))
2166 s->flags |= SF_ERR_PRXCOND;
2167 if (!(s->flags & SF_FINST_MASK))
2168 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002169
2170 s->req.analysers &= AN_REQ_FLT_END;
2171 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002172 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002173}
2174
2175/* This function is an analyser which forwards response body (including chunk
2176 * sizes if any). It is called as soon as we must forward, even if we forward
2177 * zero byte. The only situation where it must not be called is when we're in
2178 * tunnel mode and we want to forward till the close. It's used both to forward
2179 * remaining data and to resync after end of body. It expects the msg_state to
2180 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2181 * read more data, or 1 once we can go on with next request or end the stream.
2182 *
2183 * It is capable of compressing response data both in content-length mode and
2184 * in chunked mode. The state machines follows different flows depending on
2185 * whether content-length and chunked modes are used, since there are no
2186 * trailers in content-length :
2187 *
2188 * chk-mode cl-mode
2189 * ,----- BODY -----.
2190 * / \
2191 * V size > 0 V chk-mode
2192 * .--> SIZE -------------> DATA -------------> CRLF
2193 * | | size == 0 | last byte |
2194 * | v final crlf v inspected |
2195 * | TRAILERS -----------> DONE |
2196 * | |
2197 * `----------------------------------------------'
2198 *
2199 * Compression only happens in the DATA state, and must be flushed in final
2200 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2201 * is performed at once on final states for all bytes parsed, or when leaving
2202 * on missing data.
2203 */
2204int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2205{
2206 struct session *sess = s->sess;
2207 struct http_txn *txn = s->txn;
2208 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002209 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002210 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211
2212 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2213 now_ms, __FUNCTION__,
2214 s,
2215 res,
2216 res->rex, res->wex,
2217 res->flags,
2218 ci_data(res),
2219 res->analysers);
2220
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002221 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222
2223 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002224 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 /* Output closed while we were sending data. We must abort and
2226 * wake the other side up.
2227 */
2228 msg->err_state = msg->msg_state;
2229 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002230 htx_end_response(s);
2231 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 return 1;
2233 }
2234
Christopher Faulet9768c262018-10-22 09:34:31 +02002235 if (msg->msg_state == HTTP_MSG_BODY)
2236 msg->msg_state = HTTP_MSG_DATA;
2237
Christopher Faulete0768eb2018-10-03 16:38:02 +02002238 /* in most states, we should abort in case of early close */
2239 channel_auto_close(res);
2240
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002242 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002243 if (res->flags & CF_EOI)
2244 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002245 }
2246 else {
2247 /* We can't process the buffer's contents yet */
2248 res->flags |= CF_WAKE_WRITE;
2249 goto missing_data_or_waiting;
2250 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 }
2252
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002253 if (msg->msg_state >= HTTP_MSG_ENDING)
2254 goto ending;
2255
2256 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2257 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2258 msg->msg_state = HTTP_MSG_ENDING;
2259 goto ending;
2260 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002261
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002262 /* Forward input data. We get it by removing all outgoing data not
2263 * forwarded yet from HTX data size. If there are some data filters, we
2264 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002265 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002266 if (HAS_RSP_DATA_FILTERS(s)) {
2267 ret = flt_http_payload(s, msg, htx->data);
2268 if (ret < 0)
2269 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002270 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002271 }
2272 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002273 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002274 if (msg->flags & HTTP_MSGF_XFER_LEN)
2275 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002276 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002277
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002278 if (htx->data != co_data(res))
2279 goto missing_data_or_waiting;
2280
2281 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2282 msg->msg_state = HTTP_MSG_ENDING;
2283 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 }
2285
Christopher Faulet9768c262018-10-22 09:34:31 +02002286 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002287 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2288 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002289 */
2290 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2291 goto missing_data_or_waiting;
2292
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002293 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002294
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002295 ending:
2296 /* other states, ENDING...TUNNEL */
2297 if (msg->msg_state >= HTTP_MSG_DONE)
2298 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002299
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002300 if (HAS_RSP_DATA_FILTERS(s)) {
2301 ret = flt_http_end(s, msg);
2302 if (ret <= 0) {
2303 if (!ret)
2304 goto missing_data_or_waiting;
2305 goto return_bad_res;
2306 }
2307 }
2308
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002309 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2310 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2311 msg->msg_state = HTTP_MSG_TUNNEL;
2312 goto ending;
2313 }
2314 else {
2315 msg->msg_state = HTTP_MSG_DONE;
2316 res->to_forward = 0;
2317 }
2318
2319 done:
2320
2321 channel_dont_close(res);
2322
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002324 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002325 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2327 if (res->flags & CF_SHUTW) {
2328 /* response errors are most likely due to the
2329 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002330 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332 goto return_bad_res;
2333 }
2334 return 1;
2335 }
2336 return 0;
2337
2338 missing_data_or_waiting:
2339 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002340 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002341
Christopher Faulet47365272018-10-31 17:40:50 +01002342 if (htx->flags & HTX_FL_PARSING_ERROR)
2343 goto return_bad_res;
2344
Christopher Faulete0768eb2018-10-03 16:38:02 +02002345 /* stop waiting for data if the input is closed before the end. If the
2346 * client side was already closed, it means that the client has aborted,
2347 * so we don't want to count this as a server abort. Otherwise it's a
2348 * server abort.
2349 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002350 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002351 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002352 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002353 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002354 if (htx_is_empty(htx))
2355 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002356 }
2357
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 /* When TE: chunked is used, we need to get there again to parse
2359 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002360 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2361 * are filters registered on the stream, we don't want to forward a
2362 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002364 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002365 channel_dont_close(res);
2366
2367 /* We know that more data are expected, but we couldn't send more that
2368 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2369 * system knows it must not set a PUSH on this first part. Interactive
2370 * modes are already handled by the stream sock layer. We must not do
2371 * this in content-length mode because it could present the MSG_MORE
2372 * flag with the last block of forwarded data, which would cause an
2373 * additional delay to be observed by the receiver.
2374 */
2375 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2376 res->flags |= CF_EXPECT_MORE;
2377
2378 /* the stream handler will take care of timeouts and errors */
2379 return 0;
2380
Christopher Faulet93e02d82019-03-08 14:18:50 +01002381 return_srv_abort:
2382 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2383 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002384 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002385 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2386 if (!(s->flags & SF_ERR_MASK))
2387 s->flags |= SF_ERR_SRVCL;
2388 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002389
Christopher Faulet93e02d82019-03-08 14:18:50 +01002390 return_cli_abort:
2391 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2392 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002393 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002394 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2395 if (!(s->flags & SF_ERR_MASK))
2396 s->flags |= SF_ERR_CLICL;
2397 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002398
Christopher Faulet93e02d82019-03-08 14:18:50 +01002399 return_bad_res:
2400 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2401 if (objt_server(s->target)) {
2402 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2403 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2404 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002405 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002406 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002407
Christopher Faulet93e02d82019-03-08 14:18:50 +01002408 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002409 txn->rsp.err_state = txn->rsp.msg_state;
2410 txn->rsp.msg_state = HTTP_MSG_ERROR;
2411 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002412 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002413 res->analysers &= AN_RES_FLT_END;
2414 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 +02002415 if (!(s->flags & SF_FINST_MASK))
2416 s->flags |= SF_FINST_D;
2417 return 0;
2418}
2419
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002421 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422 * as too large a request to build a valid response.
2423 */
2424int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2425{
Christopher Faulet99daf282018-11-28 22:58:13 +01002426 struct channel *req = &s->req;
2427 struct channel *res = &s->res;
2428 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002429 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002431 struct ist status, reason, location;
2432 unsigned int flags;
2433 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002434 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435
2436 chunk = alloc_trash_chunk();
2437 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439
Christopher Faulet99daf282018-11-28 22:58:13 +01002440 /*
2441 * Create the location
2442 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002443 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 case REDIRECT_TYPE_SCHEME: {
2446 struct http_hdr_ctx ctx;
2447 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448
Christopher Faulet99daf282018-11-28 22:58:13 +01002449 host = ist("");
2450 ctx.blk = NULL;
2451 if (http_find_header(htx, ist("Host"), &ctx, 0))
2452 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453
Christopher Faulet297fbb42019-05-13 14:41:27 +02002454 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 path = http_get_path(htx_sl_req_uri(sl));
2456 /* build message using path */
2457 if (path.ptr) {
2458 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2459 int qs = 0;
2460 while (qs < path.len) {
2461 if (*(path.ptr + qs) == '?') {
2462 path.len = qs;
2463 break;
2464 }
2465 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002467 }
2468 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002469 else
2470 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471
Christopher Faulet99daf282018-11-28 22:58:13 +01002472 if (rule->rdr_str) { /* this is an old "redirect" rule */
2473 /* add scheme */
2474 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2475 goto fail;
2476 }
2477 else {
2478 /* add scheme with executing log format */
2479 chunk->data += build_logline(s, chunk->area + chunk->data,
2480 chunk->size - chunk->data,
2481 &rule->rdr_fmt);
2482 }
2483 /* add "://" + host + path */
2484 if (!chunk_memcat(chunk, "://", 3) ||
2485 !chunk_memcat(chunk, host.ptr, host.len) ||
2486 !chunk_memcat(chunk, path.ptr, path.len))
2487 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002488
Christopher Faulet99daf282018-11-28 22:58:13 +01002489 /* append a slash at the end of the location if needed and missing */
2490 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2491 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2492 if (chunk->data + 1 >= chunk->size)
2493 goto fail;
2494 chunk->area[chunk->data++] = '/';
2495 }
2496 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002497 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002498
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 case REDIRECT_TYPE_PREFIX: {
2500 struct ist path;
2501
Christopher Faulet297fbb42019-05-13 14:41:27 +02002502 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002503 path = http_get_path(htx_sl_req_uri(sl));
2504 /* build message using path */
2505 if (path.ptr) {
2506 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2507 int qs = 0;
2508 while (qs < path.len) {
2509 if (*(path.ptr + qs) == '?') {
2510 path.len = qs;
2511 break;
2512 }
2513 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002514 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002515 }
2516 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002517 else
2518 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002519
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 if (rule->rdr_str) { /* this is an old "redirect" rule */
2521 /* add prefix. Note that if prefix == "/", we don't want to
2522 * add anything, otherwise it makes it hard for the user to
2523 * configure a self-redirection.
2524 */
2525 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2526 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2527 goto fail;
2528 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002529 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002530 else {
2531 /* add prefix with executing log format */
2532 chunk->data += build_logline(s, chunk->area + chunk->data,
2533 chunk->size - chunk->data,
2534 &rule->rdr_fmt);
2535 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002536
Christopher Faulet99daf282018-11-28 22:58:13 +01002537 /* add path */
2538 if (!chunk_memcat(chunk, path.ptr, path.len))
2539 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002540
Christopher Faulet99daf282018-11-28 22:58:13 +01002541 /* append a slash at the end of the location if needed and missing */
2542 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2543 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2544 if (chunk->data + 1 >= chunk->size)
2545 goto fail;
2546 chunk->area[chunk->data++] = '/';
2547 }
2548 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002549 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002550 case REDIRECT_TYPE_LOCATION:
2551 default:
2552 if (rule->rdr_str) { /* this is an old "redirect" rule */
2553 /* add location */
2554 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2555 goto fail;
2556 }
2557 else {
2558 /* add location with executing log format */
2559 chunk->data += build_logline(s, chunk->area + chunk->data,
2560 chunk->size - chunk->data,
2561 &rule->rdr_fmt);
2562 }
2563 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002564 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002565 location = ist2(chunk->area, chunk->data);
2566
2567 /*
2568 * Create the 30x response
2569 */
2570 switch (rule->code) {
2571 case 308:
2572 status = ist("308");
2573 reason = ist("Permanent Redirect");
2574 break;
2575 case 307:
2576 status = ist("307");
2577 reason = ist("Temporary Redirect");
2578 break;
2579 case 303:
2580 status = ist("303");
2581 reason = ist("See Other");
2582 break;
2583 case 301:
2584 status = ist("301");
2585 reason = ist("Moved Permanently");
2586 break;
2587 case 302:
2588 default:
2589 status = ist("302");
2590 reason = ist("Found");
2591 break;
2592 }
2593
Christopher Faulet08e66462019-05-23 16:44:59 +02002594 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2595 close = 1;
2596
Christopher Faulet99daf282018-11-28 22:58:13 +01002597 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002598 /* Trim any possible response */
2599 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002600 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2601 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2602 if (!sl)
2603 goto fail;
2604 sl->info.res.status = rule->code;
2605 s->txn->status = rule->code;
2606
Christopher Faulet08e66462019-05-23 16:44:59 +02002607 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2608 goto fail;
2609
2610 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002611 !htx_add_header(htx, ist("Location"), location))
2612 goto fail;
2613
2614 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2615 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2616 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002617 }
2618
2619 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002620 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2621 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002622 }
2623
Christopher Faulet99daf282018-11-28 22:58:13 +01002624 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2625 goto fail;
2626
Kevin Zhu0fd70882020-01-07 09:42:55 +01002627 htx_to_buf(htx, &res->buf);
2628
Christopher Faulet99daf282018-11-28 22:58:13 +01002629 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002630 c_adv(res, data);
2631 res->total += data;
2632
2633 channel_auto_read(req);
2634 channel_abort(req);
2635 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002636 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002637
2638 res->wex = tick_add_ifset(now_ms, res->wto);
2639 channel_auto_read(res);
2640 channel_auto_close(res);
2641 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002642 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2643 /* let's log the request time */
2644 s->logs.tv_request = now;
2645 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002646
Christopher Faulet7d84db32020-01-28 09:18:10 +01002647 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2648 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2649 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002650
2651 if (!(s->flags & SF_ERR_MASK))
2652 s->flags |= SF_ERR_LOCAL;
2653 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002654 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002655
Christopher Faulet99daf282018-11-28 22:58:13 +01002656 free_trash_chunk(chunk);
2657 return 1;
2658
2659 fail:
2660 /* If an error occurred, remove the incomplete HTTP response from the
2661 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002662 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002663 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002664 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002665}
2666
Christopher Faulet72333522018-10-24 11:25:02 +02002667int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2668 struct ist name, const char *str, struct my_regex *re, int action)
2669{
2670 struct http_hdr_ctx ctx;
2671 struct buffer *output = get_trash_chunk();
2672
2673 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2674 ctx.blk = NULL;
2675 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2676 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2677 continue;
2678
2679 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2680 if (output->data == -1)
2681 return -1;
2682 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2683 return -1;
2684 }
2685 return 0;
2686}
2687
2688static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2689 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2690{
2691 struct buffer *replace;
2692 int ret = -1;
2693
2694 replace = alloc_trash_chunk();
2695 if (!replace)
2696 goto leave;
2697
2698 replace->data = build_logline(s, replace->area, replace->size, fmt);
2699 if (replace->data >= replace->size - 1)
2700 goto leave;
2701
2702 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2703
2704 leave:
2705 free_trash_chunk(replace);
2706 return ret;
2707}
2708
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002709
2710/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2711 * on success and -1 on error. The response channel is updated accordingly.
2712 */
2713static int htx_reply_103_early_hints(struct channel *res)
2714{
2715 struct htx *htx = htx_from_buf(&res->buf);
2716 size_t data;
2717
Christopher Faulet9869f932019-06-26 14:23:54 +02002718 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002719 /* If an error occurred during an Early-hint rule,
2720 * remove the incomplete HTTP 103 response from the
2721 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002722 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002723 return -1;
2724 }
2725
2726 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002727 c_adv(res, data);
2728 res->total += data;
2729 return 0;
2730}
2731
Christopher Faulet6eb92892018-11-15 16:39:29 +01002732/*
2733 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2734 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002735 * If <early_hints> is 0, it is starts a new response by adding the start
2736 * line. If an error occurred -1 is returned. On success 0 is returned. The
2737 * channel is not updated here. It must be done calling the function
2738 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002739 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002740static 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 +01002741{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002742 struct channel *res = &s->res;
2743 struct htx *htx = htx_from_buf(&res->buf);
2744 struct buffer *value = alloc_trash_chunk();
2745
Christopher Faulet6eb92892018-11-15 16:39:29 +01002746 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002747 struct htx_sl *sl;
2748 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2749 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2750
2751 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2752 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2753 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002754 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002755 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002756 }
2757
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002758 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2759 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002760 goto fail;
2761
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002762 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002763 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002764
2765 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002766 /* If an error occurred during an Early-hint rule, remove the incomplete
2767 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002768 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002769 free_trash_chunk(value);
2770 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002771}
2772
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002773/* This function executes one of the set-{method,path,query,uri} actions. It
2774 * takes the string from the variable 'replace' with length 'len', then modifies
2775 * the relevant part of the request line accordingly. Then it updates various
2776 * pointers to the next elements which were moved, and the total buffer length.
2777 * It finds the action to be performed in p[2], previously filled by function
2778 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2779 * error, though this can be revisited when this code is finally exploited.
2780 *
2781 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2782 * query string and 3 to replace uri.
2783 *
2784 * In query string case, the mark question '?' must be set at the start of the
2785 * string by the caller, event if the replacement query string is empty.
2786 */
2787int htx_req_replace_stline(int action, const char *replace, int len,
2788 struct proxy *px, struct stream *s)
2789{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002790 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002791
2792 switch (action) {
2793 case 0: // method
2794 if (!http_replace_req_meth(htx, ist2(replace, len)))
2795 return -1;
2796 break;
2797
2798 case 1: // path
2799 if (!http_replace_req_path(htx, ist2(replace, len)))
2800 return -1;
2801 break;
2802
2803 case 2: // query
2804 if (!http_replace_req_query(htx, ist2(replace, len)))
2805 return -1;
2806 break;
2807
2808 case 3: // uri
2809 if (!http_replace_req_uri(htx, ist2(replace, len)))
2810 return -1;
2811 break;
2812
2813 default:
2814 return -1;
2815 }
2816 return 0;
2817}
2818
2819/* This function replace the HTTP status code and the associated message. The
2820 * variable <status> contains the new status code. This function never fails.
2821 */
2822void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2823{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002824 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002825 char *res;
2826
2827 chunk_reset(&trash);
2828 res = ultoa_o(status, trash.area, trash.size);
2829 trash.data = res - trash.area;
2830
2831 /* Do we have a custom reason format string? */
2832 if (reason == NULL)
2833 reason = http_get_reason(status);
2834
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002835 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002836 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2837}
2838
Christopher Faulet3e964192018-10-24 11:39:23 +02002839/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2840 * transaction <txn>. Returns the verdict of the first rule that prevents
2841 * further processing of the request (auth, deny, ...), and defaults to
2842 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2843 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2844 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2845 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2846 * status.
2847 */
2848static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2849 struct stream *s, int *deny_status)
2850{
2851 struct session *sess = strm_sess(s);
2852 struct http_txn *txn = s->txn;
2853 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002854 struct act_rule *rule;
2855 struct http_hdr_ctx ctx;
2856 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002857 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2858 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002859 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002860
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002861 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002862
2863 /* If "the current_rule_list" match the executed rule list, we are in
2864 * resume condition. If a resume is needed it is always in the action
2865 * and never in the ACL or converters. In this case, we initialise the
2866 * current rule, and go to the action execution point.
2867 */
2868 if (s->current_rule) {
2869 rule = s->current_rule;
2870 s->current_rule = NULL;
2871 if (s->current_rule_list == rules)
2872 goto resume_execution;
2873 }
2874 s->current_rule_list = rules;
2875
2876 list_for_each_entry(rule, rules, list) {
2877 /* check optional condition */
2878 if (rule->cond) {
2879 int ret;
2880
2881 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2882 ret = acl_pass(ret);
2883
2884 if (rule->cond->pol == ACL_COND_UNLESS)
2885 ret = !ret;
2886
2887 if (!ret) /* condition not matched */
2888 continue;
2889 }
2890
2891 act_flags |= ACT_FLAG_FIRST;
2892 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002893 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2894 early_hints = 0;
2895 if (htx_reply_103_early_hints(&s->res) == -1) {
2896 rule_ret = HTTP_RULE_RES_BADREQ;
2897 goto end;
2898 }
2899 }
2900
Christopher Faulet3e964192018-10-24 11:39:23 +02002901 switch (rule->action) {
2902 case ACT_ACTION_ALLOW:
2903 rule_ret = HTTP_RULE_RES_STOP;
2904 goto end;
2905
2906 case ACT_ACTION_DENY:
2907 if (deny_status)
2908 *deny_status = rule->deny_status;
2909 rule_ret = HTTP_RULE_RES_DENY;
2910 goto end;
2911
2912 case ACT_HTTP_REQ_TARPIT:
2913 txn->flags |= TX_CLTARPIT;
2914 if (deny_status)
2915 *deny_status = rule->deny_status;
2916 rule_ret = HTTP_RULE_RES_DENY;
2917 goto end;
2918
2919 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002920 /* Auth might be performed on regular http-req rules as well as on stats */
2921 auth_realm = rule->arg.auth.realm;
2922 if (!auth_realm) {
2923 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2924 auth_realm = STATS_DEFAULT_REALM;
2925 else
2926 auth_realm = px->id;
2927 }
2928 /* send 401/407 depending on whether we use a proxy or not. We still
2929 * count one error, because normal browsing won't significantly
2930 * increase the counter but brute force attempts will.
2931 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002932 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002933 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2934 rule_ret = HTTP_RULE_RES_BADREQ;
2935 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002936 goto end;
2937
2938 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002939 rule_ret = HTTP_RULE_RES_DONE;
2940 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2941 rule_ret = HTTP_RULE_RES_BADREQ;
2942 goto end;
2943
2944 case ACT_HTTP_SET_NICE:
2945 s->task->nice = rule->arg.nice;
2946 break;
2947
2948 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002949 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002950 break;
2951
2952 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002953 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002954 break;
2955
2956 case ACT_HTTP_SET_LOGL:
2957 s->logs.level = rule->arg.loglevel;
2958 break;
2959
2960 case ACT_HTTP_REPLACE_HDR:
2961 case ACT_HTTP_REPLACE_VAL:
2962 if (htx_transform_header(s, &s->req, htx,
2963 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2964 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002965 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002966 rule_ret = HTTP_RULE_RES_BADREQ;
2967 goto end;
2968 }
2969 break;
2970
2971 case ACT_HTTP_DEL_HDR:
2972 /* remove all occurrences of the header */
2973 ctx.blk = NULL;
2974 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2975 http_remove_header(htx, &ctx);
2976 break;
2977
2978 case ACT_HTTP_SET_HDR:
2979 case ACT_HTTP_ADD_HDR: {
2980 /* The scope of the trash buffer must be limited to this function. The
2981 * build_logline() function can execute a lot of other function which
2982 * can use the trash buffer. So for limiting the scope of this global
2983 * buffer, we build first the header value using build_logline, and
2984 * after we store the header name.
2985 */
2986 struct buffer *replace;
2987 struct ist n, v;
2988
2989 replace = alloc_trash_chunk();
2990 if (!replace) {
2991 rule_ret = HTTP_RULE_RES_BADREQ;
2992 goto end;
2993 }
2994
2995 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2996 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2997 v = ist2(replace->area, replace->data);
2998
2999 if (rule->action == ACT_HTTP_SET_HDR) {
3000 /* remove all occurrences of the header */
3001 ctx.blk = NULL;
3002 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3003 http_remove_header(htx, &ctx);
3004 }
3005
3006 if (!http_add_header(htx, n, v)) {
3007 static unsigned char rate_limit = 0;
3008
3009 if ((rate_limit++ & 255) == 0) {
3010 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);
3011 }
3012
Olivier Houcharda798bf52019-03-08 18:52:00 +01003013 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003014 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003015 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003016 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003017 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003018 }
3019 free_trash_chunk(replace);
3020 break;
3021 }
3022
3023 case ACT_HTTP_DEL_ACL:
3024 case ACT_HTTP_DEL_MAP: {
3025 struct pat_ref *ref;
3026 struct buffer *key;
3027
3028 /* collect reference */
3029 ref = pat_ref_lookup(rule->arg.map.ref);
3030 if (!ref)
3031 continue;
3032
3033 /* allocate key */
3034 key = alloc_trash_chunk();
3035 if (!key) {
3036 rule_ret = HTTP_RULE_RES_BADREQ;
3037 goto end;
3038 }
3039
3040 /* collect key */
3041 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3042 key->area[key->data] = '\0';
3043
3044 /* perform update */
3045 /* returned code: 1=ok, 0=ko */
3046 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3047 pat_ref_delete(ref, key->area);
3048 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3049
3050 free_trash_chunk(key);
3051 break;
3052 }
3053
3054 case ACT_HTTP_ADD_ACL: {
3055 struct pat_ref *ref;
3056 struct buffer *key;
3057
3058 /* collect reference */
3059 ref = pat_ref_lookup(rule->arg.map.ref);
3060 if (!ref)
3061 continue;
3062
3063 /* allocate key */
3064 key = alloc_trash_chunk();
3065 if (!key) {
3066 rule_ret = HTTP_RULE_RES_BADREQ;
3067 goto end;
3068 }
3069
3070 /* collect key */
3071 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3072 key->area[key->data] = '\0';
3073
3074 /* perform update */
3075 /* add entry only if it does not already exist */
3076 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3077 if (pat_ref_find_elt(ref, key->area) == NULL)
3078 pat_ref_add(ref, key->area, NULL, NULL);
3079 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3080
3081 free_trash_chunk(key);
3082 break;
3083 }
3084
3085 case ACT_HTTP_SET_MAP: {
3086 struct pat_ref *ref;
3087 struct buffer *key, *value;
3088
3089 /* collect reference */
3090 ref = pat_ref_lookup(rule->arg.map.ref);
3091 if (!ref)
3092 continue;
3093
3094 /* allocate key */
3095 key = alloc_trash_chunk();
3096 if (!key) {
3097 rule_ret = HTTP_RULE_RES_BADREQ;
3098 goto end;
3099 }
3100
3101 /* allocate value */
3102 value = alloc_trash_chunk();
3103 if (!value) {
3104 free_trash_chunk(key);
3105 rule_ret = HTTP_RULE_RES_BADREQ;
3106 goto end;
3107 }
3108
3109 /* collect key */
3110 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3111 key->area[key->data] = '\0';
3112
3113 /* collect value */
3114 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3115 value->area[value->data] = '\0';
3116
3117 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003118 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003119 if (pat_ref_find_elt(ref, key->area) != NULL)
3120 /* update entry if it exists */
3121 pat_ref_set(ref, key->area, value->area, NULL);
3122 else
3123 /* insert a new entry */
3124 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003125 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003126 free_trash_chunk(key);
3127 free_trash_chunk(value);
3128 break;
3129 }
3130
3131 case ACT_HTTP_EARLY_HINT:
3132 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3133 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003134 early_hints = htx_add_early_hint_header(s, early_hints,
3135 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003136 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003137 if (early_hints == -1) {
3138 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003139 goto end;
3140 }
3141 break;
3142
3143 case ACT_CUSTOM:
3144 if ((s->req.flags & CF_READ_ERROR) ||
3145 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003146 (px->options & PR_O_ABRT_CLOSE)))
3147 act_flags |= ACT_FLAG_FINAL;
3148
3149 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3150 case ACT_RET_ERR:
3151 case ACT_RET_CONT:
3152 break;
3153 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003154 rule_ret = HTTP_RULE_RES_STOP;
3155 goto end;
3156 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003157 rule_ret = HTTP_RULE_RES_DONE;
3158 goto end;
3159 case ACT_RET_YIELD:
3160 s->current_rule = rule;
3161 rule_ret = HTTP_RULE_RES_YIELD;
3162 goto end;
3163 }
3164 break;
3165
3166 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3167 /* Note: only the first valid tracking parameter of each
3168 * applies.
3169 */
3170
3171 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3172 struct stktable *t;
3173 struct stksess *ts;
3174 struct stktable_key *key;
3175 void *ptr1, *ptr2;
3176
3177 t = rule->arg.trk_ctr.table.t;
3178 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3179 rule->arg.trk_ctr.expr, NULL);
3180
3181 if (key && (ts = stktable_get_entry(t, key))) {
3182 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3183
3184 /* let's count a new HTTP request as it's the first time we do it */
3185 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3186 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3187 if (ptr1 || ptr2) {
3188 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3189
3190 if (ptr1)
3191 stktable_data_cast(ptr1, http_req_cnt)++;
3192
3193 if (ptr2)
3194 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3195 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3196
3197 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3198
3199 /* If data was modified, we need to touch to re-schedule sync */
3200 stktable_touch_local(t, ts, 0);
3201 }
3202
3203 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3204 if (sess->fe != s->be)
3205 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3206 }
3207 }
3208 break;
3209
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003210 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003211 default:
3212 break;
3213 }
3214 }
3215
3216 end:
3217 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003218 if (htx_reply_103_early_hints(&s->res) == -1)
3219 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003220 }
3221
3222 /* we reached the end of the rules, nothing to report */
3223 return rule_ret;
3224}
3225
3226/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3227 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3228 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3229 * is returned, the process can continue the evaluation of next rule list. If
3230 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3231 * is returned, it means the operation could not be processed and a server error
3232 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3233 * deny rule. If *YIELD is returned, the caller must call again the function
3234 * with the same context.
3235 */
3236static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3237 struct stream *s)
3238{
3239 struct session *sess = strm_sess(s);
3240 struct http_txn *txn = s->txn;
3241 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003242 struct act_rule *rule;
3243 struct http_hdr_ctx ctx;
3244 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3245 int act_flags = 0;
3246
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003247 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003248
3249 /* If "the current_rule_list" match the executed rule list, we are in
3250 * resume condition. If a resume is needed it is always in the action
3251 * and never in the ACL or converters. In this case, we initialise the
3252 * current rule, and go to the action execution point.
3253 */
3254 if (s->current_rule) {
3255 rule = s->current_rule;
3256 s->current_rule = NULL;
3257 if (s->current_rule_list == rules)
3258 goto resume_execution;
3259 }
3260 s->current_rule_list = rules;
3261
3262 list_for_each_entry(rule, rules, list) {
3263 /* check optional condition */
3264 if (rule->cond) {
3265 int ret;
3266
3267 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3268 ret = acl_pass(ret);
3269
3270 if (rule->cond->pol == ACL_COND_UNLESS)
3271 ret = !ret;
3272
3273 if (!ret) /* condition not matched */
3274 continue;
3275 }
3276
3277 act_flags |= ACT_FLAG_FIRST;
3278resume_execution:
3279 switch (rule->action) {
3280 case ACT_ACTION_ALLOW:
3281 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3282 goto end;
3283
3284 case ACT_ACTION_DENY:
3285 txn->flags |= TX_SVDENY;
3286 rule_ret = HTTP_RULE_RES_STOP;
3287 goto end;
3288
3289 case ACT_HTTP_SET_NICE:
3290 s->task->nice = rule->arg.nice;
3291 break;
3292
3293 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003294 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003295 break;
3296
3297 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003298 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003299 break;
3300
3301 case ACT_HTTP_SET_LOGL:
3302 s->logs.level = rule->arg.loglevel;
3303 break;
3304
3305 case ACT_HTTP_REPLACE_HDR:
3306 case ACT_HTTP_REPLACE_VAL:
3307 if (htx_transform_header(s, &s->res, htx,
3308 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3309 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003310 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003311 rule_ret = HTTP_RULE_RES_BADREQ;
3312 goto end;
3313 }
3314 break;
3315
3316 case ACT_HTTP_DEL_HDR:
3317 /* remove all occurrences of the header */
3318 ctx.blk = NULL;
3319 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3320 http_remove_header(htx, &ctx);
3321 break;
3322
3323 case ACT_HTTP_SET_HDR:
3324 case ACT_HTTP_ADD_HDR: {
3325 struct buffer *replace;
3326 struct ist n, v;
3327
3328 replace = alloc_trash_chunk();
3329 if (!replace) {
3330 rule_ret = HTTP_RULE_RES_BADREQ;
3331 goto end;
3332 }
3333
3334 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3335 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3336 v = ist2(replace->area, replace->data);
3337
3338 if (rule->action == ACT_HTTP_SET_HDR) {
3339 /* remove all occurrences of the header */
3340 ctx.blk = NULL;
3341 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3342 http_remove_header(htx, &ctx);
3343 }
3344
3345 if (!http_add_header(htx, n, v)) {
3346 static unsigned char rate_limit = 0;
3347
3348 if ((rate_limit++ & 255) == 0) {
3349 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);
3350 }
3351
Olivier Houcharda798bf52019-03-08 18:52:00 +01003352 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003353 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003354 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003355 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003356 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003357 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003358 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003359 }
3360 free_trash_chunk(replace);
3361 break;
3362 }
3363
3364 case ACT_HTTP_DEL_ACL:
3365 case ACT_HTTP_DEL_MAP: {
3366 struct pat_ref *ref;
3367 struct buffer *key;
3368
3369 /* collect reference */
3370 ref = pat_ref_lookup(rule->arg.map.ref);
3371 if (!ref)
3372 continue;
3373
3374 /* allocate key */
3375 key = alloc_trash_chunk();
3376 if (!key) {
3377 rule_ret = HTTP_RULE_RES_BADREQ;
3378 goto end;
3379 }
3380
3381 /* collect key */
3382 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3383 key->area[key->data] = '\0';
3384
3385 /* perform update */
3386 /* returned code: 1=ok, 0=ko */
3387 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3388 pat_ref_delete(ref, key->area);
3389 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3390
3391 free_trash_chunk(key);
3392 break;
3393 }
3394
3395 case ACT_HTTP_ADD_ACL: {
3396 struct pat_ref *ref;
3397 struct buffer *key;
3398
3399 /* collect reference */
3400 ref = pat_ref_lookup(rule->arg.map.ref);
3401 if (!ref)
3402 continue;
3403
3404 /* allocate key */
3405 key = alloc_trash_chunk();
3406 if (!key) {
3407 rule_ret = HTTP_RULE_RES_BADREQ;
3408 goto end;
3409 }
3410
3411 /* collect key */
3412 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3413 key->area[key->data] = '\0';
3414
3415 /* perform update */
3416 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003417 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003418 if (pat_ref_find_elt(ref, key->area) == NULL)
3419 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003420 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003421 free_trash_chunk(key);
3422 break;
3423 }
3424
3425 case ACT_HTTP_SET_MAP: {
3426 struct pat_ref *ref;
3427 struct buffer *key, *value;
3428
3429 /* collect reference */
3430 ref = pat_ref_lookup(rule->arg.map.ref);
3431 if (!ref)
3432 continue;
3433
3434 /* allocate key */
3435 key = alloc_trash_chunk();
3436 if (!key) {
3437 rule_ret = HTTP_RULE_RES_BADREQ;
3438 goto end;
3439 }
3440
3441 /* allocate value */
3442 value = alloc_trash_chunk();
3443 if (!value) {
3444 free_trash_chunk(key);
3445 rule_ret = HTTP_RULE_RES_BADREQ;
3446 goto end;
3447 }
3448
3449 /* collect key */
3450 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3451 key->area[key->data] = '\0';
3452
3453 /* collect value */
3454 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3455 value->area[value->data] = '\0';
3456
3457 /* perform update */
3458 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3459 if (pat_ref_find_elt(ref, key->area) != NULL)
3460 /* update entry if it exists */
3461 pat_ref_set(ref, key->area, value->area, NULL);
3462 else
3463 /* insert a new entry */
3464 pat_ref_add(ref, key->area, value->area, NULL);
3465 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3466 free_trash_chunk(key);
3467 free_trash_chunk(value);
3468 break;
3469 }
3470
3471 case ACT_HTTP_REDIR:
3472 rule_ret = HTTP_RULE_RES_DONE;
3473 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3474 rule_ret = HTTP_RULE_RES_BADREQ;
3475 goto end;
3476
3477 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3478 /* Note: only the first valid tracking parameter of each
3479 * applies.
3480 */
3481 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3482 struct stktable *t;
3483 struct stksess *ts;
3484 struct stktable_key *key;
3485 void *ptr;
3486
3487 t = rule->arg.trk_ctr.table.t;
3488 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3489 rule->arg.trk_ctr.expr, NULL);
3490
3491 if (key && (ts = stktable_get_entry(t, key))) {
3492 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3493
3494 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3495
3496 /* let's count a new HTTP request as it's the first time we do it */
3497 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3498 if (ptr)
3499 stktable_data_cast(ptr, http_req_cnt)++;
3500
3501 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3502 if (ptr)
3503 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3504 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3505
3506 /* When the client triggers a 4xx from the server, it's most often due
3507 * to a missing object or permission. These events should be tracked
3508 * because if they happen often, it may indicate a brute force or a
3509 * vulnerability scan. Normally this is done when receiving the response
3510 * but here we're tracking after this ought to have been done so we have
3511 * to do it on purpose.
3512 */
3513 if ((unsigned)(txn->status - 400) < 100) {
3514 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3515 if (ptr)
3516 stktable_data_cast(ptr, http_err_cnt)++;
3517
3518 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3519 if (ptr)
3520 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3521 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3522 }
3523
3524 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3525
3526 /* If data was modified, we need to touch to re-schedule sync */
3527 stktable_touch_local(t, ts, 0);
3528
3529 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3530 if (sess->fe != s->be)
3531 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3532 }
3533 }
3534 break;
3535
3536 case ACT_CUSTOM:
3537 if ((s->req.flags & CF_READ_ERROR) ||
3538 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003539 (px->options & PR_O_ABRT_CLOSE)))
3540 act_flags |= ACT_FLAG_FINAL;
3541
3542 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3543 case ACT_RET_ERR:
3544 case ACT_RET_CONT:
3545 break;
3546 case ACT_RET_STOP:
3547 rule_ret = HTTP_RULE_RES_STOP;
3548 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003549 case ACT_RET_DONE:
3550 rule_ret = HTTP_RULE_RES_DONE;
3551 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003552 case ACT_RET_YIELD:
3553 s->current_rule = rule;
3554 rule_ret = HTTP_RULE_RES_YIELD;
3555 goto end;
3556 }
3557 break;
3558
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003559 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003560 default:
3561 break;
3562 }
3563 }
3564
3565 end:
3566 /* we reached the end of the rules, nothing to report */
3567 return rule_ret;
3568}
3569
Christopher Faulet33640082018-10-24 11:53:01 +02003570/* Iterate the same filter through all request headers.
3571 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3572 * Since it can manage the switch to another backend, it updates the per-proxy
3573 * DENY stats.
3574 */
3575static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3576{
3577 struct http_txn *txn = s->txn;
3578 struct htx *htx;
3579 struct buffer *hdr = get_trash_chunk();
3580 int32_t pos;
3581
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003582 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003583
Christopher Fauleta3f15502019-05-13 15:27:23 +02003584 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003585 struct htx_blk *blk = htx_get_blk(htx, pos);
3586 enum htx_blk_type type;
3587 struct ist n, v;
3588
3589 next_hdr:
3590 type = htx_get_blk_type(blk);
3591 if (type == HTX_BLK_EOH)
3592 break;
3593 if (type != HTX_BLK_HDR)
3594 continue;
3595
3596 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3597 return 1;
3598 else if (unlikely(txn->flags & TX_CLALLOW) &&
3599 (exp->action == ACT_ALLOW ||
3600 exp->action == ACT_DENY ||
3601 exp->action == ACT_TARPIT))
3602 return 0;
3603
3604 n = htx_get_blk_name(htx, blk);
3605 v = htx_get_blk_value(htx, blk);
3606
Christopher Faulet02e771a2019-02-26 15:36:05 +01003607 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003608 hdr->area[hdr->data++] = ':';
3609 hdr->area[hdr->data++] = ' ';
3610 chunk_memcat(hdr, v.ptr, v.len);
3611
3612 /* Now we have one header in <hdr> */
3613
3614 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3615 struct http_hdr_ctx ctx;
3616 int len;
3617
3618 switch (exp->action) {
3619 case ACT_ALLOW:
3620 txn->flags |= TX_CLALLOW;
3621 goto end;
3622
3623 case ACT_DENY:
3624 txn->flags |= TX_CLDENY;
3625 goto end;
3626
3627 case ACT_TARPIT:
3628 txn->flags |= TX_CLTARPIT;
3629 goto end;
3630
3631 case ACT_REPLACE:
3632 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3633 if (len < 0)
3634 return -1;
3635
3636 http_parse_header(ist2(trash.area, len), &n, &v);
3637 ctx.blk = blk;
3638 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003639 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003640 if (!http_replace_header(htx, &ctx, n, v))
3641 return -1;
3642 if (!ctx.blk)
3643 goto end;
3644 pos = htx_get_blk_pos(htx, blk);
3645 break;
3646
3647 case ACT_REMOVE:
3648 ctx.blk = blk;
3649 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003650 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003651 if (!http_remove_header(htx, &ctx))
3652 return -1;
3653 if (!ctx.blk)
3654 goto end;
3655 pos = htx_get_blk_pos(htx, blk);
3656 goto next_hdr;
3657
3658 }
3659 }
3660 }
3661 end:
3662 return 0;
3663}
3664
3665/* Apply the filter to the request line.
3666 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3667 * or -1 if a replacement resulted in an invalid request line.
3668 * Since it can manage the switch to another backend, it updates the per-proxy
3669 * DENY stats.
3670 */
3671static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3672{
3673 struct http_txn *txn = s->txn;
3674 struct htx *htx;
3675 struct buffer *reqline = get_trash_chunk();
3676 int done;
3677
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003678 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003679
3680 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3681 return 1;
3682 else if (unlikely(txn->flags & TX_CLALLOW) &&
3683 (exp->action == ACT_ALLOW ||
3684 exp->action == ACT_DENY ||
3685 exp->action == ACT_TARPIT))
3686 return 0;
3687 else if (exp->action == ACT_REMOVE)
3688 return 0;
3689
3690 done = 0;
3691
Christopher Faulet297fbb42019-05-13 14:41:27 +02003692 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003693
3694 /* Now we have the request line between cur_ptr and cur_end */
3695 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003696 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003697 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003698 int len;
3699
3700 switch (exp->action) {
3701 case ACT_ALLOW:
3702 txn->flags |= TX_CLALLOW;
3703 done = 1;
3704 break;
3705
3706 case ACT_DENY:
3707 txn->flags |= TX_CLDENY;
3708 done = 1;
3709 break;
3710
3711 case ACT_TARPIT:
3712 txn->flags |= TX_CLTARPIT;
3713 done = 1;
3714 break;
3715
3716 case ACT_REPLACE:
3717 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3718 if (len < 0)
3719 return -1;
3720
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003721 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3722 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3723 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003724 return -1;
3725 done = 1;
3726 break;
3727 }
3728 }
3729 return done;
3730}
3731
3732/*
3733 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3734 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3735 * unparsable request. Since it can manage the switch to another backend, it
3736 * updates the per-proxy DENY stats.
3737 */
3738static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3739{
3740 struct session *sess = s->sess;
3741 struct http_txn *txn = s->txn;
3742 struct hdr_exp *exp;
3743
3744 for (exp = px->req_exp; exp; exp = exp->next) {
3745 int ret;
3746
3747 /*
3748 * The interleaving of transformations and verdicts
3749 * makes it difficult to decide to continue or stop
3750 * the evaluation.
3751 */
3752
3753 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3754 break;
3755
3756 if ((txn->flags & TX_CLALLOW) &&
3757 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3758 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3759 continue;
3760
3761 /* if this filter had a condition, evaluate it now and skip to
3762 * next filter if the condition does not match.
3763 */
3764 if (exp->cond) {
3765 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3766 ret = acl_pass(ret);
3767 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3768 ret = !ret;
3769
3770 if (!ret)
3771 continue;
3772 }
3773
3774 /* Apply the filter to the request line. */
3775 ret = htx_apply_filter_to_req_line(s, req, exp);
3776 if (unlikely(ret < 0))
3777 return -1;
3778
3779 if (likely(ret == 0)) {
3780 /* The filter did not match the request, it can be
3781 * iterated through all headers.
3782 */
3783 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3784 return -1;
3785 }
3786 }
3787 return 0;
3788}
3789
3790/* Iterate the same filter through all response headers contained in <res>.
3791 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3792 */
3793static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3794{
3795 struct http_txn *txn = s->txn;
3796 struct htx *htx;
3797 struct buffer *hdr = get_trash_chunk();
3798 int32_t pos;
3799
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003800 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003801
Christopher Fauleta3f15502019-05-13 15:27:23 +02003802 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003803 struct htx_blk *blk = htx_get_blk(htx, pos);
3804 enum htx_blk_type type;
3805 struct ist n, v;
3806
3807 next_hdr:
3808 type = htx_get_blk_type(blk);
3809 if (type == HTX_BLK_EOH)
3810 break;
3811 if (type != HTX_BLK_HDR)
3812 continue;
3813
3814 if (unlikely(txn->flags & TX_SVDENY))
3815 return 1;
3816 else if (unlikely(txn->flags & TX_SVALLOW) &&
3817 (exp->action == ACT_ALLOW ||
3818 exp->action == ACT_DENY))
3819 return 0;
3820
3821 n = htx_get_blk_name(htx, blk);
3822 v = htx_get_blk_value(htx, blk);
3823
Christopher Faulet02e771a2019-02-26 15:36:05 +01003824 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003825 hdr->area[hdr->data++] = ':';
3826 hdr->area[hdr->data++] = ' ';
3827 chunk_memcat(hdr, v.ptr, v.len);
3828
3829 /* Now we have one header in <hdr> */
3830
3831 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3832 struct http_hdr_ctx ctx;
3833 int len;
3834
3835 switch (exp->action) {
3836 case ACT_ALLOW:
3837 txn->flags |= TX_SVALLOW;
3838 goto end;
3839 break;
3840
3841 case ACT_DENY:
3842 txn->flags |= TX_SVDENY;
3843 goto end;
3844 break;
3845
3846 case ACT_REPLACE:
3847 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3848 if (len < 0)
3849 return -1;
3850
3851 http_parse_header(ist2(trash.area, len), &n, &v);
3852 ctx.blk = blk;
3853 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003854 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003855 if (!http_replace_header(htx, &ctx, n, v))
3856 return -1;
3857 if (!ctx.blk)
3858 goto end;
3859 pos = htx_get_blk_pos(htx, blk);
3860 break;
3861
3862 case ACT_REMOVE:
3863 ctx.blk = blk;
3864 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003865 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003866 if (!http_remove_header(htx, &ctx))
3867 return -1;
3868 if (!ctx.blk)
3869 goto end;
3870 pos = htx_get_blk_pos(htx, blk);
3871 goto next_hdr;
3872 }
3873 }
3874
3875 }
3876 end:
3877 return 0;
3878}
3879
3880/* Apply the filter to the status line in the response buffer <res>.
3881 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3882 * or -1 if a replacement resulted in an invalid status line.
3883 */
3884static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3885{
3886 struct http_txn *txn = s->txn;
3887 struct htx *htx;
3888 struct buffer *resline = get_trash_chunk();
3889 int done;
3890
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003891 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003892
3893 if (unlikely(txn->flags & TX_SVDENY))
3894 return 1;
3895 else if (unlikely(txn->flags & TX_SVALLOW) &&
3896 (exp->action == ACT_ALLOW ||
3897 exp->action == ACT_DENY))
3898 return 0;
3899 else if (exp->action == ACT_REMOVE)
3900 return 0;
3901
3902 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003903 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003904
3905 /* Now we have the status line between cur_ptr and cur_end */
3906 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003907 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003908 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003909 int len;
3910
3911 switch (exp->action) {
3912 case ACT_ALLOW:
3913 txn->flags |= TX_SVALLOW;
3914 done = 1;
3915 break;
3916
3917 case ACT_DENY:
3918 txn->flags |= TX_SVDENY;
3919 done = 1;
3920 break;
3921
3922 case ACT_REPLACE:
3923 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3924 if (len < 0)
3925 return -1;
3926
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003927 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3928 sl->info.res.status = strl2ui(code.ptr, code.len);
3929 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003930 return -1;
3931
3932 done = 1;
3933 return 1;
3934 }
3935 }
3936 return done;
3937}
3938
3939/*
3940 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3941 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3942 * unparsable response.
3943 */
3944static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3945{
3946 struct session *sess = s->sess;
3947 struct http_txn *txn = s->txn;
3948 struct hdr_exp *exp;
3949
3950 for (exp = px->rsp_exp; exp; exp = exp->next) {
3951 int ret;
3952
3953 /*
3954 * The interleaving of transformations and verdicts
3955 * makes it difficult to decide to continue or stop
3956 * the evaluation.
3957 */
3958
3959 if (txn->flags & TX_SVDENY)
3960 break;
3961
3962 if ((txn->flags & TX_SVALLOW) &&
3963 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3964 exp->action == ACT_PASS)) {
3965 exp = exp->next;
3966 continue;
3967 }
3968
3969 /* if this filter had a condition, evaluate it now and skip to
3970 * next filter if the condition does not match.
3971 */
3972 if (exp->cond) {
3973 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3974 ret = acl_pass(ret);
3975 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3976 ret = !ret;
3977 if (!ret)
3978 continue;
3979 }
3980
3981 /* Apply the filter to the status line. */
3982 ret = htx_apply_filter_to_sts_line(s, res, exp);
3983 if (unlikely(ret < 0))
3984 return -1;
3985
3986 if (likely(ret == 0)) {
3987 /* The filter did not match the response, it can be
3988 * iterated through all headers.
3989 */
3990 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3991 return -1;
3992 }
3993 }
3994 return 0;
3995}
3996
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003997/*
3998 * Manage client-side cookie. It can impact performance by about 2% so it is
3999 * desirable to call it only when needed. This code is quite complex because
4000 * of the multiple very crappy and ambiguous syntaxes we have to support. it
4001 * highly recommended not to touch this part without a good reason !
4002 */
4003static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
4004{
4005 struct session *sess = s->sess;
4006 struct http_txn *txn = s->txn;
4007 struct htx *htx;
4008 struct http_hdr_ctx ctx;
4009 char *hdr_beg, *hdr_end, *del_from;
4010 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4011 int preserve_hdr;
4012
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004013 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004014 ctx.blk = NULL;
4015 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004016 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004017 del_from = NULL; /* nothing to be deleted */
4018 preserve_hdr = 0; /* assume we may kill the whole header */
4019
4020 /* Now look for cookies. Conforming to RFC2109, we have to support
4021 * attributes whose name begin with a '$', and associate them with
4022 * the right cookie, if we want to delete this cookie.
4023 * So there are 3 cases for each cookie read :
4024 * 1) it's a special attribute, beginning with a '$' : ignore it.
4025 * 2) it's a server id cookie that we *MAY* want to delete : save
4026 * some pointers on it (last semi-colon, beginning of cookie...)
4027 * 3) it's an application cookie : we *MAY* have to delete a previous
4028 * "special" cookie.
4029 * At the end of loop, if a "special" cookie remains, we may have to
4030 * remove it. If no application cookie persists in the header, we
4031 * *MUST* delete it.
4032 *
4033 * Note: RFC2965 is unclear about the processing of spaces around
4034 * the equal sign in the ATTR=VALUE form. A careful inspection of
4035 * the RFC explicitly allows spaces before it, and not within the
4036 * tokens (attrs or values). An inspection of RFC2109 allows that
4037 * too but section 10.1.3 lets one think that spaces may be allowed
4038 * after the equal sign too, resulting in some (rare) buggy
4039 * implementations trying to do that. So let's do what servers do.
4040 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4041 * allowed quoted strings in values, with any possible character
4042 * after a backslash, including control chars and delimitors, which
4043 * causes parsing to become ambiguous. Browsers also allow spaces
4044 * within values even without quotes.
4045 *
4046 * We have to keep multiple pointers in order to support cookie
4047 * removal at the beginning, middle or end of header without
4048 * corrupting the header. All of these headers are valid :
4049 *
4050 * hdr_beg hdr_end
4051 * | |
4052 * v |
4053 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4054 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4055 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4056 * | | | | | | |
4057 * | | | | | | |
4058 * | | | | | | +--> next
4059 * | | | | | +----> val_end
4060 * | | | | +-----------> val_beg
4061 * | | | +--------------> equal
4062 * | | +----------------> att_end
4063 * | +---------------------> att_beg
4064 * +--------------------------> prev
4065 *
4066 */
4067 hdr_beg = ctx.value.ptr;
4068 hdr_end = hdr_beg + ctx.value.len;
4069 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4070 /* Iterate through all cookies on this line */
4071
4072 /* find att_beg */
4073 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004074 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004075 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004076 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004077
4078 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4079 att_beg++;
4080
4081 /* find att_end : this is the first character after the last non
4082 * space before the equal. It may be equal to hdr_end.
4083 */
4084 equal = att_end = att_beg;
4085 while (equal < hdr_end) {
4086 if (*equal == '=' || *equal == ',' || *equal == ';')
4087 break;
4088 if (HTTP_IS_SPHT(*equal++))
4089 continue;
4090 att_end = equal;
4091 }
4092
4093 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4094 * is between <att_beg> and <equal>, both may be identical.
4095 */
4096 /* look for end of cookie if there is an equal sign */
4097 if (equal < hdr_end && *equal == '=') {
4098 /* look for the beginning of the value */
4099 val_beg = equal + 1;
4100 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4101 val_beg++;
4102
4103 /* find the end of the value, respecting quotes */
4104 next = http_find_cookie_value_end(val_beg, hdr_end);
4105
4106 /* make val_end point to the first white space or delimitor after the value */
4107 val_end = next;
4108 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4109 val_end--;
4110 }
4111 else
4112 val_beg = val_end = next = equal;
4113
4114 /* We have nothing to do with attributes beginning with
4115 * '$'. However, they will automatically be removed if a
4116 * header before them is removed, since they're supposed
4117 * to be linked together.
4118 */
4119 if (*att_beg == '$')
4120 continue;
4121
4122 /* Ignore cookies with no equal sign */
4123 if (equal == next) {
4124 /* This is not our cookie, so we must preserve it. But if we already
4125 * scheduled another cookie for removal, we cannot remove the
4126 * complete header, but we can remove the previous block itself.
4127 */
4128 preserve_hdr = 1;
4129 if (del_from != NULL) {
4130 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4131 val_end += delta;
4132 next += delta;
4133 hdr_end += delta;
4134 prev = del_from;
4135 del_from = NULL;
4136 }
4137 continue;
4138 }
4139
4140 /* if there are spaces around the equal sign, we need to
4141 * strip them otherwise we'll get trouble for cookie captures,
4142 * or even for rewrites. Since this happens extremely rarely,
4143 * it does not hurt performance.
4144 */
4145 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4146 int stripped_before = 0;
4147 int stripped_after = 0;
4148
4149 if (att_end != equal) {
4150 memmove(att_end, equal, hdr_end - equal);
4151 stripped_before = (att_end - equal);
4152 equal += stripped_before;
4153 val_beg += stripped_before;
4154 }
4155
4156 if (val_beg > equal + 1) {
4157 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4158 stripped_after = (equal + 1) - val_beg;
4159 val_beg += stripped_after;
4160 stripped_before += stripped_after;
4161 }
4162
4163 val_end += stripped_before;
4164 next += stripped_before;
4165 hdr_end += stripped_before;
4166 }
4167 /* now everything is as on the diagram above */
4168
4169 /* First, let's see if we want to capture this cookie. We check
4170 * that we don't already have a client side cookie, because we
4171 * can only capture one. Also as an optimisation, we ignore
4172 * cookies shorter than the declared name.
4173 */
4174 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4175 (val_end - att_beg >= sess->fe->capture_namelen) &&
4176 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4177 int log_len = val_end - att_beg;
4178
4179 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4180 ha_alert("HTTP logging : out of memory.\n");
4181 } else {
4182 if (log_len > sess->fe->capture_len)
4183 log_len = sess->fe->capture_len;
4184 memcpy(txn->cli_cookie, att_beg, log_len);
4185 txn->cli_cookie[log_len] = 0;
4186 }
4187 }
4188
4189 /* Persistence cookies in passive, rewrite or insert mode have the
4190 * following form :
4191 *
4192 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4193 *
4194 * For cookies in prefix mode, the form is :
4195 *
4196 * Cookie: NAME=SRV~VALUE
4197 */
4198 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4199 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4200 struct server *srv = s->be->srv;
4201 char *delim;
4202
4203 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4204 * have the server ID between val_beg and delim, and the original cookie between
4205 * delim+1 and val_end. Otherwise, delim==val_end :
4206 *
4207 * hdr_beg
4208 * |
4209 * v
4210 * NAME=SRV; # in all but prefix modes
4211 * NAME=SRV~OPAQUE ; # in prefix mode
4212 * || || | |+-> next
4213 * || || | +--> val_end
4214 * || || +---------> delim
4215 * || |+------------> val_beg
4216 * || +-------------> att_end = equal
4217 * |+-----------------> att_beg
4218 * +------------------> prev
4219 *
4220 */
4221 if (s->be->ck_opts & PR_CK_PFX) {
4222 for (delim = val_beg; delim < val_end; delim++)
4223 if (*delim == COOKIE_DELIM)
4224 break;
4225 }
4226 else {
4227 char *vbar1;
4228 delim = val_end;
4229 /* Now check if the cookie contains a date field, which would
4230 * appear after a vertical bar ('|') just after the server name
4231 * and before the delimiter.
4232 */
4233 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4234 if (vbar1) {
4235 /* OK, so left of the bar is the server's cookie and
4236 * right is the last seen date. It is a base64 encoded
4237 * 30-bit value representing the UNIX date since the
4238 * epoch in 4-second quantities.
4239 */
4240 int val;
4241 delim = vbar1++;
4242 if (val_end - vbar1 >= 5) {
4243 val = b64tos30(vbar1);
4244 if (val > 0)
4245 txn->cookie_last_date = val << 2;
4246 }
4247 /* look for a second vertical bar */
4248 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4249 if (vbar1 && (val_end - vbar1 > 5)) {
4250 val = b64tos30(vbar1 + 1);
4251 if (val > 0)
4252 txn->cookie_first_date = val << 2;
4253 }
4254 }
4255 }
4256
4257 /* if the cookie has an expiration date and the proxy wants to check
4258 * it, then we do that now. We first check if the cookie is too old,
4259 * then only if it has expired. We detect strict overflow because the
4260 * time resolution here is not great (4 seconds). Cookies with dates
4261 * in the future are ignored if their offset is beyond one day. This
4262 * allows an admin to fix timezone issues without expiring everyone
4263 * and at the same time avoids keeping unwanted side effects for too
4264 * long.
4265 */
4266 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4267 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4268 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4269 txn->flags &= ~TX_CK_MASK;
4270 txn->flags |= TX_CK_OLD;
4271 delim = val_beg; // let's pretend we have not found the cookie
4272 txn->cookie_first_date = 0;
4273 txn->cookie_last_date = 0;
4274 }
4275 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4276 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4277 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4278 txn->flags &= ~TX_CK_MASK;
4279 txn->flags |= TX_CK_EXPIRED;
4280 delim = val_beg; // let's pretend we have not found the cookie
4281 txn->cookie_first_date = 0;
4282 txn->cookie_last_date = 0;
4283 }
4284
4285 /* Here, we'll look for the first running server which supports the cookie.
4286 * This allows to share a same cookie between several servers, for example
4287 * to dedicate backup servers to specific servers only.
4288 * However, to prevent clients from sticking to cookie-less backup server
4289 * when they have incidentely learned an empty cookie, we simply ignore
4290 * empty cookies and mark them as invalid.
4291 * The same behaviour is applied when persistence must be ignored.
4292 */
4293 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4294 srv = NULL;
4295
4296 while (srv) {
4297 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4298 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4299 if ((srv->cur_state != SRV_ST_STOPPED) ||
4300 (s->be->options & PR_O_PERSIST) ||
4301 (s->flags & SF_FORCE_PRST)) {
4302 /* we found the server and we can use it */
4303 txn->flags &= ~TX_CK_MASK;
4304 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4305 s->flags |= SF_DIRECT | SF_ASSIGNED;
4306 s->target = &srv->obj_type;
4307 break;
4308 } else {
4309 /* we found a server, but it's down,
4310 * mark it as such and go on in case
4311 * another one is available.
4312 */
4313 txn->flags &= ~TX_CK_MASK;
4314 txn->flags |= TX_CK_DOWN;
4315 }
4316 }
4317 srv = srv->next;
4318 }
4319
4320 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4321 /* no server matched this cookie or we deliberately skipped it */
4322 txn->flags &= ~TX_CK_MASK;
4323 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4324 txn->flags |= TX_CK_UNUSED;
4325 else
4326 txn->flags |= TX_CK_INVALID;
4327 }
4328
4329 /* depending on the cookie mode, we may have to either :
4330 * - delete the complete cookie if we're in insert+indirect mode, so that
4331 * the server never sees it ;
4332 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004333 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004334 * if we're in cookie prefix mode
4335 */
4336 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4337 int delta; /* negative */
4338
4339 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4340 delta = val_beg - (delim + 1);
4341 val_end += delta;
4342 next += delta;
4343 hdr_end += delta;
4344 del_from = NULL;
4345 preserve_hdr = 1; /* we want to keep this cookie */
4346 }
4347 else if (del_from == NULL &&
4348 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4349 del_from = prev;
4350 }
4351 }
4352 else {
4353 /* This is not our cookie, so we must preserve it. But if we already
4354 * scheduled another cookie for removal, we cannot remove the
4355 * complete header, but we can remove the previous block itself.
4356 */
4357 preserve_hdr = 1;
4358
4359 if (del_from != NULL) {
4360 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4361 if (att_beg >= del_from)
4362 att_beg += delta;
4363 if (att_end >= del_from)
4364 att_end += delta;
4365 val_beg += delta;
4366 val_end += delta;
4367 next += delta;
4368 hdr_end += delta;
4369 prev = del_from;
4370 del_from = NULL;
4371 }
4372 }
4373
4374 /* continue with next cookie on this header line */
4375 att_beg = next;
4376 } /* for each cookie */
4377
4378
4379 /* There are no more cookies on this line.
4380 * We may still have one (or several) marked for deletion at the
4381 * end of the line. We must do this now in two ways :
4382 * - if some cookies must be preserved, we only delete from the
4383 * mark to the end of line ;
4384 * - if nothing needs to be preserved, simply delete the whole header
4385 */
4386 if (del_from) {
4387 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4388 }
4389 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004390 if (hdr_beg != hdr_end)
4391 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004392 else
4393 http_remove_header(htx, &ctx);
4394 }
4395 } /* for each "Cookie header */
4396}
4397
4398/*
4399 * Manage server-side cookies. It can impact performance by about 2% so it is
4400 * desirable to call it only when needed. This function is also used when we
4401 * just need to know if there is a cookie (eg: for check-cache).
4402 */
4403static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4404{
4405 struct session *sess = s->sess;
4406 struct http_txn *txn = s->txn;
4407 struct htx *htx;
4408 struct http_hdr_ctx ctx;
4409 struct server *srv;
4410 char *hdr_beg, *hdr_end;
4411 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004412 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004413
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004414 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004415
4416 ctx.blk = NULL;
4417 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004418 int is_first = 1;
4419
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004420 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4421 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4422 break;
4423 is_cookie2 = 1;
4424 }
4425
4426 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4427 * <prev> points to the colon.
4428 */
4429 txn->flags |= TX_SCK_PRESENT;
4430
4431 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4432 * check-cache is enabled) and we are not interested in checking
4433 * them. Warning, the cookie capture is declared in the frontend.
4434 */
4435 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4436 break;
4437
4438 /* OK so now we know we have to process this response cookie.
4439 * The format of the Set-Cookie header is slightly different
4440 * from the format of the Cookie header in that it does not
4441 * support the comma as a cookie delimiter (thus the header
4442 * cannot be folded) because the Expires attribute described in
4443 * the original Netscape's spec may contain an unquoted date
4444 * with a comma inside. We have to live with this because
4445 * many browsers don't support Max-Age and some browsers don't
4446 * support quoted strings. However the Set-Cookie2 header is
4447 * clean.
4448 *
4449 * We have to keep multiple pointers in order to support cookie
4450 * removal at the beginning, middle or end of header without
4451 * corrupting the header (in case of set-cookie2). A special
4452 * pointer, <scav> points to the beginning of the set-cookie-av
4453 * fields after the first semi-colon. The <next> pointer points
4454 * either to the end of line (set-cookie) or next unquoted comma
4455 * (set-cookie2). All of these headers are valid :
4456 *
4457 * hdr_beg hdr_end
4458 * | |
4459 * v |
4460 * NAME1 = VALUE 1 ; Secure; Path="/" |
4461 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4462 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4463 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4464 * | | | | | | | |
4465 * | | | | | | | +-> next
4466 * | | | | | | +------------> scav
4467 * | | | | | +--------------> val_end
4468 * | | | | +--------------------> val_beg
4469 * | | | +----------------------> equal
4470 * | | +------------------------> att_end
4471 * | +----------------------------> att_beg
4472 * +------------------------------> prev
4473 * -------------------------------> hdr_beg
4474 */
4475 hdr_beg = ctx.value.ptr;
4476 hdr_end = hdr_beg + ctx.value.len;
4477 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4478
4479 /* Iterate through all cookies on this line */
4480
4481 /* find att_beg */
4482 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004483 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004484 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004485 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004486
4487 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4488 att_beg++;
4489
4490 /* find att_end : this is the first character after the last non
4491 * space before the equal. It may be equal to hdr_end.
4492 */
4493 equal = att_end = att_beg;
4494
4495 while (equal < hdr_end) {
4496 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4497 break;
4498 if (HTTP_IS_SPHT(*equal++))
4499 continue;
4500 att_end = equal;
4501 }
4502
4503 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4504 * is between <att_beg> and <equal>, both may be identical.
4505 */
4506
4507 /* look for end of cookie if there is an equal sign */
4508 if (equal < hdr_end && *equal == '=') {
4509 /* look for the beginning of the value */
4510 val_beg = equal + 1;
4511 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4512 val_beg++;
4513
4514 /* find the end of the value, respecting quotes */
4515 next = http_find_cookie_value_end(val_beg, hdr_end);
4516
4517 /* make val_end point to the first white space or delimitor after the value */
4518 val_end = next;
4519 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4520 val_end--;
4521 }
4522 else {
4523 /* <equal> points to next comma, semi-colon or EOL */
4524 val_beg = val_end = next = equal;
4525 }
4526
4527 if (next < hdr_end) {
4528 /* Set-Cookie2 supports multiple cookies, and <next> points to
4529 * a colon or semi-colon before the end. So skip all attr-value
4530 * pairs and look for the next comma. For Set-Cookie, since
4531 * commas are permitted in values, skip to the end.
4532 */
4533 if (is_cookie2)
4534 next = http_find_hdr_value_end(next, hdr_end);
4535 else
4536 next = hdr_end;
4537 }
4538
4539 /* Now everything is as on the diagram above */
4540
4541 /* Ignore cookies with no equal sign */
4542 if (equal == val_end)
4543 continue;
4544
4545 /* If there are spaces around the equal sign, we need to
4546 * strip them otherwise we'll get trouble for cookie captures,
4547 * or even for rewrites. Since this happens extremely rarely,
4548 * it does not hurt performance.
4549 */
4550 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4551 int stripped_before = 0;
4552 int stripped_after = 0;
4553
4554 if (att_end != equal) {
4555 memmove(att_end, equal, hdr_end - equal);
4556 stripped_before = (att_end - equal);
4557 equal += stripped_before;
4558 val_beg += stripped_before;
4559 }
4560
4561 if (val_beg > equal + 1) {
4562 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4563 stripped_after = (equal + 1) - val_beg;
4564 val_beg += stripped_after;
4565 stripped_before += stripped_after;
4566 }
4567
4568 val_end += stripped_before;
4569 next += stripped_before;
4570 hdr_end += stripped_before;
4571
Christopher Faulet41dc8432019-06-18 09:49:16 +02004572 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004573 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004574 }
4575
4576 /* First, let's see if we want to capture this cookie. We check
4577 * that we don't already have a server side cookie, because we
4578 * can only capture one. Also as an optimisation, we ignore
4579 * cookies shorter than the declared name.
4580 */
4581 if (sess->fe->capture_name != NULL &&
4582 txn->srv_cookie == NULL &&
4583 (val_end - att_beg >= sess->fe->capture_namelen) &&
4584 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4585 int log_len = val_end - att_beg;
4586 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4587 ha_alert("HTTP logging : out of memory.\n");
4588 }
4589 else {
4590 if (log_len > sess->fe->capture_len)
4591 log_len = sess->fe->capture_len;
4592 memcpy(txn->srv_cookie, att_beg, log_len);
4593 txn->srv_cookie[log_len] = 0;
4594 }
4595 }
4596
4597 srv = objt_server(s->target);
4598 /* now check if we need to process it for persistence */
4599 if (!(s->flags & SF_IGNORE_PRST) &&
4600 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4601 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4602 /* assume passive cookie by default */
4603 txn->flags &= ~TX_SCK_MASK;
4604 txn->flags |= TX_SCK_FOUND;
4605
4606 /* If the cookie is in insert mode on a known server, we'll delete
4607 * this occurrence because we'll insert another one later.
4608 * We'll delete it too if the "indirect" option is set and we're in
4609 * a direct access.
4610 */
4611 if (s->be->ck_opts & PR_CK_PSV) {
4612 /* The "preserve" flag was set, we don't want to touch the
4613 * server's cookie.
4614 */
4615 }
4616 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4617 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4618 /* this cookie must be deleted */
4619 if (prev == hdr_beg && next == hdr_end) {
4620 /* whole header */
4621 http_remove_header(htx, &ctx);
4622 /* note: while both invalid now, <next> and <hdr_end>
4623 * are still equal, so the for() will stop as expected.
4624 */
4625 } else {
4626 /* just remove the value */
4627 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4628 next = prev;
4629 hdr_end += delta;
4630 }
4631 txn->flags &= ~TX_SCK_MASK;
4632 txn->flags |= TX_SCK_DELETED;
4633 /* and go on with next cookie */
4634 }
4635 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4636 /* replace bytes val_beg->val_end with the cookie name associated
4637 * with this server since we know it.
4638 */
4639 int sliding, delta;
4640
4641 ctx.value = ist2(val_beg, val_end - val_beg);
4642 ctx.lws_before = ctx.lws_after = 0;
4643 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4644 delta = srv->cklen - (val_end - val_beg);
4645 sliding = (ctx.value.ptr - val_beg);
4646 hdr_beg += sliding;
4647 val_beg += sliding;
4648 next += sliding + delta;
4649 hdr_end += sliding + delta;
4650
4651 txn->flags &= ~TX_SCK_MASK;
4652 txn->flags |= TX_SCK_REPLACED;
4653 }
4654 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4655 /* insert the cookie name associated with this server
4656 * before existing cookie, and insert a delimiter between them..
4657 */
4658 int sliding, delta;
4659 ctx.value = ist2(val_beg, 0);
4660 ctx.lws_before = ctx.lws_after = 0;
4661 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4662 delta = srv->cklen + 1;
4663 sliding = (ctx.value.ptr - val_beg);
4664 hdr_beg += sliding;
4665 val_beg += sliding;
4666 next += sliding + delta;
4667 hdr_end += sliding + delta;
4668
4669 val_beg[srv->cklen] = COOKIE_DELIM;
4670 txn->flags &= ~TX_SCK_MASK;
4671 txn->flags |= TX_SCK_REPLACED;
4672 }
4673 }
4674 /* that's done for this cookie, check the next one on the same
4675 * line when next != hdr_end (only if is_cookie2).
4676 */
4677 }
4678 }
4679}
4680
Christopher Faulet25a02f62018-10-24 12:00:25 +02004681/*
4682 * Parses the Cache-Control and Pragma request header fields to determine if
4683 * the request may be served from the cache and/or if it is cacheable. Updates
4684 * s->txn->flags.
4685 */
4686void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4687{
4688 struct http_txn *txn = s->txn;
4689 struct htx *htx;
4690 int32_t pos;
4691 int pragma_found, cc_found, i;
4692
4693 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4694 return; /* nothing more to do here */
4695
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004696 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004697 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004698 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004699 struct htx_blk *blk = htx_get_blk(htx, pos);
4700 enum htx_blk_type type = htx_get_blk_type(blk);
4701 struct ist n, v;
4702
4703 if (type == HTX_BLK_EOH)
4704 break;
4705 if (type != HTX_BLK_HDR)
4706 continue;
4707
4708 n = htx_get_blk_name(htx, blk);
4709 v = htx_get_blk_value(htx, blk);
4710
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004711 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004712 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4713 pragma_found = 1;
4714 continue;
4715 }
4716 }
4717
4718 /* Don't use the cache and don't try to store if we found the
4719 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004720 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004721 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4722 txn->flags |= TX_CACHE_IGNORE;
4723 continue;
4724 }
4725
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004726 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004727 continue;
4728
4729 /* OK, right now we know we have a cache-control header */
4730 cc_found = 1;
4731 if (!v.len) /* no info */
4732 continue;
4733
4734 i = 0;
4735 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4736 !isspace((unsigned char)*(v.ptr+i)))
4737 i++;
4738
4739 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4740 * values after max-age, max-stale nor min-fresh, we simply don't
4741 * use the cache when they're specified.
4742 */
4743 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4744 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4745 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4746 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4747 txn->flags |= TX_CACHE_IGNORE;
4748 continue;
4749 }
4750
4751 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4752 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4753 continue;
4754 }
4755 }
4756
4757 /* RFC7234#5.4:
4758 * When the Cache-Control header field is also present and
4759 * understood in a request, Pragma is ignored.
4760 * When the Cache-Control header field is not present in a
4761 * request, caches MUST consider the no-cache request
4762 * pragma-directive as having the same effect as if
4763 * "Cache-Control: no-cache" were present.
4764 */
4765 if (!cc_found && pragma_found)
4766 txn->flags |= TX_CACHE_IGNORE;
4767}
4768
4769/*
4770 * Check if response is cacheable or not. Updates s->txn->flags.
4771 */
4772void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4773{
4774 struct http_txn *txn = s->txn;
4775 struct htx *htx;
4776 int32_t pos;
4777 int i;
4778
4779 if (txn->status < 200) {
4780 /* do not try to cache interim responses! */
4781 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4782 return;
4783 }
4784
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004785 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004786 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004787 struct htx_blk *blk = htx_get_blk(htx, pos);
4788 enum htx_blk_type type = htx_get_blk_type(blk);
4789 struct ist n, v;
4790
4791 if (type == HTX_BLK_EOH)
4792 break;
4793 if (type != HTX_BLK_HDR)
4794 continue;
4795
4796 n = htx_get_blk_name(htx, blk);
4797 v = htx_get_blk_value(htx, blk);
4798
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004799 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004800 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4801 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4802 return;
4803 }
4804 }
4805
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004806 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004807 continue;
4808
4809 /* OK, right now we know we have a cache-control header */
4810 if (!v.len) /* no info */
4811 continue;
4812
4813 i = 0;
4814 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4815 !isspace((unsigned char)*(v.ptr+i)))
4816 i++;
4817
4818 /* we have a complete value between v.ptr and (v.ptr+i) */
4819 if (i < v.len && *(v.ptr + i) == '=') {
4820 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4821 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4822 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4823 continue;
4824 }
4825
4826 /* we have something of the form no-cache="set-cookie" */
4827 if ((v.len >= 21) &&
4828 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4829 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4830 txn->flags &= ~TX_CACHE_COOK;
4831 continue;
4832 }
4833
4834 /* OK, so we know that either p2 points to the end of string or to a comma */
4835 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4836 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4837 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4838 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4839 return;
4840 }
4841
4842 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4843 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4844 continue;
4845 }
4846 }
4847}
4848
Christopher Faulet64159df2018-10-24 21:15:35 +02004849/* send a server's name with an outgoing request over an established connection.
4850 * Note: this function is designed to be called once the request has been
4851 * scheduled for being forwarded. This is the reason why the number of forwarded
4852 * bytes have to be adjusted.
4853 */
4854int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4855{
4856 struct htx *htx;
4857 struct http_hdr_ctx ctx;
4858 struct ist hdr;
4859 uint32_t data;
4860
4861 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004862 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004863 data = htx->data;
4864
4865 ctx.blk = NULL;
4866 while (http_find_header(htx, hdr, &ctx, 1))
4867 http_remove_header(htx, &ctx);
4868 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4869
4870 if (co_data(&s->req)) {
4871 if (data >= htx->data)
4872 c_rew(&s->req, data - htx->data);
4873 else
4874 c_adv(&s->req, htx->data - data);
4875 }
4876 return 0;
4877}
4878
Christopher Faulet377c5a52018-10-24 21:21:30 +02004879/*
4880 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4881 * for the current backend.
4882 *
4883 * It is assumed that the request is either a HEAD, GET, or POST and that the
4884 * uri_auth field is valid.
4885 *
4886 * Returns 1 if stats should be provided, otherwise 0.
4887 */
4888static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4889{
4890 struct uri_auth *uri_auth = backend->uri_auth;
4891 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004892 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004893 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004894
4895 if (!uri_auth)
4896 return 0;
4897
4898 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4899 return 0;
4900
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004901 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004902 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004903 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004904
4905 /* check URI size */
4906 if (uri_auth->uri_len > uri.len)
4907 return 0;
4908
4909 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4910 return 0;
4911
4912 return 1;
4913}
4914
4915/* This function prepares an applet to handle the stats. It can deal with the
4916 * "100-continue" expectation, check that admin rules are met for POST requests,
4917 * and program a response message if something was unexpected. It cannot fail
4918 * and always relies on the stats applet to complete the job. It does not touch
4919 * analysers nor counters, which are left to the caller. It does not touch
4920 * s->target which is supposed to already point to the stats applet. The caller
4921 * is expected to have already assigned an appctx to the stream.
4922 */
4923static int htx_handle_stats(struct stream *s, struct channel *req)
4924{
4925 struct stats_admin_rule *stats_admin_rule;
4926 struct stream_interface *si = &s->si[1];
4927 struct session *sess = s->sess;
4928 struct http_txn *txn = s->txn;
4929 struct http_msg *msg = &txn->req;
4930 struct uri_auth *uri_auth = s->be->uri_auth;
4931 const char *h, *lookup, *end;
4932 struct appctx *appctx;
4933 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004934 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004935
4936 appctx = si_appctx(si);
4937 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4938 appctx->st1 = appctx->st2 = 0;
4939 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4940 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4941 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4942 appctx->ctx.stats.flags |= STAT_CHUNKED;
4943
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004944 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004945 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004946 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4947 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004948
4949 for (h = lookup; h <= end - 3; h++) {
4950 if (memcmp(h, ";up", 3) == 0) {
4951 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4952 break;
4953 }
4954 }
4955
4956 if (uri_auth->refresh) {
4957 for (h = lookup; h <= end - 10; h++) {
4958 if (memcmp(h, ";norefresh", 10) == 0) {
4959 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4960 break;
4961 }
4962 }
4963 }
4964
4965 for (h = lookup; h <= end - 4; h++) {
4966 if (memcmp(h, ";csv", 4) == 0) {
4967 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4968 break;
4969 }
4970 }
4971
4972 for (h = lookup; h <= end - 6; h++) {
4973 if (memcmp(h, ";typed", 6) == 0) {
4974 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4975 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4976 break;
4977 }
4978 }
4979
4980 for (h = lookup; h <= end - 8; h++) {
4981 if (memcmp(h, ";st=", 4) == 0) {
4982 int i;
4983 h += 4;
4984 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4985 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4986 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4987 appctx->ctx.stats.st_code = i;
4988 break;
4989 }
4990 }
4991 break;
4992 }
4993 }
4994
4995 appctx->ctx.stats.scope_str = 0;
4996 appctx->ctx.stats.scope_len = 0;
4997 for (h = lookup; h <= end - 8; h++) {
4998 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4999 int itx = 0;
5000 const char *h2;
5001 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
5002 const char *err;
5003
5004 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
5005 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01005006 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
5007 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005008 if (*h == ';' || *h == '&' || *h == ' ')
5009 break;
5010 itx++;
5011 h++;
5012 }
5013
5014 if (itx > STAT_SCOPE_TXT_MAXLEN)
5015 itx = STAT_SCOPE_TXT_MAXLEN;
5016 appctx->ctx.stats.scope_len = itx;
5017
5018 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5019 memcpy(scope_txt, h2, itx);
5020 scope_txt[itx] = '\0';
5021 err = invalid_char(scope_txt);
5022 if (err) {
5023 /* bad char in search text => clear scope */
5024 appctx->ctx.stats.scope_str = 0;
5025 appctx->ctx.stats.scope_len = 0;
5026 }
5027 break;
5028 }
5029 }
5030
5031 /* now check whether we have some admin rules for this request */
5032 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5033 int ret = 1;
5034
5035 if (stats_admin_rule->cond) {
5036 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5037 ret = acl_pass(ret);
5038 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5039 ret = !ret;
5040 }
5041
5042 if (ret) {
5043 /* no rule, or the rule matches */
5044 appctx->ctx.stats.flags |= STAT_ADMIN;
5045 break;
5046 }
5047 }
5048
Christopher Faulet5d45e382019-02-27 15:15:23 +01005049 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5050 appctx->st0 = STAT_HTTP_HEAD;
5051 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005052 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005053 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005054 if (msg->msg_state < HTTP_MSG_DATA)
5055 req->analysers |= AN_REQ_HTTP_BODY;
5056 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005057 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005058 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005059 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5060 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5061 appctx->st0 = STAT_HTTP_LAST;
5062 }
5063 }
5064 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005065 /* Unsupported method */
5066 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5067 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5068 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005069 }
5070
5071 s->task->nice = -32; /* small boost for HTTP statistics */
5072 return 1;
5073}
5074
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005075void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5076{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005077 struct channel *req = &s->req;
5078 struct channel *res = &s->res;
5079 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005081 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005082 struct ist path, location;
5083 unsigned int flags;
5084 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005085
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005086 /*
5087 * Create the location
5088 */
5089 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005090
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005091 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005092 /* special prefix "/" means don't change URL */
5093 srv = __objt_server(s->target);
5094 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5095 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5096 return;
5097 }
5098
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005099 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005100 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005101 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005102 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005103 if (!path.ptr)
5104 return;
5105
5106 if (!chunk_memcat(&trash, path.ptr, path.len))
5107 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005108 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005109
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005110 /*
5111 * Create the 302 respone
5112 */
5113 htx = htx_from_buf(&res->buf);
5114 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5115 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5116 ist("HTTP/1.1"), ist("302"), ist("Found"));
5117 if (!sl)
5118 goto fail;
5119 sl->info.res.status = 302;
5120 s->txn->status = 302;
5121
5122 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5123 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5124 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5125 !htx_add_header(htx, ist("Location"), location))
5126 goto fail;
5127
5128 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5129 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005130
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005131 /*
5132 * Send the message
5133 */
5134 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005135 c_adv(res, data);
5136 res->total += data;
5137
5138 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005139 si_shutr(si);
5140 si_shutw(si);
5141 si->err_type = SI_ET_NONE;
5142 si->state = SI_ST_CLO;
5143
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005144 channel_auto_read(req);
5145 channel_abort(req);
5146 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005147 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005148 channel_auto_read(res);
5149 channel_auto_close(res);
5150
5151 if (!(s->flags & SF_ERR_MASK))
5152 s->flags |= SF_ERR_LOCAL;
5153 if (!(s->flags & SF_FINST_MASK))
5154 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005155
5156 /* FIXME: we should increase a counter of redirects per server and per backend. */
5157 srv_inc_sess_ctr(srv);
5158 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005159 return;
5160
5161 fail:
5162 /* If an error occurred, remove the incomplete HTTP response from the
5163 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005164 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005165}
5166
Christopher Fauletf2824e62018-10-01 12:12:37 +02005167/* This function terminates the request because it was completly analyzed or
5168 * because an error was triggered during the body forwarding.
5169 */
5170static void htx_end_request(struct stream *s)
5171{
5172 struct channel *chn = &s->req;
5173 struct http_txn *txn = s->txn;
5174
5175 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5176 now_ms, __FUNCTION__, s,
5177 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5178 s->req.analysers, s->res.analysers);
5179
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005180 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5181 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005182 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005183 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005184 goto end;
5185 }
5186
5187 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5188 return;
5189
5190 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005191 /* No need to read anymore, the request was completely parsed.
5192 * We can shut the read side unless we want to abort_on_close,
5193 * or we have a POST request. The issue with POST requests is
5194 * that some browsers still send a CRLF after the request, and
5195 * this CRLF must be read so that it does not remain in the kernel
5196 * buffers, otherwise a close could cause an RST on some systems
5197 * (eg: Linux).
5198 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005199 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005200 channel_dont_read(chn);
5201
5202 /* if the server closes the connection, we want to immediately react
5203 * and close the socket to save packets and syscalls.
5204 */
5205 s->si[1].flags |= SI_FL_NOHALF;
5206
5207 /* In any case we've finished parsing the request so we must
5208 * disable Nagle when sending data because 1) we're not going
5209 * to shut this side, and 2) the server is waiting for us to
5210 * send pending data.
5211 */
5212 chn->flags |= CF_NEVER_WAIT;
5213
Christopher Fauletd01ce402019-01-02 17:44:13 +01005214 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5215 /* The server has not finished to respond, so we
5216 * don't want to move in order not to upset it.
5217 */
5218 return;
5219 }
5220
Christopher Fauletf2824e62018-10-01 12:12:37 +02005221 /* When we get here, it means that both the request and the
5222 * response have finished receiving. Depending on the connection
5223 * mode, we'll have to wait for the last bytes to leave in either
5224 * direction, and sometimes for a close to be effective.
5225 */
5226 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5227 /* Tunnel mode will not have any analyser so it needs to
5228 * poll for reads.
5229 */
5230 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005231 if (b_data(&chn->buf))
5232 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 txn->req.msg_state = HTTP_MSG_TUNNEL;
5234 }
5235 else {
5236 /* we're not expecting any new data to come for this
5237 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005238 *
5239 * However, there is an exception if the response
5240 * length is undefined. In this case, we need to wait
5241 * the close from the server. The response will be
5242 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005243 */
5244 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5245 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005246 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005247
5248 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5249 channel_shutr_now(chn);
5250 channel_shutw_now(chn);
5251 }
5252 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005253 goto check_channel_flags;
5254 }
5255
5256 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5257 http_msg_closing:
5258 /* nothing else to forward, just waiting for the output buffer
5259 * to be empty and for the shutw_now to take effect.
5260 */
5261 if (channel_is_empty(chn)) {
5262 txn->req.msg_state = HTTP_MSG_CLOSED;
5263 goto http_msg_closed;
5264 }
5265 else if (chn->flags & CF_SHUTW) {
5266 txn->req.err_state = txn->req.msg_state;
5267 txn->req.msg_state = HTTP_MSG_ERROR;
5268 goto end;
5269 }
5270 return;
5271 }
5272
5273 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5274 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005275 /* if we don't know whether the server will close, we need to hard close */
5276 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5277 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005278 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005279 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005280 channel_dont_read(chn);
5281 goto end;
5282 }
5283
5284 check_channel_flags:
5285 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5286 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5287 /* if we've just closed an output, let's switch */
5288 txn->req.msg_state = HTTP_MSG_CLOSING;
5289 goto http_msg_closing;
5290 }
5291
5292 end:
5293 chn->analysers &= AN_REQ_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005294 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
5295 chn->flags |= CF_NEVER_WAIT;
5296 if (HAS_REQ_DATA_FILTERS(s))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005297 chn->analysers |= AN_REQ_FLT_XFER_DATA;
Christopher Faulet86c82202020-12-15 13:32:55 +01005298 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 channel_auto_close(chn);
5300 channel_auto_read(chn);
5301}
5302
5303
5304/* This function terminates the response because it was completly analyzed or
5305 * because an error was triggered during the body forwarding.
5306 */
5307static void htx_end_response(struct stream *s)
5308{
5309 struct channel *chn = &s->res;
5310 struct http_txn *txn = s->txn;
5311
5312 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5313 now_ms, __FUNCTION__, s,
5314 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5315 s->req.analysers, s->res.analysers);
5316
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005317 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5318 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005319 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005320 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005321 goto end;
5322 }
5323
5324 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5325 return;
5326
5327 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5328 /* In theory, we don't need to read anymore, but we must
5329 * still monitor the server connection for a possible close
5330 * while the request is being uploaded, so we don't disable
5331 * reading.
5332 */
5333 /* channel_dont_read(chn); */
5334
5335 if (txn->req.msg_state < HTTP_MSG_DONE) {
5336 /* The client seems to still be sending data, probably
5337 * because we got an error response during an upload.
5338 * We have the choice of either breaking the connection
5339 * or letting it pass through. Let's do the later.
5340 */
5341 return;
5342 }
5343
5344 /* When we get here, it means that both the request and the
5345 * response have finished receiving. Depending on the connection
5346 * mode, we'll have to wait for the last bytes to leave in either
5347 * direction, and sometimes for a close to be effective.
5348 */
5349 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5350 channel_auto_read(chn);
5351 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005352 if (b_data(&chn->buf))
5353 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005354 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5355 }
5356 else {
5357 /* we're not expecting any new data to come for this
5358 * transaction, so we can close it.
5359 */
5360 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5361 channel_shutr_now(chn);
5362 channel_shutw_now(chn);
5363 }
5364 }
5365 goto check_channel_flags;
5366 }
5367
5368 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5369 http_msg_closing:
5370 /* nothing else to forward, just waiting for the output buffer
5371 * to be empty and for the shutw_now to take effect.
5372 */
5373 if (channel_is_empty(chn)) {
5374 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5375 goto http_msg_closed;
5376 }
5377 else if (chn->flags & CF_SHUTW) {
5378 txn->rsp.err_state = txn->rsp.msg_state;
5379 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005380 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005381 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005382 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005383 goto end;
5384 }
5385 return;
5386 }
5387
5388 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5389 http_msg_closed:
5390 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005391 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005392 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005393 goto end;
5394 }
5395
5396 check_channel_flags:
5397 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5398 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5399 /* if we've just closed an output, let's switch */
5400 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5401 goto http_msg_closing;
5402 }
5403
5404 end:
5405 chn->analysers &= AN_RES_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005406 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5407 chn->flags |= CF_NEVER_WAIT;
5408 if (HAS_RSP_DATA_FILTERS(s))
5409 chn->analysers |= AN_RES_FLT_XFER_DATA;
5410 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005411 channel_auto_close(chn);
5412 channel_auto_read(chn);
5413}
5414
Christopher Faulet0f226952018-10-22 09:29:56 +02005415void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5416 int finst, const struct buffer *msg)
5417{
5418 channel_auto_read(si_oc(si));
5419 channel_abort(si_oc(si));
5420 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005421 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005422 channel_auto_close(si_ic(si));
5423 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005424
5425 /* <msg> is an HTX structure. So we copy it in the response's
5426 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005427 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005428 struct channel *chn = si_ic(si);
5429 struct htx *htx;
5430
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005431 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005432 chn->buf.data = msg->data;
5433 memcpy(chn->buf.area, msg->area, msg->data);
5434 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005435 if (s->txn->meth == HTTP_METH_HEAD)
5436 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005437 c_adv(chn, htx->data);
5438 chn->total += htx->data;
5439 }
5440 if (!(s->flags & SF_ERR_MASK))
5441 s->flags |= err;
5442 if (!(s->flags & SF_FINST_MASK))
5443 s->flags |= finst;
5444}
5445
5446void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5447{
5448 channel_auto_read(&s->req);
5449 channel_abort(&s->req);
5450 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005451 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5452 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005453
5454 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005455
5456 /* <msg> is an HTX structure. So we copy it in the response's
5457 * channel */
5458 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005459 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005460 struct channel *chn = &s->res;
5461 struct htx *htx;
5462
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005463 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005464 chn->buf.data = msg->data;
5465 memcpy(chn->buf.area, msg->area, msg->data);
5466 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005467 if (s->txn->meth == HTTP_METH_HEAD)
5468 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005469 c_adv(chn, htx->data);
5470 chn->total += htx->data;
5471 }
5472
5473 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5474 channel_auto_read(&s->res);
5475 channel_auto_close(&s->res);
5476 channel_shutr_now(&s->res);
5477}
5478
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005479struct buffer *htx_error_message(struct stream *s)
5480{
5481 const int msgnum = http_get_status_idx(s->txn->status);
5482
5483 if (s->be->errmsg[msgnum].area)
5484 return &s->be->errmsg[msgnum];
5485 else if (strm_fe(s)->errmsg[msgnum].area)
5486 return &strm_fe(s)->errmsg[msgnum];
5487 else
5488 return &htx_err_chunks[msgnum];
5489}
5490
5491
Christopher Faulet4a28a532019-03-01 11:19:40 +01005492/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5493 * on success and -1 on error.
5494 */
5495static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5496{
5497 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5498 * then we must send an HTTP/1.1 100 Continue intermediate response.
5499 */
5500 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5501 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5502 struct ist hdr = { .ptr = "Expect", .len = 6 };
5503 struct http_hdr_ctx ctx;
5504
5505 ctx.blk = NULL;
5506 /* Expect is allowed in 1.1, look for it */
5507 if (http_find_header(htx, hdr, &ctx, 0) &&
5508 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5509 if (htx_reply_100_continue(s) == -1)
5510 return -1;
5511 http_remove_header(htx, &ctx);
5512 }
5513 }
5514 return 0;
5515}
5516
Christopher Faulet23a3c792018-11-28 10:01:23 +01005517/* Send a 100-Continue response to the client. It returns 0 on success and -1
5518 * on error. The response channel is updated accordingly.
5519 */
5520static int htx_reply_100_continue(struct stream *s)
5521{
5522 struct channel *res = &s->res;
5523 struct htx *htx = htx_from_buf(&res->buf);
5524 struct htx_sl *sl;
5525 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5526 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5527 size_t data;
5528
5529 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5530 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5531 if (!sl)
5532 goto fail;
5533 sl->info.res.status = 100;
5534
Christopher Faulet9869f932019-06-26 14:23:54 +02005535 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005536 goto fail;
5537
5538 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005539 c_adv(res, data);
5540 res->total += data;
5541 return 0;
5542
5543 fail:
5544 /* If an error occurred, remove the incomplete HTTP response from the
5545 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005546 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005547 return -1;
5548}
5549
Christopher Faulet12c51e22018-11-28 15:59:42 +01005550
5551/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5552 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5553 * error. The response channel is updated accordingly.
5554 */
5555static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5556{
5557 struct channel *res = &s->res;
5558 struct htx *htx = htx_from_buf(&res->buf);
5559 struct htx_sl *sl;
5560 struct ist code, body;
5561 int status;
5562 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5563 size_t data;
5564
5565 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5566 status = 401;
5567 code = ist("401");
5568 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5569 "You need a valid user and password to access this content.\n"
5570 "</body></html>\n");
5571 }
5572 else {
5573 status = 407;
5574 code = ist("407");
5575 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5576 "You need a valid user and password to access this content.\n"
5577 "</body></html>\n");
5578 }
5579
5580 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5581 ist("HTTP/1.1"), code, ist("Unauthorized"));
5582 if (!sl)
5583 goto fail;
5584 sl->info.res.status = status;
5585 s->txn->status = status;
5586
5587 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5588 goto fail;
5589
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005590 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5591 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005592 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005593 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5594 goto fail;
5595 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5596 goto fail;
5597 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005598 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005599 if (!htx_add_endof(htx, HTX_BLK_EOH))
5600 goto fail;
5601
Christopher Faulete6ee4652020-10-19 18:01:38 +02005602 if (s->txn->meth == HTTP_METH_HEAD)
5603 body.len = 0;
5604
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005605 while (body.len) {
5606 size_t sent = htx_add_data(htx, body);
5607 if (!sent)
5608 goto fail;
5609 body.ptr += sent;
5610 body.len -= sent;
5611 }
5612
5613 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005614 goto fail;
5615
5616 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005617 c_adv(res, data);
5618 res->total += data;
5619
5620 channel_auto_read(&s->req);
5621 channel_abort(&s->req);
5622 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005623 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005624
5625 res->wex = tick_add_ifset(now_ms, res->wto);
5626 channel_auto_read(res);
5627 channel_auto_close(res);
5628 channel_shutr_now(res);
5629 return 0;
5630
5631 fail:
5632 /* If an error occurred, remove the incomplete HTTP response from the
5633 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005634 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005635 return -1;
5636}
5637
Christopher Faulet0f226952018-10-22 09:29:56 +02005638/*
5639 * Capture headers from message <htx> according to header list <cap_hdr>, and
5640 * fill the <cap> pointers appropriately.
5641 */
5642static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5643{
5644 struct cap_hdr *h;
5645 int32_t pos;
5646
Christopher Fauleta3f15502019-05-13 15:27:23 +02005647 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005648 struct htx_blk *blk = htx_get_blk(htx, pos);
5649 enum htx_blk_type type = htx_get_blk_type(blk);
5650 struct ist n, v;
5651
5652 if (type == HTX_BLK_EOH)
5653 break;
5654 if (type != HTX_BLK_HDR)
5655 continue;
5656
5657 n = htx_get_blk_name(htx, blk);
5658
5659 for (h = cap_hdr; h; h = h->next) {
5660 if (h->namelen && (h->namelen == n.len) &&
5661 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5662 if (cap[h->index] == NULL)
5663 cap[h->index] =
5664 pool_alloc(h->pool);
5665
5666 if (cap[h->index] == NULL) {
5667 ha_alert("HTTP capture : out of memory.\n");
5668 break;
5669 }
5670
5671 v = htx_get_blk_value(htx, blk);
5672 if (v.len > h->len)
5673 v.len = h->len;
5674
5675 memcpy(cap[h->index], v.ptr, v.len);
5676 cap[h->index][v.len]=0;
5677 }
5678 }
5679 }
5680}
5681
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005682/* Delete a value in a header between delimiters <from> and <next>. The header
5683 * itself is delimited by <start> and <end> pointers. The number of characters
5684 * displaced is returned, and the pointer to the first delimiter is updated if
5685 * required. The function tries as much as possible to respect the following
5686 * principles :
5687 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5688 * in which case <next> is simply removed
5689 * - set exactly one space character after the new first delimiter, unless there
5690 * are not enough characters in the block being moved to do so.
5691 * - remove unneeded spaces before the previous delimiter and after the new
5692 * one.
5693 *
5694 * It is the caller's responsibility to ensure that :
5695 * - <from> points to a valid delimiter or <start> ;
5696 * - <next> points to a valid delimiter or <end> ;
5697 * - there are non-space chars before <from>.
5698 */
5699static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5700{
5701 char *prev = *from;
5702
5703 if (prev == start) {
5704 /* We're removing the first value. eat the semicolon, if <next>
5705 * is lower than <end> */
5706 if (next < end)
5707 next++;
5708
5709 while (next < end && HTTP_IS_SPHT(*next))
5710 next++;
5711 }
5712 else {
5713 /* Remove useless spaces before the old delimiter. */
5714 while (HTTP_IS_SPHT(*(prev-1)))
5715 prev--;
5716 *from = prev;
5717
5718 /* copy the delimiter and if possible a space if we're
5719 * not at the end of the line.
5720 */
5721 if (next < end) {
5722 *prev++ = *next++;
5723 if (prev + 1 < next)
5724 *prev++ = ' ';
5725 while (next < end && HTTP_IS_SPHT(*next))
5726 next++;
5727 }
5728 }
5729 memmove(prev, next, end - next);
5730 return (prev - next);
5731}
5732
Christopher Faulet0f226952018-10-22 09:29:56 +02005733
5734/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005735 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005736 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005737static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005738{
5739 struct ist dst = ist2(str, 0);
5740
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005741 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005742 goto end;
5743 if (dst.len + 1 > len)
5744 goto end;
5745 dst.ptr[dst.len++] = ' ';
5746
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005747 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005748 goto end;
5749 if (dst.len + 1 > len)
5750 goto end;
5751 dst.ptr[dst.len++] = ' ';
5752
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005753 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005754 end:
5755 return dst.len;
5756}
5757
Christopher Fauletf0523542018-10-24 11:06:58 +02005758/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005759 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005760 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005761static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005762{
5763 struct ist dst = ist2(str, 0);
5764
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005765 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005766 goto end;
5767 if (dst.len + 1 > len)
5768 goto end;
5769 dst.ptr[dst.len++] = ' ';
5770
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005771 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005772 goto end;
5773 if (dst.len + 1 > len)
5774 goto end;
5775 dst.ptr[dst.len++] = ' ';
5776
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005777 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005778 end:
5779 return dst.len;
5780}
5781
5782
Christopher Faulet0f226952018-10-22 09:29:56 +02005783/*
5784 * Print a debug line with a start line.
5785 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005786static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005787{
5788 struct session *sess = strm_sess(s);
5789 int max;
5790
5791 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5792 dir,
5793 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5794 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5795
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005796 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005797 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005798 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005799 trash.area[trash.data++] = ' ';
5800
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005801 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005802 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005803 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005804 trash.area[trash.data++] = ' ';
5805
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005806 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005807 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005808 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005809 trash.area[trash.data++] = '\n';
5810
5811 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5812}
5813
5814/*
5815 * Print a debug line with a header.
5816 */
5817static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5818{
5819 struct session *sess = strm_sess(s);
5820 int max;
5821
5822 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5823 dir,
5824 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5825 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5826
5827 max = n.len;
5828 UBOUND(max, trash.size - trash.data - 3);
5829 chunk_memcat(&trash, n.ptr, max);
5830 trash.area[trash.data++] = ':';
5831 trash.area[trash.data++] = ' ';
5832
5833 max = v.len;
5834 UBOUND(max, trash.size - trash.data - 1);
5835 chunk_memcat(&trash, v.ptr, max);
5836 trash.area[trash.data++] = '\n';
5837
5838 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5839}
5840
5841
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005842__attribute__((constructor))
5843static void __htx_protocol_init(void)
5844{
5845}
5846
5847
5848/*
5849 * Local variables:
5850 * c-indent-level: 8
5851 * c-basic-offset: 8
5852 * End:
5853 */