blob: c5cc70ce5cb8bd2f1d3b45b0021e28437e492313 [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);
Olivier Houchardc86a9662020-05-12 22:18:14 +02001423 s->flags &= ~SF_ADDR_SET;
Olivier Houchard530249c2019-07-12 16:16:59 +02001424 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001425 si->exp = TICK_ETERNITY;
1426 res->rex = TICK_ETERNITY;
1427 res->to_forward = 0;
1428 res->analyse_exp = TICK_ETERNITY;
1429 res->total = 0;
Willy Tarreau9b9a83a2021-05-07 08:19:30 +02001430 s->flags &= ~SF_ERR_MASK;
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
Olivier Houchard6db16992019-05-17 15:40:49 +02001518 if (txn->flags & TX_NOT_FIRST)
1519 goto abort_keep_alive;
1520
Olivier Houcharda798bf52019-03-08 18:52:00 +01001521 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001523 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001524 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 }
1526
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001528 s->req.analysers &= AN_REQ_FLT_END;
1529 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 txn->status = 502;
1531
1532 /* Check to see if the server refused the early data.
1533 * If so, just send a 425
1534 */
Willy Tarreau1b4cc2e2020-06-23 05:58:20 +02001535 if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001536 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001537 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001538 do_l7_retry(s, si_b) == 0)
1539 return 0;
1540 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 }
1542
1543 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001544 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545
1546 if (!(s->flags & SF_ERR_MASK))
1547 s->flags |= SF_ERR_SRVCL;
1548 if (!(s->flags & SF_FINST_MASK))
1549 s->flags |= SF_FINST_H;
1550 return 0;
1551 }
1552
Christopher Faulet9768c262018-10-22 09:34:31 +02001553 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001555 if ((si_b->flags & SI_FL_L7_RETRY) &&
1556 (s->be->retry_type & PR_RE_TIMEOUT)) {
1557 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1558 return 0;
1559 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001560 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001562 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001563 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564 }
1565
Christopher Faulete0768eb2018-10-03 16:38:02 +02001566 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001567 s->req.analysers &= AN_REQ_FLT_END;
1568 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569 txn->status = 504;
1570 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001571 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572
1573 if (!(s->flags & SF_ERR_MASK))
1574 s->flags |= SF_ERR_SRVTO;
1575 if (!(s->flags & SF_FINST_MASK))
1576 s->flags |= SF_FINST_H;
1577 return 0;
1578 }
1579
Christopher Faulet9768c262018-10-22 09:34:31 +02001580 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001581 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001582 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1583 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001585 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001586
1587 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001588 s->req.analysers &= AN_REQ_FLT_END;
1589 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001590 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001591 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001592
1593 if (!(s->flags & SF_ERR_MASK))
1594 s->flags |= SF_ERR_CLICL;
1595 if (!(s->flags & SF_FINST_MASK))
1596 s->flags |= SF_FINST_H;
1597
1598 /* process_stream() will take care of the error */
1599 return 0;
1600 }
1601
Christopher Faulet9768c262018-10-22 09:34:31 +02001602 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001604 if ((si_b->flags & SI_FL_L7_RETRY) &&
1605 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1606 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1607 return 0;
1608 }
1609
Olivier Houchard6db16992019-05-17 15:40:49 +02001610 if (txn->flags & TX_NOT_FIRST)
1611 goto abort_keep_alive;
1612
Olivier Houcharda798bf52019-03-08 18:52:00 +01001613 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001615 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001616 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001617 }
1618
Christopher Faulete0768eb2018-10-03 16:38:02 +02001619 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001620 s->req.analysers &= AN_REQ_FLT_END;
1621 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622 txn->status = 502;
1623 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001624 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625
1626 if (!(s->flags & SF_ERR_MASK))
1627 s->flags |= SF_ERR_SRVCL;
1628 if (!(s->flags & SF_FINST_MASK))
1629 s->flags |= SF_FINST_H;
1630 return 0;
1631 }
1632
Christopher Faulet9768c262018-10-22 09:34:31 +02001633 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001635 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001636 goto abort_keep_alive;
1637
Olivier Houcharda798bf52019-03-08 18:52:00 +01001638 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001640 s->req.analysers &= AN_REQ_FLT_END;
1641 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001642
1643 if (!(s->flags & SF_ERR_MASK))
1644 s->flags |= SF_ERR_CLICL;
1645 if (!(s->flags & SF_FINST_MASK))
1646 s->flags |= SF_FINST_H;
1647
1648 /* process_stream() will take care of the error */
1649 return 0;
1650 }
1651
1652 channel_dont_close(rep);
1653 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1654 return 0;
1655 }
1656
1657 /* More interesting part now : we know that we have a complete
1658 * response which at least looks like HTTP. We have an indicator
1659 * of each header's length, so we can parse them quickly.
1660 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001661 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001662 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001663 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001664
Christopher Faulet9768c262018-10-22 09:34:31 +02001665 /* 0: we might have to print this header in debug mode */
1666 if (unlikely((global.mode & MODE_DEBUG) &&
1667 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1668 int32_t pos;
1669
Christopher Faulet03599112018-11-27 11:21:21 +01001670 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001671
Christopher Fauleta3f15502019-05-13 15:27:23 +02001672 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001673 struct htx_blk *blk = htx_get_blk(htx, pos);
1674 enum htx_blk_type type = htx_get_blk_type(blk);
1675
1676 if (type == HTX_BLK_EOH)
1677 break;
1678 if (type != HTX_BLK_HDR)
1679 continue;
1680
1681 htx_debug_hdr("srvhdr", s,
1682 htx_get_blk_name(htx, blk),
1683 htx_get_blk_value(htx, blk));
1684 }
1685 }
1686
Christopher Faulet03599112018-11-27 11:21:21 +01001687 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001688 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001689 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001690 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001691 if (sl->flags & HTX_SL_F_XFER_LEN) {
1692 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001693 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001694 if (sl->flags & HTX_SL_F_BODYLESS)
1695 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001696 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001697
1698 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001699 if (n < 1 || n > 5)
1700 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001701
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 /* when the client triggers a 4xx from the server, it's most often due
1703 * to a missing object or permission. These events should be tracked
1704 * because if they happen often, it may indicate a brute force or a
1705 * vulnerability scan.
1706 */
1707 if (n == 4)
1708 stream_inc_http_err_ctr(s);
1709
1710 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001711 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001712
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713 /* Adjust server's health based on status code. Note: status codes 501
1714 * and 505 are triggered on demand by client request, so we must not
1715 * count them as server failures.
1716 */
1717 if (objt_server(s->target)) {
1718 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001719 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001721 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001722 }
1723
1724 /*
1725 * We may be facing a 100-continue response, or any other informational
1726 * 1xx response which is non-final, in which case this is not the right
1727 * response, and we're waiting for the next one. Let's allow this response
1728 * to go to the client and wait for the next one. There's an exception for
1729 * 101 which is used later in the code to switch protocols.
1730 */
1731 if (txn->status < 200 &&
1732 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001733 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001734 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001735 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001736 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001737 txn->status = 0;
1738 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet5761e7d2020-08-31 11:07:07 +02001739 rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001740 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001741 }
1742
1743 /*
1744 * 2: check for cacheability.
1745 */
1746
1747 switch (txn->status) {
1748 case 200:
1749 case 203:
1750 case 204:
1751 case 206:
1752 case 300:
1753 case 301:
1754 case 404:
1755 case 405:
1756 case 410:
1757 case 414:
1758 case 501:
1759 break;
1760 default:
1761 /* RFC7231#6.1:
1762 * Responses with status codes that are defined as
1763 * cacheable by default (e.g., 200, 203, 204, 206,
1764 * 300, 301, 404, 405, 410, 414, and 501 in this
1765 * specification) can be reused by a cache with
1766 * heuristic expiration unless otherwise indicated
1767 * by the method definition or explicit cache
1768 * controls [RFC7234]; all other status codes are
1769 * not cacheable by default.
1770 */
1771 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1772 break;
1773 }
1774
1775 /*
1776 * 3: we may need to capture headers
1777 */
1778 s->logs.logwait &= ~LW_RESP;
1779 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001780 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001781
Christopher Faulet9768c262018-10-22 09:34:31 +02001782 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001783 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1784 txn->status == 101)) {
1785 /* Either we've established an explicit tunnel, or we're
1786 * switching the protocol. In both cases, we're very unlikely
1787 * to understand the next protocols. We have to switch to tunnel
1788 * mode, so that we transfer the request and responses then let
1789 * this protocol pass unmodified. When we later implement specific
1790 * parsers for such protocols, we'll want to check the Upgrade
1791 * header which contains information about that protocol for
1792 * responses with status 101 (eg: see RFC2817 about TLS).
1793 */
1794 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001795 }
1796
Christopher Faulet61608322018-11-23 16:23:45 +01001797 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1798 * 407 (Proxy-Authenticate) responses and set the connection to private
1799 */
1800 srv_conn = cs_conn(objt_cs(s->si[1].end));
1801 if (srv_conn) {
1802 struct ist hdr;
1803 struct http_hdr_ctx ctx;
1804
1805 if (txn->status == 401)
1806 hdr = ist("WWW-Authenticate");
1807 else if (txn->status == 407)
1808 hdr = ist("Proxy-Authenticate");
1809 else
1810 goto end;
1811
1812 ctx.blk = NULL;
1813 while (http_find_header(htx, hdr, &ctx, 0)) {
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001814 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1815 * possibly followed by blanks and a base64 string, the connection
1816 * is private. Since it's a mess to deal with, we only check for
1817 * values starting with "NTLM" or "Nego". Note that often multiple
1818 * headers are sent by the server there.
1819 */
1820 if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
Willy Tarreaud3be89b2020-05-07 19:10:15 +02001821 (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001822 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001823 srv_conn->flags |= CO_FL_PRIVATE;
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001824 break;
Olivier Houchard250031e2019-05-29 15:01:50 +02001825 }
Christopher Faulet61608322018-11-23 16:23:45 +01001826 }
1827 }
1828
1829 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001830 /* we want to have the response time before we start processing it */
1831 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1832
1833 /* end of job, return OK */
1834 rep->analysers &= ~an_bit;
1835 rep->analyse_exp = TICK_ETERNITY;
1836 channel_auto_close(rep);
1837 return 1;
1838
Christopher Faulet47365272018-10-31 17:40:50 +01001839 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001840 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001841 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001842 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001843 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001844 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001845 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001846 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001847 do_l7_retry(s, si_b) == 0)
1848 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001849 txn->status = 502;
1850 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001851 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001852 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001853 s->req.analysers &= AN_REQ_FLT_END;
1854 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001855
1856 if (!(s->flags & SF_ERR_MASK))
1857 s->flags |= SF_ERR_PRXCOND;
1858 if (!(s->flags & SF_FINST_MASK))
1859 s->flags |= SF_FINST_H;
1860 return 0;
1861
Christopher Faulete0768eb2018-10-03 16:38:02 +02001862 abort_keep_alive:
1863 /* A keep-alive request to the server failed on a network error.
1864 * The client is required to retry. We need to close without returning
1865 * any other information so that the client retries.
1866 */
1867 txn->status = 0;
1868 rep->analysers &= AN_RES_FLT_END;
1869 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001870 s->logs.logwait = 0;
1871 s->logs.level = 0;
1872 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001873 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001874 return 0;
1875}
1876
1877/* This function performs all the processing enabled for the current response.
1878 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1879 * and updates s->res.analysers. It might make sense to explode it into several
1880 * other functions. It works like process_request (see indications above).
1881 */
1882int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1883{
1884 struct session *sess = s->sess;
1885 struct http_txn *txn = s->txn;
1886 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001887 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001888 struct proxy *cur_proxy;
1889 struct cond_wordlist *wl;
1890 enum rule_result ret = HTTP_RULE_RES_CONT;
1891
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001892 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1893 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001894
Christopher Faulete0768eb2018-10-03 16:38:02 +02001895 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1896 now_ms, __FUNCTION__,
1897 s,
1898 rep,
1899 rep->rex, rep->wex,
1900 rep->flags,
1901 ci_data(rep),
1902 rep->analysers);
1903
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001904 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001905
1906 /* The stats applet needs to adjust the Connection header but we don't
1907 * apply any filter there.
1908 */
1909 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1910 rep->analysers &= ~an_bit;
1911 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001912 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001913 }
1914
1915 /*
1916 * We will have to evaluate the filters.
1917 * As opposed to version 1.2, now they will be evaluated in the
1918 * filters order and not in the header order. This means that
1919 * each filter has to be validated among all headers.
1920 *
1921 * Filters are tried with ->be first, then with ->fe if it is
1922 * different from ->be.
1923 *
1924 * Maybe we are in resume condiion. In this case I choose the
1925 * "struct proxy" which contains the rule list matching the resume
1926 * pointer. If none of theses "struct proxy" match, I initialise
1927 * the process with the first one.
1928 *
1929 * In fact, I check only correspondance betwwen the current list
1930 * pointer and the ->fe rule list. If it doesn't match, I initialize
1931 * the loop with the ->be.
1932 */
1933 if (s->current_rule_list == &sess->fe->http_res_rules)
1934 cur_proxy = sess->fe;
1935 else
1936 cur_proxy = s->be;
1937 while (1) {
1938 struct proxy *rule_set = cur_proxy;
1939
1940 /* evaluate http-response rules */
1941 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001942 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001943
1944 if (ret == HTTP_RULE_RES_BADREQ)
1945 goto return_srv_prx_502;
1946
1947 if (ret == HTTP_RULE_RES_DONE) {
1948 rep->analysers &= ~an_bit;
1949 rep->analyse_exp = TICK_ETERNITY;
1950 return 1;
1951 }
1952 }
1953
1954 /* we need to be called again. */
1955 if (ret == HTTP_RULE_RES_YIELD) {
1956 channel_dont_close(rep);
1957 return 0;
1958 }
1959
1960 /* try headers filters */
1961 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001962 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1963 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001964 }
1965
1966 /* has the response been denied ? */
1967 if (txn->flags & TX_SVDENY) {
1968 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001969 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001970
Olivier Houcharda798bf52019-03-08 18:52:00 +01001971 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1972 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01001973 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001974 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001975 goto return_srv_prx_502;
1976 }
1977
1978 /* add response headers from the rule sets in the same order */
1979 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001980 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001981 if (txn->status < 200 && txn->status != 101)
1982 break;
1983 if (wl->cond) {
1984 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1985 ret = acl_pass(ret);
1986 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1987 ret = !ret;
1988 if (!ret)
1989 continue;
1990 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001991
1992 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1993 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001994 goto return_bad_resp;
1995 }
1996
1997 /* check whether we're already working on the frontend */
1998 if (cur_proxy == sess->fe)
1999 break;
2000 cur_proxy = sess->fe;
2001 }
2002
2003 /* After this point, this anayzer can't return yield, so we can
2004 * remove the bit corresponding to this analyzer from the list.
2005 *
2006 * Note that the intermediate returns and goto found previously
2007 * reset the analyzers.
2008 */
2009 rep->analysers &= ~an_bit;
2010 rep->analyse_exp = TICK_ETERNITY;
2011
2012 /* OK that's all we can do for 1xx responses */
2013 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002014 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002015
2016 /*
2017 * Now check for a server cookie.
2018 */
2019 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002020 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002021
2022 /*
2023 * Check for cache-control or pragma headers if required.
2024 */
2025 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2026 check_response_for_cacheability(s, rep);
2027
2028 /*
2029 * Add server cookie in the response if needed
2030 */
2031 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2032 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2033 (!(s->flags & SF_DIRECT) ||
2034 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2035 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2036 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2037 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2038 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2039 !(s->flags & SF_IGNORE_PRST)) {
2040 /* the server is known, it's not the one the client requested, or the
2041 * cookie's last seen date needs to be refreshed. We have to
2042 * insert a set-cookie here, except if we want to insert only on POST
2043 * requests and this one isn't. Note that servers which don't have cookies
2044 * (eg: some backup servers) will return a full cookie removal request.
2045 */
2046 if (!objt_server(s->target)->cookie) {
2047 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002048 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002049 s->be->cookie_name);
2050 }
2051 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002052 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002053
2054 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2055 /* emit last_date, which is mandatory */
2056 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2057 s30tob64((date.tv_sec+3) >> 2,
2058 trash.area + trash.data);
2059 trash.data += 5;
2060
2061 if (s->be->cookie_maxlife) {
2062 /* emit first_date, which is either the original one or
2063 * the current date.
2064 */
2065 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2066 s30tob64(txn->cookie_first_date ?
2067 txn->cookie_first_date >> 2 :
2068 (date.tv_sec+3) >> 2,
2069 trash.area + trash.data);
2070 trash.data += 5;
2071 }
2072 }
2073 chunk_appendf(&trash, "; path=/");
2074 }
2075
2076 if (s->be->cookie_domain)
2077 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2078
2079 if (s->be->ck_opts & PR_CK_HTTPONLY)
2080 chunk_appendf(&trash, "; HttpOnly");
2081
2082 if (s->be->ck_opts & PR_CK_SECURE)
2083 chunk_appendf(&trash, "; Secure");
2084
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002085 if (s->be->cookie_attrs)
2086 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2087
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002088 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002089 goto return_bad_resp;
2090
2091 txn->flags &= ~TX_SCK_MASK;
2092 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2093 /* the server did not change, only the date was updated */
2094 txn->flags |= TX_SCK_UPDATED;
2095 else
2096 txn->flags |= TX_SCK_INSERTED;
2097
2098 /* Here, we will tell an eventual cache on the client side that we don't
2099 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2100 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2101 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2102 */
2103 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2104
2105 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2106
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002107 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002108 goto return_bad_resp;
2109 }
2110 }
2111
2112 /*
2113 * Check if result will be cacheable with a cookie.
2114 * We'll block the response if security checks have caught
2115 * nasty things such as a cacheable cookie.
2116 */
2117 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2118 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2119 (s->be->options & PR_O_CHK_CACHE)) {
2120 /* we're in presence of a cacheable response containing
2121 * a set-cookie header. We'll block it as requested by
2122 * the 'checkcache' option, and send an alert.
2123 */
2124 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002125 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126
Olivier Houcharda798bf52019-03-08 18:52:00 +01002127 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2128 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01002129 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002130 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002131
2132 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2133 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2134 send_log(s->be, LOG_ALERT,
2135 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2136 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2137 goto return_srv_prx_502;
2138 }
2139
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002140 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002141 /* Always enter in the body analyzer */
2142 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2143 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2144
2145 /* if the user wants to log as soon as possible, without counting
2146 * bytes from the server, then this is the right moment. We have
2147 * to temporarily assign bytes_out to log what we currently have.
2148 */
2149 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2150 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002151 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002152 s->do_log(s);
2153 s->logs.bytes_out = 0;
2154 }
2155 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002156
2157 return_bad_resp:
2158 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002159 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002160 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002161 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002162 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002163
2164 return_srv_prx_502:
2165 rep->analysers &= AN_RES_FLT_END;
2166 txn->status = 502;
2167 s->logs.t_data = -1; /* was not a valid response */
2168 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002169 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002170 if (!(s->flags & SF_ERR_MASK))
2171 s->flags |= SF_ERR_PRXCOND;
2172 if (!(s->flags & SF_FINST_MASK))
2173 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002174
2175 s->req.analysers &= AN_REQ_FLT_END;
2176 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002177 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002178}
2179
2180/* This function is an analyser which forwards response body (including chunk
2181 * sizes if any). It is called as soon as we must forward, even if we forward
2182 * zero byte. The only situation where it must not be called is when we're in
2183 * tunnel mode and we want to forward till the close. It's used both to forward
2184 * remaining data and to resync after end of body. It expects the msg_state to
2185 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2186 * read more data, or 1 once we can go on with next request or end the stream.
2187 *
2188 * It is capable of compressing response data both in content-length mode and
2189 * in chunked mode. The state machines follows different flows depending on
2190 * whether content-length and chunked modes are used, since there are no
2191 * trailers in content-length :
2192 *
2193 * chk-mode cl-mode
2194 * ,----- BODY -----.
2195 * / \
2196 * V size > 0 V chk-mode
2197 * .--> SIZE -------------> DATA -------------> CRLF
2198 * | | size == 0 | last byte |
2199 * | v final crlf v inspected |
2200 * | TRAILERS -----------> DONE |
2201 * | |
2202 * `----------------------------------------------'
2203 *
2204 * Compression only happens in the DATA state, and must be flushed in final
2205 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2206 * is performed at once on final states for all bytes parsed, or when leaving
2207 * on missing data.
2208 */
2209int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2210{
2211 struct session *sess = s->sess;
2212 struct http_txn *txn = s->txn;
2213 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002214 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002215 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002216
2217 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2218 now_ms, __FUNCTION__,
2219 s,
2220 res,
2221 res->rex, res->wex,
2222 res->flags,
2223 ci_data(res),
2224 res->analysers);
2225
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002226 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227
2228 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002229 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 /* Output closed while we were sending data. We must abort and
2231 * wake the other side up.
2232 */
2233 msg->err_state = msg->msg_state;
2234 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002235 htx_end_response(s);
2236 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 return 1;
2238 }
2239
Christopher Faulet9768c262018-10-22 09:34:31 +02002240 if (msg->msg_state == HTTP_MSG_BODY)
2241 msg->msg_state = HTTP_MSG_DATA;
2242
Christopher Faulete0768eb2018-10-03 16:38:02 +02002243 /* in most states, we should abort in case of early close */
2244 channel_auto_close(res);
2245
Christopher Faulete0768eb2018-10-03 16:38:02 +02002246 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002247 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002248 if (res->flags & CF_EOI)
2249 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002250 }
2251 else {
2252 /* We can't process the buffer's contents yet */
2253 res->flags |= CF_WAKE_WRITE;
2254 goto missing_data_or_waiting;
2255 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 }
2257
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002258 if (msg->msg_state >= HTTP_MSG_ENDING)
2259 goto ending;
2260
2261 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2262 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2263 msg->msg_state = HTTP_MSG_ENDING;
2264 goto ending;
2265 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002266
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002267 /* Forward input data. We get it by removing all outgoing data not
2268 * forwarded yet from HTX data size. If there are some data filters, we
2269 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002270 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002271 if (HAS_RSP_DATA_FILTERS(s)) {
2272 ret = flt_http_payload(s, msg, htx->data);
2273 if (ret < 0)
2274 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002275 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002276 }
2277 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002278 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002279 if (msg->flags & HTTP_MSGF_XFER_LEN)
2280 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002281 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002282
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002283 if (htx->data != co_data(res))
2284 goto missing_data_or_waiting;
2285
2286 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2287 msg->msg_state = HTTP_MSG_ENDING;
2288 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002289 }
2290
Christopher Faulet9768c262018-10-22 09:34:31 +02002291 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002292 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2293 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002294 */
2295 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2296 goto missing_data_or_waiting;
2297
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002298 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002299
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002300 ending:
2301 /* other states, ENDING...TUNNEL */
2302 if (msg->msg_state >= HTTP_MSG_DONE)
2303 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002304
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002305 if (HAS_RSP_DATA_FILTERS(s)) {
2306 ret = flt_http_end(s, msg);
2307 if (ret <= 0) {
2308 if (!ret)
2309 goto missing_data_or_waiting;
2310 goto return_bad_res;
2311 }
2312 }
2313
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002314 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2315 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2316 msg->msg_state = HTTP_MSG_TUNNEL;
2317 goto ending;
2318 }
2319 else {
2320 msg->msg_state = HTTP_MSG_DONE;
2321 res->to_forward = 0;
2322 }
2323
2324 done:
2325
2326 channel_dont_close(res);
2327
Christopher Fauletf2824e62018-10-01 12:12:37 +02002328 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002329 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002330 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2332 if (res->flags & CF_SHUTW) {
2333 /* response errors are most likely due to the
2334 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002335 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002336 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 goto return_bad_res;
2338 }
2339 return 1;
2340 }
2341 return 0;
2342
2343 missing_data_or_waiting:
2344 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002345 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002346
Christopher Faulet47365272018-10-31 17:40:50 +01002347 if (htx->flags & HTX_FL_PARSING_ERROR)
2348 goto return_bad_res;
2349
Christopher Faulete0768eb2018-10-03 16:38:02 +02002350 /* stop waiting for data if the input is closed before the end. If the
2351 * client side was already closed, it means that the client has aborted,
2352 * so we don't want to count this as a server abort. Otherwise it's a
2353 * server abort.
2354 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002355 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002356 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002357 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002359 if (htx_is_empty(htx))
2360 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002361 }
2362
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363 /* When TE: chunked is used, we need to get there again to parse
2364 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002365 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2366 * are filters registered on the stream, we don't want to forward a
2367 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002368 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002369 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002370 channel_dont_close(res);
2371
2372 /* We know that more data are expected, but we couldn't send more that
2373 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2374 * system knows it must not set a PUSH on this first part. Interactive
2375 * modes are already handled by the stream sock layer. We must not do
2376 * this in content-length mode because it could present the MSG_MORE
2377 * flag with the last block of forwarded data, which would cause an
2378 * additional delay to be observed by the receiver.
2379 */
2380 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2381 res->flags |= CF_EXPECT_MORE;
2382
2383 /* the stream handler will take care of timeouts and errors */
2384 return 0;
2385
Christopher Faulet93e02d82019-03-08 14:18:50 +01002386 return_srv_abort:
2387 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2388 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002389 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002390 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2391 if (!(s->flags & SF_ERR_MASK))
2392 s->flags |= SF_ERR_SRVCL;
2393 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002394
Christopher Faulet93e02d82019-03-08 14:18:50 +01002395 return_cli_abort:
2396 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2397 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002398 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002399 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2400 if (!(s->flags & SF_ERR_MASK))
2401 s->flags |= SF_ERR_CLICL;
2402 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002403
Christopher Faulet93e02d82019-03-08 14:18:50 +01002404 return_bad_res:
2405 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2406 if (objt_server(s->target)) {
2407 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2408 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2409 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002410 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002411 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002412
Christopher Faulet93e02d82019-03-08 14:18:50 +01002413 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002414 txn->rsp.err_state = txn->rsp.msg_state;
2415 txn->rsp.msg_state = HTTP_MSG_ERROR;
2416 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002417 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002418 res->analysers &= AN_RES_FLT_END;
2419 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 +02002420 if (!(s->flags & SF_FINST_MASK))
2421 s->flags |= SF_FINST_D;
2422 return 0;
2423}
2424
Christopher Fauletf2824e62018-10-01 12:12:37 +02002425/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002426 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427 * as too large a request to build a valid response.
2428 */
2429int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2430{
Christopher Faulet99daf282018-11-28 22:58:13 +01002431 struct channel *req = &s->req;
2432 struct channel *res = &s->res;
2433 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002434 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 struct ist status, reason, location;
2437 unsigned int flags;
2438 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002439 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002440
2441 chunk = alloc_trash_chunk();
2442 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 /*
2446 * Create the location
2447 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002448 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 case REDIRECT_TYPE_SCHEME: {
2451 struct http_hdr_ctx ctx;
2452 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453
Christopher Faulet99daf282018-11-28 22:58:13 +01002454 host = ist("");
2455 ctx.blk = NULL;
2456 if (http_find_header(htx, ist("Host"), &ctx, 0))
2457 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002458
Christopher Faulet297fbb42019-05-13 14:41:27 +02002459 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002460 path = http_get_path(htx_sl_req_uri(sl));
2461 /* build message using path */
2462 if (path.ptr) {
2463 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2464 int qs = 0;
2465 while (qs < path.len) {
2466 if (*(path.ptr + qs) == '?') {
2467 path.len = qs;
2468 break;
2469 }
2470 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472 }
2473 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 else
2475 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002476
Christopher Faulet99daf282018-11-28 22:58:13 +01002477 if (rule->rdr_str) { /* this is an old "redirect" rule */
2478 /* add scheme */
2479 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2480 goto fail;
2481 }
2482 else {
2483 /* add scheme with executing log format */
2484 chunk->data += build_logline(s, chunk->area + chunk->data,
2485 chunk->size - chunk->data,
2486 &rule->rdr_fmt);
2487 }
2488 /* add "://" + host + path */
2489 if (!chunk_memcat(chunk, "://", 3) ||
2490 !chunk_memcat(chunk, host.ptr, host.len) ||
2491 !chunk_memcat(chunk, path.ptr, path.len))
2492 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 /* append a slash at the end of the location if needed and missing */
2495 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2496 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2497 if (chunk->data + 1 >= chunk->size)
2498 goto fail;
2499 chunk->area[chunk->data++] = '/';
2500 }
2501 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002503
Christopher Faulet99daf282018-11-28 22:58:13 +01002504 case REDIRECT_TYPE_PREFIX: {
2505 struct ist path;
2506
Christopher Faulet297fbb42019-05-13 14:41:27 +02002507 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002508 path = http_get_path(htx_sl_req_uri(sl));
2509 /* build message using path */
2510 if (path.ptr) {
2511 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2512 int qs = 0;
2513 while (qs < path.len) {
2514 if (*(path.ptr + qs) == '?') {
2515 path.len = qs;
2516 break;
2517 }
2518 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002519 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002520 }
2521 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002522 else
2523 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002524
Christopher Faulet99daf282018-11-28 22:58:13 +01002525 if (rule->rdr_str) { /* this is an old "redirect" rule */
2526 /* add prefix. Note that if prefix == "/", we don't want to
2527 * add anything, otherwise it makes it hard for the user to
2528 * configure a self-redirection.
2529 */
2530 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2531 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2532 goto fail;
2533 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002534 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002535 else {
2536 /* add prefix with executing log format */
2537 chunk->data += build_logline(s, chunk->area + chunk->data,
2538 chunk->size - chunk->data,
2539 &rule->rdr_fmt);
2540 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002541
Christopher Faulet99daf282018-11-28 22:58:13 +01002542 /* add path */
2543 if (!chunk_memcat(chunk, path.ptr, path.len))
2544 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002545
Christopher Faulet99daf282018-11-28 22:58:13 +01002546 /* append a slash at the end of the location if needed and missing */
2547 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2548 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2549 if (chunk->data + 1 >= chunk->size)
2550 goto fail;
2551 chunk->area[chunk->data++] = '/';
2552 }
2553 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002554 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002555 case REDIRECT_TYPE_LOCATION:
2556 default:
2557 if (rule->rdr_str) { /* this is an old "redirect" rule */
2558 /* add location */
2559 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2560 goto fail;
2561 }
2562 else {
2563 /* add location with executing log format */
2564 chunk->data += build_logline(s, chunk->area + chunk->data,
2565 chunk->size - chunk->data,
2566 &rule->rdr_fmt);
2567 }
2568 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002569 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002570 location = ist2(chunk->area, chunk->data);
2571
2572 /*
2573 * Create the 30x response
2574 */
2575 switch (rule->code) {
2576 case 308:
2577 status = ist("308");
2578 reason = ist("Permanent Redirect");
2579 break;
2580 case 307:
2581 status = ist("307");
2582 reason = ist("Temporary Redirect");
2583 break;
2584 case 303:
2585 status = ist("303");
2586 reason = ist("See Other");
2587 break;
2588 case 301:
2589 status = ist("301");
2590 reason = ist("Moved Permanently");
2591 break;
2592 case 302:
2593 default:
2594 status = ist("302");
2595 reason = ist("Found");
2596 break;
2597 }
2598
Christopher Faulet08e66462019-05-23 16:44:59 +02002599 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2600 close = 1;
2601
Christopher Faulet99daf282018-11-28 22:58:13 +01002602 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002603 /* Trim any possible response */
2604 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002605 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2606 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2607 if (!sl)
2608 goto fail;
2609 sl->info.res.status = rule->code;
2610 s->txn->status = rule->code;
2611
Christopher Faulet08e66462019-05-23 16:44:59 +02002612 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2613 goto fail;
2614
2615 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002616 !htx_add_header(htx, ist("Location"), location))
2617 goto fail;
2618
2619 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2620 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2621 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002622 }
2623
2624 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002625 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2626 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002627 }
2628
Christopher Faulet99daf282018-11-28 22:58:13 +01002629 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2630 goto fail;
2631
Kevin Zhu0fd70882020-01-07 09:42:55 +01002632 htx_to_buf(htx, &res->buf);
2633
Christopher Faulet99daf282018-11-28 22:58:13 +01002634 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002635 c_adv(res, data);
2636 res->total += data;
2637
2638 channel_auto_read(req);
2639 channel_abort(req);
2640 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002641 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002642
2643 res->wex = tick_add_ifset(now_ms, res->wto);
2644 channel_auto_read(res);
2645 channel_auto_close(res);
2646 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002647 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2648 /* let's log the request time */
2649 s->logs.tv_request = now;
2650 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002651
Christopher Faulet7d84db32020-01-28 09:18:10 +01002652 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2653 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2654 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002655
2656 if (!(s->flags & SF_ERR_MASK))
2657 s->flags |= SF_ERR_LOCAL;
2658 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002659 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002660
Christopher Faulet99daf282018-11-28 22:58:13 +01002661 free_trash_chunk(chunk);
2662 return 1;
2663
2664 fail:
2665 /* If an error occurred, remove the incomplete HTTP response from the
2666 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002667 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002668 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002669 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002670}
2671
Christopher Faulet72333522018-10-24 11:25:02 +02002672int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2673 struct ist name, const char *str, struct my_regex *re, int action)
2674{
2675 struct http_hdr_ctx ctx;
2676 struct buffer *output = get_trash_chunk();
2677
2678 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2679 ctx.blk = NULL;
2680 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2681 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2682 continue;
2683
2684 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2685 if (output->data == -1)
2686 return -1;
2687 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2688 return -1;
2689 }
2690 return 0;
2691}
2692
2693static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2694 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2695{
2696 struct buffer *replace;
2697 int ret = -1;
2698
2699 replace = alloc_trash_chunk();
2700 if (!replace)
2701 goto leave;
2702
2703 replace->data = build_logline(s, replace->area, replace->size, fmt);
2704 if (replace->data >= replace->size - 1)
2705 goto leave;
2706
2707 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2708
2709 leave:
2710 free_trash_chunk(replace);
2711 return ret;
2712}
2713
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002714
2715/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2716 * on success and -1 on error. The response channel is updated accordingly.
2717 */
2718static int htx_reply_103_early_hints(struct channel *res)
2719{
2720 struct htx *htx = htx_from_buf(&res->buf);
2721 size_t data;
2722
Christopher Faulet9869f932019-06-26 14:23:54 +02002723 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002724 /* If an error occurred during an Early-hint rule,
2725 * remove the incomplete HTTP 103 response from the
2726 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002727 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002728 return -1;
2729 }
2730
2731 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002732 c_adv(res, data);
2733 res->total += data;
2734 return 0;
2735}
2736
Christopher Faulet6eb92892018-11-15 16:39:29 +01002737/*
2738 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2739 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002740 * If <early_hints> is 0, it is starts a new response by adding the start
2741 * line. If an error occurred -1 is returned. On success 0 is returned. The
2742 * channel is not updated here. It must be done calling the function
2743 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002744 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002745static 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 +01002746{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002747 struct channel *res = &s->res;
2748 struct htx *htx = htx_from_buf(&res->buf);
2749 struct buffer *value = alloc_trash_chunk();
2750
Christopher Faulet6eb92892018-11-15 16:39:29 +01002751 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002752 struct htx_sl *sl;
2753 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2754 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2755
2756 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2757 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2758 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002759 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002760 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002761 }
2762
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002763 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2764 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002765 goto fail;
2766
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002767 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002768 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002769
2770 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002771 /* If an error occurred during an Early-hint rule, remove the incomplete
2772 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002773 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002774 free_trash_chunk(value);
2775 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002776}
2777
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002778/* This function executes one of the set-{method,path,query,uri} actions. It
2779 * takes the string from the variable 'replace' with length 'len', then modifies
2780 * the relevant part of the request line accordingly. Then it updates various
2781 * pointers to the next elements which were moved, and the total buffer length.
2782 * It finds the action to be performed in p[2], previously filled by function
2783 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2784 * error, though this can be revisited when this code is finally exploited.
2785 *
2786 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2787 * query string and 3 to replace uri.
2788 *
2789 * In query string case, the mark question '?' must be set at the start of the
2790 * string by the caller, event if the replacement query string is empty.
2791 */
2792int htx_req_replace_stline(int action, const char *replace, int len,
2793 struct proxy *px, struct stream *s)
2794{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002795 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002796
2797 switch (action) {
2798 case 0: // method
2799 if (!http_replace_req_meth(htx, ist2(replace, len)))
2800 return -1;
2801 break;
2802
2803 case 1: // path
2804 if (!http_replace_req_path(htx, ist2(replace, len)))
2805 return -1;
2806 break;
2807
2808 case 2: // query
2809 if (!http_replace_req_query(htx, ist2(replace, len)))
2810 return -1;
2811 break;
2812
2813 case 3: // uri
2814 if (!http_replace_req_uri(htx, ist2(replace, len)))
2815 return -1;
2816 break;
2817
2818 default:
2819 return -1;
2820 }
2821 return 0;
2822}
2823
2824/* This function replace the HTTP status code and the associated message. The
2825 * variable <status> contains the new status code. This function never fails.
2826 */
2827void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2828{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002829 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002830 char *res;
2831
2832 chunk_reset(&trash);
2833 res = ultoa_o(status, trash.area, trash.size);
2834 trash.data = res - trash.area;
2835
2836 /* Do we have a custom reason format string? */
2837 if (reason == NULL)
2838 reason = http_get_reason(status);
2839
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002840 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002841 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2842}
2843
Christopher Faulet3e964192018-10-24 11:39:23 +02002844/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2845 * transaction <txn>. Returns the verdict of the first rule that prevents
2846 * further processing of the request (auth, deny, ...), and defaults to
2847 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2848 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2849 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2850 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2851 * status.
2852 */
2853static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2854 struct stream *s, int *deny_status)
2855{
2856 struct session *sess = strm_sess(s);
2857 struct http_txn *txn = s->txn;
2858 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002859 struct act_rule *rule;
2860 struct http_hdr_ctx ctx;
2861 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2863 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002864 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002865
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002866 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002867
2868 /* If "the current_rule_list" match the executed rule list, we are in
2869 * resume condition. If a resume is needed it is always in the action
2870 * and never in the ACL or converters. In this case, we initialise the
2871 * current rule, and go to the action execution point.
2872 */
2873 if (s->current_rule) {
2874 rule = s->current_rule;
2875 s->current_rule = NULL;
2876 if (s->current_rule_list == rules)
2877 goto resume_execution;
2878 }
2879 s->current_rule_list = rules;
2880
2881 list_for_each_entry(rule, rules, list) {
2882 /* check optional condition */
2883 if (rule->cond) {
2884 int ret;
2885
2886 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2887 ret = acl_pass(ret);
2888
2889 if (rule->cond->pol == ACL_COND_UNLESS)
2890 ret = !ret;
2891
2892 if (!ret) /* condition not matched */
2893 continue;
2894 }
2895
2896 act_flags |= ACT_FLAG_FIRST;
2897 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002898 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2899 early_hints = 0;
2900 if (htx_reply_103_early_hints(&s->res) == -1) {
2901 rule_ret = HTTP_RULE_RES_BADREQ;
2902 goto end;
2903 }
2904 }
2905
Christopher Faulet3e964192018-10-24 11:39:23 +02002906 switch (rule->action) {
2907 case ACT_ACTION_ALLOW:
2908 rule_ret = HTTP_RULE_RES_STOP;
2909 goto end;
2910
2911 case ACT_ACTION_DENY:
2912 if (deny_status)
2913 *deny_status = rule->deny_status;
2914 rule_ret = HTTP_RULE_RES_DENY;
2915 goto end;
2916
2917 case ACT_HTTP_REQ_TARPIT:
2918 txn->flags |= TX_CLTARPIT;
2919 if (deny_status)
2920 *deny_status = rule->deny_status;
2921 rule_ret = HTTP_RULE_RES_DENY;
2922 goto end;
2923
2924 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002925 /* Auth might be performed on regular http-req rules as well as on stats */
2926 auth_realm = rule->arg.auth.realm;
2927 if (!auth_realm) {
2928 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2929 auth_realm = STATS_DEFAULT_REALM;
2930 else
2931 auth_realm = px->id;
2932 }
2933 /* send 401/407 depending on whether we use a proxy or not. We still
2934 * count one error, because normal browsing won't significantly
2935 * increase the counter but brute force attempts will.
2936 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002937 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002938 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2939 rule_ret = HTTP_RULE_RES_BADREQ;
2940 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002941 goto end;
2942
2943 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 rule_ret = HTTP_RULE_RES_DONE;
2945 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2946 rule_ret = HTTP_RULE_RES_BADREQ;
2947 goto end;
2948
2949 case ACT_HTTP_SET_NICE:
2950 s->task->nice = rule->arg.nice;
2951 break;
2952
2953 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002954 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002955 break;
2956
2957 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002958 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002959 break;
2960
2961 case ACT_HTTP_SET_LOGL:
2962 s->logs.level = rule->arg.loglevel;
2963 break;
2964
2965 case ACT_HTTP_REPLACE_HDR:
2966 case ACT_HTTP_REPLACE_VAL:
2967 if (htx_transform_header(s, &s->req, htx,
2968 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2969 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002970 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002971 rule_ret = HTTP_RULE_RES_BADREQ;
2972 goto end;
2973 }
2974 break;
2975
2976 case ACT_HTTP_DEL_HDR:
2977 /* remove all occurrences of the header */
2978 ctx.blk = NULL;
2979 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2980 http_remove_header(htx, &ctx);
2981 break;
2982
2983 case ACT_HTTP_SET_HDR:
2984 case ACT_HTTP_ADD_HDR: {
2985 /* The scope of the trash buffer must be limited to this function. The
2986 * build_logline() function can execute a lot of other function which
2987 * can use the trash buffer. So for limiting the scope of this global
2988 * buffer, we build first the header value using build_logline, and
2989 * after we store the header name.
2990 */
2991 struct buffer *replace;
2992 struct ist n, v;
2993
2994 replace = alloc_trash_chunk();
2995 if (!replace) {
2996 rule_ret = HTTP_RULE_RES_BADREQ;
2997 goto end;
2998 }
2999
3000 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3001 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3002 v = ist2(replace->area, replace->data);
3003
3004 if (rule->action == ACT_HTTP_SET_HDR) {
3005 /* remove all occurrences of the header */
3006 ctx.blk = NULL;
3007 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3008 http_remove_header(htx, &ctx);
3009 }
3010
3011 if (!http_add_header(htx, n, v)) {
3012 static unsigned char rate_limit = 0;
3013
3014 if ((rate_limit++ & 255) == 0) {
3015 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);
3016 }
3017
Olivier Houcharda798bf52019-03-08 18:52:00 +01003018 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003019 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003020 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003021 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003022 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003023 }
3024 free_trash_chunk(replace);
3025 break;
3026 }
3027
3028 case ACT_HTTP_DEL_ACL:
3029 case ACT_HTTP_DEL_MAP: {
3030 struct pat_ref *ref;
3031 struct buffer *key;
3032
3033 /* collect reference */
3034 ref = pat_ref_lookup(rule->arg.map.ref);
3035 if (!ref)
3036 continue;
3037
3038 /* allocate key */
3039 key = alloc_trash_chunk();
3040 if (!key) {
3041 rule_ret = HTTP_RULE_RES_BADREQ;
3042 goto end;
3043 }
3044
3045 /* collect key */
3046 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3047 key->area[key->data] = '\0';
3048
3049 /* perform update */
3050 /* returned code: 1=ok, 0=ko */
3051 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3052 pat_ref_delete(ref, key->area);
3053 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3054
3055 free_trash_chunk(key);
3056 break;
3057 }
3058
3059 case ACT_HTTP_ADD_ACL: {
3060 struct pat_ref *ref;
3061 struct buffer *key;
3062
3063 /* collect reference */
3064 ref = pat_ref_lookup(rule->arg.map.ref);
3065 if (!ref)
3066 continue;
3067
3068 /* allocate key */
3069 key = alloc_trash_chunk();
3070 if (!key) {
3071 rule_ret = HTTP_RULE_RES_BADREQ;
3072 goto end;
3073 }
3074
3075 /* collect key */
3076 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3077 key->area[key->data] = '\0';
3078
3079 /* perform update */
3080 /* add entry only if it does not already exist */
3081 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3082 if (pat_ref_find_elt(ref, key->area) == NULL)
3083 pat_ref_add(ref, key->area, NULL, NULL);
3084 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3085
3086 free_trash_chunk(key);
3087 break;
3088 }
3089
3090 case ACT_HTTP_SET_MAP: {
3091 struct pat_ref *ref;
3092 struct buffer *key, *value;
3093
3094 /* collect reference */
3095 ref = pat_ref_lookup(rule->arg.map.ref);
3096 if (!ref)
3097 continue;
3098
3099 /* allocate key */
3100 key = alloc_trash_chunk();
3101 if (!key) {
3102 rule_ret = HTTP_RULE_RES_BADREQ;
3103 goto end;
3104 }
3105
3106 /* allocate value */
3107 value = alloc_trash_chunk();
3108 if (!value) {
3109 free_trash_chunk(key);
3110 rule_ret = HTTP_RULE_RES_BADREQ;
3111 goto end;
3112 }
3113
3114 /* collect key */
3115 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3116 key->area[key->data] = '\0';
3117
3118 /* collect value */
3119 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3120 value->area[value->data] = '\0';
3121
3122 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003123 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003124 if (pat_ref_find_elt(ref, key->area) != NULL)
3125 /* update entry if it exists */
3126 pat_ref_set(ref, key->area, value->area, NULL);
3127 else
3128 /* insert a new entry */
3129 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003130 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003131 free_trash_chunk(key);
3132 free_trash_chunk(value);
3133 break;
3134 }
3135
3136 case ACT_HTTP_EARLY_HINT:
3137 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3138 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003139 early_hints = htx_add_early_hint_header(s, early_hints,
3140 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003141 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003142 if (early_hints == -1) {
3143 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003144 goto end;
3145 }
3146 break;
3147
3148 case ACT_CUSTOM:
3149 if ((s->req.flags & CF_READ_ERROR) ||
3150 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003151 (px->options & PR_O_ABRT_CLOSE)))
3152 act_flags |= ACT_FLAG_FINAL;
3153
3154 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3155 case ACT_RET_ERR:
3156 case ACT_RET_CONT:
3157 break;
3158 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003159 rule_ret = HTTP_RULE_RES_STOP;
3160 goto end;
3161 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003162 rule_ret = HTTP_RULE_RES_DONE;
3163 goto end;
3164 case ACT_RET_YIELD:
3165 s->current_rule = rule;
3166 rule_ret = HTTP_RULE_RES_YIELD;
3167 goto end;
3168 }
3169 break;
3170
3171 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3172 /* Note: only the first valid tracking parameter of each
3173 * applies.
3174 */
3175
3176 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3177 struct stktable *t;
3178 struct stksess *ts;
3179 struct stktable_key *key;
3180 void *ptr1, *ptr2;
3181
3182 t = rule->arg.trk_ctr.table.t;
3183 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3184 rule->arg.trk_ctr.expr, NULL);
3185
3186 if (key && (ts = stktable_get_entry(t, key))) {
3187 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3188
3189 /* let's count a new HTTP request as it's the first time we do it */
3190 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3191 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3192 if (ptr1 || ptr2) {
3193 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3194
3195 if (ptr1)
3196 stktable_data_cast(ptr1, http_req_cnt)++;
3197
3198 if (ptr2)
3199 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3200 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3201
3202 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3203
3204 /* If data was modified, we need to touch to re-schedule sync */
3205 stktable_touch_local(t, ts, 0);
3206 }
3207
3208 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3209 if (sess->fe != s->be)
3210 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3211 }
3212 }
3213 break;
3214
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003215 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003216 default:
3217 break;
3218 }
3219 }
3220
3221 end:
3222 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003223 if (htx_reply_103_early_hints(&s->res) == -1)
3224 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003225 }
3226
3227 /* we reached the end of the rules, nothing to report */
3228 return rule_ret;
3229}
3230
3231/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3232 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3233 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3234 * is returned, the process can continue the evaluation of next rule list. If
3235 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3236 * is returned, it means the operation could not be processed and a server error
3237 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3238 * deny rule. If *YIELD is returned, the caller must call again the function
3239 * with the same context.
3240 */
3241static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3242 struct stream *s)
3243{
3244 struct session *sess = strm_sess(s);
3245 struct http_txn *txn = s->txn;
3246 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003247 struct act_rule *rule;
3248 struct http_hdr_ctx ctx;
3249 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3250 int act_flags = 0;
3251
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003252 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003253
3254 /* If "the current_rule_list" match the executed rule list, we are in
3255 * resume condition. If a resume is needed it is always in the action
3256 * and never in the ACL or converters. In this case, we initialise the
3257 * current rule, and go to the action execution point.
3258 */
3259 if (s->current_rule) {
3260 rule = s->current_rule;
3261 s->current_rule = NULL;
3262 if (s->current_rule_list == rules)
3263 goto resume_execution;
3264 }
3265 s->current_rule_list = rules;
3266
3267 list_for_each_entry(rule, rules, list) {
3268 /* check optional condition */
3269 if (rule->cond) {
3270 int ret;
3271
3272 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3273 ret = acl_pass(ret);
3274
3275 if (rule->cond->pol == ACL_COND_UNLESS)
3276 ret = !ret;
3277
3278 if (!ret) /* condition not matched */
3279 continue;
3280 }
3281
3282 act_flags |= ACT_FLAG_FIRST;
3283resume_execution:
3284 switch (rule->action) {
3285 case ACT_ACTION_ALLOW:
3286 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3287 goto end;
3288
3289 case ACT_ACTION_DENY:
3290 txn->flags |= TX_SVDENY;
3291 rule_ret = HTTP_RULE_RES_STOP;
3292 goto end;
3293
3294 case ACT_HTTP_SET_NICE:
3295 s->task->nice = rule->arg.nice;
3296 break;
3297
3298 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003299 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003300 break;
3301
3302 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003303 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003304 break;
3305
3306 case ACT_HTTP_SET_LOGL:
3307 s->logs.level = rule->arg.loglevel;
3308 break;
3309
3310 case ACT_HTTP_REPLACE_HDR:
3311 case ACT_HTTP_REPLACE_VAL:
3312 if (htx_transform_header(s, &s->res, htx,
3313 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3314 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003315 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003316 rule_ret = HTTP_RULE_RES_BADREQ;
3317 goto end;
3318 }
3319 break;
3320
3321 case ACT_HTTP_DEL_HDR:
3322 /* remove all occurrences of the header */
3323 ctx.blk = NULL;
3324 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3325 http_remove_header(htx, &ctx);
3326 break;
3327
3328 case ACT_HTTP_SET_HDR:
3329 case ACT_HTTP_ADD_HDR: {
3330 struct buffer *replace;
3331 struct ist n, v;
3332
3333 replace = alloc_trash_chunk();
3334 if (!replace) {
3335 rule_ret = HTTP_RULE_RES_BADREQ;
3336 goto end;
3337 }
3338
3339 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3340 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3341 v = ist2(replace->area, replace->data);
3342
3343 if (rule->action == ACT_HTTP_SET_HDR) {
3344 /* remove all occurrences of the header */
3345 ctx.blk = NULL;
3346 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3347 http_remove_header(htx, &ctx);
3348 }
3349
3350 if (!http_add_header(htx, n, v)) {
3351 static unsigned char rate_limit = 0;
3352
3353 if ((rate_limit++ & 255) == 0) {
3354 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);
3355 }
3356
Olivier Houcharda798bf52019-03-08 18:52:00 +01003357 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003358 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003359 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
William Lallemanddb9fd042021-03-08 15:26:48 +01003360 if (sess->listener && sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003361 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003362 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003363 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003364 }
3365 free_trash_chunk(replace);
3366 break;
3367 }
3368
3369 case ACT_HTTP_DEL_ACL:
3370 case ACT_HTTP_DEL_MAP: {
3371 struct pat_ref *ref;
3372 struct buffer *key;
3373
3374 /* collect reference */
3375 ref = pat_ref_lookup(rule->arg.map.ref);
3376 if (!ref)
3377 continue;
3378
3379 /* allocate key */
3380 key = alloc_trash_chunk();
3381 if (!key) {
3382 rule_ret = HTTP_RULE_RES_BADREQ;
3383 goto end;
3384 }
3385
3386 /* collect key */
3387 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3388 key->area[key->data] = '\0';
3389
3390 /* perform update */
3391 /* returned code: 1=ok, 0=ko */
3392 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3393 pat_ref_delete(ref, key->area);
3394 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3395
3396 free_trash_chunk(key);
3397 break;
3398 }
3399
3400 case ACT_HTTP_ADD_ACL: {
3401 struct pat_ref *ref;
3402 struct buffer *key;
3403
3404 /* collect reference */
3405 ref = pat_ref_lookup(rule->arg.map.ref);
3406 if (!ref)
3407 continue;
3408
3409 /* allocate key */
3410 key = alloc_trash_chunk();
3411 if (!key) {
3412 rule_ret = HTTP_RULE_RES_BADREQ;
3413 goto end;
3414 }
3415
3416 /* collect key */
3417 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3418 key->area[key->data] = '\0';
3419
3420 /* perform update */
3421 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003422 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003423 if (pat_ref_find_elt(ref, key->area) == NULL)
3424 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003425 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003426 free_trash_chunk(key);
3427 break;
3428 }
3429
3430 case ACT_HTTP_SET_MAP: {
3431 struct pat_ref *ref;
3432 struct buffer *key, *value;
3433
3434 /* collect reference */
3435 ref = pat_ref_lookup(rule->arg.map.ref);
3436 if (!ref)
3437 continue;
3438
3439 /* allocate key */
3440 key = alloc_trash_chunk();
3441 if (!key) {
3442 rule_ret = HTTP_RULE_RES_BADREQ;
3443 goto end;
3444 }
3445
3446 /* allocate value */
3447 value = alloc_trash_chunk();
3448 if (!value) {
3449 free_trash_chunk(key);
3450 rule_ret = HTTP_RULE_RES_BADREQ;
3451 goto end;
3452 }
3453
3454 /* collect key */
3455 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3456 key->area[key->data] = '\0';
3457
3458 /* collect value */
3459 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3460 value->area[value->data] = '\0';
3461
3462 /* perform update */
3463 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3464 if (pat_ref_find_elt(ref, key->area) != NULL)
3465 /* update entry if it exists */
3466 pat_ref_set(ref, key->area, value->area, NULL);
3467 else
3468 /* insert a new entry */
3469 pat_ref_add(ref, key->area, value->area, NULL);
3470 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3471 free_trash_chunk(key);
3472 free_trash_chunk(value);
3473 break;
3474 }
3475
3476 case ACT_HTTP_REDIR:
3477 rule_ret = HTTP_RULE_RES_DONE;
3478 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3479 rule_ret = HTTP_RULE_RES_BADREQ;
3480 goto end;
3481
3482 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3483 /* Note: only the first valid tracking parameter of each
3484 * applies.
3485 */
3486 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3487 struct stktable *t;
3488 struct stksess *ts;
3489 struct stktable_key *key;
3490 void *ptr;
3491
3492 t = rule->arg.trk_ctr.table.t;
3493 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3494 rule->arg.trk_ctr.expr, NULL);
3495
3496 if (key && (ts = stktable_get_entry(t, key))) {
3497 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3498
3499 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3500
3501 /* let's count a new HTTP request as it's the first time we do it */
3502 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3503 if (ptr)
3504 stktable_data_cast(ptr, http_req_cnt)++;
3505
3506 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3507 if (ptr)
3508 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3509 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3510
3511 /* When the client triggers a 4xx from the server, it's most often due
3512 * to a missing object or permission. These events should be tracked
3513 * because if they happen often, it may indicate a brute force or a
3514 * vulnerability scan. Normally this is done when receiving the response
3515 * but here we're tracking after this ought to have been done so we have
3516 * to do it on purpose.
3517 */
3518 if ((unsigned)(txn->status - 400) < 100) {
3519 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3520 if (ptr)
3521 stktable_data_cast(ptr, http_err_cnt)++;
3522
3523 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3524 if (ptr)
3525 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3526 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3527 }
3528
3529 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3530
3531 /* If data was modified, we need to touch to re-schedule sync */
3532 stktable_touch_local(t, ts, 0);
3533
3534 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3535 if (sess->fe != s->be)
3536 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3537 }
3538 }
3539 break;
3540
3541 case ACT_CUSTOM:
3542 if ((s->req.flags & CF_READ_ERROR) ||
3543 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003544 (px->options & PR_O_ABRT_CLOSE)))
3545 act_flags |= ACT_FLAG_FINAL;
3546
3547 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3548 case ACT_RET_ERR:
3549 case ACT_RET_CONT:
3550 break;
3551 case ACT_RET_STOP:
3552 rule_ret = HTTP_RULE_RES_STOP;
3553 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003554 case ACT_RET_DONE:
3555 rule_ret = HTTP_RULE_RES_DONE;
3556 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003557 case ACT_RET_YIELD:
3558 s->current_rule = rule;
3559 rule_ret = HTTP_RULE_RES_YIELD;
3560 goto end;
3561 }
3562 break;
3563
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003564 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003565 default:
3566 break;
3567 }
3568 }
3569
3570 end:
3571 /* we reached the end of the rules, nothing to report */
3572 return rule_ret;
3573}
3574
Christopher Faulet33640082018-10-24 11:53:01 +02003575/* Iterate the same filter through all request headers.
3576 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3577 * Since it can manage the switch to another backend, it updates the per-proxy
3578 * DENY stats.
3579 */
3580static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3581{
3582 struct http_txn *txn = s->txn;
3583 struct htx *htx;
3584 struct buffer *hdr = get_trash_chunk();
3585 int32_t pos;
3586
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003587 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003588
Christopher Fauleta3f15502019-05-13 15:27:23 +02003589 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003590 struct htx_blk *blk = htx_get_blk(htx, pos);
3591 enum htx_blk_type type;
3592 struct ist n, v;
3593
3594 next_hdr:
3595 type = htx_get_blk_type(blk);
3596 if (type == HTX_BLK_EOH)
3597 break;
3598 if (type != HTX_BLK_HDR)
3599 continue;
3600
3601 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3602 return 1;
3603 else if (unlikely(txn->flags & TX_CLALLOW) &&
3604 (exp->action == ACT_ALLOW ||
3605 exp->action == ACT_DENY ||
3606 exp->action == ACT_TARPIT))
3607 return 0;
3608
3609 n = htx_get_blk_name(htx, blk);
3610 v = htx_get_blk_value(htx, blk);
3611
Christopher Faulet02e771a2019-02-26 15:36:05 +01003612 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003613 hdr->area[hdr->data++] = ':';
3614 hdr->area[hdr->data++] = ' ';
3615 chunk_memcat(hdr, v.ptr, v.len);
3616
3617 /* Now we have one header in <hdr> */
3618
3619 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3620 struct http_hdr_ctx ctx;
3621 int len;
3622
3623 switch (exp->action) {
3624 case ACT_ALLOW:
3625 txn->flags |= TX_CLALLOW;
3626 goto end;
3627
3628 case ACT_DENY:
3629 txn->flags |= TX_CLDENY;
3630 goto end;
3631
3632 case ACT_TARPIT:
3633 txn->flags |= TX_CLTARPIT;
3634 goto end;
3635
3636 case ACT_REPLACE:
3637 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3638 if (len < 0)
3639 return -1;
3640
3641 http_parse_header(ist2(trash.area, len), &n, &v);
3642 ctx.blk = blk;
3643 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003644 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003645 if (!http_replace_header(htx, &ctx, n, v))
3646 return -1;
3647 if (!ctx.blk)
3648 goto end;
3649 pos = htx_get_blk_pos(htx, blk);
3650 break;
3651
3652 case ACT_REMOVE:
3653 ctx.blk = blk;
3654 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003655 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003656 if (!http_remove_header(htx, &ctx))
3657 return -1;
3658 if (!ctx.blk)
3659 goto end;
3660 pos = htx_get_blk_pos(htx, blk);
3661 goto next_hdr;
3662
3663 }
3664 }
3665 }
3666 end:
3667 return 0;
3668}
3669
3670/* Apply the filter to the request line.
3671 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3672 * or -1 if a replacement resulted in an invalid request line.
3673 * Since it can manage the switch to another backend, it updates the per-proxy
3674 * DENY stats.
3675 */
3676static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3677{
3678 struct http_txn *txn = s->txn;
3679 struct htx *htx;
3680 struct buffer *reqline = get_trash_chunk();
3681 int done;
3682
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003683 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003684
3685 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3686 return 1;
3687 else if (unlikely(txn->flags & TX_CLALLOW) &&
3688 (exp->action == ACT_ALLOW ||
3689 exp->action == ACT_DENY ||
3690 exp->action == ACT_TARPIT))
3691 return 0;
3692 else if (exp->action == ACT_REMOVE)
3693 return 0;
3694
3695 done = 0;
3696
Christopher Faulet297fbb42019-05-13 14:41:27 +02003697 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003698
3699 /* Now we have the request line between cur_ptr and cur_end */
3700 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003701 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003702 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003703 int len;
3704
3705 switch (exp->action) {
3706 case ACT_ALLOW:
3707 txn->flags |= TX_CLALLOW;
3708 done = 1;
3709 break;
3710
3711 case ACT_DENY:
3712 txn->flags |= TX_CLDENY;
3713 done = 1;
3714 break;
3715
3716 case ACT_TARPIT:
3717 txn->flags |= TX_CLTARPIT;
3718 done = 1;
3719 break;
3720
3721 case ACT_REPLACE:
3722 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3723 if (len < 0)
3724 return -1;
3725
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003726 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3727 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3728 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003729 return -1;
3730 done = 1;
3731 break;
3732 }
3733 }
3734 return done;
3735}
3736
3737/*
3738 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3739 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3740 * unparsable request. Since it can manage the switch to another backend, it
3741 * updates the per-proxy DENY stats.
3742 */
3743static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3744{
3745 struct session *sess = s->sess;
3746 struct http_txn *txn = s->txn;
3747 struct hdr_exp *exp;
3748
3749 for (exp = px->req_exp; exp; exp = exp->next) {
3750 int ret;
3751
3752 /*
3753 * The interleaving of transformations and verdicts
3754 * makes it difficult to decide to continue or stop
3755 * the evaluation.
3756 */
3757
3758 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3759 break;
3760
3761 if ((txn->flags & TX_CLALLOW) &&
3762 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3763 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3764 continue;
3765
3766 /* if this filter had a condition, evaluate it now and skip to
3767 * next filter if the condition does not match.
3768 */
3769 if (exp->cond) {
3770 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3771 ret = acl_pass(ret);
3772 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3773 ret = !ret;
3774
3775 if (!ret)
3776 continue;
3777 }
3778
3779 /* Apply the filter to the request line. */
3780 ret = htx_apply_filter_to_req_line(s, req, exp);
3781 if (unlikely(ret < 0))
3782 return -1;
3783
3784 if (likely(ret == 0)) {
3785 /* The filter did not match the request, it can be
3786 * iterated through all headers.
3787 */
3788 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3789 return -1;
3790 }
3791 }
3792 return 0;
3793}
3794
3795/* Iterate the same filter through all response headers contained in <res>.
3796 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3797 */
3798static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3799{
3800 struct http_txn *txn = s->txn;
3801 struct htx *htx;
3802 struct buffer *hdr = get_trash_chunk();
3803 int32_t pos;
3804
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003805 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003806
Christopher Fauleta3f15502019-05-13 15:27:23 +02003807 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003808 struct htx_blk *blk = htx_get_blk(htx, pos);
3809 enum htx_blk_type type;
3810 struct ist n, v;
3811
3812 next_hdr:
3813 type = htx_get_blk_type(blk);
3814 if (type == HTX_BLK_EOH)
3815 break;
3816 if (type != HTX_BLK_HDR)
3817 continue;
3818
3819 if (unlikely(txn->flags & TX_SVDENY))
3820 return 1;
3821 else if (unlikely(txn->flags & TX_SVALLOW) &&
3822 (exp->action == ACT_ALLOW ||
3823 exp->action == ACT_DENY))
3824 return 0;
3825
3826 n = htx_get_blk_name(htx, blk);
3827 v = htx_get_blk_value(htx, blk);
3828
Christopher Faulet02e771a2019-02-26 15:36:05 +01003829 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003830 hdr->area[hdr->data++] = ':';
3831 hdr->area[hdr->data++] = ' ';
3832 chunk_memcat(hdr, v.ptr, v.len);
3833
3834 /* Now we have one header in <hdr> */
3835
3836 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3837 struct http_hdr_ctx ctx;
3838 int len;
3839
3840 switch (exp->action) {
3841 case ACT_ALLOW:
3842 txn->flags |= TX_SVALLOW;
3843 goto end;
3844 break;
3845
3846 case ACT_DENY:
3847 txn->flags |= TX_SVDENY;
3848 goto end;
3849 break;
3850
3851 case ACT_REPLACE:
3852 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3853 if (len < 0)
3854 return -1;
3855
3856 http_parse_header(ist2(trash.area, len), &n, &v);
3857 ctx.blk = blk;
3858 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003859 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003860 if (!http_replace_header(htx, &ctx, n, v))
3861 return -1;
3862 if (!ctx.blk)
3863 goto end;
3864 pos = htx_get_blk_pos(htx, blk);
3865 break;
3866
3867 case ACT_REMOVE:
3868 ctx.blk = blk;
3869 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003870 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003871 if (!http_remove_header(htx, &ctx))
3872 return -1;
3873 if (!ctx.blk)
3874 goto end;
3875 pos = htx_get_blk_pos(htx, blk);
3876 goto next_hdr;
3877 }
3878 }
3879
3880 }
3881 end:
3882 return 0;
3883}
3884
3885/* Apply the filter to the status line in the response buffer <res>.
3886 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3887 * or -1 if a replacement resulted in an invalid status line.
3888 */
3889static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3890{
3891 struct http_txn *txn = s->txn;
3892 struct htx *htx;
3893 struct buffer *resline = get_trash_chunk();
3894 int done;
3895
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003896 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003897
3898 if (unlikely(txn->flags & TX_SVDENY))
3899 return 1;
3900 else if (unlikely(txn->flags & TX_SVALLOW) &&
3901 (exp->action == ACT_ALLOW ||
3902 exp->action == ACT_DENY))
3903 return 0;
3904 else if (exp->action == ACT_REMOVE)
3905 return 0;
3906
3907 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003908 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003909
3910 /* Now we have the status line between cur_ptr and cur_end */
3911 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003912 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003913 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003914 int len;
3915
3916 switch (exp->action) {
3917 case ACT_ALLOW:
3918 txn->flags |= TX_SVALLOW;
3919 done = 1;
3920 break;
3921
3922 case ACT_DENY:
3923 txn->flags |= TX_SVDENY;
3924 done = 1;
3925 break;
3926
3927 case ACT_REPLACE:
3928 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3929 if (len < 0)
3930 return -1;
3931
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003932 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3933 sl->info.res.status = strl2ui(code.ptr, code.len);
3934 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003935 return -1;
3936
3937 done = 1;
3938 return 1;
3939 }
3940 }
3941 return done;
3942}
3943
3944/*
3945 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3946 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3947 * unparsable response.
3948 */
3949static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3950{
3951 struct session *sess = s->sess;
3952 struct http_txn *txn = s->txn;
3953 struct hdr_exp *exp;
3954
3955 for (exp = px->rsp_exp; exp; exp = exp->next) {
3956 int ret;
3957
3958 /*
3959 * The interleaving of transformations and verdicts
3960 * makes it difficult to decide to continue or stop
3961 * the evaluation.
3962 */
3963
3964 if (txn->flags & TX_SVDENY)
3965 break;
3966
3967 if ((txn->flags & TX_SVALLOW) &&
3968 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3969 exp->action == ACT_PASS)) {
3970 exp = exp->next;
3971 continue;
3972 }
3973
3974 /* if this filter had a condition, evaluate it now and skip to
3975 * next filter if the condition does not match.
3976 */
3977 if (exp->cond) {
3978 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3979 ret = acl_pass(ret);
3980 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3981 ret = !ret;
3982 if (!ret)
3983 continue;
3984 }
3985
3986 /* Apply the filter to the status line. */
3987 ret = htx_apply_filter_to_sts_line(s, res, exp);
3988 if (unlikely(ret < 0))
3989 return -1;
3990
3991 if (likely(ret == 0)) {
3992 /* The filter did not match the response, it can be
3993 * iterated through all headers.
3994 */
3995 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3996 return -1;
3997 }
3998 }
3999 return 0;
4000}
4001
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004002/*
4003 * Manage client-side cookie. It can impact performance by about 2% so it is
4004 * desirable to call it only when needed. This code is quite complex because
4005 * of the multiple very crappy and ambiguous syntaxes we have to support. it
4006 * highly recommended not to touch this part without a good reason !
4007 */
4008static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
4009{
4010 struct session *sess = s->sess;
4011 struct http_txn *txn = s->txn;
4012 struct htx *htx;
4013 struct http_hdr_ctx ctx;
4014 char *hdr_beg, *hdr_end, *del_from;
4015 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4016 int preserve_hdr;
4017
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004018 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004019 ctx.blk = NULL;
4020 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004021 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004022 del_from = NULL; /* nothing to be deleted */
4023 preserve_hdr = 0; /* assume we may kill the whole header */
4024
4025 /* Now look for cookies. Conforming to RFC2109, we have to support
4026 * attributes whose name begin with a '$', and associate them with
4027 * the right cookie, if we want to delete this cookie.
4028 * So there are 3 cases for each cookie read :
4029 * 1) it's a special attribute, beginning with a '$' : ignore it.
4030 * 2) it's a server id cookie that we *MAY* want to delete : save
4031 * some pointers on it (last semi-colon, beginning of cookie...)
4032 * 3) it's an application cookie : we *MAY* have to delete a previous
4033 * "special" cookie.
4034 * At the end of loop, if a "special" cookie remains, we may have to
4035 * remove it. If no application cookie persists in the header, we
4036 * *MUST* delete it.
4037 *
4038 * Note: RFC2965 is unclear about the processing of spaces around
4039 * the equal sign in the ATTR=VALUE form. A careful inspection of
4040 * the RFC explicitly allows spaces before it, and not within the
4041 * tokens (attrs or values). An inspection of RFC2109 allows that
4042 * too but section 10.1.3 lets one think that spaces may be allowed
4043 * after the equal sign too, resulting in some (rare) buggy
4044 * implementations trying to do that. So let's do what servers do.
4045 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4046 * allowed quoted strings in values, with any possible character
4047 * after a backslash, including control chars and delimitors, which
4048 * causes parsing to become ambiguous. Browsers also allow spaces
4049 * within values even without quotes.
4050 *
4051 * We have to keep multiple pointers in order to support cookie
4052 * removal at the beginning, middle or end of header without
4053 * corrupting the header. All of these headers are valid :
4054 *
4055 * hdr_beg hdr_end
4056 * | |
4057 * v |
4058 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4059 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4060 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4061 * | | | | | | |
4062 * | | | | | | |
4063 * | | | | | | +--> next
4064 * | | | | | +----> val_end
4065 * | | | | +-----------> val_beg
4066 * | | | +--------------> equal
4067 * | | +----------------> att_end
4068 * | +---------------------> att_beg
4069 * +--------------------------> prev
4070 *
4071 */
4072 hdr_beg = ctx.value.ptr;
4073 hdr_end = hdr_beg + ctx.value.len;
4074 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4075 /* Iterate through all cookies on this line */
4076
4077 /* find att_beg */
4078 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004079 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004080 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004081 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004082
4083 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4084 att_beg++;
4085
4086 /* find att_end : this is the first character after the last non
4087 * space before the equal. It may be equal to hdr_end.
4088 */
4089 equal = att_end = att_beg;
4090 while (equal < hdr_end) {
4091 if (*equal == '=' || *equal == ',' || *equal == ';')
4092 break;
4093 if (HTTP_IS_SPHT(*equal++))
4094 continue;
4095 att_end = equal;
4096 }
4097
4098 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4099 * is between <att_beg> and <equal>, both may be identical.
4100 */
4101 /* look for end of cookie if there is an equal sign */
4102 if (equal < hdr_end && *equal == '=') {
4103 /* look for the beginning of the value */
4104 val_beg = equal + 1;
4105 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4106 val_beg++;
4107
4108 /* find the end of the value, respecting quotes */
4109 next = http_find_cookie_value_end(val_beg, hdr_end);
4110
4111 /* make val_end point to the first white space or delimitor after the value */
4112 val_end = next;
4113 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4114 val_end--;
4115 }
4116 else
4117 val_beg = val_end = next = equal;
4118
4119 /* We have nothing to do with attributes beginning with
4120 * '$'. However, they will automatically be removed if a
4121 * header before them is removed, since they're supposed
4122 * to be linked together.
4123 */
4124 if (*att_beg == '$')
4125 continue;
4126
4127 /* Ignore cookies with no equal sign */
4128 if (equal == next) {
4129 /* This is not our cookie, so we must preserve it. But if we already
4130 * scheduled another cookie for removal, we cannot remove the
4131 * complete header, but we can remove the previous block itself.
4132 */
4133 preserve_hdr = 1;
4134 if (del_from != NULL) {
4135 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4136 val_end += delta;
4137 next += delta;
4138 hdr_end += delta;
4139 prev = del_from;
4140 del_from = NULL;
4141 }
4142 continue;
4143 }
4144
4145 /* if there are spaces around the equal sign, we need to
4146 * strip them otherwise we'll get trouble for cookie captures,
4147 * or even for rewrites. Since this happens extremely rarely,
4148 * it does not hurt performance.
4149 */
4150 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4151 int stripped_before = 0;
4152 int stripped_after = 0;
4153
4154 if (att_end != equal) {
4155 memmove(att_end, equal, hdr_end - equal);
4156 stripped_before = (att_end - equal);
4157 equal += stripped_before;
4158 val_beg += stripped_before;
4159 }
4160
4161 if (val_beg > equal + 1) {
4162 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4163 stripped_after = (equal + 1) - val_beg;
4164 val_beg += stripped_after;
4165 stripped_before += stripped_after;
4166 }
4167
4168 val_end += stripped_before;
4169 next += stripped_before;
4170 hdr_end += stripped_before;
4171 }
4172 /* now everything is as on the diagram above */
4173
4174 /* First, let's see if we want to capture this cookie. We check
4175 * that we don't already have a client side cookie, because we
4176 * can only capture one. Also as an optimisation, we ignore
4177 * cookies shorter than the declared name.
4178 */
4179 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4180 (val_end - att_beg >= sess->fe->capture_namelen) &&
4181 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4182 int log_len = val_end - att_beg;
4183
4184 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4185 ha_alert("HTTP logging : out of memory.\n");
4186 } else {
4187 if (log_len > sess->fe->capture_len)
4188 log_len = sess->fe->capture_len;
4189 memcpy(txn->cli_cookie, att_beg, log_len);
4190 txn->cli_cookie[log_len] = 0;
4191 }
4192 }
4193
4194 /* Persistence cookies in passive, rewrite or insert mode have the
4195 * following form :
4196 *
4197 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4198 *
4199 * For cookies in prefix mode, the form is :
4200 *
4201 * Cookie: NAME=SRV~VALUE
4202 */
4203 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4204 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4205 struct server *srv = s->be->srv;
4206 char *delim;
4207
4208 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4209 * have the server ID between val_beg and delim, and the original cookie between
4210 * delim+1 and val_end. Otherwise, delim==val_end :
4211 *
4212 * hdr_beg
4213 * |
4214 * v
4215 * NAME=SRV; # in all but prefix modes
4216 * NAME=SRV~OPAQUE ; # in prefix mode
4217 * || || | |+-> next
4218 * || || | +--> val_end
4219 * || || +---------> delim
4220 * || |+------------> val_beg
4221 * || +-------------> att_end = equal
4222 * |+-----------------> att_beg
4223 * +------------------> prev
4224 *
4225 */
4226 if (s->be->ck_opts & PR_CK_PFX) {
4227 for (delim = val_beg; delim < val_end; delim++)
4228 if (*delim == COOKIE_DELIM)
4229 break;
4230 }
4231 else {
4232 char *vbar1;
4233 delim = val_end;
4234 /* Now check if the cookie contains a date field, which would
4235 * appear after a vertical bar ('|') just after the server name
4236 * and before the delimiter.
4237 */
4238 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4239 if (vbar1) {
4240 /* OK, so left of the bar is the server's cookie and
4241 * right is the last seen date. It is a base64 encoded
4242 * 30-bit value representing the UNIX date since the
4243 * epoch in 4-second quantities.
4244 */
4245 int val;
4246 delim = vbar1++;
4247 if (val_end - vbar1 >= 5) {
4248 val = b64tos30(vbar1);
4249 if (val > 0)
4250 txn->cookie_last_date = val << 2;
4251 }
4252 /* look for a second vertical bar */
4253 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4254 if (vbar1 && (val_end - vbar1 > 5)) {
4255 val = b64tos30(vbar1 + 1);
4256 if (val > 0)
4257 txn->cookie_first_date = val << 2;
4258 }
4259 }
4260 }
4261
4262 /* if the cookie has an expiration date and the proxy wants to check
4263 * it, then we do that now. We first check if the cookie is too old,
4264 * then only if it has expired. We detect strict overflow because the
4265 * time resolution here is not great (4 seconds). Cookies with dates
4266 * in the future are ignored if their offset is beyond one day. This
4267 * allows an admin to fix timezone issues without expiring everyone
4268 * and at the same time avoids keeping unwanted side effects for too
4269 * long.
4270 */
4271 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4272 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4273 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4274 txn->flags &= ~TX_CK_MASK;
4275 txn->flags |= TX_CK_OLD;
4276 delim = val_beg; // let's pretend we have not found the cookie
4277 txn->cookie_first_date = 0;
4278 txn->cookie_last_date = 0;
4279 }
4280 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4281 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4282 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4283 txn->flags &= ~TX_CK_MASK;
4284 txn->flags |= TX_CK_EXPIRED;
4285 delim = val_beg; // let's pretend we have not found the cookie
4286 txn->cookie_first_date = 0;
4287 txn->cookie_last_date = 0;
4288 }
4289
4290 /* Here, we'll look for the first running server which supports the cookie.
4291 * This allows to share a same cookie between several servers, for example
4292 * to dedicate backup servers to specific servers only.
4293 * However, to prevent clients from sticking to cookie-less backup server
4294 * when they have incidentely learned an empty cookie, we simply ignore
4295 * empty cookies and mark them as invalid.
4296 * The same behaviour is applied when persistence must be ignored.
4297 */
4298 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4299 srv = NULL;
4300
4301 while (srv) {
4302 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4303 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4304 if ((srv->cur_state != SRV_ST_STOPPED) ||
4305 (s->be->options & PR_O_PERSIST) ||
4306 (s->flags & SF_FORCE_PRST)) {
4307 /* we found the server and we can use it */
4308 txn->flags &= ~TX_CK_MASK;
4309 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4310 s->flags |= SF_DIRECT | SF_ASSIGNED;
4311 s->target = &srv->obj_type;
4312 break;
4313 } else {
4314 /* we found a server, but it's down,
4315 * mark it as such and go on in case
4316 * another one is available.
4317 */
4318 txn->flags &= ~TX_CK_MASK;
4319 txn->flags |= TX_CK_DOWN;
4320 }
4321 }
4322 srv = srv->next;
4323 }
4324
4325 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4326 /* no server matched this cookie or we deliberately skipped it */
4327 txn->flags &= ~TX_CK_MASK;
4328 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4329 txn->flags |= TX_CK_UNUSED;
4330 else
4331 txn->flags |= TX_CK_INVALID;
4332 }
4333
4334 /* depending on the cookie mode, we may have to either :
4335 * - delete the complete cookie if we're in insert+indirect mode, so that
4336 * the server never sees it ;
4337 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004338 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004339 * if we're in cookie prefix mode
4340 */
4341 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4342 int delta; /* negative */
4343
4344 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4345 delta = val_beg - (delim + 1);
4346 val_end += delta;
4347 next += delta;
4348 hdr_end += delta;
4349 del_from = NULL;
4350 preserve_hdr = 1; /* we want to keep this cookie */
4351 }
4352 else if (del_from == NULL &&
4353 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4354 del_from = prev;
4355 }
4356 }
4357 else {
4358 /* This is not our cookie, so we must preserve it. But if we already
4359 * scheduled another cookie for removal, we cannot remove the
4360 * complete header, but we can remove the previous block itself.
4361 */
4362 preserve_hdr = 1;
4363
4364 if (del_from != NULL) {
4365 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4366 if (att_beg >= del_from)
4367 att_beg += delta;
4368 if (att_end >= del_from)
4369 att_end += delta;
4370 val_beg += delta;
4371 val_end += delta;
4372 next += delta;
4373 hdr_end += delta;
4374 prev = del_from;
4375 del_from = NULL;
4376 }
4377 }
4378
4379 /* continue with next cookie on this header line */
4380 att_beg = next;
4381 } /* for each cookie */
4382
4383
4384 /* There are no more cookies on this line.
4385 * We may still have one (or several) marked for deletion at the
4386 * end of the line. We must do this now in two ways :
4387 * - if some cookies must be preserved, we only delete from the
4388 * mark to the end of line ;
4389 * - if nothing needs to be preserved, simply delete the whole header
4390 */
4391 if (del_from) {
4392 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4393 }
4394 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004395 if (hdr_beg != hdr_end)
4396 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004397 else
4398 http_remove_header(htx, &ctx);
4399 }
4400 } /* for each "Cookie header */
4401}
4402
4403/*
4404 * Manage server-side cookies. It can impact performance by about 2% so it is
4405 * desirable to call it only when needed. This function is also used when we
4406 * just need to know if there is a cookie (eg: for check-cache).
4407 */
4408static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4409{
4410 struct session *sess = s->sess;
4411 struct http_txn *txn = s->txn;
4412 struct htx *htx;
4413 struct http_hdr_ctx ctx;
4414 struct server *srv;
4415 char *hdr_beg, *hdr_end;
4416 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004417 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004418
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004419 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004420
4421 ctx.blk = NULL;
4422 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004423 int is_first = 1;
4424
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004425 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4426 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4427 break;
4428 is_cookie2 = 1;
4429 }
4430
4431 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4432 * <prev> points to the colon.
4433 */
4434 txn->flags |= TX_SCK_PRESENT;
4435
4436 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4437 * check-cache is enabled) and we are not interested in checking
4438 * them. Warning, the cookie capture is declared in the frontend.
4439 */
4440 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4441 break;
4442
4443 /* OK so now we know we have to process this response cookie.
4444 * The format of the Set-Cookie header is slightly different
4445 * from the format of the Cookie header in that it does not
4446 * support the comma as a cookie delimiter (thus the header
4447 * cannot be folded) because the Expires attribute described in
4448 * the original Netscape's spec may contain an unquoted date
4449 * with a comma inside. We have to live with this because
4450 * many browsers don't support Max-Age and some browsers don't
4451 * support quoted strings. However the Set-Cookie2 header is
4452 * clean.
4453 *
4454 * We have to keep multiple pointers in order to support cookie
4455 * removal at the beginning, middle or end of header without
4456 * corrupting the header (in case of set-cookie2). A special
4457 * pointer, <scav> points to the beginning of the set-cookie-av
4458 * fields after the first semi-colon. The <next> pointer points
4459 * either to the end of line (set-cookie) or next unquoted comma
4460 * (set-cookie2). All of these headers are valid :
4461 *
4462 * hdr_beg hdr_end
4463 * | |
4464 * v |
4465 * NAME1 = VALUE 1 ; Secure; Path="/" |
4466 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4467 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4468 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4469 * | | | | | | | |
4470 * | | | | | | | +-> next
4471 * | | | | | | +------------> scav
4472 * | | | | | +--------------> val_end
4473 * | | | | +--------------------> val_beg
4474 * | | | +----------------------> equal
4475 * | | +------------------------> att_end
4476 * | +----------------------------> att_beg
4477 * +------------------------------> prev
4478 * -------------------------------> hdr_beg
4479 */
4480 hdr_beg = ctx.value.ptr;
4481 hdr_end = hdr_beg + ctx.value.len;
4482 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4483
4484 /* Iterate through all cookies on this line */
4485
4486 /* find att_beg */
4487 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004488 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004489 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004490 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004491
4492 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4493 att_beg++;
4494
4495 /* find att_end : this is the first character after the last non
4496 * space before the equal. It may be equal to hdr_end.
4497 */
4498 equal = att_end = att_beg;
4499
4500 while (equal < hdr_end) {
4501 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4502 break;
4503 if (HTTP_IS_SPHT(*equal++))
4504 continue;
4505 att_end = equal;
4506 }
4507
4508 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4509 * is between <att_beg> and <equal>, both may be identical.
4510 */
4511
4512 /* look for end of cookie if there is an equal sign */
4513 if (equal < hdr_end && *equal == '=') {
4514 /* look for the beginning of the value */
4515 val_beg = equal + 1;
4516 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4517 val_beg++;
4518
4519 /* find the end of the value, respecting quotes */
4520 next = http_find_cookie_value_end(val_beg, hdr_end);
4521
4522 /* make val_end point to the first white space or delimitor after the value */
4523 val_end = next;
4524 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4525 val_end--;
4526 }
4527 else {
4528 /* <equal> points to next comma, semi-colon or EOL */
4529 val_beg = val_end = next = equal;
4530 }
4531
4532 if (next < hdr_end) {
4533 /* Set-Cookie2 supports multiple cookies, and <next> points to
4534 * a colon or semi-colon before the end. So skip all attr-value
4535 * pairs and look for the next comma. For Set-Cookie, since
4536 * commas are permitted in values, skip to the end.
4537 */
4538 if (is_cookie2)
4539 next = http_find_hdr_value_end(next, hdr_end);
4540 else
4541 next = hdr_end;
4542 }
4543
4544 /* Now everything is as on the diagram above */
4545
4546 /* Ignore cookies with no equal sign */
4547 if (equal == val_end)
4548 continue;
4549
4550 /* If there are spaces around the equal sign, we need to
4551 * strip them otherwise we'll get trouble for cookie captures,
4552 * or even for rewrites. Since this happens extremely rarely,
4553 * it does not hurt performance.
4554 */
4555 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4556 int stripped_before = 0;
4557 int stripped_after = 0;
4558
4559 if (att_end != equal) {
4560 memmove(att_end, equal, hdr_end - equal);
4561 stripped_before = (att_end - equal);
4562 equal += stripped_before;
4563 val_beg += stripped_before;
4564 }
4565
4566 if (val_beg > equal + 1) {
4567 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4568 stripped_after = (equal + 1) - val_beg;
4569 val_beg += stripped_after;
4570 stripped_before += stripped_after;
4571 }
4572
4573 val_end += stripped_before;
4574 next += stripped_before;
4575 hdr_end += stripped_before;
4576
Christopher Faulet41dc8432019-06-18 09:49:16 +02004577 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004578 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004579 }
4580
4581 /* First, let's see if we want to capture this cookie. We check
4582 * that we don't already have a server side cookie, because we
4583 * can only capture one. Also as an optimisation, we ignore
4584 * cookies shorter than the declared name.
4585 */
4586 if (sess->fe->capture_name != NULL &&
4587 txn->srv_cookie == NULL &&
4588 (val_end - att_beg >= sess->fe->capture_namelen) &&
4589 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4590 int log_len = val_end - att_beg;
4591 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4592 ha_alert("HTTP logging : out of memory.\n");
4593 }
4594 else {
4595 if (log_len > sess->fe->capture_len)
4596 log_len = sess->fe->capture_len;
4597 memcpy(txn->srv_cookie, att_beg, log_len);
4598 txn->srv_cookie[log_len] = 0;
4599 }
4600 }
4601
4602 srv = objt_server(s->target);
4603 /* now check if we need to process it for persistence */
4604 if (!(s->flags & SF_IGNORE_PRST) &&
4605 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4606 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4607 /* assume passive cookie by default */
4608 txn->flags &= ~TX_SCK_MASK;
4609 txn->flags |= TX_SCK_FOUND;
4610
4611 /* If the cookie is in insert mode on a known server, we'll delete
4612 * this occurrence because we'll insert another one later.
4613 * We'll delete it too if the "indirect" option is set and we're in
4614 * a direct access.
4615 */
4616 if (s->be->ck_opts & PR_CK_PSV) {
4617 /* The "preserve" flag was set, we don't want to touch the
4618 * server's cookie.
4619 */
4620 }
4621 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4622 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4623 /* this cookie must be deleted */
4624 if (prev == hdr_beg && next == hdr_end) {
4625 /* whole header */
4626 http_remove_header(htx, &ctx);
4627 /* note: while both invalid now, <next> and <hdr_end>
4628 * are still equal, so the for() will stop as expected.
4629 */
4630 } else {
4631 /* just remove the value */
4632 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4633 next = prev;
4634 hdr_end += delta;
4635 }
4636 txn->flags &= ~TX_SCK_MASK;
4637 txn->flags |= TX_SCK_DELETED;
4638 /* and go on with next cookie */
4639 }
4640 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4641 /* replace bytes val_beg->val_end with the cookie name associated
4642 * with this server since we know it.
4643 */
4644 int sliding, delta;
4645
4646 ctx.value = ist2(val_beg, val_end - val_beg);
4647 ctx.lws_before = ctx.lws_after = 0;
4648 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4649 delta = srv->cklen - (val_end - val_beg);
4650 sliding = (ctx.value.ptr - val_beg);
4651 hdr_beg += sliding;
4652 val_beg += sliding;
4653 next += sliding + delta;
4654 hdr_end += sliding + delta;
4655
4656 txn->flags &= ~TX_SCK_MASK;
4657 txn->flags |= TX_SCK_REPLACED;
4658 }
4659 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4660 /* insert the cookie name associated with this server
4661 * before existing cookie, and insert a delimiter between them..
4662 */
4663 int sliding, delta;
4664 ctx.value = ist2(val_beg, 0);
4665 ctx.lws_before = ctx.lws_after = 0;
4666 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4667 delta = srv->cklen + 1;
4668 sliding = (ctx.value.ptr - val_beg);
4669 hdr_beg += sliding;
4670 val_beg += sliding;
4671 next += sliding + delta;
4672 hdr_end += sliding + delta;
4673
4674 val_beg[srv->cklen] = COOKIE_DELIM;
4675 txn->flags &= ~TX_SCK_MASK;
4676 txn->flags |= TX_SCK_REPLACED;
4677 }
4678 }
4679 /* that's done for this cookie, check the next one on the same
4680 * line when next != hdr_end (only if is_cookie2).
4681 */
4682 }
4683 }
4684}
4685
Christopher Faulet25a02f62018-10-24 12:00:25 +02004686/*
4687 * Parses the Cache-Control and Pragma request header fields to determine if
4688 * the request may be served from the cache and/or if it is cacheable. Updates
4689 * s->txn->flags.
4690 */
4691void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4692{
4693 struct http_txn *txn = s->txn;
4694 struct htx *htx;
4695 int32_t pos;
4696 int pragma_found, cc_found, i;
4697
4698 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4699 return; /* nothing more to do here */
4700
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004701 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004702 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004703 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004704 struct htx_blk *blk = htx_get_blk(htx, pos);
4705 enum htx_blk_type type = htx_get_blk_type(blk);
4706 struct ist n, v;
4707
4708 if (type == HTX_BLK_EOH)
4709 break;
4710 if (type != HTX_BLK_HDR)
4711 continue;
4712
4713 n = htx_get_blk_name(htx, blk);
4714 v = htx_get_blk_value(htx, blk);
4715
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004716 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004717 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4718 pragma_found = 1;
4719 continue;
4720 }
4721 }
4722
4723 /* Don't use the cache and don't try to store if we found the
4724 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004725 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004726 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4727 txn->flags |= TX_CACHE_IGNORE;
4728 continue;
4729 }
4730
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004731 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004732 continue;
4733
4734 /* OK, right now we know we have a cache-control header */
4735 cc_found = 1;
4736 if (!v.len) /* no info */
4737 continue;
4738
4739 i = 0;
4740 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4741 !isspace((unsigned char)*(v.ptr+i)))
4742 i++;
4743
4744 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4745 * values after max-age, max-stale nor min-fresh, we simply don't
4746 * use the cache when they're specified.
4747 */
4748 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4749 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4750 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4751 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4752 txn->flags |= TX_CACHE_IGNORE;
4753 continue;
4754 }
4755
4756 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4757 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4758 continue;
4759 }
4760 }
4761
4762 /* RFC7234#5.4:
4763 * When the Cache-Control header field is also present and
4764 * understood in a request, Pragma is ignored.
4765 * When the Cache-Control header field is not present in a
4766 * request, caches MUST consider the no-cache request
4767 * pragma-directive as having the same effect as if
4768 * "Cache-Control: no-cache" were present.
4769 */
4770 if (!cc_found && pragma_found)
4771 txn->flags |= TX_CACHE_IGNORE;
4772}
4773
4774/*
4775 * Check if response is cacheable or not. Updates s->txn->flags.
4776 */
4777void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4778{
4779 struct http_txn *txn = s->txn;
4780 struct htx *htx;
4781 int32_t pos;
4782 int i;
4783
4784 if (txn->status < 200) {
4785 /* do not try to cache interim responses! */
4786 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4787 return;
4788 }
4789
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004790 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004791 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004792 struct htx_blk *blk = htx_get_blk(htx, pos);
4793 enum htx_blk_type type = htx_get_blk_type(blk);
4794 struct ist n, v;
4795
4796 if (type == HTX_BLK_EOH)
4797 break;
4798 if (type != HTX_BLK_HDR)
4799 continue;
4800
4801 n = htx_get_blk_name(htx, blk);
4802 v = htx_get_blk_value(htx, blk);
4803
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004804 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004805 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4806 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4807 return;
4808 }
4809 }
4810
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004811 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004812 continue;
4813
4814 /* OK, right now we know we have a cache-control header */
4815 if (!v.len) /* no info */
4816 continue;
4817
4818 i = 0;
4819 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4820 !isspace((unsigned char)*(v.ptr+i)))
4821 i++;
4822
4823 /* we have a complete value between v.ptr and (v.ptr+i) */
4824 if (i < v.len && *(v.ptr + i) == '=') {
4825 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4826 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4827 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4828 continue;
4829 }
4830
4831 /* we have something of the form no-cache="set-cookie" */
4832 if ((v.len >= 21) &&
4833 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4834 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4835 txn->flags &= ~TX_CACHE_COOK;
4836 continue;
4837 }
4838
4839 /* OK, so we know that either p2 points to the end of string or to a comma */
4840 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4841 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4842 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4843 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4844 return;
4845 }
4846
4847 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4848 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4849 continue;
4850 }
4851 }
4852}
4853
Christopher Faulet64159df2018-10-24 21:15:35 +02004854/* send a server's name with an outgoing request over an established connection.
4855 * Note: this function is designed to be called once the request has been
4856 * scheduled for being forwarded. This is the reason why the number of forwarded
4857 * bytes have to be adjusted.
4858 */
4859int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4860{
4861 struct htx *htx;
4862 struct http_hdr_ctx ctx;
4863 struct ist hdr;
4864 uint32_t data;
4865
4866 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004867 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004868 data = htx->data;
4869
4870 ctx.blk = NULL;
4871 while (http_find_header(htx, hdr, &ctx, 1))
4872 http_remove_header(htx, &ctx);
4873 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4874
4875 if (co_data(&s->req)) {
4876 if (data >= htx->data)
4877 c_rew(&s->req, data - htx->data);
4878 else
4879 c_adv(&s->req, htx->data - data);
4880 }
4881 return 0;
4882}
4883
Christopher Faulet377c5a52018-10-24 21:21:30 +02004884/*
4885 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4886 * for the current backend.
4887 *
4888 * It is assumed that the request is either a HEAD, GET, or POST and that the
4889 * uri_auth field is valid.
4890 *
4891 * Returns 1 if stats should be provided, otherwise 0.
4892 */
4893static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4894{
4895 struct uri_auth *uri_auth = backend->uri_auth;
4896 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004897 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004898 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004899
4900 if (!uri_auth)
4901 return 0;
4902
4903 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4904 return 0;
4905
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004906 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004907 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004908 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004909
4910 /* check URI size */
4911 if (uri_auth->uri_len > uri.len)
4912 return 0;
4913
4914 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4915 return 0;
4916
4917 return 1;
4918}
4919
4920/* This function prepares an applet to handle the stats. It can deal with the
4921 * "100-continue" expectation, check that admin rules are met for POST requests,
4922 * and program a response message if something was unexpected. It cannot fail
4923 * and always relies on the stats applet to complete the job. It does not touch
4924 * analysers nor counters, which are left to the caller. It does not touch
4925 * s->target which is supposed to already point to the stats applet. The caller
4926 * is expected to have already assigned an appctx to the stream.
4927 */
4928static int htx_handle_stats(struct stream *s, struct channel *req)
4929{
4930 struct stats_admin_rule *stats_admin_rule;
4931 struct stream_interface *si = &s->si[1];
4932 struct session *sess = s->sess;
4933 struct http_txn *txn = s->txn;
4934 struct http_msg *msg = &txn->req;
4935 struct uri_auth *uri_auth = s->be->uri_auth;
4936 const char *h, *lookup, *end;
4937 struct appctx *appctx;
4938 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004939 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004940
4941 appctx = si_appctx(si);
4942 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4943 appctx->st1 = appctx->st2 = 0;
4944 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4945 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4946 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4947 appctx->ctx.stats.flags |= STAT_CHUNKED;
4948
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004949 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004950 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004951 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4952 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004953
4954 for (h = lookup; h <= end - 3; h++) {
4955 if (memcmp(h, ";up", 3) == 0) {
4956 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4957 break;
4958 }
4959 }
4960
4961 if (uri_auth->refresh) {
4962 for (h = lookup; h <= end - 10; h++) {
4963 if (memcmp(h, ";norefresh", 10) == 0) {
4964 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4965 break;
4966 }
4967 }
4968 }
4969
4970 for (h = lookup; h <= end - 4; h++) {
4971 if (memcmp(h, ";csv", 4) == 0) {
4972 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4973 break;
4974 }
4975 }
4976
4977 for (h = lookup; h <= end - 6; h++) {
4978 if (memcmp(h, ";typed", 6) == 0) {
4979 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4980 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4981 break;
4982 }
4983 }
4984
4985 for (h = lookup; h <= end - 8; h++) {
4986 if (memcmp(h, ";st=", 4) == 0) {
4987 int i;
4988 h += 4;
4989 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4990 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4991 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4992 appctx->ctx.stats.st_code = i;
4993 break;
4994 }
4995 }
4996 break;
4997 }
4998 }
4999
5000 appctx->ctx.stats.scope_str = 0;
5001 appctx->ctx.stats.scope_len = 0;
5002 for (h = lookup; h <= end - 8; h++) {
5003 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
5004 int itx = 0;
5005 const char *h2;
5006 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
5007 const char *err;
5008
5009 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
5010 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01005011 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
5012 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005013 if (*h == ';' || *h == '&' || *h == ' ')
5014 break;
5015 itx++;
5016 h++;
5017 }
5018
5019 if (itx > STAT_SCOPE_TXT_MAXLEN)
5020 itx = STAT_SCOPE_TXT_MAXLEN;
5021 appctx->ctx.stats.scope_len = itx;
5022
5023 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5024 memcpy(scope_txt, h2, itx);
5025 scope_txt[itx] = '\0';
5026 err = invalid_char(scope_txt);
5027 if (err) {
5028 /* bad char in search text => clear scope */
5029 appctx->ctx.stats.scope_str = 0;
5030 appctx->ctx.stats.scope_len = 0;
5031 }
5032 break;
5033 }
5034 }
5035
5036 /* now check whether we have some admin rules for this request */
5037 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5038 int ret = 1;
5039
5040 if (stats_admin_rule->cond) {
5041 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5042 ret = acl_pass(ret);
5043 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5044 ret = !ret;
5045 }
5046
5047 if (ret) {
5048 /* no rule, or the rule matches */
5049 appctx->ctx.stats.flags |= STAT_ADMIN;
5050 break;
5051 }
5052 }
5053
Christopher Faulet5d45e382019-02-27 15:15:23 +01005054 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5055 appctx->st0 = STAT_HTTP_HEAD;
5056 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005057 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005058 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005059 if (msg->msg_state < HTTP_MSG_DATA)
5060 req->analysers |= AN_REQ_HTTP_BODY;
5061 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005062 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005063 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005064 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5065 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5066 appctx->st0 = STAT_HTTP_LAST;
5067 }
5068 }
5069 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005070 /* Unsupported method */
5071 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5072 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5073 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005074 }
5075
5076 s->task->nice = -32; /* small boost for HTTP statistics */
5077 return 1;
5078}
5079
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5081{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005082 struct channel *req = &s->req;
5083 struct channel *res = &s->res;
5084 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005085 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005086 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005087 struct ist path, location;
5088 unsigned int flags;
5089 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005090
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005091 /*
5092 * Create the location
5093 */
5094 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005095
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005096 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005097 /* special prefix "/" means don't change URL */
5098 srv = __objt_server(s->target);
5099 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5100 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5101 return;
5102 }
5103
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005104 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005105 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005106 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005107 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005108 if (!path.ptr)
5109 return;
5110
5111 if (!chunk_memcat(&trash, path.ptr, path.len))
5112 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005113 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005114
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005115 /*
5116 * Create the 302 respone
5117 */
5118 htx = htx_from_buf(&res->buf);
5119 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5120 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5121 ist("HTTP/1.1"), ist("302"), ist("Found"));
5122 if (!sl)
5123 goto fail;
5124 sl->info.res.status = 302;
5125 s->txn->status = 302;
5126
5127 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5128 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5129 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5130 !htx_add_header(htx, ist("Location"), location))
5131 goto fail;
5132
5133 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5134 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005135
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005136 /*
5137 * Send the message
5138 */
5139 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005140 c_adv(res, data);
5141 res->total += data;
5142
5143 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005144 si_shutr(si);
5145 si_shutw(si);
5146 si->err_type = SI_ET_NONE;
5147 si->state = SI_ST_CLO;
5148
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005149 channel_auto_read(req);
5150 channel_abort(req);
5151 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005152 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005153 channel_auto_read(res);
5154 channel_auto_close(res);
5155
5156 if (!(s->flags & SF_ERR_MASK))
5157 s->flags |= SF_ERR_LOCAL;
5158 if (!(s->flags & SF_FINST_MASK))
5159 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005160
5161 /* FIXME: we should increase a counter of redirects per server and per backend. */
5162 srv_inc_sess_ctr(srv);
5163 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005164 return;
5165
5166 fail:
5167 /* If an error occurred, remove the incomplete HTTP response from the
5168 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005169 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005170}
5171
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172/* This function terminates the request because it was completly analyzed or
5173 * because an error was triggered during the body forwarding.
5174 */
5175static void htx_end_request(struct stream *s)
5176{
5177 struct channel *chn = &s->req;
5178 struct http_txn *txn = s->txn;
5179
5180 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5181 now_ms, __FUNCTION__, s,
5182 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5183 s->req.analysers, s->res.analysers);
5184
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005185 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5186 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005187 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005188 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005189 goto end;
5190 }
5191
5192 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5193 return;
5194
5195 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005196 /* No need to read anymore, the request was completely parsed.
5197 * We can shut the read side unless we want to abort_on_close,
5198 * or we have a POST request. The issue with POST requests is
5199 * that some browsers still send a CRLF after the request, and
5200 * this CRLF must be read so that it does not remain in the kernel
5201 * buffers, otherwise a close could cause an RST on some systems
5202 * (eg: Linux).
5203 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005204 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005205 channel_dont_read(chn);
5206
5207 /* if the server closes the connection, we want to immediately react
5208 * and close the socket to save packets and syscalls.
5209 */
5210 s->si[1].flags |= SI_FL_NOHALF;
5211
5212 /* In any case we've finished parsing the request so we must
5213 * disable Nagle when sending data because 1) we're not going
5214 * to shut this side, and 2) the server is waiting for us to
5215 * send pending data.
5216 */
5217 chn->flags |= CF_NEVER_WAIT;
5218
Christopher Fauletd01ce402019-01-02 17:44:13 +01005219 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5220 /* The server has not finished to respond, so we
5221 * don't want to move in order not to upset it.
5222 */
5223 return;
5224 }
5225
Christopher Fauletf2824e62018-10-01 12:12:37 +02005226 /* When we get here, it means that both the request and the
5227 * response have finished receiving. Depending on the connection
5228 * mode, we'll have to wait for the last bytes to leave in either
5229 * direction, and sometimes for a close to be effective.
5230 */
5231 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5232 /* Tunnel mode will not have any analyser so it needs to
5233 * poll for reads.
5234 */
5235 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 if (b_data(&chn->buf))
5237 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005238 txn->req.msg_state = HTTP_MSG_TUNNEL;
5239 }
5240 else {
5241 /* we're not expecting any new data to come for this
5242 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005243 *
5244 * However, there is an exception if the response
5245 * length is undefined. In this case, we need to wait
5246 * the close from the server. The response will be
5247 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005248 */
5249 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5250 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005251 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005252
5253 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5254 channel_shutr_now(chn);
5255 channel_shutw_now(chn);
5256 }
5257 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005258 goto check_channel_flags;
5259 }
5260
5261 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5262 http_msg_closing:
5263 /* nothing else to forward, just waiting for the output buffer
5264 * to be empty and for the shutw_now to take effect.
5265 */
5266 if (channel_is_empty(chn)) {
5267 txn->req.msg_state = HTTP_MSG_CLOSED;
5268 goto http_msg_closed;
5269 }
5270 else if (chn->flags & CF_SHUTW) {
5271 txn->req.err_state = txn->req.msg_state;
5272 txn->req.msg_state = HTTP_MSG_ERROR;
5273 goto end;
5274 }
5275 return;
5276 }
5277
5278 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5279 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005280 /* if we don't know whether the server will close, we need to hard close */
5281 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5282 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005283 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005284 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005285 channel_dont_read(chn);
5286 goto end;
5287 }
5288
5289 check_channel_flags:
5290 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5291 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5292 /* if we've just closed an output, let's switch */
5293 txn->req.msg_state = HTTP_MSG_CLOSING;
5294 goto http_msg_closing;
5295 }
5296
5297 end:
5298 chn->analysers &= AN_REQ_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005299 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
5300 chn->flags |= CF_NEVER_WAIT;
5301 if (HAS_REQ_DATA_FILTERS(s))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005302 chn->analysers |= AN_REQ_FLT_XFER_DATA;
Christopher Faulet86c82202020-12-15 13:32:55 +01005303 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005304 channel_auto_close(chn);
5305 channel_auto_read(chn);
5306}
5307
5308
5309/* This function terminates the response because it was completly analyzed or
5310 * because an error was triggered during the body forwarding.
5311 */
5312static void htx_end_response(struct stream *s)
5313{
5314 struct channel *chn = &s->res;
5315 struct http_txn *txn = s->txn;
5316
5317 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5318 now_ms, __FUNCTION__, s,
5319 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5320 s->req.analysers, s->res.analysers);
5321
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005322 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5323 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005324 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005325 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005326 goto end;
5327 }
5328
5329 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5330 return;
5331
5332 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5333 /* In theory, we don't need to read anymore, but we must
5334 * still monitor the server connection for a possible close
5335 * while the request is being uploaded, so we don't disable
5336 * reading.
5337 */
5338 /* channel_dont_read(chn); */
5339
5340 if (txn->req.msg_state < HTTP_MSG_DONE) {
5341 /* The client seems to still be sending data, probably
5342 * because we got an error response during an upload.
5343 * We have the choice of either breaking the connection
5344 * or letting it pass through. Let's do the later.
5345 */
5346 return;
5347 }
5348
5349 /* When we get here, it means that both the request and the
5350 * response have finished receiving. Depending on the connection
5351 * mode, we'll have to wait for the last bytes to leave in either
5352 * direction, and sometimes for a close to be effective.
5353 */
5354 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5355 channel_auto_read(chn);
5356 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005357 if (b_data(&chn->buf))
5358 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005359 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5360 }
5361 else {
5362 /* we're not expecting any new data to come for this
5363 * transaction, so we can close it.
5364 */
5365 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5366 channel_shutr_now(chn);
5367 channel_shutw_now(chn);
5368 }
5369 }
5370 goto check_channel_flags;
5371 }
5372
5373 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5374 http_msg_closing:
5375 /* nothing else to forward, just waiting for the output buffer
5376 * to be empty and for the shutw_now to take effect.
5377 */
5378 if (channel_is_empty(chn)) {
5379 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5380 goto http_msg_closed;
5381 }
5382 else if (chn->flags & CF_SHUTW) {
5383 txn->rsp.err_state = txn->rsp.msg_state;
5384 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005385 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005386 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005387 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005388 goto end;
5389 }
5390 return;
5391 }
5392
5393 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5394 http_msg_closed:
5395 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005396 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005397 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005398 goto end;
5399 }
5400
5401 check_channel_flags:
5402 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5403 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5404 /* if we've just closed an output, let's switch */
5405 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5406 goto http_msg_closing;
5407 }
5408
5409 end:
5410 chn->analysers &= AN_RES_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005411 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5412 chn->flags |= CF_NEVER_WAIT;
5413 if (HAS_RSP_DATA_FILTERS(s))
5414 chn->analysers |= AN_RES_FLT_XFER_DATA;
5415 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005416 channel_auto_close(chn);
5417 channel_auto_read(chn);
5418}
5419
Christopher Faulet0f226952018-10-22 09:29:56 +02005420void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5421 int finst, const struct buffer *msg)
5422{
5423 channel_auto_read(si_oc(si));
5424 channel_abort(si_oc(si));
5425 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005426 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005427 channel_auto_close(si_ic(si));
5428 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005429
5430 /* <msg> is an HTX structure. So we copy it in the response's
5431 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005432 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005433 struct channel *chn = si_ic(si);
5434 struct htx *htx;
5435
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005436 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005437 chn->buf.data = msg->data;
5438 memcpy(chn->buf.area, msg->area, msg->data);
5439 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005440 if (s->txn->meth == HTTP_METH_HEAD)
5441 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005442 c_adv(chn, htx->data);
5443 chn->total += htx->data;
5444 }
5445 if (!(s->flags & SF_ERR_MASK))
5446 s->flags |= err;
5447 if (!(s->flags & SF_FINST_MASK))
5448 s->flags |= finst;
5449}
5450
5451void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5452{
5453 channel_auto_read(&s->req);
5454 channel_abort(&s->req);
5455 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005456 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5457 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005458
5459 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005460
5461 /* <msg> is an HTX structure. So we copy it in the response's
5462 * channel */
5463 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005464 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005465 struct channel *chn = &s->res;
5466 struct htx *htx;
5467
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005468 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005469 chn->buf.data = msg->data;
5470 memcpy(chn->buf.area, msg->area, msg->data);
5471 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005472 if (s->txn->meth == HTTP_METH_HEAD)
5473 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005474 c_adv(chn, htx->data);
5475 chn->total += htx->data;
5476 }
5477
5478 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5479 channel_auto_read(&s->res);
5480 channel_auto_close(&s->res);
5481 channel_shutr_now(&s->res);
5482}
5483
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005484struct buffer *htx_error_message(struct stream *s)
5485{
5486 const int msgnum = http_get_status_idx(s->txn->status);
5487
5488 if (s->be->errmsg[msgnum].area)
5489 return &s->be->errmsg[msgnum];
5490 else if (strm_fe(s)->errmsg[msgnum].area)
5491 return &strm_fe(s)->errmsg[msgnum];
5492 else
5493 return &htx_err_chunks[msgnum];
5494}
5495
5496
Christopher Faulet4a28a532019-03-01 11:19:40 +01005497/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5498 * on success and -1 on error.
5499 */
5500static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5501{
5502 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5503 * then we must send an HTTP/1.1 100 Continue intermediate response.
5504 */
5505 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5506 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5507 struct ist hdr = { .ptr = "Expect", .len = 6 };
5508 struct http_hdr_ctx ctx;
5509
5510 ctx.blk = NULL;
5511 /* Expect is allowed in 1.1, look for it */
5512 if (http_find_header(htx, hdr, &ctx, 0) &&
5513 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5514 if (htx_reply_100_continue(s) == -1)
5515 return -1;
5516 http_remove_header(htx, &ctx);
5517 }
5518 }
5519 return 0;
5520}
5521
Christopher Faulet23a3c792018-11-28 10:01:23 +01005522/* Send a 100-Continue response to the client. It returns 0 on success and -1
5523 * on error. The response channel is updated accordingly.
5524 */
5525static int htx_reply_100_continue(struct stream *s)
5526{
5527 struct channel *res = &s->res;
5528 struct htx *htx = htx_from_buf(&res->buf);
5529 struct htx_sl *sl;
5530 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5531 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5532 size_t data;
5533
5534 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5535 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5536 if (!sl)
5537 goto fail;
5538 sl->info.res.status = 100;
5539
Christopher Faulet9869f932019-06-26 14:23:54 +02005540 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005541 goto fail;
5542
5543 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005544 c_adv(res, data);
5545 res->total += data;
5546 return 0;
5547
5548 fail:
5549 /* If an error occurred, remove the incomplete HTTP response from the
5550 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005551 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005552 return -1;
5553}
5554
Christopher Faulet12c51e22018-11-28 15:59:42 +01005555
5556/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5557 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5558 * error. The response channel is updated accordingly.
5559 */
5560static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5561{
5562 struct channel *res = &s->res;
5563 struct htx *htx = htx_from_buf(&res->buf);
5564 struct htx_sl *sl;
5565 struct ist code, body;
5566 int status;
5567 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5568 size_t data;
5569
5570 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5571 status = 401;
5572 code = ist("401");
5573 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5574 "You need a valid user and password to access this content.\n"
5575 "</body></html>\n");
5576 }
5577 else {
5578 status = 407;
5579 code = ist("407");
5580 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5581 "You need a valid user and password to access this content.\n"
5582 "</body></html>\n");
5583 }
5584
5585 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5586 ist("HTTP/1.1"), code, ist("Unauthorized"));
5587 if (!sl)
5588 goto fail;
5589 sl->info.res.status = status;
5590 s->txn->status = status;
5591
5592 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5593 goto fail;
5594
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005595 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5596 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005597 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005598 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5599 goto fail;
5600 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5601 goto fail;
5602 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005603 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005604 if (!htx_add_endof(htx, HTX_BLK_EOH))
5605 goto fail;
5606
Christopher Faulete6ee4652020-10-19 18:01:38 +02005607 if (s->txn->meth == HTTP_METH_HEAD)
5608 body.len = 0;
5609
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005610 while (body.len) {
5611 size_t sent = htx_add_data(htx, body);
5612 if (!sent)
5613 goto fail;
5614 body.ptr += sent;
5615 body.len -= sent;
5616 }
5617
5618 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005619 goto fail;
5620
5621 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005622 c_adv(res, data);
5623 res->total += data;
5624
5625 channel_auto_read(&s->req);
5626 channel_abort(&s->req);
5627 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005628 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005629
5630 res->wex = tick_add_ifset(now_ms, res->wto);
5631 channel_auto_read(res);
5632 channel_auto_close(res);
5633 channel_shutr_now(res);
5634 return 0;
5635
5636 fail:
5637 /* If an error occurred, remove the incomplete HTTP response from the
5638 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005639 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005640 return -1;
5641}
5642
Christopher Faulet0f226952018-10-22 09:29:56 +02005643/*
5644 * Capture headers from message <htx> according to header list <cap_hdr>, and
5645 * fill the <cap> pointers appropriately.
5646 */
5647static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5648{
5649 struct cap_hdr *h;
5650 int32_t pos;
5651
Christopher Fauleta3f15502019-05-13 15:27:23 +02005652 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 struct htx_blk *blk = htx_get_blk(htx, pos);
5654 enum htx_blk_type type = htx_get_blk_type(blk);
5655 struct ist n, v;
5656
5657 if (type == HTX_BLK_EOH)
5658 break;
5659 if (type != HTX_BLK_HDR)
5660 continue;
5661
5662 n = htx_get_blk_name(htx, blk);
5663
5664 for (h = cap_hdr; h; h = h->next) {
5665 if (h->namelen && (h->namelen == n.len) &&
5666 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5667 if (cap[h->index] == NULL)
5668 cap[h->index] =
5669 pool_alloc(h->pool);
5670
5671 if (cap[h->index] == NULL) {
5672 ha_alert("HTTP capture : out of memory.\n");
5673 break;
5674 }
5675
5676 v = htx_get_blk_value(htx, blk);
5677 if (v.len > h->len)
5678 v.len = h->len;
5679
5680 memcpy(cap[h->index], v.ptr, v.len);
5681 cap[h->index][v.len]=0;
5682 }
5683 }
5684 }
5685}
5686
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005687/* Delete a value in a header between delimiters <from> and <next>. The header
5688 * itself is delimited by <start> and <end> pointers. The number of characters
5689 * displaced is returned, and the pointer to the first delimiter is updated if
5690 * required. The function tries as much as possible to respect the following
5691 * principles :
5692 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5693 * in which case <next> is simply removed
5694 * - set exactly one space character after the new first delimiter, unless there
5695 * are not enough characters in the block being moved to do so.
5696 * - remove unneeded spaces before the previous delimiter and after the new
5697 * one.
5698 *
5699 * It is the caller's responsibility to ensure that :
5700 * - <from> points to a valid delimiter or <start> ;
5701 * - <next> points to a valid delimiter or <end> ;
5702 * - there are non-space chars before <from>.
5703 */
5704static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5705{
5706 char *prev = *from;
5707
5708 if (prev == start) {
5709 /* We're removing the first value. eat the semicolon, if <next>
5710 * is lower than <end> */
5711 if (next < end)
5712 next++;
5713
5714 while (next < end && HTTP_IS_SPHT(*next))
5715 next++;
5716 }
5717 else {
5718 /* Remove useless spaces before the old delimiter. */
5719 while (HTTP_IS_SPHT(*(prev-1)))
5720 prev--;
5721 *from = prev;
5722
5723 /* copy the delimiter and if possible a space if we're
5724 * not at the end of the line.
5725 */
5726 if (next < end) {
5727 *prev++ = *next++;
5728 if (prev + 1 < next)
5729 *prev++ = ' ';
5730 while (next < end && HTTP_IS_SPHT(*next))
5731 next++;
5732 }
5733 }
5734 memmove(prev, next, end - next);
5735 return (prev - next);
5736}
5737
Christopher Faulet0f226952018-10-22 09:29:56 +02005738
5739/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005740 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005741 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005742static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005743{
5744 struct ist dst = ist2(str, 0);
5745
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005746 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005747 goto end;
5748 if (dst.len + 1 > len)
5749 goto end;
5750 dst.ptr[dst.len++] = ' ';
5751
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005752 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005753 goto end;
5754 if (dst.len + 1 > len)
5755 goto end;
5756 dst.ptr[dst.len++] = ' ';
5757
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005758 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005759 end:
5760 return dst.len;
5761}
5762
Christopher Fauletf0523542018-10-24 11:06:58 +02005763/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005764 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005765 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005766static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005767{
5768 struct ist dst = ist2(str, 0);
5769
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005770 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005771 goto end;
5772 if (dst.len + 1 > len)
5773 goto end;
5774 dst.ptr[dst.len++] = ' ';
5775
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005776 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005777 goto end;
5778 if (dst.len + 1 > len)
5779 goto end;
5780 dst.ptr[dst.len++] = ' ';
5781
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005782 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005783 end:
5784 return dst.len;
5785}
5786
5787
Christopher Faulet0f226952018-10-22 09:29:56 +02005788/*
5789 * Print a debug line with a start line.
5790 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005791static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005792{
5793 struct session *sess = strm_sess(s);
5794 int max;
5795
5796 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5797 dir,
5798 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5799 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5800
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005801 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005802 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005803 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005804 trash.area[trash.data++] = ' ';
5805
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005806 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005807 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005808 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005809 trash.area[trash.data++] = ' ';
5810
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005811 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005812 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005813 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005814 trash.area[trash.data++] = '\n';
5815
5816 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5817}
5818
5819/*
5820 * Print a debug line with a header.
5821 */
5822static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5823{
5824 struct session *sess = strm_sess(s);
5825 int max;
5826
5827 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5828 dir,
5829 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5830 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5831
5832 max = n.len;
5833 UBOUND(max, trash.size - trash.data - 3);
5834 chunk_memcat(&trash, n.ptr, max);
5835 trash.area[trash.data++] = ':';
5836 trash.area[trash.data++] = ' ';
5837
5838 max = v.len;
5839 UBOUND(max, trash.size - trash.data - 1);
5840 chunk_memcat(&trash, v.ptr, max);
5841 trash.area[trash.data++] = '\n';
5842
5843 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5844}
5845
5846
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005847__attribute__((constructor))
5848static void __htx_protocol_init(void)
5849{
5850}
5851
5852
5853/*
5854 * Local variables:
5855 * c-indent-level: 8
5856 * c-basic-offset: 8
5857 * End:
5858 */