blob: cff98bf59a1807c3efa1da735f8bfd572c09f9cf [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
Christopher Faulete01140d2021-05-05 18:23:59 +02001407 if (objt_server(s->target)) {
1408 if (s->flags & SF_CURR_SESS) {
1409 s->flags &= ~SF_CURR_SESS;
1410 _HA_ATOMIC_SUB(&__objt_server(s->target)->cur_sess, 1);
1411 }
Willy Tarreau223995e2019-05-04 10:38:31 +02001412 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
Christopher Faulete01140d2021-05-05 18:23:59 +02001413 }
Willy Tarreau223995e2019-05-04 10:38:31 +02001414 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1415
Olivier Houcharda254a372019-04-05 15:30:12 +02001416 req = &s->req;
1417 res = &s->res;
1418 /* Remove any write error from the request, and read error from the response */
1419 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1420 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1421 res->analysers = 0;
1422 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Christopher Faulet750beb72021-05-05 21:05:09 +02001423 si->err_type = SI_ET_NONE;
1424 s->flags &= ~(SF_ERR_MASK | SF_FINST_MASK);
Olivier Houchard530249c2019-07-12 16:16:59 +02001425 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001426 si->exp = TICK_ETERNITY;
1427 res->rex = TICK_ETERNITY;
1428 res->to_forward = 0;
1429 res->analyse_exp = TICK_ETERNITY;
1430 res->total = 0;
Olivier Houcharda254a372019-04-05 15:30:12 +02001431 si_release_endpoint(&s->si[1]);
1432 b_free(&req->buf);
1433 /* Swap the L7 buffer with the channel buffer */
1434 /* We know we stored the co_data as b_data, so get it there */
1435 co_data = b_data(&si->l7_buffer);
1436 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1437 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1438
1439 co_set_data(req, co_data);
1440 b_reset(&res->buf);
1441 co_set_data(res, 0);
1442 return 0;
1443}
1444
Christopher Faulete0768eb2018-10-03 16:38:02 +02001445/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1446 * processing can continue on next analysers, or zero if it either needs more
1447 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1448 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1449 * when it has nothing left to do, and may remove any analyser when it wants to
1450 * abort.
1451 */
1452int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1453{
Christopher Faulet9768c262018-10-22 09:34:31 +02001454 /*
1455 * We will analyze a complete HTTP response to check the its syntax.
1456 *
1457 * Once the start line and all headers are received, we may perform a
1458 * capture of the error (if any), and we will set a few fields. We also
1459 * logging and finally headers capture.
1460 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 struct session *sess = s->sess;
1462 struct http_txn *txn = s->txn;
1463 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001464 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001465 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001466 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001467 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001468 int n;
1469
1470 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1471 now_ms, __FUNCTION__,
1472 s,
1473 rep,
1474 rep->rex, rep->wex,
1475 rep->flags,
1476 ci_data(rep),
1477 rep->analysers);
1478
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001479 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001480
Willy Tarreau4236f032019-03-05 10:43:32 +01001481 /* Parsing errors are caught here */
1482 if (htx->flags & HTX_FL_PARSING_ERROR)
1483 goto return_bad_res;
1484
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485 /*
1486 * Now we quickly check if we have found a full valid response.
1487 * If not so, we check the FD and buffer states before leaving.
1488 * A full response is indicated by the fact that we have seen
1489 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1490 * responses are checked first.
1491 *
1492 * Depending on whether the client is still there or not, we
1493 * may send an error response back or not. Note that normally
1494 * we should only check for HTTP status there, and check I/O
1495 * errors somewhere else.
1496 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001497 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001498 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001499 /* 1: have we encountered a read error ? */
1500 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001501 struct connection *conn = NULL;
1502
Olivier Houchard865d8392019-05-03 22:46:27 +02001503 if (objt_cs(s->si[1].end))
1504 conn = objt_cs(s->si[1].end)->conn;
1505
1506 if (si_b->flags & SI_FL_L7_RETRY &&
1507 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001508 /* If we arrive here, then CF_READ_ERROR was
1509 * set by si_cs_recv() because we matched a
1510 * status, overwise it would have removed
1511 * the SI_FL_L7_RETRY flag, so it's ok not
1512 * to check s->be->retry_type.
1513 */
1514 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1515 return 0;
1516 }
1517
Christopher Faulet71d85522021-05-26 12:15:37 +02001518 /* Perform a L7 retry because server refuses the early data. */
1519 if ((si_b->flags & SI_FL_L7_RETRY) &&
1520 (s->be->retry_type & PR_RE_EARLY_ERROR) &&
1521 conn && conn->err_code == CO_ER_SSL_EARLY_FAILED &&
1522 do_l7_retry(s, si_b) == 0) {
1523 return 0;
1524 }
1525
Olivier Houchard6db16992019-05-17 15:40:49 +02001526 if (txn->flags & TX_NOT_FIRST)
1527 goto abort_keep_alive;
1528
Olivier Houcharda798bf52019-03-08 18:52:00 +01001529 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001531 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001532 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001533 }
1534
Christopher Faulet71d85522021-05-26 12:15:37 +02001535 /* if the server refused the early data, just send a 425 */
1536 if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED)
1537 txn->status = 425;
1538 else
1539 txn->status = 502;
1540
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001542 s->req.analysers &= AN_REQ_FLT_END;
1543 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001545 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001546
1547 if (!(s->flags & SF_ERR_MASK))
1548 s->flags |= SF_ERR_SRVCL;
1549 if (!(s->flags & SF_FINST_MASK))
1550 s->flags |= SF_FINST_H;
1551 return 0;
1552 }
1553
Christopher Faulet9768c262018-10-22 09:34:31 +02001554 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001556 if ((si_b->flags & SI_FL_L7_RETRY) &&
1557 (s->be->retry_type & PR_RE_TIMEOUT)) {
1558 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1559 return 0;
1560 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001561 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001563 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001564 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565 }
1566
Christopher Faulete0768eb2018-10-03 16:38:02 +02001567 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001568 s->req.analysers &= AN_REQ_FLT_END;
1569 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001570 txn->status = 504;
1571 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001572 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573
1574 if (!(s->flags & SF_ERR_MASK))
1575 s->flags |= SF_ERR_SRVTO;
1576 if (!(s->flags & SF_FINST_MASK))
1577 s->flags |= SF_FINST_H;
1578 return 0;
1579 }
1580
Christopher Faulet9768c262018-10-22 09:34:31 +02001581 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001582 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001583 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1584 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001586 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587
1588 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001589 s->req.analysers &= AN_REQ_FLT_END;
1590 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001591 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001592 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593
1594 if (!(s->flags & SF_ERR_MASK))
1595 s->flags |= SF_ERR_CLICL;
1596 if (!(s->flags & SF_FINST_MASK))
1597 s->flags |= SF_FINST_H;
1598
1599 /* process_stream() will take care of the error */
1600 return 0;
1601 }
1602
Christopher Faulet9768c262018-10-22 09:34:31 +02001603 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001605 if ((si_b->flags & SI_FL_L7_RETRY) &&
1606 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1607 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1608 return 0;
1609 }
1610
Olivier Houchard6db16992019-05-17 15:40:49 +02001611 if (txn->flags & TX_NOT_FIRST)
1612 goto abort_keep_alive;
1613
Olivier Houcharda798bf52019-03-08 18:52:00 +01001614 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001616 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001617 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618 }
1619
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001621 s->req.analysers &= AN_REQ_FLT_END;
1622 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 txn->status = 502;
1624 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001625 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626
1627 if (!(s->flags & SF_ERR_MASK))
1628 s->flags |= SF_ERR_SRVCL;
1629 if (!(s->flags & SF_FINST_MASK))
1630 s->flags |= SF_FINST_H;
1631 return 0;
1632 }
1633
Christopher Faulet9768c262018-10-22 09:34:31 +02001634 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001636 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001637 goto abort_keep_alive;
1638
Olivier Houcharda798bf52019-03-08 18:52:00 +01001639 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001640 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001641 s->req.analysers &= AN_REQ_FLT_END;
1642 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001643
1644 if (!(s->flags & SF_ERR_MASK))
1645 s->flags |= SF_ERR_CLICL;
1646 if (!(s->flags & SF_FINST_MASK))
1647 s->flags |= SF_FINST_H;
1648
1649 /* process_stream() will take care of the error */
1650 return 0;
1651 }
1652
1653 channel_dont_close(rep);
1654 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1655 return 0;
1656 }
1657
1658 /* More interesting part now : we know that we have a complete
1659 * response which at least looks like HTTP. We have an indicator
1660 * of each header's length, so we can parse them quickly.
1661 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001662 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001663 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001664 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001665
Christopher Faulet9768c262018-10-22 09:34:31 +02001666 /* 0: we might have to print this header in debug mode */
1667 if (unlikely((global.mode & MODE_DEBUG) &&
1668 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1669 int32_t pos;
1670
Christopher Faulet03599112018-11-27 11:21:21 +01001671 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001672
Christopher Fauleta3f15502019-05-13 15:27:23 +02001673 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001674 struct htx_blk *blk = htx_get_blk(htx, pos);
1675 enum htx_blk_type type = htx_get_blk_type(blk);
1676
1677 if (type == HTX_BLK_EOH)
1678 break;
1679 if (type != HTX_BLK_HDR)
1680 continue;
1681
1682 htx_debug_hdr("srvhdr", s,
1683 htx_get_blk_name(htx, blk),
1684 htx_get_blk_value(htx, blk));
1685 }
1686 }
1687
Christopher Faulet03599112018-11-27 11:21:21 +01001688 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001689 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001690 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001691 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001692 if (sl->flags & HTX_SL_F_XFER_LEN) {
1693 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001694 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001695 if (sl->flags & HTX_SL_F_BODYLESS)
1696 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001697 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001698
1699 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001700 if (n < 1 || n > 5)
1701 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001702
Christopher Faulete0768eb2018-10-03 16:38:02 +02001703 /* when the client triggers a 4xx from the server, it's most often due
1704 * to a missing object or permission. These events should be tracked
1705 * because if they happen often, it may indicate a brute force or a
1706 * vulnerability scan.
1707 */
1708 if (n == 4)
1709 stream_inc_http_err_ctr(s);
1710
1711 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001712 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713
Christopher Faulete0768eb2018-10-03 16:38:02 +02001714 /* Adjust server's health based on status code. Note: status codes 501
1715 * and 505 are triggered on demand by client request, so we must not
1716 * count them as server failures.
1717 */
1718 if (objt_server(s->target)) {
1719 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001720 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001721 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001722 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001723 }
1724
1725 /*
1726 * We may be facing a 100-continue response, or any other informational
1727 * 1xx response which is non-final, in which case this is not the right
1728 * response, and we're waiting for the next one. Let's allow this response
1729 * to go to the client and wait for the next one. There's an exception for
1730 * 101 which is used later in the code to switch protocols.
1731 */
1732 if (txn->status < 200 &&
1733 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001734 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001735 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001736 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001737 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001738 txn->status = 0;
1739 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet5761e7d2020-08-31 11:07:07 +02001740 rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001741 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001742 }
1743
1744 /*
1745 * 2: check for cacheability.
1746 */
1747
1748 switch (txn->status) {
1749 case 200:
1750 case 203:
1751 case 204:
1752 case 206:
1753 case 300:
1754 case 301:
1755 case 404:
1756 case 405:
1757 case 410:
1758 case 414:
1759 case 501:
1760 break;
1761 default:
1762 /* RFC7231#6.1:
1763 * Responses with status codes that are defined as
1764 * cacheable by default (e.g., 200, 203, 204, 206,
1765 * 300, 301, 404, 405, 410, 414, and 501 in this
1766 * specification) can be reused by a cache with
1767 * heuristic expiration unless otherwise indicated
1768 * by the method definition or explicit cache
1769 * controls [RFC7234]; all other status codes are
1770 * not cacheable by default.
1771 */
1772 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1773 break;
1774 }
1775
1776 /*
1777 * 3: we may need to capture headers
1778 */
1779 s->logs.logwait &= ~LW_RESP;
1780 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001781 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001782
Christopher Faulet9768c262018-10-22 09:34:31 +02001783 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1785 txn->status == 101)) {
1786 /* Either we've established an explicit tunnel, or we're
1787 * switching the protocol. In both cases, we're very unlikely
1788 * to understand the next protocols. We have to switch to tunnel
1789 * mode, so that we transfer the request and responses then let
1790 * this protocol pass unmodified. When we later implement specific
1791 * parsers for such protocols, we'll want to check the Upgrade
1792 * header which contains information about that protocol for
1793 * responses with status 101 (eg: see RFC2817 about TLS).
1794 */
1795 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001796 }
1797
Christopher Faulet61608322018-11-23 16:23:45 +01001798 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1799 * 407 (Proxy-Authenticate) responses and set the connection to private
1800 */
1801 srv_conn = cs_conn(objt_cs(s->si[1].end));
1802 if (srv_conn) {
1803 struct ist hdr;
1804 struct http_hdr_ctx ctx;
1805
1806 if (txn->status == 401)
1807 hdr = ist("WWW-Authenticate");
1808 else if (txn->status == 407)
1809 hdr = ist("Proxy-Authenticate");
1810 else
1811 goto end;
1812
1813 ctx.blk = NULL;
1814 while (http_find_header(htx, hdr, &ctx, 0)) {
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001815 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1816 * possibly followed by blanks and a base64 string, the connection
1817 * is private. Since it's a mess to deal with, we only check for
1818 * values starting with "NTLM" or "Nego". Note that often multiple
1819 * headers are sent by the server there.
1820 */
1821 if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
Willy Tarreaud3be89b2020-05-07 19:10:15 +02001822 (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001823 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001824 srv_conn->flags |= CO_FL_PRIVATE;
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001825 break;
Olivier Houchard250031e2019-05-29 15:01:50 +02001826 }
Christopher Faulet61608322018-11-23 16:23:45 +01001827 }
1828 }
1829
1830 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001831 /* we want to have the response time before we start processing it */
1832 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1833
1834 /* end of job, return OK */
1835 rep->analysers &= ~an_bit;
1836 rep->analyse_exp = TICK_ETERNITY;
1837 channel_auto_close(rep);
1838 return 1;
1839
Christopher Faulet47365272018-10-31 17:40:50 +01001840 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001841 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001842 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001843 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001844 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001845 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001846 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001847 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001848 do_l7_retry(s, si_b) == 0)
1849 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001850 txn->status = 502;
1851 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001852 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001853 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001854 s->req.analysers &= AN_REQ_FLT_END;
1855 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001856
1857 if (!(s->flags & SF_ERR_MASK))
1858 s->flags |= SF_ERR_PRXCOND;
1859 if (!(s->flags & SF_FINST_MASK))
1860 s->flags |= SF_FINST_H;
1861 return 0;
1862
Christopher Faulete0768eb2018-10-03 16:38:02 +02001863 abort_keep_alive:
1864 /* A keep-alive request to the server failed on a network error.
1865 * The client is required to retry. We need to close without returning
1866 * any other information so that the client retries.
1867 */
1868 txn->status = 0;
1869 rep->analysers &= AN_RES_FLT_END;
1870 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 s->logs.logwait = 0;
1872 s->logs.level = 0;
1873 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001874 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001875 return 0;
1876}
1877
1878/* This function performs all the processing enabled for the current response.
1879 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1880 * and updates s->res.analysers. It might make sense to explode it into several
1881 * other functions. It works like process_request (see indications above).
1882 */
1883int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1884{
1885 struct session *sess = s->sess;
1886 struct http_txn *txn = s->txn;
1887 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001888 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001889 struct proxy *cur_proxy;
1890 struct cond_wordlist *wl;
1891 enum rule_result ret = HTTP_RULE_RES_CONT;
1892
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001893 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1894 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001895
Christopher Faulete0768eb2018-10-03 16:38:02 +02001896 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1897 now_ms, __FUNCTION__,
1898 s,
1899 rep,
1900 rep->rex, rep->wex,
1901 rep->flags,
1902 ci_data(rep),
1903 rep->analysers);
1904
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001905 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001906
1907 /* The stats applet needs to adjust the Connection header but we don't
1908 * apply any filter there.
1909 */
1910 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1911 rep->analysers &= ~an_bit;
1912 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001913 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001914 }
1915
1916 /*
1917 * We will have to evaluate the filters.
1918 * As opposed to version 1.2, now they will be evaluated in the
1919 * filters order and not in the header order. This means that
1920 * each filter has to be validated among all headers.
1921 *
1922 * Filters are tried with ->be first, then with ->fe if it is
1923 * different from ->be.
1924 *
1925 * Maybe we are in resume condiion. In this case I choose the
1926 * "struct proxy" which contains the rule list matching the resume
1927 * pointer. If none of theses "struct proxy" match, I initialise
1928 * the process with the first one.
1929 *
1930 * In fact, I check only correspondance betwwen the current list
1931 * pointer and the ->fe rule list. If it doesn't match, I initialize
1932 * the loop with the ->be.
1933 */
1934 if (s->current_rule_list == &sess->fe->http_res_rules)
1935 cur_proxy = sess->fe;
1936 else
1937 cur_proxy = s->be;
1938 while (1) {
1939 struct proxy *rule_set = cur_proxy;
1940
1941 /* evaluate http-response rules */
1942 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944
1945 if (ret == HTTP_RULE_RES_BADREQ)
1946 goto return_srv_prx_502;
1947
1948 if (ret == HTTP_RULE_RES_DONE) {
1949 rep->analysers &= ~an_bit;
1950 rep->analyse_exp = TICK_ETERNITY;
1951 return 1;
1952 }
1953 }
1954
1955 /* we need to be called again. */
1956 if (ret == HTTP_RULE_RES_YIELD) {
1957 channel_dont_close(rep);
1958 return 0;
1959 }
1960
1961 /* try headers filters */
1962 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001963 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1964 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001965 }
1966
1967 /* has the response been denied ? */
1968 if (txn->flags & TX_SVDENY) {
1969 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001970 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001971
Olivier Houcharda798bf52019-03-08 18:52:00 +01001972 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1973 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01001974 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001975 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001976 goto return_srv_prx_502;
1977 }
1978
1979 /* add response headers from the rule sets in the same order */
1980 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001981 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001982 if (txn->status < 200 && txn->status != 101)
1983 break;
1984 if (wl->cond) {
1985 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1986 ret = acl_pass(ret);
1987 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1988 ret = !ret;
1989 if (!ret)
1990 continue;
1991 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001992
1993 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1994 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001995 goto return_bad_resp;
1996 }
1997
1998 /* check whether we're already working on the frontend */
1999 if (cur_proxy == sess->fe)
2000 break;
2001 cur_proxy = sess->fe;
2002 }
2003
2004 /* After this point, this anayzer can't return yield, so we can
2005 * remove the bit corresponding to this analyzer from the list.
2006 *
2007 * Note that the intermediate returns and goto found previously
2008 * reset the analyzers.
2009 */
2010 rep->analysers &= ~an_bit;
2011 rep->analyse_exp = TICK_ETERNITY;
2012
2013 /* OK that's all we can do for 1xx responses */
2014 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002015 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002016
2017 /*
2018 * Now check for a server cookie.
2019 */
2020 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002021 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022
2023 /*
2024 * Check for cache-control or pragma headers if required.
2025 */
2026 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2027 check_response_for_cacheability(s, rep);
2028
2029 /*
2030 * Add server cookie in the response if needed
2031 */
2032 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2033 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2034 (!(s->flags & SF_DIRECT) ||
2035 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2036 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2037 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2038 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2039 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2040 !(s->flags & SF_IGNORE_PRST)) {
2041 /* the server is known, it's not the one the client requested, or the
2042 * cookie's last seen date needs to be refreshed. We have to
2043 * insert a set-cookie here, except if we want to insert only on POST
2044 * requests and this one isn't. Note that servers which don't have cookies
2045 * (eg: some backup servers) will return a full cookie removal request.
2046 */
2047 if (!objt_server(s->target)->cookie) {
2048 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002050 s->be->cookie_name);
2051 }
2052 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002053 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002054
2055 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2056 /* emit last_date, which is mandatory */
2057 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2058 s30tob64((date.tv_sec+3) >> 2,
2059 trash.area + trash.data);
2060 trash.data += 5;
2061
2062 if (s->be->cookie_maxlife) {
2063 /* emit first_date, which is either the original one or
2064 * the current date.
2065 */
2066 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2067 s30tob64(txn->cookie_first_date ?
2068 txn->cookie_first_date >> 2 :
2069 (date.tv_sec+3) >> 2,
2070 trash.area + trash.data);
2071 trash.data += 5;
2072 }
2073 }
2074 chunk_appendf(&trash, "; path=/");
2075 }
2076
2077 if (s->be->cookie_domain)
2078 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2079
2080 if (s->be->ck_opts & PR_CK_HTTPONLY)
2081 chunk_appendf(&trash, "; HttpOnly");
2082
2083 if (s->be->ck_opts & PR_CK_SECURE)
2084 chunk_appendf(&trash, "; Secure");
2085
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002086 if (s->be->cookie_attrs)
2087 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2088
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002089 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090 goto return_bad_resp;
2091
2092 txn->flags &= ~TX_SCK_MASK;
2093 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2094 /* the server did not change, only the date was updated */
2095 txn->flags |= TX_SCK_UPDATED;
2096 else
2097 txn->flags |= TX_SCK_INSERTED;
2098
2099 /* Here, we will tell an eventual cache on the client side that we don't
2100 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2101 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2102 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2103 */
2104 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2105
2106 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2107
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002108 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002109 goto return_bad_resp;
2110 }
2111 }
2112
2113 /*
2114 * Check if result will be cacheable with a cookie.
2115 * We'll block the response if security checks have caught
2116 * nasty things such as a cacheable cookie.
2117 */
2118 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2119 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2120 (s->be->options & PR_O_CHK_CACHE)) {
2121 /* we're in presence of a cacheable response containing
2122 * a set-cookie header. We'll block it as requested by
2123 * the 'checkcache' option, and send an alert.
2124 */
2125 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002126 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002127
Olivier Houcharda798bf52019-03-08 18:52:00 +01002128 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2129 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01002130 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002131 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002132
2133 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2134 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2135 send_log(s->be, LOG_ALERT,
2136 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2137 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2138 goto return_srv_prx_502;
2139 }
2140
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002141 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002142 /* Always enter in the body analyzer */
2143 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2144 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2145
2146 /* if the user wants to log as soon as possible, without counting
2147 * bytes from the server, then this is the right moment. We have
2148 * to temporarily assign bytes_out to log what we currently have.
2149 */
2150 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2151 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002152 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002153 s->do_log(s);
2154 s->logs.bytes_out = 0;
2155 }
2156 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002157
2158 return_bad_resp:
2159 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002160 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002161 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002162 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002163 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002164
2165 return_srv_prx_502:
2166 rep->analysers &= AN_RES_FLT_END;
2167 txn->status = 502;
2168 s->logs.t_data = -1; /* was not a valid response */
2169 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002170 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002171 if (!(s->flags & SF_ERR_MASK))
2172 s->flags |= SF_ERR_PRXCOND;
2173 if (!(s->flags & SF_FINST_MASK))
2174 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002175
2176 s->req.analysers &= AN_REQ_FLT_END;
2177 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002178 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002179}
2180
2181/* This function is an analyser which forwards response body (including chunk
2182 * sizes if any). It is called as soon as we must forward, even if we forward
2183 * zero byte. The only situation where it must not be called is when we're in
2184 * tunnel mode and we want to forward till the close. It's used both to forward
2185 * remaining data and to resync after end of body. It expects the msg_state to
2186 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2187 * read more data, or 1 once we can go on with next request or end the stream.
2188 *
2189 * It is capable of compressing response data both in content-length mode and
2190 * in chunked mode. The state machines follows different flows depending on
2191 * whether content-length and chunked modes are used, since there are no
2192 * trailers in content-length :
2193 *
2194 * chk-mode cl-mode
2195 * ,----- BODY -----.
2196 * / \
2197 * V size > 0 V chk-mode
2198 * .--> SIZE -------------> DATA -------------> CRLF
2199 * | | size == 0 | last byte |
2200 * | v final crlf v inspected |
2201 * | TRAILERS -----------> DONE |
2202 * | |
2203 * `----------------------------------------------'
2204 *
2205 * Compression only happens in the DATA state, and must be flushed in final
2206 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2207 * is performed at once on final states for all bytes parsed, or when leaving
2208 * on missing data.
2209 */
2210int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2211{
2212 struct session *sess = s->sess;
2213 struct http_txn *txn = s->txn;
2214 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002215 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002216 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217
2218 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2219 now_ms, __FUNCTION__,
2220 s,
2221 res,
2222 res->rex, res->wex,
2223 res->flags,
2224 ci_data(res),
2225 res->analysers);
2226
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002227 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228
2229 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002230 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002231 /* Output closed while we were sending data. We must abort and
2232 * wake the other side up.
2233 */
2234 msg->err_state = msg->msg_state;
2235 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002236 htx_end_response(s);
2237 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002238 return 1;
2239 }
2240
Christopher Faulet9768c262018-10-22 09:34:31 +02002241 if (msg->msg_state == HTTP_MSG_BODY)
2242 msg->msg_state = HTTP_MSG_DATA;
2243
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 /* in most states, we should abort in case of early close */
2245 channel_auto_close(res);
2246
Christopher Faulete0768eb2018-10-03 16:38:02 +02002247 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002248 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002249 if (res->flags & CF_EOI)
2250 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002251 }
2252 else {
2253 /* We can't process the buffer's contents yet */
2254 res->flags |= CF_WAKE_WRITE;
2255 goto missing_data_or_waiting;
2256 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002257 }
2258
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002259 if (msg->msg_state >= HTTP_MSG_ENDING)
2260 goto ending;
2261
2262 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2263 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2264 msg->msg_state = HTTP_MSG_ENDING;
2265 goto ending;
2266 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002267
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002268 /* Forward input data. We get it by removing all outgoing data not
2269 * forwarded yet from HTX data size. If there are some data filters, we
2270 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002271 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002272 if (HAS_RSP_DATA_FILTERS(s)) {
2273 ret = flt_http_payload(s, msg, htx->data);
2274 if (ret < 0)
2275 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002276 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002277 }
2278 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002279 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002280 if (msg->flags & HTTP_MSGF_XFER_LEN)
2281 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002282 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002283
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002284 if (htx->data != co_data(res))
2285 goto missing_data_or_waiting;
2286
2287 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2288 msg->msg_state = HTTP_MSG_ENDING;
2289 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 }
2291
Christopher Faulet9768c262018-10-22 09:34:31 +02002292 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002293 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2294 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002295 */
2296 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2297 goto missing_data_or_waiting;
2298
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002299 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002300
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002301 ending:
2302 /* other states, ENDING...TUNNEL */
2303 if (msg->msg_state >= HTTP_MSG_DONE)
2304 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002305
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002306 if (HAS_RSP_DATA_FILTERS(s)) {
2307 ret = flt_http_end(s, msg);
2308 if (ret <= 0) {
2309 if (!ret)
2310 goto missing_data_or_waiting;
2311 goto return_bad_res;
2312 }
2313 }
2314
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002315 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2316 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2317 msg->msg_state = HTTP_MSG_TUNNEL;
2318 goto ending;
2319 }
2320 else {
2321 msg->msg_state = HTTP_MSG_DONE;
2322 res->to_forward = 0;
2323 }
2324
2325 done:
2326
2327 channel_dont_close(res);
2328
Christopher Fauletf2824e62018-10-01 12:12:37 +02002329 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002331 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2333 if (res->flags & CF_SHUTW) {
2334 /* response errors are most likely due to the
2335 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002336 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338 goto return_bad_res;
2339 }
2340 return 1;
2341 }
2342 return 0;
2343
2344 missing_data_or_waiting:
2345 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002346 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347
Christopher Faulet47365272018-10-31 17:40:50 +01002348 if (htx->flags & HTX_FL_PARSING_ERROR)
2349 goto return_bad_res;
2350
Christopher Faulete0768eb2018-10-03 16:38:02 +02002351 /* stop waiting for data if the input is closed before the end. If the
2352 * client side was already closed, it means that the client has aborted,
2353 * so we don't want to count this as a server abort. Otherwise it's a
2354 * server abort.
2355 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002356 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002357 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002358 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002359 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002360 if (htx_is_empty(htx))
2361 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002362 }
2363
Christopher Faulete0768eb2018-10-03 16:38:02 +02002364 /* When TE: chunked is used, we need to get there again to parse
2365 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002366 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2367 * are filters registered on the stream, we don't want to forward a
2368 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002369 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002370 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002371 channel_dont_close(res);
2372
2373 /* We know that more data are expected, but we couldn't send more that
2374 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2375 * system knows it must not set a PUSH on this first part. Interactive
2376 * modes are already handled by the stream sock layer. We must not do
2377 * this in content-length mode because it could present the MSG_MORE
2378 * flag with the last block of forwarded data, which would cause an
2379 * additional delay to be observed by the receiver.
2380 */
2381 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2382 res->flags |= CF_EXPECT_MORE;
2383
2384 /* the stream handler will take care of timeouts and errors */
2385 return 0;
2386
Christopher Faulet93e02d82019-03-08 14:18:50 +01002387 return_srv_abort:
2388 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2389 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002390 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002391 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2392 if (!(s->flags & SF_ERR_MASK))
2393 s->flags |= SF_ERR_SRVCL;
2394 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002395
Christopher Faulet93e02d82019-03-08 14:18:50 +01002396 return_cli_abort:
2397 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2398 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002399 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002400 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2401 if (!(s->flags & SF_ERR_MASK))
2402 s->flags |= SF_ERR_CLICL;
2403 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002404
Christopher Faulet93e02d82019-03-08 14:18:50 +01002405 return_bad_res:
2406 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2407 if (objt_server(s->target)) {
2408 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2409 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2410 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002411 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002412 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002413
Christopher Faulet93e02d82019-03-08 14:18:50 +01002414 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002415 txn->rsp.err_state = txn->rsp.msg_state;
2416 txn->rsp.msg_state = HTTP_MSG_ERROR;
2417 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002418 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002419 res->analysers &= AN_RES_FLT_END;
2420 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 +02002421 if (!(s->flags & SF_FINST_MASK))
2422 s->flags |= SF_FINST_D;
2423 return 0;
2424}
2425
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428 * as too large a request to build a valid response.
2429 */
2430int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2431{
Christopher Faulet99daf282018-11-28 22:58:13 +01002432 struct channel *req = &s->req;
2433 struct channel *res = &s->res;
2434 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002435 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002436 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 struct ist status, reason, location;
2438 unsigned int flags;
2439 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002440 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441
2442 chunk = alloc_trash_chunk();
2443 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002444 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002445
Christopher Faulet99daf282018-11-28 22:58:13 +01002446 /*
2447 * Create the location
2448 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002449 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002451 case REDIRECT_TYPE_SCHEME: {
2452 struct http_hdr_ctx ctx;
2453 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002454
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 host = ist("");
2456 ctx.blk = NULL;
2457 if (http_find_header(htx, ist("Host"), &ctx, 0))
2458 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459
Christopher Faulet297fbb42019-05-13 14:41:27 +02002460 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002461 path = http_get_path(htx_sl_req_uri(sl));
2462 /* build message using path */
2463 if (path.ptr) {
2464 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2465 int qs = 0;
2466 while (qs < path.len) {
2467 if (*(path.ptr + qs) == '?') {
2468 path.len = qs;
2469 break;
2470 }
2471 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473 }
2474 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002475 else
2476 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002477
Christopher Faulet99daf282018-11-28 22:58:13 +01002478 if (rule->rdr_str) { /* this is an old "redirect" rule */
2479 /* add scheme */
2480 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2481 goto fail;
2482 }
2483 else {
2484 /* add scheme with executing log format */
2485 chunk->data += build_logline(s, chunk->area + chunk->data,
2486 chunk->size - chunk->data,
2487 &rule->rdr_fmt);
2488 }
2489 /* add "://" + host + path */
2490 if (!chunk_memcat(chunk, "://", 3) ||
2491 !chunk_memcat(chunk, host.ptr, host.len) ||
2492 !chunk_memcat(chunk, path.ptr, path.len))
2493 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002494
Christopher Faulet99daf282018-11-28 22:58:13 +01002495 /* append a slash at the end of the location if needed and missing */
2496 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2497 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2498 if (chunk->data + 1 >= chunk->size)
2499 goto fail;
2500 chunk->area[chunk->data++] = '/';
2501 }
2502 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002503 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002504
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 case REDIRECT_TYPE_PREFIX: {
2506 struct ist path;
2507
Christopher Faulet297fbb42019-05-13 14:41:27 +02002508 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 path = http_get_path(htx_sl_req_uri(sl));
2510 /* build message using path */
2511 if (path.ptr) {
2512 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2513 int qs = 0;
2514 while (qs < path.len) {
2515 if (*(path.ptr + qs) == '?') {
2516 path.len = qs;
2517 break;
2518 }
2519 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002520 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002521 }
2522 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002523 else
2524 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002525
Christopher Faulet99daf282018-11-28 22:58:13 +01002526 if (rule->rdr_str) { /* this is an old "redirect" rule */
2527 /* add prefix. Note that if prefix == "/", we don't want to
2528 * add anything, otherwise it makes it hard for the user to
2529 * configure a self-redirection.
2530 */
2531 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2532 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2533 goto fail;
2534 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002535 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002536 else {
2537 /* add prefix with executing log format */
2538 chunk->data += build_logline(s, chunk->area + chunk->data,
2539 chunk->size - chunk->data,
2540 &rule->rdr_fmt);
2541 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002542
Christopher Faulet99daf282018-11-28 22:58:13 +01002543 /* add path */
2544 if (!chunk_memcat(chunk, path.ptr, path.len))
2545 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002546
Christopher Faulet99daf282018-11-28 22:58:13 +01002547 /* append a slash at the end of the location if needed and missing */
2548 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2549 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2550 if (chunk->data + 1 >= chunk->size)
2551 goto fail;
2552 chunk->area[chunk->data++] = '/';
2553 }
2554 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002555 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002556 case REDIRECT_TYPE_LOCATION:
2557 default:
2558 if (rule->rdr_str) { /* this is an old "redirect" rule */
2559 /* add location */
2560 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2561 goto fail;
2562 }
2563 else {
2564 /* add location with executing log format */
2565 chunk->data += build_logline(s, chunk->area + chunk->data,
2566 chunk->size - chunk->data,
2567 &rule->rdr_fmt);
2568 }
2569 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002570 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002571 location = ist2(chunk->area, chunk->data);
2572
2573 /*
2574 * Create the 30x response
2575 */
2576 switch (rule->code) {
2577 case 308:
2578 status = ist("308");
2579 reason = ist("Permanent Redirect");
2580 break;
2581 case 307:
2582 status = ist("307");
2583 reason = ist("Temporary Redirect");
2584 break;
2585 case 303:
2586 status = ist("303");
2587 reason = ist("See Other");
2588 break;
2589 case 301:
2590 status = ist("301");
2591 reason = ist("Moved Permanently");
2592 break;
2593 case 302:
2594 default:
2595 status = ist("302");
2596 reason = ist("Found");
2597 break;
2598 }
2599
Christopher Faulet08e66462019-05-23 16:44:59 +02002600 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2601 close = 1;
2602
Christopher Faulet99daf282018-11-28 22:58:13 +01002603 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002604 /* Trim any possible response */
2605 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002606 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2607 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2608 if (!sl)
2609 goto fail;
2610 sl->info.res.status = rule->code;
2611 s->txn->status = rule->code;
2612
Christopher Faulet08e66462019-05-23 16:44:59 +02002613 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2614 goto fail;
2615
2616 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002617 !htx_add_header(htx, ist("Location"), location))
2618 goto fail;
2619
2620 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2621 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2622 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002623 }
2624
2625 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002626 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2627 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002628 }
2629
Christopher Faulet99daf282018-11-28 22:58:13 +01002630 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2631 goto fail;
2632
Kevin Zhu0fd70882020-01-07 09:42:55 +01002633 htx_to_buf(htx, &res->buf);
2634
Christopher Faulet99daf282018-11-28 22:58:13 +01002635 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002636 c_adv(res, data);
2637 res->total += data;
2638
2639 channel_auto_read(req);
2640 channel_abort(req);
2641 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002642 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002643
2644 res->wex = tick_add_ifset(now_ms, res->wto);
2645 channel_auto_read(res);
2646 channel_auto_close(res);
2647 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002648 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2649 /* let's log the request time */
2650 s->logs.tv_request = now;
2651 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002652
Christopher Faulet7d84db32020-01-28 09:18:10 +01002653 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2654 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2655 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002656
2657 if (!(s->flags & SF_ERR_MASK))
2658 s->flags |= SF_ERR_LOCAL;
2659 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002660 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002661
Christopher Faulet99daf282018-11-28 22:58:13 +01002662 free_trash_chunk(chunk);
2663 return 1;
2664
2665 fail:
2666 /* If an error occurred, remove the incomplete HTTP response from the
2667 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002668 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002669 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002670 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002671}
2672
Christopher Faulet72333522018-10-24 11:25:02 +02002673int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2674 struct ist name, const char *str, struct my_regex *re, int action)
2675{
2676 struct http_hdr_ctx ctx;
2677 struct buffer *output = get_trash_chunk();
2678
2679 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2680 ctx.blk = NULL;
2681 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2682 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2683 continue;
2684
2685 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2686 if (output->data == -1)
2687 return -1;
2688 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2689 return -1;
2690 }
2691 return 0;
2692}
2693
2694static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2695 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2696{
2697 struct buffer *replace;
2698 int ret = -1;
2699
2700 replace = alloc_trash_chunk();
2701 if (!replace)
2702 goto leave;
2703
2704 replace->data = build_logline(s, replace->area, replace->size, fmt);
2705 if (replace->data >= replace->size - 1)
2706 goto leave;
2707
2708 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2709
2710 leave:
2711 free_trash_chunk(replace);
2712 return ret;
2713}
2714
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002715
2716/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2717 * on success and -1 on error. The response channel is updated accordingly.
2718 */
2719static int htx_reply_103_early_hints(struct channel *res)
2720{
2721 struct htx *htx = htx_from_buf(&res->buf);
2722 size_t data;
2723
Christopher Faulet9869f932019-06-26 14:23:54 +02002724 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002725 /* If an error occurred during an Early-hint rule,
2726 * remove the incomplete HTTP 103 response from the
2727 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002728 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002729 return -1;
2730 }
2731
2732 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002733 c_adv(res, data);
2734 res->total += data;
2735 return 0;
2736}
2737
Christopher Faulet6eb92892018-11-15 16:39:29 +01002738/*
2739 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2740 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002741 * If <early_hints> is 0, it is starts a new response by adding the start
2742 * line. If an error occurred -1 is returned. On success 0 is returned. The
2743 * channel is not updated here. It must be done calling the function
2744 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002745 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002746static 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 +01002747{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002748 struct channel *res = &s->res;
2749 struct htx *htx = htx_from_buf(&res->buf);
2750 struct buffer *value = alloc_trash_chunk();
2751
Christopher Faulet6eb92892018-11-15 16:39:29 +01002752 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002753 struct htx_sl *sl;
2754 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2755 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2756
2757 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2758 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2759 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002760 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002761 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002762 }
2763
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002764 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2765 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002766 goto fail;
2767
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002768 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002769 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002770
2771 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002772 /* If an error occurred during an Early-hint rule, remove the incomplete
2773 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002774 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002775 free_trash_chunk(value);
2776 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002777}
2778
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002779/* This function executes one of the set-{method,path,query,uri} actions. It
2780 * takes the string from the variable 'replace' with length 'len', then modifies
2781 * the relevant part of the request line accordingly. Then it updates various
2782 * pointers to the next elements which were moved, and the total buffer length.
2783 * It finds the action to be performed in p[2], previously filled by function
2784 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2785 * error, though this can be revisited when this code is finally exploited.
2786 *
2787 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2788 * query string and 3 to replace uri.
2789 *
2790 * In query string case, the mark question '?' must be set at the start of the
2791 * string by the caller, event if the replacement query string is empty.
2792 */
2793int htx_req_replace_stline(int action, const char *replace, int len,
2794 struct proxy *px, struct stream *s)
2795{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002796 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002797
2798 switch (action) {
2799 case 0: // method
2800 if (!http_replace_req_meth(htx, ist2(replace, len)))
2801 return -1;
2802 break;
2803
2804 case 1: // path
2805 if (!http_replace_req_path(htx, ist2(replace, len)))
2806 return -1;
2807 break;
2808
2809 case 2: // query
2810 if (!http_replace_req_query(htx, ist2(replace, len)))
2811 return -1;
2812 break;
2813
2814 case 3: // uri
2815 if (!http_replace_req_uri(htx, ist2(replace, len)))
2816 return -1;
2817 break;
2818
2819 default:
2820 return -1;
2821 }
2822 return 0;
2823}
2824
2825/* This function replace the HTTP status code and the associated message. The
2826 * variable <status> contains the new status code. This function never fails.
2827 */
2828void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2829{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002830 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002831 char *res;
2832
2833 chunk_reset(&trash);
2834 res = ultoa_o(status, trash.area, trash.size);
2835 trash.data = res - trash.area;
2836
2837 /* Do we have a custom reason format string? */
2838 if (reason == NULL)
2839 reason = http_get_reason(status);
2840
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002841 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002842 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2843}
2844
Christopher Faulet3e964192018-10-24 11:39:23 +02002845/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2846 * transaction <txn>. Returns the verdict of the first rule that prevents
2847 * further processing of the request (auth, deny, ...), and defaults to
2848 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2849 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2850 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2851 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2852 * status.
2853 */
2854static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2855 struct stream *s, int *deny_status)
2856{
2857 struct session *sess = strm_sess(s);
2858 struct http_txn *txn = s->txn;
2859 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002860 struct act_rule *rule;
2861 struct http_hdr_ctx ctx;
2862 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002863 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2864 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002865 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002866
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002867 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002868
2869 /* If "the current_rule_list" match the executed rule list, we are in
2870 * resume condition. If a resume is needed it is always in the action
2871 * and never in the ACL or converters. In this case, we initialise the
2872 * current rule, and go to the action execution point.
2873 */
2874 if (s->current_rule) {
2875 rule = s->current_rule;
2876 s->current_rule = NULL;
2877 if (s->current_rule_list == rules)
2878 goto resume_execution;
2879 }
2880 s->current_rule_list = rules;
2881
2882 list_for_each_entry(rule, rules, list) {
2883 /* check optional condition */
2884 if (rule->cond) {
2885 int ret;
2886
2887 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2888 ret = acl_pass(ret);
2889
2890 if (rule->cond->pol == ACL_COND_UNLESS)
2891 ret = !ret;
2892
2893 if (!ret) /* condition not matched */
2894 continue;
2895 }
2896
2897 act_flags |= ACT_FLAG_FIRST;
2898 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002899 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2900 early_hints = 0;
2901 if (htx_reply_103_early_hints(&s->res) == -1) {
2902 rule_ret = HTTP_RULE_RES_BADREQ;
2903 goto end;
2904 }
2905 }
2906
Christopher Faulet3e964192018-10-24 11:39:23 +02002907 switch (rule->action) {
2908 case ACT_ACTION_ALLOW:
2909 rule_ret = HTTP_RULE_RES_STOP;
2910 goto end;
2911
2912 case ACT_ACTION_DENY:
2913 if (deny_status)
2914 *deny_status = rule->deny_status;
2915 rule_ret = HTTP_RULE_RES_DENY;
2916 goto end;
2917
2918 case ACT_HTTP_REQ_TARPIT:
2919 txn->flags |= TX_CLTARPIT;
2920 if (deny_status)
2921 *deny_status = rule->deny_status;
2922 rule_ret = HTTP_RULE_RES_DENY;
2923 goto end;
2924
2925 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002926 /* Auth might be performed on regular http-req rules as well as on stats */
2927 auth_realm = rule->arg.auth.realm;
2928 if (!auth_realm) {
2929 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2930 auth_realm = STATS_DEFAULT_REALM;
2931 else
2932 auth_realm = px->id;
2933 }
2934 /* send 401/407 depending on whether we use a proxy or not. We still
2935 * count one error, because normal browsing won't significantly
2936 * increase the counter but brute force attempts will.
2937 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002938 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002939 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2940 rule_ret = HTTP_RULE_RES_BADREQ;
2941 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 goto end;
2943
2944 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002945 rule_ret = HTTP_RULE_RES_DONE;
2946 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2947 rule_ret = HTTP_RULE_RES_BADREQ;
2948 goto end;
2949
2950 case ACT_HTTP_SET_NICE:
2951 s->task->nice = rule->arg.nice;
2952 break;
2953
2954 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002955 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002956 break;
2957
2958 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002959 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002960 break;
2961
2962 case ACT_HTTP_SET_LOGL:
2963 s->logs.level = rule->arg.loglevel;
2964 break;
2965
2966 case ACT_HTTP_REPLACE_HDR:
2967 case ACT_HTTP_REPLACE_VAL:
2968 if (htx_transform_header(s, &s->req, htx,
2969 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2970 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002971 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002972 rule_ret = HTTP_RULE_RES_BADREQ;
2973 goto end;
2974 }
2975 break;
2976
2977 case ACT_HTTP_DEL_HDR:
2978 /* remove all occurrences of the header */
2979 ctx.blk = NULL;
2980 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2981 http_remove_header(htx, &ctx);
2982 break;
2983
2984 case ACT_HTTP_SET_HDR:
2985 case ACT_HTTP_ADD_HDR: {
2986 /* The scope of the trash buffer must be limited to this function. The
2987 * build_logline() function can execute a lot of other function which
2988 * can use the trash buffer. So for limiting the scope of this global
2989 * buffer, we build first the header value using build_logline, and
2990 * after we store the header name.
2991 */
2992 struct buffer *replace;
2993 struct ist n, v;
2994
2995 replace = alloc_trash_chunk();
2996 if (!replace) {
2997 rule_ret = HTTP_RULE_RES_BADREQ;
2998 goto end;
2999 }
3000
3001 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3002 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3003 v = ist2(replace->area, replace->data);
3004
3005 if (rule->action == ACT_HTTP_SET_HDR) {
3006 /* remove all occurrences of the header */
3007 ctx.blk = NULL;
3008 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3009 http_remove_header(htx, &ctx);
3010 }
3011
3012 if (!http_add_header(htx, n, v)) {
3013 static unsigned char rate_limit = 0;
3014
3015 if ((rate_limit++ & 255) == 0) {
3016 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);
3017 }
3018
Olivier Houcharda798bf52019-03-08 18:52:00 +01003019 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003020 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003021 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003022 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003023 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003024 }
3025 free_trash_chunk(replace);
3026 break;
3027 }
3028
3029 case ACT_HTTP_DEL_ACL:
3030 case ACT_HTTP_DEL_MAP: {
3031 struct pat_ref *ref;
3032 struct buffer *key;
3033
3034 /* collect reference */
3035 ref = pat_ref_lookup(rule->arg.map.ref);
3036 if (!ref)
3037 continue;
3038
3039 /* allocate key */
3040 key = alloc_trash_chunk();
3041 if (!key) {
3042 rule_ret = HTTP_RULE_RES_BADREQ;
3043 goto end;
3044 }
3045
3046 /* collect key */
3047 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3048 key->area[key->data] = '\0';
3049
3050 /* perform update */
3051 /* returned code: 1=ok, 0=ko */
3052 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3053 pat_ref_delete(ref, key->area);
3054 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3055
3056 free_trash_chunk(key);
3057 break;
3058 }
3059
3060 case ACT_HTTP_ADD_ACL: {
3061 struct pat_ref *ref;
3062 struct buffer *key;
3063
3064 /* collect reference */
3065 ref = pat_ref_lookup(rule->arg.map.ref);
3066 if (!ref)
3067 continue;
3068
3069 /* allocate key */
3070 key = alloc_trash_chunk();
3071 if (!key) {
3072 rule_ret = HTTP_RULE_RES_BADREQ;
3073 goto end;
3074 }
3075
3076 /* collect key */
3077 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3078 key->area[key->data] = '\0';
3079
3080 /* perform update */
3081 /* add entry only if it does not already exist */
3082 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3083 if (pat_ref_find_elt(ref, key->area) == NULL)
3084 pat_ref_add(ref, key->area, NULL, NULL);
3085 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3086
3087 free_trash_chunk(key);
3088 break;
3089 }
3090
3091 case ACT_HTTP_SET_MAP: {
3092 struct pat_ref *ref;
3093 struct buffer *key, *value;
3094
3095 /* collect reference */
3096 ref = pat_ref_lookup(rule->arg.map.ref);
3097 if (!ref)
3098 continue;
3099
3100 /* allocate key */
3101 key = alloc_trash_chunk();
3102 if (!key) {
3103 rule_ret = HTTP_RULE_RES_BADREQ;
3104 goto end;
3105 }
3106
3107 /* allocate value */
3108 value = alloc_trash_chunk();
3109 if (!value) {
3110 free_trash_chunk(key);
3111 rule_ret = HTTP_RULE_RES_BADREQ;
3112 goto end;
3113 }
3114
3115 /* collect key */
3116 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3117 key->area[key->data] = '\0';
3118
3119 /* collect value */
3120 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3121 value->area[value->data] = '\0';
3122
3123 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003124 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003125 if (pat_ref_find_elt(ref, key->area) != NULL)
3126 /* update entry if it exists */
3127 pat_ref_set(ref, key->area, value->area, NULL);
3128 else
3129 /* insert a new entry */
3130 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003131 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003132 free_trash_chunk(key);
3133 free_trash_chunk(value);
3134 break;
3135 }
3136
3137 case ACT_HTTP_EARLY_HINT:
3138 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3139 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003140 early_hints = htx_add_early_hint_header(s, early_hints,
3141 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003142 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003143 if (early_hints == -1) {
3144 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003145 goto end;
3146 }
3147 break;
3148
3149 case ACT_CUSTOM:
3150 if ((s->req.flags & CF_READ_ERROR) ||
3151 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003152 (px->options & PR_O_ABRT_CLOSE)))
3153 act_flags |= ACT_FLAG_FINAL;
3154
3155 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3156 case ACT_RET_ERR:
3157 case ACT_RET_CONT:
3158 break;
3159 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003160 rule_ret = HTTP_RULE_RES_STOP;
3161 goto end;
3162 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003163 rule_ret = HTTP_RULE_RES_DONE;
3164 goto end;
3165 case ACT_RET_YIELD:
3166 s->current_rule = rule;
3167 rule_ret = HTTP_RULE_RES_YIELD;
3168 goto end;
3169 }
3170 break;
3171
3172 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3173 /* Note: only the first valid tracking parameter of each
3174 * applies.
3175 */
3176
3177 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3178 struct stktable *t;
3179 struct stksess *ts;
3180 struct stktable_key *key;
3181 void *ptr1, *ptr2;
3182
3183 t = rule->arg.trk_ctr.table.t;
3184 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3185 rule->arg.trk_ctr.expr, NULL);
3186
3187 if (key && (ts = stktable_get_entry(t, key))) {
3188 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3189
3190 /* let's count a new HTTP request as it's the first time we do it */
3191 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3192 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3193 if (ptr1 || ptr2) {
3194 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3195
3196 if (ptr1)
3197 stktable_data_cast(ptr1, http_req_cnt)++;
3198
3199 if (ptr2)
3200 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3201 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3202
3203 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3204
3205 /* If data was modified, we need to touch to re-schedule sync */
3206 stktable_touch_local(t, ts, 0);
3207 }
3208
3209 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3210 if (sess->fe != s->be)
3211 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3212 }
3213 }
3214 break;
3215
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003216 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003217 default:
3218 break;
3219 }
3220 }
3221
3222 end:
3223 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003224 if (htx_reply_103_early_hints(&s->res) == -1)
3225 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003226 }
3227
3228 /* we reached the end of the rules, nothing to report */
3229 return rule_ret;
3230}
3231
3232/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3233 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3234 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3235 * is returned, the process can continue the evaluation of next rule list. If
3236 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3237 * is returned, it means the operation could not be processed and a server error
3238 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3239 * deny rule. If *YIELD is returned, the caller must call again the function
3240 * with the same context.
3241 */
3242static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3243 struct stream *s)
3244{
3245 struct session *sess = strm_sess(s);
3246 struct http_txn *txn = s->txn;
3247 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003248 struct act_rule *rule;
3249 struct http_hdr_ctx ctx;
3250 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3251 int act_flags = 0;
3252
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003253 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003254
3255 /* If "the current_rule_list" match the executed rule list, we are in
3256 * resume condition. If a resume is needed it is always in the action
3257 * and never in the ACL or converters. In this case, we initialise the
3258 * current rule, and go to the action execution point.
3259 */
3260 if (s->current_rule) {
3261 rule = s->current_rule;
3262 s->current_rule = NULL;
3263 if (s->current_rule_list == rules)
3264 goto resume_execution;
3265 }
3266 s->current_rule_list = rules;
3267
3268 list_for_each_entry(rule, rules, list) {
3269 /* check optional condition */
3270 if (rule->cond) {
3271 int ret;
3272
3273 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3274 ret = acl_pass(ret);
3275
3276 if (rule->cond->pol == ACL_COND_UNLESS)
3277 ret = !ret;
3278
3279 if (!ret) /* condition not matched */
3280 continue;
3281 }
3282
3283 act_flags |= ACT_FLAG_FIRST;
3284resume_execution:
3285 switch (rule->action) {
3286 case ACT_ACTION_ALLOW:
3287 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3288 goto end;
3289
3290 case ACT_ACTION_DENY:
3291 txn->flags |= TX_SVDENY;
3292 rule_ret = HTTP_RULE_RES_STOP;
3293 goto end;
3294
3295 case ACT_HTTP_SET_NICE:
3296 s->task->nice = rule->arg.nice;
3297 break;
3298
3299 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003300 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003301 break;
3302
3303 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003304 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003305 break;
3306
3307 case ACT_HTTP_SET_LOGL:
3308 s->logs.level = rule->arg.loglevel;
3309 break;
3310
3311 case ACT_HTTP_REPLACE_HDR:
3312 case ACT_HTTP_REPLACE_VAL:
3313 if (htx_transform_header(s, &s->res, htx,
3314 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3315 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003316 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003317 rule_ret = HTTP_RULE_RES_BADREQ;
3318 goto end;
3319 }
3320 break;
3321
3322 case ACT_HTTP_DEL_HDR:
3323 /* remove all occurrences of the header */
3324 ctx.blk = NULL;
3325 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3326 http_remove_header(htx, &ctx);
3327 break;
3328
3329 case ACT_HTTP_SET_HDR:
3330 case ACT_HTTP_ADD_HDR: {
3331 struct buffer *replace;
3332 struct ist n, v;
3333
3334 replace = alloc_trash_chunk();
3335 if (!replace) {
3336 rule_ret = HTTP_RULE_RES_BADREQ;
3337 goto end;
3338 }
3339
3340 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3341 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3342 v = ist2(replace->area, replace->data);
3343
3344 if (rule->action == ACT_HTTP_SET_HDR) {
3345 /* remove all occurrences of the header */
3346 ctx.blk = NULL;
3347 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3348 http_remove_header(htx, &ctx);
3349 }
3350
3351 if (!http_add_header(htx, n, v)) {
3352 static unsigned char rate_limit = 0;
3353
3354 if ((rate_limit++ & 255) == 0) {
3355 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);
3356 }
3357
Olivier Houcharda798bf52019-03-08 18:52:00 +01003358 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003359 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003360 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003361 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003362 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003363 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003364 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003365 }
3366 free_trash_chunk(replace);
3367 break;
3368 }
3369
3370 case ACT_HTTP_DEL_ACL:
3371 case ACT_HTTP_DEL_MAP: {
3372 struct pat_ref *ref;
3373 struct buffer *key;
3374
3375 /* collect reference */
3376 ref = pat_ref_lookup(rule->arg.map.ref);
3377 if (!ref)
3378 continue;
3379
3380 /* allocate key */
3381 key = alloc_trash_chunk();
3382 if (!key) {
3383 rule_ret = HTTP_RULE_RES_BADREQ;
3384 goto end;
3385 }
3386
3387 /* collect key */
3388 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3389 key->area[key->data] = '\0';
3390
3391 /* perform update */
3392 /* returned code: 1=ok, 0=ko */
3393 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3394 pat_ref_delete(ref, key->area);
3395 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3396
3397 free_trash_chunk(key);
3398 break;
3399 }
3400
3401 case ACT_HTTP_ADD_ACL: {
3402 struct pat_ref *ref;
3403 struct buffer *key;
3404
3405 /* collect reference */
3406 ref = pat_ref_lookup(rule->arg.map.ref);
3407 if (!ref)
3408 continue;
3409
3410 /* allocate key */
3411 key = alloc_trash_chunk();
3412 if (!key) {
3413 rule_ret = HTTP_RULE_RES_BADREQ;
3414 goto end;
3415 }
3416
3417 /* collect key */
3418 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3419 key->area[key->data] = '\0';
3420
3421 /* perform update */
3422 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003423 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003424 if (pat_ref_find_elt(ref, key->area) == NULL)
3425 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003426 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003427 free_trash_chunk(key);
3428 break;
3429 }
3430
3431 case ACT_HTTP_SET_MAP: {
3432 struct pat_ref *ref;
3433 struct buffer *key, *value;
3434
3435 /* collect reference */
3436 ref = pat_ref_lookup(rule->arg.map.ref);
3437 if (!ref)
3438 continue;
3439
3440 /* allocate key */
3441 key = alloc_trash_chunk();
3442 if (!key) {
3443 rule_ret = HTTP_RULE_RES_BADREQ;
3444 goto end;
3445 }
3446
3447 /* allocate value */
3448 value = alloc_trash_chunk();
3449 if (!value) {
3450 free_trash_chunk(key);
3451 rule_ret = HTTP_RULE_RES_BADREQ;
3452 goto end;
3453 }
3454
3455 /* collect key */
3456 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3457 key->area[key->data] = '\0';
3458
3459 /* collect value */
3460 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3461 value->area[value->data] = '\0';
3462
3463 /* perform update */
3464 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3465 if (pat_ref_find_elt(ref, key->area) != NULL)
3466 /* update entry if it exists */
3467 pat_ref_set(ref, key->area, value->area, NULL);
3468 else
3469 /* insert a new entry */
3470 pat_ref_add(ref, key->area, value->area, NULL);
3471 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3472 free_trash_chunk(key);
3473 free_trash_chunk(value);
3474 break;
3475 }
3476
3477 case ACT_HTTP_REDIR:
3478 rule_ret = HTTP_RULE_RES_DONE;
3479 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3480 rule_ret = HTTP_RULE_RES_BADREQ;
3481 goto end;
3482
3483 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3484 /* Note: only the first valid tracking parameter of each
3485 * applies.
3486 */
3487 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3488 struct stktable *t;
3489 struct stksess *ts;
3490 struct stktable_key *key;
3491 void *ptr;
3492
3493 t = rule->arg.trk_ctr.table.t;
3494 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3495 rule->arg.trk_ctr.expr, NULL);
3496
3497 if (key && (ts = stktable_get_entry(t, key))) {
3498 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3499
3500 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3501
3502 /* let's count a new HTTP request as it's the first time we do it */
3503 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3504 if (ptr)
3505 stktable_data_cast(ptr, http_req_cnt)++;
3506
3507 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3508 if (ptr)
3509 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3510 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3511
3512 /* When the client triggers a 4xx from the server, it's most often due
3513 * to a missing object or permission. These events should be tracked
3514 * because if they happen often, it may indicate a brute force or a
3515 * vulnerability scan. Normally this is done when receiving the response
3516 * but here we're tracking after this ought to have been done so we have
3517 * to do it on purpose.
3518 */
3519 if ((unsigned)(txn->status - 400) < 100) {
3520 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3521 if (ptr)
3522 stktable_data_cast(ptr, http_err_cnt)++;
3523
3524 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3525 if (ptr)
3526 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3527 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3528 }
3529
3530 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3531
3532 /* If data was modified, we need to touch to re-schedule sync */
3533 stktable_touch_local(t, ts, 0);
3534
3535 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3536 if (sess->fe != s->be)
3537 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3538 }
3539 }
3540 break;
3541
3542 case ACT_CUSTOM:
3543 if ((s->req.flags & CF_READ_ERROR) ||
3544 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003545 (px->options & PR_O_ABRT_CLOSE)))
3546 act_flags |= ACT_FLAG_FINAL;
3547
3548 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3549 case ACT_RET_ERR:
3550 case ACT_RET_CONT:
3551 break;
3552 case ACT_RET_STOP:
3553 rule_ret = HTTP_RULE_RES_STOP;
3554 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003555 case ACT_RET_DONE:
3556 rule_ret = HTTP_RULE_RES_DONE;
3557 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003558 case ACT_RET_YIELD:
3559 s->current_rule = rule;
3560 rule_ret = HTTP_RULE_RES_YIELD;
3561 goto end;
3562 }
3563 break;
3564
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003565 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003566 default:
3567 break;
3568 }
3569 }
3570
3571 end:
3572 /* we reached the end of the rules, nothing to report */
3573 return rule_ret;
3574}
3575
Christopher Faulet33640082018-10-24 11:53:01 +02003576/* Iterate the same filter through all request headers.
3577 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3578 * Since it can manage the switch to another backend, it updates the per-proxy
3579 * DENY stats.
3580 */
3581static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3582{
3583 struct http_txn *txn = s->txn;
3584 struct htx *htx;
3585 struct buffer *hdr = get_trash_chunk();
3586 int32_t pos;
3587
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003588 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003589
Christopher Fauleta3f15502019-05-13 15:27:23 +02003590 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003591 struct htx_blk *blk = htx_get_blk(htx, pos);
3592 enum htx_blk_type type;
3593 struct ist n, v;
3594
3595 next_hdr:
3596 type = htx_get_blk_type(blk);
3597 if (type == HTX_BLK_EOH)
3598 break;
3599 if (type != HTX_BLK_HDR)
3600 continue;
3601
3602 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3603 return 1;
3604 else if (unlikely(txn->flags & TX_CLALLOW) &&
3605 (exp->action == ACT_ALLOW ||
3606 exp->action == ACT_DENY ||
3607 exp->action == ACT_TARPIT))
3608 return 0;
3609
3610 n = htx_get_blk_name(htx, blk);
3611 v = htx_get_blk_value(htx, blk);
3612
Christopher Faulet02e771a2019-02-26 15:36:05 +01003613 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003614 hdr->area[hdr->data++] = ':';
3615 hdr->area[hdr->data++] = ' ';
3616 chunk_memcat(hdr, v.ptr, v.len);
3617
3618 /* Now we have one header in <hdr> */
3619
3620 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3621 struct http_hdr_ctx ctx;
3622 int len;
3623
3624 switch (exp->action) {
3625 case ACT_ALLOW:
3626 txn->flags |= TX_CLALLOW;
3627 goto end;
3628
3629 case ACT_DENY:
3630 txn->flags |= TX_CLDENY;
3631 goto end;
3632
3633 case ACT_TARPIT:
3634 txn->flags |= TX_CLTARPIT;
3635 goto end;
3636
3637 case ACT_REPLACE:
3638 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3639 if (len < 0)
3640 return -1;
3641
3642 http_parse_header(ist2(trash.area, len), &n, &v);
3643 ctx.blk = blk;
3644 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003645 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003646 if (!http_replace_header(htx, &ctx, n, v))
3647 return -1;
3648 if (!ctx.blk)
3649 goto end;
3650 pos = htx_get_blk_pos(htx, blk);
3651 break;
3652
3653 case ACT_REMOVE:
3654 ctx.blk = blk;
3655 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003656 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003657 if (!http_remove_header(htx, &ctx))
3658 return -1;
3659 if (!ctx.blk)
3660 goto end;
3661 pos = htx_get_blk_pos(htx, blk);
3662 goto next_hdr;
3663
3664 }
3665 }
3666 }
3667 end:
3668 return 0;
3669}
3670
3671/* Apply the filter to the request line.
3672 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3673 * or -1 if a replacement resulted in an invalid request line.
3674 * Since it can manage the switch to another backend, it updates the per-proxy
3675 * DENY stats.
3676 */
3677static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3678{
3679 struct http_txn *txn = s->txn;
3680 struct htx *htx;
3681 struct buffer *reqline = get_trash_chunk();
3682 int done;
3683
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003684 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003685
3686 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3687 return 1;
3688 else if (unlikely(txn->flags & TX_CLALLOW) &&
3689 (exp->action == ACT_ALLOW ||
3690 exp->action == ACT_DENY ||
3691 exp->action == ACT_TARPIT))
3692 return 0;
3693 else if (exp->action == ACT_REMOVE)
3694 return 0;
3695
3696 done = 0;
3697
Christopher Faulet297fbb42019-05-13 14:41:27 +02003698 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003699
3700 /* Now we have the request line between cur_ptr and cur_end */
3701 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003702 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003703 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003704 int len;
3705
3706 switch (exp->action) {
3707 case ACT_ALLOW:
3708 txn->flags |= TX_CLALLOW;
3709 done = 1;
3710 break;
3711
3712 case ACT_DENY:
3713 txn->flags |= TX_CLDENY;
3714 done = 1;
3715 break;
3716
3717 case ACT_TARPIT:
3718 txn->flags |= TX_CLTARPIT;
3719 done = 1;
3720 break;
3721
3722 case ACT_REPLACE:
3723 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3724 if (len < 0)
3725 return -1;
3726
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003727 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3728 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3729 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003730 return -1;
3731 done = 1;
3732 break;
3733 }
3734 }
3735 return done;
3736}
3737
3738/*
3739 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3740 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3741 * unparsable request. Since it can manage the switch to another backend, it
3742 * updates the per-proxy DENY stats.
3743 */
3744static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3745{
3746 struct session *sess = s->sess;
3747 struct http_txn *txn = s->txn;
3748 struct hdr_exp *exp;
3749
3750 for (exp = px->req_exp; exp; exp = exp->next) {
3751 int ret;
3752
3753 /*
3754 * The interleaving of transformations and verdicts
3755 * makes it difficult to decide to continue or stop
3756 * the evaluation.
3757 */
3758
3759 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3760 break;
3761
3762 if ((txn->flags & TX_CLALLOW) &&
3763 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3764 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3765 continue;
3766
3767 /* if this filter had a condition, evaluate it now and skip to
3768 * next filter if the condition does not match.
3769 */
3770 if (exp->cond) {
3771 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3772 ret = acl_pass(ret);
3773 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3774 ret = !ret;
3775
3776 if (!ret)
3777 continue;
3778 }
3779
3780 /* Apply the filter to the request line. */
3781 ret = htx_apply_filter_to_req_line(s, req, exp);
3782 if (unlikely(ret < 0))
3783 return -1;
3784
3785 if (likely(ret == 0)) {
3786 /* The filter did not match the request, it can be
3787 * iterated through all headers.
3788 */
3789 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3790 return -1;
3791 }
3792 }
3793 return 0;
3794}
3795
3796/* Iterate the same filter through all response headers contained in <res>.
3797 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3798 */
3799static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3800{
3801 struct http_txn *txn = s->txn;
3802 struct htx *htx;
3803 struct buffer *hdr = get_trash_chunk();
3804 int32_t pos;
3805
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003806 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003807
Christopher Fauleta3f15502019-05-13 15:27:23 +02003808 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003809 struct htx_blk *blk = htx_get_blk(htx, pos);
3810 enum htx_blk_type type;
3811 struct ist n, v;
3812
3813 next_hdr:
3814 type = htx_get_blk_type(blk);
3815 if (type == HTX_BLK_EOH)
3816 break;
3817 if (type != HTX_BLK_HDR)
3818 continue;
3819
3820 if (unlikely(txn->flags & TX_SVDENY))
3821 return 1;
3822 else if (unlikely(txn->flags & TX_SVALLOW) &&
3823 (exp->action == ACT_ALLOW ||
3824 exp->action == ACT_DENY))
3825 return 0;
3826
3827 n = htx_get_blk_name(htx, blk);
3828 v = htx_get_blk_value(htx, blk);
3829
Christopher Faulet02e771a2019-02-26 15:36:05 +01003830 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003831 hdr->area[hdr->data++] = ':';
3832 hdr->area[hdr->data++] = ' ';
3833 chunk_memcat(hdr, v.ptr, v.len);
3834
3835 /* Now we have one header in <hdr> */
3836
3837 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3838 struct http_hdr_ctx ctx;
3839 int len;
3840
3841 switch (exp->action) {
3842 case ACT_ALLOW:
3843 txn->flags |= TX_SVALLOW;
3844 goto end;
3845 break;
3846
3847 case ACT_DENY:
3848 txn->flags |= TX_SVDENY;
3849 goto end;
3850 break;
3851
3852 case ACT_REPLACE:
3853 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3854 if (len < 0)
3855 return -1;
3856
3857 http_parse_header(ist2(trash.area, len), &n, &v);
3858 ctx.blk = blk;
3859 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003860 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003861 if (!http_replace_header(htx, &ctx, n, v))
3862 return -1;
3863 if (!ctx.blk)
3864 goto end;
3865 pos = htx_get_blk_pos(htx, blk);
3866 break;
3867
3868 case ACT_REMOVE:
3869 ctx.blk = blk;
3870 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003871 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003872 if (!http_remove_header(htx, &ctx))
3873 return -1;
3874 if (!ctx.blk)
3875 goto end;
3876 pos = htx_get_blk_pos(htx, blk);
3877 goto next_hdr;
3878 }
3879 }
3880
3881 }
3882 end:
3883 return 0;
3884}
3885
3886/* Apply the filter to the status line in the response buffer <res>.
3887 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3888 * or -1 if a replacement resulted in an invalid status line.
3889 */
3890static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3891{
3892 struct http_txn *txn = s->txn;
3893 struct htx *htx;
3894 struct buffer *resline = get_trash_chunk();
3895 int done;
3896
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003897 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003898
3899 if (unlikely(txn->flags & TX_SVDENY))
3900 return 1;
3901 else if (unlikely(txn->flags & TX_SVALLOW) &&
3902 (exp->action == ACT_ALLOW ||
3903 exp->action == ACT_DENY))
3904 return 0;
3905 else if (exp->action == ACT_REMOVE)
3906 return 0;
3907
3908 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003909 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003910
3911 /* Now we have the status line between cur_ptr and cur_end */
3912 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003913 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003914 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003915 int len;
3916
3917 switch (exp->action) {
3918 case ACT_ALLOW:
3919 txn->flags |= TX_SVALLOW;
3920 done = 1;
3921 break;
3922
3923 case ACT_DENY:
3924 txn->flags |= TX_SVDENY;
3925 done = 1;
3926 break;
3927
3928 case ACT_REPLACE:
3929 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3930 if (len < 0)
3931 return -1;
3932
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003933 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3934 sl->info.res.status = strl2ui(code.ptr, code.len);
3935 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003936 return -1;
3937
3938 done = 1;
3939 return 1;
3940 }
3941 }
3942 return done;
3943}
3944
3945/*
3946 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3947 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3948 * unparsable response.
3949 */
3950static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3951{
3952 struct session *sess = s->sess;
3953 struct http_txn *txn = s->txn;
3954 struct hdr_exp *exp;
3955
3956 for (exp = px->rsp_exp; exp; exp = exp->next) {
3957 int ret;
3958
3959 /*
3960 * The interleaving of transformations and verdicts
3961 * makes it difficult to decide to continue or stop
3962 * the evaluation.
3963 */
3964
3965 if (txn->flags & TX_SVDENY)
3966 break;
3967
3968 if ((txn->flags & TX_SVALLOW) &&
3969 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3970 exp->action == ACT_PASS)) {
3971 exp = exp->next;
3972 continue;
3973 }
3974
3975 /* if this filter had a condition, evaluate it now and skip to
3976 * next filter if the condition does not match.
3977 */
3978 if (exp->cond) {
3979 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3980 ret = acl_pass(ret);
3981 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3982 ret = !ret;
3983 if (!ret)
3984 continue;
3985 }
3986
3987 /* Apply the filter to the status line. */
3988 ret = htx_apply_filter_to_sts_line(s, res, exp);
3989 if (unlikely(ret < 0))
3990 return -1;
3991
3992 if (likely(ret == 0)) {
3993 /* The filter did not match the response, it can be
3994 * iterated through all headers.
3995 */
3996 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3997 return -1;
3998 }
3999 }
4000 return 0;
4001}
4002
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004003/*
4004 * Manage client-side cookie. It can impact performance by about 2% so it is
4005 * desirable to call it only when needed. This code is quite complex because
4006 * of the multiple very crappy and ambiguous syntaxes we have to support. it
4007 * highly recommended not to touch this part without a good reason !
4008 */
4009static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
4010{
4011 struct session *sess = s->sess;
4012 struct http_txn *txn = s->txn;
4013 struct htx *htx;
4014 struct http_hdr_ctx ctx;
4015 char *hdr_beg, *hdr_end, *del_from;
4016 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4017 int preserve_hdr;
4018
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004019 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004020 ctx.blk = NULL;
4021 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004022 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004023 del_from = NULL; /* nothing to be deleted */
4024 preserve_hdr = 0; /* assume we may kill the whole header */
4025
4026 /* Now look for cookies. Conforming to RFC2109, we have to support
4027 * attributes whose name begin with a '$', and associate them with
4028 * the right cookie, if we want to delete this cookie.
4029 * So there are 3 cases for each cookie read :
4030 * 1) it's a special attribute, beginning with a '$' : ignore it.
4031 * 2) it's a server id cookie that we *MAY* want to delete : save
4032 * some pointers on it (last semi-colon, beginning of cookie...)
4033 * 3) it's an application cookie : we *MAY* have to delete a previous
4034 * "special" cookie.
4035 * At the end of loop, if a "special" cookie remains, we may have to
4036 * remove it. If no application cookie persists in the header, we
4037 * *MUST* delete it.
4038 *
4039 * Note: RFC2965 is unclear about the processing of spaces around
4040 * the equal sign in the ATTR=VALUE form. A careful inspection of
4041 * the RFC explicitly allows spaces before it, and not within the
4042 * tokens (attrs or values). An inspection of RFC2109 allows that
4043 * too but section 10.1.3 lets one think that spaces may be allowed
4044 * after the equal sign too, resulting in some (rare) buggy
4045 * implementations trying to do that. So let's do what servers do.
4046 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4047 * allowed quoted strings in values, with any possible character
4048 * after a backslash, including control chars and delimitors, which
4049 * causes parsing to become ambiguous. Browsers also allow spaces
4050 * within values even without quotes.
4051 *
4052 * We have to keep multiple pointers in order to support cookie
4053 * removal at the beginning, middle or end of header without
4054 * corrupting the header. All of these headers are valid :
4055 *
4056 * hdr_beg hdr_end
4057 * | |
4058 * v |
4059 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4060 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4061 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4062 * | | | | | | |
4063 * | | | | | | |
4064 * | | | | | | +--> next
4065 * | | | | | +----> val_end
4066 * | | | | +-----------> val_beg
4067 * | | | +--------------> equal
4068 * | | +----------------> att_end
4069 * | +---------------------> att_beg
4070 * +--------------------------> prev
4071 *
4072 */
4073 hdr_beg = ctx.value.ptr;
4074 hdr_end = hdr_beg + ctx.value.len;
4075 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4076 /* Iterate through all cookies on this line */
4077
4078 /* find att_beg */
4079 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004080 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004081 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004082 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004083
4084 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4085 att_beg++;
4086
4087 /* find att_end : this is the first character after the last non
4088 * space before the equal. It may be equal to hdr_end.
4089 */
4090 equal = att_end = att_beg;
4091 while (equal < hdr_end) {
4092 if (*equal == '=' || *equal == ',' || *equal == ';')
4093 break;
4094 if (HTTP_IS_SPHT(*equal++))
4095 continue;
4096 att_end = equal;
4097 }
4098
4099 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4100 * is between <att_beg> and <equal>, both may be identical.
4101 */
4102 /* look for end of cookie if there is an equal sign */
4103 if (equal < hdr_end && *equal == '=') {
4104 /* look for the beginning of the value */
4105 val_beg = equal + 1;
4106 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4107 val_beg++;
4108
4109 /* find the end of the value, respecting quotes */
4110 next = http_find_cookie_value_end(val_beg, hdr_end);
4111
4112 /* make val_end point to the first white space or delimitor after the value */
4113 val_end = next;
4114 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4115 val_end--;
4116 }
4117 else
4118 val_beg = val_end = next = equal;
4119
4120 /* We have nothing to do with attributes beginning with
4121 * '$'. However, they will automatically be removed if a
4122 * header before them is removed, since they're supposed
4123 * to be linked together.
4124 */
4125 if (*att_beg == '$')
4126 continue;
4127
4128 /* Ignore cookies with no equal sign */
4129 if (equal == next) {
4130 /* This is not our cookie, so we must preserve it. But if we already
4131 * scheduled another cookie for removal, we cannot remove the
4132 * complete header, but we can remove the previous block itself.
4133 */
4134 preserve_hdr = 1;
4135 if (del_from != NULL) {
4136 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4137 val_end += delta;
4138 next += delta;
4139 hdr_end += delta;
4140 prev = del_from;
4141 del_from = NULL;
4142 }
4143 continue;
4144 }
4145
4146 /* if there are spaces around the equal sign, we need to
4147 * strip them otherwise we'll get trouble for cookie captures,
4148 * or even for rewrites. Since this happens extremely rarely,
4149 * it does not hurt performance.
4150 */
4151 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4152 int stripped_before = 0;
4153 int stripped_after = 0;
4154
4155 if (att_end != equal) {
4156 memmove(att_end, equal, hdr_end - equal);
4157 stripped_before = (att_end - equal);
4158 equal += stripped_before;
4159 val_beg += stripped_before;
4160 }
4161
4162 if (val_beg > equal + 1) {
4163 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4164 stripped_after = (equal + 1) - val_beg;
4165 val_beg += stripped_after;
4166 stripped_before += stripped_after;
4167 }
4168
4169 val_end += stripped_before;
4170 next += stripped_before;
4171 hdr_end += stripped_before;
4172 }
4173 /* now everything is as on the diagram above */
4174
4175 /* First, let's see if we want to capture this cookie. We check
4176 * that we don't already have a client side cookie, because we
4177 * can only capture one. Also as an optimisation, we ignore
4178 * cookies shorter than the declared name.
4179 */
4180 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4181 (val_end - att_beg >= sess->fe->capture_namelen) &&
4182 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4183 int log_len = val_end - att_beg;
4184
4185 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4186 ha_alert("HTTP logging : out of memory.\n");
4187 } else {
4188 if (log_len > sess->fe->capture_len)
4189 log_len = sess->fe->capture_len;
4190 memcpy(txn->cli_cookie, att_beg, log_len);
4191 txn->cli_cookie[log_len] = 0;
4192 }
4193 }
4194
4195 /* Persistence cookies in passive, rewrite or insert mode have the
4196 * following form :
4197 *
4198 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4199 *
4200 * For cookies in prefix mode, the form is :
4201 *
4202 * Cookie: NAME=SRV~VALUE
4203 */
4204 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4205 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4206 struct server *srv = s->be->srv;
4207 char *delim;
4208
4209 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4210 * have the server ID between val_beg and delim, and the original cookie between
4211 * delim+1 and val_end. Otherwise, delim==val_end :
4212 *
4213 * hdr_beg
4214 * |
4215 * v
4216 * NAME=SRV; # in all but prefix modes
4217 * NAME=SRV~OPAQUE ; # in prefix mode
4218 * || || | |+-> next
4219 * || || | +--> val_end
4220 * || || +---------> delim
4221 * || |+------------> val_beg
4222 * || +-------------> att_end = equal
4223 * |+-----------------> att_beg
4224 * +------------------> prev
4225 *
4226 */
4227 if (s->be->ck_opts & PR_CK_PFX) {
4228 for (delim = val_beg; delim < val_end; delim++)
4229 if (*delim == COOKIE_DELIM)
4230 break;
4231 }
4232 else {
4233 char *vbar1;
4234 delim = val_end;
4235 /* Now check if the cookie contains a date field, which would
4236 * appear after a vertical bar ('|') just after the server name
4237 * and before the delimiter.
4238 */
4239 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4240 if (vbar1) {
4241 /* OK, so left of the bar is the server's cookie and
4242 * right is the last seen date. It is a base64 encoded
4243 * 30-bit value representing the UNIX date since the
4244 * epoch in 4-second quantities.
4245 */
4246 int val;
4247 delim = vbar1++;
4248 if (val_end - vbar1 >= 5) {
4249 val = b64tos30(vbar1);
4250 if (val > 0)
4251 txn->cookie_last_date = val << 2;
4252 }
4253 /* look for a second vertical bar */
4254 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4255 if (vbar1 && (val_end - vbar1 > 5)) {
4256 val = b64tos30(vbar1 + 1);
4257 if (val > 0)
4258 txn->cookie_first_date = val << 2;
4259 }
4260 }
4261 }
4262
4263 /* if the cookie has an expiration date and the proxy wants to check
4264 * it, then we do that now. We first check if the cookie is too old,
4265 * then only if it has expired. We detect strict overflow because the
4266 * time resolution here is not great (4 seconds). Cookies with dates
4267 * in the future are ignored if their offset is beyond one day. This
4268 * allows an admin to fix timezone issues without expiring everyone
4269 * and at the same time avoids keeping unwanted side effects for too
4270 * long.
4271 */
4272 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4273 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4274 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4275 txn->flags &= ~TX_CK_MASK;
4276 txn->flags |= TX_CK_OLD;
4277 delim = val_beg; // let's pretend we have not found the cookie
4278 txn->cookie_first_date = 0;
4279 txn->cookie_last_date = 0;
4280 }
4281 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4282 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4283 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4284 txn->flags &= ~TX_CK_MASK;
4285 txn->flags |= TX_CK_EXPIRED;
4286 delim = val_beg; // let's pretend we have not found the cookie
4287 txn->cookie_first_date = 0;
4288 txn->cookie_last_date = 0;
4289 }
4290
4291 /* Here, we'll look for the first running server which supports the cookie.
4292 * This allows to share a same cookie between several servers, for example
4293 * to dedicate backup servers to specific servers only.
4294 * However, to prevent clients from sticking to cookie-less backup server
4295 * when they have incidentely learned an empty cookie, we simply ignore
4296 * empty cookies and mark them as invalid.
4297 * The same behaviour is applied when persistence must be ignored.
4298 */
4299 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4300 srv = NULL;
4301
4302 while (srv) {
4303 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4304 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4305 if ((srv->cur_state != SRV_ST_STOPPED) ||
4306 (s->be->options & PR_O_PERSIST) ||
4307 (s->flags & SF_FORCE_PRST)) {
4308 /* we found the server and we can use it */
4309 txn->flags &= ~TX_CK_MASK;
4310 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4311 s->flags |= SF_DIRECT | SF_ASSIGNED;
4312 s->target = &srv->obj_type;
4313 break;
4314 } else {
4315 /* we found a server, but it's down,
4316 * mark it as such and go on in case
4317 * another one is available.
4318 */
4319 txn->flags &= ~TX_CK_MASK;
4320 txn->flags |= TX_CK_DOWN;
4321 }
4322 }
4323 srv = srv->next;
4324 }
4325
4326 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4327 /* no server matched this cookie or we deliberately skipped it */
4328 txn->flags &= ~TX_CK_MASK;
4329 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4330 txn->flags |= TX_CK_UNUSED;
4331 else
4332 txn->flags |= TX_CK_INVALID;
4333 }
4334
4335 /* depending on the cookie mode, we may have to either :
4336 * - delete the complete cookie if we're in insert+indirect mode, so that
4337 * the server never sees it ;
4338 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004339 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004340 * if we're in cookie prefix mode
4341 */
4342 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4343 int delta; /* negative */
4344
4345 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4346 delta = val_beg - (delim + 1);
4347 val_end += delta;
4348 next += delta;
4349 hdr_end += delta;
4350 del_from = NULL;
4351 preserve_hdr = 1; /* we want to keep this cookie */
4352 }
4353 else if (del_from == NULL &&
4354 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4355 del_from = prev;
4356 }
4357 }
4358 else {
4359 /* This is not our cookie, so we must preserve it. But if we already
4360 * scheduled another cookie for removal, we cannot remove the
4361 * complete header, but we can remove the previous block itself.
4362 */
4363 preserve_hdr = 1;
4364
4365 if (del_from != NULL) {
4366 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4367 if (att_beg >= del_from)
4368 att_beg += delta;
4369 if (att_end >= del_from)
4370 att_end += delta;
4371 val_beg += delta;
4372 val_end += delta;
4373 next += delta;
4374 hdr_end += delta;
4375 prev = del_from;
4376 del_from = NULL;
4377 }
4378 }
4379
4380 /* continue with next cookie on this header line */
4381 att_beg = next;
4382 } /* for each cookie */
4383
4384
4385 /* There are no more cookies on this line.
4386 * We may still have one (or several) marked for deletion at the
4387 * end of the line. We must do this now in two ways :
4388 * - if some cookies must be preserved, we only delete from the
4389 * mark to the end of line ;
4390 * - if nothing needs to be preserved, simply delete the whole header
4391 */
4392 if (del_from) {
4393 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4394 }
4395 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004396 if (hdr_beg != hdr_end)
4397 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004398 else
4399 http_remove_header(htx, &ctx);
4400 }
4401 } /* for each "Cookie header */
4402}
4403
4404/*
4405 * Manage server-side cookies. It can impact performance by about 2% so it is
4406 * desirable to call it only when needed. This function is also used when we
4407 * just need to know if there is a cookie (eg: for check-cache).
4408 */
4409static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4410{
4411 struct session *sess = s->sess;
4412 struct http_txn *txn = s->txn;
4413 struct htx *htx;
4414 struct http_hdr_ctx ctx;
4415 struct server *srv;
4416 char *hdr_beg, *hdr_end;
4417 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004418 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004419
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004420 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004421
4422 ctx.blk = NULL;
4423 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004424 int is_first = 1;
4425
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004426 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4427 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4428 break;
4429 is_cookie2 = 1;
4430 }
4431
4432 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4433 * <prev> points to the colon.
4434 */
4435 txn->flags |= TX_SCK_PRESENT;
4436
4437 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4438 * check-cache is enabled) and we are not interested in checking
4439 * them. Warning, the cookie capture is declared in the frontend.
4440 */
4441 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4442 break;
4443
4444 /* OK so now we know we have to process this response cookie.
4445 * The format of the Set-Cookie header is slightly different
4446 * from the format of the Cookie header in that it does not
4447 * support the comma as a cookie delimiter (thus the header
4448 * cannot be folded) because the Expires attribute described in
4449 * the original Netscape's spec may contain an unquoted date
4450 * with a comma inside. We have to live with this because
4451 * many browsers don't support Max-Age and some browsers don't
4452 * support quoted strings. However the Set-Cookie2 header is
4453 * clean.
4454 *
4455 * We have to keep multiple pointers in order to support cookie
4456 * removal at the beginning, middle or end of header without
4457 * corrupting the header (in case of set-cookie2). A special
4458 * pointer, <scav> points to the beginning of the set-cookie-av
4459 * fields after the first semi-colon. The <next> pointer points
4460 * either to the end of line (set-cookie) or next unquoted comma
4461 * (set-cookie2). All of these headers are valid :
4462 *
4463 * hdr_beg hdr_end
4464 * | |
4465 * v |
4466 * NAME1 = VALUE 1 ; Secure; Path="/" |
4467 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4468 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4469 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4470 * | | | | | | | |
4471 * | | | | | | | +-> next
4472 * | | | | | | +------------> scav
4473 * | | | | | +--------------> val_end
4474 * | | | | +--------------------> val_beg
4475 * | | | +----------------------> equal
4476 * | | +------------------------> att_end
4477 * | +----------------------------> att_beg
4478 * +------------------------------> prev
4479 * -------------------------------> hdr_beg
4480 */
4481 hdr_beg = ctx.value.ptr;
4482 hdr_end = hdr_beg + ctx.value.len;
4483 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4484
4485 /* Iterate through all cookies on this line */
4486
4487 /* find att_beg */
4488 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004489 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004490 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004491 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004492
4493 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4494 att_beg++;
4495
4496 /* find att_end : this is the first character after the last non
4497 * space before the equal. It may be equal to hdr_end.
4498 */
4499 equal = att_end = att_beg;
4500
4501 while (equal < hdr_end) {
4502 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4503 break;
4504 if (HTTP_IS_SPHT(*equal++))
4505 continue;
4506 att_end = equal;
4507 }
4508
4509 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4510 * is between <att_beg> and <equal>, both may be identical.
4511 */
4512
4513 /* look for end of cookie if there is an equal sign */
4514 if (equal < hdr_end && *equal == '=') {
4515 /* look for the beginning of the value */
4516 val_beg = equal + 1;
4517 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4518 val_beg++;
4519
4520 /* find the end of the value, respecting quotes */
4521 next = http_find_cookie_value_end(val_beg, hdr_end);
4522
4523 /* make val_end point to the first white space or delimitor after the value */
4524 val_end = next;
4525 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4526 val_end--;
4527 }
4528 else {
4529 /* <equal> points to next comma, semi-colon or EOL */
4530 val_beg = val_end = next = equal;
4531 }
4532
4533 if (next < hdr_end) {
4534 /* Set-Cookie2 supports multiple cookies, and <next> points to
4535 * a colon or semi-colon before the end. So skip all attr-value
4536 * pairs and look for the next comma. For Set-Cookie, since
4537 * commas are permitted in values, skip to the end.
4538 */
4539 if (is_cookie2)
4540 next = http_find_hdr_value_end(next, hdr_end);
4541 else
4542 next = hdr_end;
4543 }
4544
4545 /* Now everything is as on the diagram above */
4546
4547 /* Ignore cookies with no equal sign */
4548 if (equal == val_end)
4549 continue;
4550
4551 /* If there are spaces around the equal sign, we need to
4552 * strip them otherwise we'll get trouble for cookie captures,
4553 * or even for rewrites. Since this happens extremely rarely,
4554 * it does not hurt performance.
4555 */
4556 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4557 int stripped_before = 0;
4558 int stripped_after = 0;
4559
4560 if (att_end != equal) {
4561 memmove(att_end, equal, hdr_end - equal);
4562 stripped_before = (att_end - equal);
4563 equal += stripped_before;
4564 val_beg += stripped_before;
4565 }
4566
4567 if (val_beg > equal + 1) {
4568 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4569 stripped_after = (equal + 1) - val_beg;
4570 val_beg += stripped_after;
4571 stripped_before += stripped_after;
4572 }
4573
4574 val_end += stripped_before;
4575 next += stripped_before;
4576 hdr_end += stripped_before;
4577
Christopher Faulet41dc8432019-06-18 09:49:16 +02004578 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004579 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004580 }
4581
4582 /* First, let's see if we want to capture this cookie. We check
4583 * that we don't already have a server side cookie, because we
4584 * can only capture one. Also as an optimisation, we ignore
4585 * cookies shorter than the declared name.
4586 */
4587 if (sess->fe->capture_name != NULL &&
4588 txn->srv_cookie == NULL &&
4589 (val_end - att_beg >= sess->fe->capture_namelen) &&
4590 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4591 int log_len = val_end - att_beg;
4592 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4593 ha_alert("HTTP logging : out of memory.\n");
4594 }
4595 else {
4596 if (log_len > sess->fe->capture_len)
4597 log_len = sess->fe->capture_len;
4598 memcpy(txn->srv_cookie, att_beg, log_len);
4599 txn->srv_cookie[log_len] = 0;
4600 }
4601 }
4602
4603 srv = objt_server(s->target);
4604 /* now check if we need to process it for persistence */
4605 if (!(s->flags & SF_IGNORE_PRST) &&
4606 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4607 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4608 /* assume passive cookie by default */
4609 txn->flags &= ~TX_SCK_MASK;
4610 txn->flags |= TX_SCK_FOUND;
4611
4612 /* If the cookie is in insert mode on a known server, we'll delete
4613 * this occurrence because we'll insert another one later.
4614 * We'll delete it too if the "indirect" option is set and we're in
4615 * a direct access.
4616 */
4617 if (s->be->ck_opts & PR_CK_PSV) {
4618 /* The "preserve" flag was set, we don't want to touch the
4619 * server's cookie.
4620 */
4621 }
4622 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4623 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4624 /* this cookie must be deleted */
4625 if (prev == hdr_beg && next == hdr_end) {
4626 /* whole header */
4627 http_remove_header(htx, &ctx);
4628 /* note: while both invalid now, <next> and <hdr_end>
4629 * are still equal, so the for() will stop as expected.
4630 */
4631 } else {
4632 /* just remove the value */
4633 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4634 next = prev;
4635 hdr_end += delta;
4636 }
4637 txn->flags &= ~TX_SCK_MASK;
4638 txn->flags |= TX_SCK_DELETED;
4639 /* and go on with next cookie */
4640 }
4641 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4642 /* replace bytes val_beg->val_end with the cookie name associated
4643 * with this server since we know it.
4644 */
4645 int sliding, delta;
4646
4647 ctx.value = ist2(val_beg, val_end - val_beg);
4648 ctx.lws_before = ctx.lws_after = 0;
4649 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4650 delta = srv->cklen - (val_end - val_beg);
4651 sliding = (ctx.value.ptr - val_beg);
4652 hdr_beg += sliding;
4653 val_beg += sliding;
4654 next += sliding + delta;
4655 hdr_end += sliding + delta;
4656
4657 txn->flags &= ~TX_SCK_MASK;
4658 txn->flags |= TX_SCK_REPLACED;
4659 }
4660 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4661 /* insert the cookie name associated with this server
4662 * before existing cookie, and insert a delimiter between them..
4663 */
4664 int sliding, delta;
4665 ctx.value = ist2(val_beg, 0);
4666 ctx.lws_before = ctx.lws_after = 0;
4667 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4668 delta = srv->cklen + 1;
4669 sliding = (ctx.value.ptr - val_beg);
4670 hdr_beg += sliding;
4671 val_beg += sliding;
4672 next += sliding + delta;
4673 hdr_end += sliding + delta;
4674
4675 val_beg[srv->cklen] = COOKIE_DELIM;
4676 txn->flags &= ~TX_SCK_MASK;
4677 txn->flags |= TX_SCK_REPLACED;
4678 }
4679 }
4680 /* that's done for this cookie, check the next one on the same
4681 * line when next != hdr_end (only if is_cookie2).
4682 */
4683 }
4684 }
4685}
4686
Christopher Faulet25a02f62018-10-24 12:00:25 +02004687/*
4688 * Parses the Cache-Control and Pragma request header fields to determine if
4689 * the request may be served from the cache and/or if it is cacheable. Updates
4690 * s->txn->flags.
4691 */
4692void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4693{
4694 struct http_txn *txn = s->txn;
4695 struct htx *htx;
4696 int32_t pos;
4697 int pragma_found, cc_found, i;
4698
4699 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4700 return; /* nothing more to do here */
4701
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004702 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004703 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004704 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004705 struct htx_blk *blk = htx_get_blk(htx, pos);
4706 enum htx_blk_type type = htx_get_blk_type(blk);
4707 struct ist n, v;
4708
4709 if (type == HTX_BLK_EOH)
4710 break;
4711 if (type != HTX_BLK_HDR)
4712 continue;
4713
4714 n = htx_get_blk_name(htx, blk);
4715 v = htx_get_blk_value(htx, blk);
4716
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004717 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004718 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4719 pragma_found = 1;
4720 continue;
4721 }
4722 }
4723
4724 /* Don't use the cache and don't try to store if we found the
4725 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004726 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004727 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4728 txn->flags |= TX_CACHE_IGNORE;
4729 continue;
4730 }
4731
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004732 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004733 continue;
4734
4735 /* OK, right now we know we have a cache-control header */
4736 cc_found = 1;
4737 if (!v.len) /* no info */
4738 continue;
4739
4740 i = 0;
4741 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4742 !isspace((unsigned char)*(v.ptr+i)))
4743 i++;
4744
4745 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4746 * values after max-age, max-stale nor min-fresh, we simply don't
4747 * use the cache when they're specified.
4748 */
4749 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4750 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4751 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4752 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4753 txn->flags |= TX_CACHE_IGNORE;
4754 continue;
4755 }
4756
4757 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4758 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4759 continue;
4760 }
4761 }
4762
4763 /* RFC7234#5.4:
4764 * When the Cache-Control header field is also present and
4765 * understood in a request, Pragma is ignored.
4766 * When the Cache-Control header field is not present in a
4767 * request, caches MUST consider the no-cache request
4768 * pragma-directive as having the same effect as if
4769 * "Cache-Control: no-cache" were present.
4770 */
4771 if (!cc_found && pragma_found)
4772 txn->flags |= TX_CACHE_IGNORE;
4773}
4774
4775/*
4776 * Check if response is cacheable or not. Updates s->txn->flags.
4777 */
4778void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4779{
4780 struct http_txn *txn = s->txn;
4781 struct htx *htx;
4782 int32_t pos;
4783 int i;
4784
4785 if (txn->status < 200) {
4786 /* do not try to cache interim responses! */
4787 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4788 return;
4789 }
4790
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004791 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004792 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004793 struct htx_blk *blk = htx_get_blk(htx, pos);
4794 enum htx_blk_type type = htx_get_blk_type(blk);
4795 struct ist n, v;
4796
4797 if (type == HTX_BLK_EOH)
4798 break;
4799 if (type != HTX_BLK_HDR)
4800 continue;
4801
4802 n = htx_get_blk_name(htx, blk);
4803 v = htx_get_blk_value(htx, blk);
4804
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004805 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004806 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4807 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4808 return;
4809 }
4810 }
4811
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004812 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004813 continue;
4814
4815 /* OK, right now we know we have a cache-control header */
4816 if (!v.len) /* no info */
4817 continue;
4818
4819 i = 0;
4820 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4821 !isspace((unsigned char)*(v.ptr+i)))
4822 i++;
4823
4824 /* we have a complete value between v.ptr and (v.ptr+i) */
4825 if (i < v.len && *(v.ptr + i) == '=') {
4826 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4827 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4828 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4829 continue;
4830 }
4831
4832 /* we have something of the form no-cache="set-cookie" */
4833 if ((v.len >= 21) &&
4834 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4835 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4836 txn->flags &= ~TX_CACHE_COOK;
4837 continue;
4838 }
4839
4840 /* OK, so we know that either p2 points to the end of string or to a comma */
4841 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4842 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4843 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4844 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4845 return;
4846 }
4847
4848 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4849 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4850 continue;
4851 }
4852 }
4853}
4854
Christopher Faulet64159df2018-10-24 21:15:35 +02004855/* send a server's name with an outgoing request over an established connection.
4856 * Note: this function is designed to be called once the request has been
4857 * scheduled for being forwarded. This is the reason why the number of forwarded
4858 * bytes have to be adjusted.
4859 */
4860int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4861{
4862 struct htx *htx;
4863 struct http_hdr_ctx ctx;
4864 struct ist hdr;
4865 uint32_t data;
4866
4867 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004868 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004869 data = htx->data;
4870
4871 ctx.blk = NULL;
4872 while (http_find_header(htx, hdr, &ctx, 1))
4873 http_remove_header(htx, &ctx);
4874 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4875
4876 if (co_data(&s->req)) {
4877 if (data >= htx->data)
4878 c_rew(&s->req, data - htx->data);
4879 else
4880 c_adv(&s->req, htx->data - data);
4881 }
4882 return 0;
4883}
4884
Christopher Faulet377c5a52018-10-24 21:21:30 +02004885/*
4886 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4887 * for the current backend.
4888 *
4889 * It is assumed that the request is either a HEAD, GET, or POST and that the
4890 * uri_auth field is valid.
4891 *
4892 * Returns 1 if stats should be provided, otherwise 0.
4893 */
4894static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4895{
4896 struct uri_auth *uri_auth = backend->uri_auth;
4897 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004898 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004899 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004900
4901 if (!uri_auth)
4902 return 0;
4903
4904 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4905 return 0;
4906
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004907 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004908 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004909 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004910
4911 /* check URI size */
4912 if (uri_auth->uri_len > uri.len)
4913 return 0;
4914
4915 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4916 return 0;
4917
4918 return 1;
4919}
4920
4921/* This function prepares an applet to handle the stats. It can deal with the
4922 * "100-continue" expectation, check that admin rules are met for POST requests,
4923 * and program a response message if something was unexpected. It cannot fail
4924 * and always relies on the stats applet to complete the job. It does not touch
4925 * analysers nor counters, which are left to the caller. It does not touch
4926 * s->target which is supposed to already point to the stats applet. The caller
4927 * is expected to have already assigned an appctx to the stream.
4928 */
4929static int htx_handle_stats(struct stream *s, struct channel *req)
4930{
4931 struct stats_admin_rule *stats_admin_rule;
4932 struct stream_interface *si = &s->si[1];
4933 struct session *sess = s->sess;
4934 struct http_txn *txn = s->txn;
4935 struct http_msg *msg = &txn->req;
4936 struct uri_auth *uri_auth = s->be->uri_auth;
4937 const char *h, *lookup, *end;
4938 struct appctx *appctx;
4939 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004940 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004941
4942 appctx = si_appctx(si);
4943 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4944 appctx->st1 = appctx->st2 = 0;
4945 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4946 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4947 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4948 appctx->ctx.stats.flags |= STAT_CHUNKED;
4949
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004950 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004951 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004952 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4953 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004954
4955 for (h = lookup; h <= end - 3; h++) {
4956 if (memcmp(h, ";up", 3) == 0) {
4957 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4958 break;
4959 }
4960 }
4961
4962 if (uri_auth->refresh) {
4963 for (h = lookup; h <= end - 10; h++) {
4964 if (memcmp(h, ";norefresh", 10) == 0) {
4965 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4966 break;
4967 }
4968 }
4969 }
4970
4971 for (h = lookup; h <= end - 4; h++) {
4972 if (memcmp(h, ";csv", 4) == 0) {
4973 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4974 break;
4975 }
4976 }
4977
4978 for (h = lookup; h <= end - 6; h++) {
4979 if (memcmp(h, ";typed", 6) == 0) {
4980 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4981 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4982 break;
4983 }
4984 }
4985
4986 for (h = lookup; h <= end - 8; h++) {
4987 if (memcmp(h, ";st=", 4) == 0) {
4988 int i;
4989 h += 4;
4990 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4991 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4992 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4993 appctx->ctx.stats.st_code = i;
4994 break;
4995 }
4996 }
4997 break;
4998 }
4999 }
5000
5001 appctx->ctx.stats.scope_str = 0;
5002 appctx->ctx.stats.scope_len = 0;
5003 for (h = lookup; h <= end - 8; h++) {
5004 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
5005 int itx = 0;
5006 const char *h2;
5007 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
5008 const char *err;
5009
5010 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
5011 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01005012 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
5013 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005014 if (*h == ';' || *h == '&' || *h == ' ')
5015 break;
5016 itx++;
5017 h++;
5018 }
5019
5020 if (itx > STAT_SCOPE_TXT_MAXLEN)
5021 itx = STAT_SCOPE_TXT_MAXLEN;
5022 appctx->ctx.stats.scope_len = itx;
5023
5024 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5025 memcpy(scope_txt, h2, itx);
5026 scope_txt[itx] = '\0';
5027 err = invalid_char(scope_txt);
5028 if (err) {
5029 /* bad char in search text => clear scope */
5030 appctx->ctx.stats.scope_str = 0;
5031 appctx->ctx.stats.scope_len = 0;
5032 }
5033 break;
5034 }
5035 }
5036
5037 /* now check whether we have some admin rules for this request */
5038 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5039 int ret = 1;
5040
5041 if (stats_admin_rule->cond) {
5042 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5043 ret = acl_pass(ret);
5044 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5045 ret = !ret;
5046 }
5047
5048 if (ret) {
5049 /* no rule, or the rule matches */
5050 appctx->ctx.stats.flags |= STAT_ADMIN;
5051 break;
5052 }
5053 }
5054
Christopher Faulet5d45e382019-02-27 15:15:23 +01005055 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5056 appctx->st0 = STAT_HTTP_HEAD;
5057 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005058 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005059 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005060 if (msg->msg_state < HTTP_MSG_DATA)
5061 req->analysers |= AN_REQ_HTTP_BODY;
5062 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005063 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005064 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005065 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5066 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5067 appctx->st0 = STAT_HTTP_LAST;
5068 }
5069 }
5070 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005071 /* Unsupported method */
5072 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5073 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5074 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005075 }
5076
5077 s->task->nice = -32; /* small boost for HTTP statistics */
5078 return 1;
5079}
5080
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005081void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5082{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005083 struct channel *req = &s->req;
5084 struct channel *res = &s->res;
5085 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005087 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005088 struct ist path, location;
5089 unsigned int flags;
5090 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005091
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005092 /*
5093 * Create the location
5094 */
5095 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005096
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005097 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005098 /* special prefix "/" means don't change URL */
5099 srv = __objt_server(s->target);
5100 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5101 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5102 return;
5103 }
5104
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005105 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005106 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005107 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005108 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005109 if (!path.ptr)
5110 return;
5111
5112 if (!chunk_memcat(&trash, path.ptr, path.len))
5113 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005114 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005115
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005116 /*
5117 * Create the 302 respone
5118 */
5119 htx = htx_from_buf(&res->buf);
5120 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5121 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5122 ist("HTTP/1.1"), ist("302"), ist("Found"));
5123 if (!sl)
5124 goto fail;
5125 sl->info.res.status = 302;
5126 s->txn->status = 302;
5127
5128 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5129 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5130 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5131 !htx_add_header(htx, ist("Location"), location))
5132 goto fail;
5133
5134 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5135 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005136
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005137 /*
5138 * Send the message
5139 */
5140 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005141 c_adv(res, data);
5142 res->total += data;
5143
5144 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005145 si_shutr(si);
5146 si_shutw(si);
5147 si->err_type = SI_ET_NONE;
5148 si->state = SI_ST_CLO;
5149
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005150 channel_auto_read(req);
5151 channel_abort(req);
5152 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005153 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005154 channel_auto_read(res);
5155 channel_auto_close(res);
5156
5157 if (!(s->flags & SF_ERR_MASK))
5158 s->flags |= SF_ERR_LOCAL;
5159 if (!(s->flags & SF_FINST_MASK))
5160 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005161
5162 /* FIXME: we should increase a counter of redirects per server and per backend. */
5163 srv_inc_sess_ctr(srv);
5164 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005165 return;
5166
5167 fail:
5168 /* If an error occurred, remove the incomplete HTTP response from the
5169 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005170 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005171}
5172
Christopher Fauletf2824e62018-10-01 12:12:37 +02005173/* This function terminates the request because it was completly analyzed or
5174 * because an error was triggered during the body forwarding.
5175 */
5176static void htx_end_request(struct stream *s)
5177{
5178 struct channel *chn = &s->req;
5179 struct http_txn *txn = s->txn;
5180
5181 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5182 now_ms, __FUNCTION__, s,
5183 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5184 s->req.analysers, s->res.analysers);
5185
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005186 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5187 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005188 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005189 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 goto end;
5191 }
5192
5193 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5194 return;
5195
5196 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 /* No need to read anymore, the request was completely parsed.
5198 * We can shut the read side unless we want to abort_on_close,
5199 * or we have a POST request. The issue with POST requests is
5200 * that some browsers still send a CRLF after the request, and
5201 * this CRLF must be read so that it does not remain in the kernel
5202 * buffers, otherwise a close could cause an RST on some systems
5203 * (eg: Linux).
5204 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005205 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005206 channel_dont_read(chn);
5207
5208 /* if the server closes the connection, we want to immediately react
5209 * and close the socket to save packets and syscalls.
5210 */
5211 s->si[1].flags |= SI_FL_NOHALF;
5212
5213 /* In any case we've finished parsing the request so we must
5214 * disable Nagle when sending data because 1) we're not going
5215 * to shut this side, and 2) the server is waiting for us to
5216 * send pending data.
5217 */
5218 chn->flags |= CF_NEVER_WAIT;
5219
Christopher Fauletd01ce402019-01-02 17:44:13 +01005220 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5221 /* The server has not finished to respond, so we
5222 * don't want to move in order not to upset it.
5223 */
5224 return;
5225 }
5226
Christopher Fauletf2824e62018-10-01 12:12:37 +02005227 /* When we get here, it means that both the request and the
5228 * response have finished receiving. Depending on the connection
5229 * mode, we'll have to wait for the last bytes to leave in either
5230 * direction, and sometimes for a close to be effective.
5231 */
5232 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5233 /* Tunnel mode will not have any analyser so it needs to
5234 * poll for reads.
5235 */
5236 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005237 if (b_data(&chn->buf))
5238 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005239 txn->req.msg_state = HTTP_MSG_TUNNEL;
5240 }
5241 else {
5242 /* we're not expecting any new data to come for this
5243 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005244 *
5245 * However, there is an exception if the response
5246 * length is undefined. In this case, we need to wait
5247 * the close from the server. The response will be
5248 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005249 */
5250 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5251 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005252 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005253
5254 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5255 channel_shutr_now(chn);
5256 channel_shutw_now(chn);
5257 }
5258 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005259 goto check_channel_flags;
5260 }
5261
5262 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5263 http_msg_closing:
5264 /* nothing else to forward, just waiting for the output buffer
5265 * to be empty and for the shutw_now to take effect.
5266 */
5267 if (channel_is_empty(chn)) {
5268 txn->req.msg_state = HTTP_MSG_CLOSED;
5269 goto http_msg_closed;
5270 }
5271 else if (chn->flags & CF_SHUTW) {
5272 txn->req.err_state = txn->req.msg_state;
5273 txn->req.msg_state = HTTP_MSG_ERROR;
5274 goto end;
5275 }
5276 return;
5277 }
5278
5279 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5280 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005281 /* if we don't know whether the server will close, we need to hard close */
5282 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5283 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005284 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005285 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005286 channel_dont_read(chn);
5287 goto end;
5288 }
5289
5290 check_channel_flags:
5291 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5292 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5293 /* if we've just closed an output, let's switch */
5294 txn->req.msg_state = HTTP_MSG_CLOSING;
5295 goto http_msg_closing;
5296 }
5297
5298 end:
5299 chn->analysers &= AN_REQ_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005300 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
5301 chn->flags |= CF_NEVER_WAIT;
5302 if (HAS_REQ_DATA_FILTERS(s))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005303 chn->analysers |= AN_REQ_FLT_XFER_DATA;
Christopher Faulet86c82202020-12-15 13:32:55 +01005304 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005305 channel_auto_close(chn);
5306 channel_auto_read(chn);
5307}
5308
5309
5310/* This function terminates the response because it was completly analyzed or
5311 * because an error was triggered during the body forwarding.
5312 */
5313static void htx_end_response(struct stream *s)
5314{
5315 struct channel *chn = &s->res;
5316 struct http_txn *txn = s->txn;
5317
5318 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5319 now_ms, __FUNCTION__, s,
5320 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5321 s->req.analysers, s->res.analysers);
5322
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005323 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5324 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005325 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005326 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005327 goto end;
5328 }
5329
5330 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5331 return;
5332
5333 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5334 /* In theory, we don't need to read anymore, but we must
5335 * still monitor the server connection for a possible close
5336 * while the request is being uploaded, so we don't disable
5337 * reading.
5338 */
5339 /* channel_dont_read(chn); */
5340
5341 if (txn->req.msg_state < HTTP_MSG_DONE) {
5342 /* The client seems to still be sending data, probably
5343 * because we got an error response during an upload.
5344 * We have the choice of either breaking the connection
5345 * or letting it pass through. Let's do the later.
5346 */
5347 return;
5348 }
5349
5350 /* When we get here, it means that both the request and the
5351 * response have finished receiving. Depending on the connection
5352 * mode, we'll have to wait for the last bytes to leave in either
5353 * direction, and sometimes for a close to be effective.
5354 */
5355 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5356 channel_auto_read(chn);
5357 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005358 if (b_data(&chn->buf))
5359 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005360 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5361 }
5362 else {
5363 /* we're not expecting any new data to come for this
5364 * transaction, so we can close it.
5365 */
5366 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5367 channel_shutr_now(chn);
5368 channel_shutw_now(chn);
5369 }
5370 }
5371 goto check_channel_flags;
5372 }
5373
5374 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5375 http_msg_closing:
5376 /* nothing else to forward, just waiting for the output buffer
5377 * to be empty and for the shutw_now to take effect.
5378 */
5379 if (channel_is_empty(chn)) {
5380 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5381 goto http_msg_closed;
5382 }
5383 else if (chn->flags & CF_SHUTW) {
5384 txn->rsp.err_state = txn->rsp.msg_state;
5385 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005386 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005387 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005388 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005389 goto end;
5390 }
5391 return;
5392 }
5393
5394 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5395 http_msg_closed:
5396 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005397 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005398 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005399 goto end;
5400 }
5401
5402 check_channel_flags:
5403 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5404 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5405 /* if we've just closed an output, let's switch */
5406 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5407 goto http_msg_closing;
5408 }
5409
5410 end:
5411 chn->analysers &= AN_RES_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005412 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5413 chn->flags |= CF_NEVER_WAIT;
5414 if (HAS_RSP_DATA_FILTERS(s))
5415 chn->analysers |= AN_RES_FLT_XFER_DATA;
5416 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005417 channel_auto_close(chn);
5418 channel_auto_read(chn);
5419}
5420
Christopher Faulet0f226952018-10-22 09:29:56 +02005421void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5422 int finst, const struct buffer *msg)
5423{
5424 channel_auto_read(si_oc(si));
5425 channel_abort(si_oc(si));
5426 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005427 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005428 channel_auto_close(si_ic(si));
5429 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005430
5431 /* <msg> is an HTX structure. So we copy it in the response's
5432 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005433 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005434 struct channel *chn = si_ic(si);
5435 struct htx *htx;
5436
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005437 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005438 chn->buf.data = msg->data;
5439 memcpy(chn->buf.area, msg->area, msg->data);
5440 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005441 if (s->txn->meth == HTTP_METH_HEAD)
5442 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005443 c_adv(chn, htx->data);
5444 chn->total += htx->data;
5445 }
5446 if (!(s->flags & SF_ERR_MASK))
5447 s->flags |= err;
5448 if (!(s->flags & SF_FINST_MASK))
5449 s->flags |= finst;
5450}
5451
5452void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5453{
5454 channel_auto_read(&s->req);
5455 channel_abort(&s->req);
5456 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005457 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5458 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005459
5460 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005461
5462 /* <msg> is an HTX structure. So we copy it in the response's
5463 * channel */
5464 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005465 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005466 struct channel *chn = &s->res;
5467 struct htx *htx;
5468
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005469 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005470 chn->buf.data = msg->data;
5471 memcpy(chn->buf.area, msg->area, msg->data);
5472 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005473 if (s->txn->meth == HTTP_METH_HEAD)
5474 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005475 c_adv(chn, htx->data);
5476 chn->total += htx->data;
5477 }
5478
5479 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5480 channel_auto_read(&s->res);
5481 channel_auto_close(&s->res);
5482 channel_shutr_now(&s->res);
5483}
5484
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005485struct buffer *htx_error_message(struct stream *s)
5486{
5487 const int msgnum = http_get_status_idx(s->txn->status);
5488
5489 if (s->be->errmsg[msgnum].area)
5490 return &s->be->errmsg[msgnum];
5491 else if (strm_fe(s)->errmsg[msgnum].area)
5492 return &strm_fe(s)->errmsg[msgnum];
5493 else
5494 return &htx_err_chunks[msgnum];
5495}
5496
5497
Christopher Faulet4a28a532019-03-01 11:19:40 +01005498/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5499 * on success and -1 on error.
5500 */
5501static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5502{
5503 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5504 * then we must send an HTTP/1.1 100 Continue intermediate response.
5505 */
5506 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5507 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5508 struct ist hdr = { .ptr = "Expect", .len = 6 };
5509 struct http_hdr_ctx ctx;
5510
5511 ctx.blk = NULL;
5512 /* Expect is allowed in 1.1, look for it */
5513 if (http_find_header(htx, hdr, &ctx, 0) &&
5514 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5515 if (htx_reply_100_continue(s) == -1)
5516 return -1;
5517 http_remove_header(htx, &ctx);
5518 }
5519 }
5520 return 0;
5521}
5522
Christopher Faulet23a3c792018-11-28 10:01:23 +01005523/* Send a 100-Continue response to the client. It returns 0 on success and -1
5524 * on error. The response channel is updated accordingly.
5525 */
5526static int htx_reply_100_continue(struct stream *s)
5527{
5528 struct channel *res = &s->res;
5529 struct htx *htx = htx_from_buf(&res->buf);
5530 struct htx_sl *sl;
5531 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5532 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5533 size_t data;
5534
5535 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5536 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5537 if (!sl)
5538 goto fail;
5539 sl->info.res.status = 100;
5540
Christopher Faulet9869f932019-06-26 14:23:54 +02005541 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005542 goto fail;
5543
5544 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005545 c_adv(res, data);
5546 res->total += data;
5547 return 0;
5548
5549 fail:
5550 /* If an error occurred, remove the incomplete HTTP response from the
5551 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005552 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005553 return -1;
5554}
5555
Christopher Faulet12c51e22018-11-28 15:59:42 +01005556
5557/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5558 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5559 * error. The response channel is updated accordingly.
5560 */
5561static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5562{
5563 struct channel *res = &s->res;
5564 struct htx *htx = htx_from_buf(&res->buf);
5565 struct htx_sl *sl;
5566 struct ist code, body;
5567 int status;
5568 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5569 size_t data;
5570
5571 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5572 status = 401;
5573 code = ist("401");
5574 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5575 "You need a valid user and password to access this content.\n"
5576 "</body></html>\n");
5577 }
5578 else {
5579 status = 407;
5580 code = ist("407");
5581 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5582 "You need a valid user and password to access this content.\n"
5583 "</body></html>\n");
5584 }
5585
5586 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5587 ist("HTTP/1.1"), code, ist("Unauthorized"));
5588 if (!sl)
5589 goto fail;
5590 sl->info.res.status = status;
5591 s->txn->status = status;
5592
5593 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5594 goto fail;
5595
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005596 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5597 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005598 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005599 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5600 goto fail;
5601 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5602 goto fail;
5603 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005604 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005605 if (!htx_add_endof(htx, HTX_BLK_EOH))
5606 goto fail;
5607
Christopher Faulete6ee4652020-10-19 18:01:38 +02005608 if (s->txn->meth == HTTP_METH_HEAD)
5609 body.len = 0;
5610
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005611 while (body.len) {
5612 size_t sent = htx_add_data(htx, body);
5613 if (!sent)
5614 goto fail;
5615 body.ptr += sent;
5616 body.len -= sent;
5617 }
5618
5619 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005620 goto fail;
5621
5622 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005623 c_adv(res, data);
5624 res->total += data;
5625
5626 channel_auto_read(&s->req);
5627 channel_abort(&s->req);
5628 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005629 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005630
5631 res->wex = tick_add_ifset(now_ms, res->wto);
5632 channel_auto_read(res);
5633 channel_auto_close(res);
5634 channel_shutr_now(res);
5635 return 0;
5636
5637 fail:
5638 /* If an error occurred, remove the incomplete HTTP response from the
5639 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005640 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005641 return -1;
5642}
5643
Christopher Faulet0f226952018-10-22 09:29:56 +02005644/*
5645 * Capture headers from message <htx> according to header list <cap_hdr>, and
5646 * fill the <cap> pointers appropriately.
5647 */
5648static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5649{
5650 struct cap_hdr *h;
5651 int32_t pos;
5652
Christopher Fauleta3f15502019-05-13 15:27:23 +02005653 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005654 struct htx_blk *blk = htx_get_blk(htx, pos);
5655 enum htx_blk_type type = htx_get_blk_type(blk);
5656 struct ist n, v;
5657
5658 if (type == HTX_BLK_EOH)
5659 break;
5660 if (type != HTX_BLK_HDR)
5661 continue;
5662
5663 n = htx_get_blk_name(htx, blk);
5664
5665 for (h = cap_hdr; h; h = h->next) {
5666 if (h->namelen && (h->namelen == n.len) &&
5667 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5668 if (cap[h->index] == NULL)
5669 cap[h->index] =
5670 pool_alloc(h->pool);
5671
5672 if (cap[h->index] == NULL) {
5673 ha_alert("HTTP capture : out of memory.\n");
5674 break;
5675 }
5676
5677 v = htx_get_blk_value(htx, blk);
5678 if (v.len > h->len)
5679 v.len = h->len;
5680
5681 memcpy(cap[h->index], v.ptr, v.len);
5682 cap[h->index][v.len]=0;
5683 }
5684 }
5685 }
5686}
5687
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005688/* Delete a value in a header between delimiters <from> and <next>. The header
5689 * itself is delimited by <start> and <end> pointers. The number of characters
5690 * displaced is returned, and the pointer to the first delimiter is updated if
5691 * required. The function tries as much as possible to respect the following
5692 * principles :
5693 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5694 * in which case <next> is simply removed
5695 * - set exactly one space character after the new first delimiter, unless there
5696 * are not enough characters in the block being moved to do so.
5697 * - remove unneeded spaces before the previous delimiter and after the new
5698 * one.
5699 *
5700 * It is the caller's responsibility to ensure that :
5701 * - <from> points to a valid delimiter or <start> ;
5702 * - <next> points to a valid delimiter or <end> ;
5703 * - there are non-space chars before <from>.
5704 */
5705static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5706{
5707 char *prev = *from;
5708
5709 if (prev == start) {
5710 /* We're removing the first value. eat the semicolon, if <next>
5711 * is lower than <end> */
5712 if (next < end)
5713 next++;
5714
5715 while (next < end && HTTP_IS_SPHT(*next))
5716 next++;
5717 }
5718 else {
5719 /* Remove useless spaces before the old delimiter. */
5720 while (HTTP_IS_SPHT(*(prev-1)))
5721 prev--;
5722 *from = prev;
5723
5724 /* copy the delimiter and if possible a space if we're
5725 * not at the end of the line.
5726 */
5727 if (next < end) {
5728 *prev++ = *next++;
5729 if (prev + 1 < next)
5730 *prev++ = ' ';
5731 while (next < end && HTTP_IS_SPHT(*next))
5732 next++;
5733 }
5734 }
5735 memmove(prev, next, end - next);
5736 return (prev - next);
5737}
5738
Christopher Faulet0f226952018-10-22 09:29:56 +02005739
5740/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005741 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005742 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005743static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005744{
5745 struct ist dst = ist2(str, 0);
5746
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005747 if (istcat(&dst, htx_sl_req_meth(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 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005754 goto end;
5755 if (dst.len + 1 > len)
5756 goto end;
5757 dst.ptr[dst.len++] = ' ';
5758
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005759 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005760 end:
5761 return dst.len;
5762}
5763
Christopher Fauletf0523542018-10-24 11:06:58 +02005764/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005765 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005766 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005767static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005768{
5769 struct ist dst = ist2(str, 0);
5770
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005771 if (istcat(&dst, htx_sl_res_vsn(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 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005778 goto end;
5779 if (dst.len + 1 > len)
5780 goto end;
5781 dst.ptr[dst.len++] = ' ';
5782
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005783 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005784 end:
5785 return dst.len;
5786}
5787
5788
Christopher Faulet0f226952018-10-22 09:29:56 +02005789/*
5790 * Print a debug line with a start line.
5791 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005792static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005793{
5794 struct session *sess = strm_sess(s);
5795 int max;
5796
5797 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5798 dir,
5799 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5800 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5801
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005802 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005803 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005804 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005805 trash.area[trash.data++] = ' ';
5806
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005807 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005808 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005809 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005810 trash.area[trash.data++] = ' ';
5811
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005812 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005813 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005814 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005815 trash.area[trash.data++] = '\n';
5816
5817 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5818}
5819
5820/*
5821 * Print a debug line with a header.
5822 */
5823static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5824{
5825 struct session *sess = strm_sess(s);
5826 int max;
5827
5828 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5829 dir,
5830 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5831 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5832
5833 max = n.len;
5834 UBOUND(max, trash.size - trash.data - 3);
5835 chunk_memcat(&trash, n.ptr, max);
5836 trash.area[trash.data++] = ':';
5837 trash.area[trash.data++] = ' ';
5838
5839 max = v.len;
5840 UBOUND(max, trash.size - trash.data - 1);
5841 chunk_memcat(&trash, v.ptr, max);
5842 trash.area[trash.data++] = '\n';
5843
5844 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5845}
5846
5847
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005848__attribute__((constructor))
5849static void __htx_protocol_init(void)
5850{
5851}
5852
5853
5854/*
5855 * Local variables:
5856 * c-indent-level: 8
5857 * c-basic-offset: 8
5858 * End:
5859 */