blob: c16d61f9bd8957a535c0253457132f18a134c811 [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>
Christopher Faulet0f226952018-10-22 09:29:56 +020027#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020028#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020029#include <proto/pattern.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020030#include <proto/http_ana.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020032#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020033#include <proto/stream.h>
34#include <proto/stream_interface.h>
35#include <proto/stats.h>
Christopher Fauleta8a46e22019-07-16 14:53:09 +020036#include <proto/vars.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020037
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
Christopher Fauleta8a46e22019-07-16 14:53:09 +020040struct pool_head *pool_head_requri = NULL;
41struct pool_head *pool_head_capture = NULL;
42
43
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020044static void http_end_request(struct stream *s);
45static void http_end_response(struct stream *s);
Christopher Fauletf2824e62018-10-01 12:12:37 +020046
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020047static void http_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
48static int http_del_hdr_value(char *start, char *end, char **from, char *next);
49static size_t http_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020050static void http_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
51static void http_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
Christopher Faulet0f226952018-10-22 09:29:56 +020052
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020053static enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
54static enum rule_result http_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
Christopher Faulet3e964192018-10-24 11:39:23 +020055
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020056static void http_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void http_manage_server_side_cookies(struct stream *s, struct channel *res);
Christopher Fauletfcda7c62018-10-24 11:56:22 +020058
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020059static int http_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int http_handle_stats(struct stream *s, struct channel *req);
Christopher Faulet377c5a52018-10-24 21:21:30 +020061
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020062static int http_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
63static int http_reply_100_continue(struct stream *s);
64static int http_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 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020073int http_wait_for_request(struct stream *s, struct channel *req, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +020074{
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 */
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200101 if (htx->flags & (HTX_FL_PARSING_ERROR|HTX_FL_PROCESSING_ERROR)) {
Willy Tarreau4236f032019-03-05 10:43:32 +0100102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200105 if (htx->flags & HTX_FL_PARSING_ERROR)
106 goto return_bad_req;
107 else
108 goto return_int_err;
Willy Tarreau4236f032019-03-05 10:43:32 +0100109 }
110
Christopher Faulete0768eb2018-10-03 16:38:02 +0200111 /* we're speaking HTTP here, so let's speak HTTP to the client */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200112 s->srv_error = http_return_srv_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200113
114 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100115 if (c_data(req) && s->logs.t_idle == -1) {
116 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
117
118 s->logs.t_idle = ((csinfo)
119 ? csinfo->t_idle
120 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
121 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200122
Christopher Faulete0768eb2018-10-03 16:38:02 +0200123 /*
124 * Now we quickly check if we have found a full valid request.
125 * If not so, we check the FD and buffer states before leaving.
126 * A full request is indicated by the fact that we have seen
127 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
128 * requests are checked first. When waiting for a second request
129 * on a keep-alive stream, if we encounter and error, close, t/o,
130 * we note the error in the stream flags but don't set any state.
131 * Since the error will be noted there, it will not be counted by
132 * process_stream() as a frontend error.
133 * Last, we may increase some tracked counters' http request errors on
134 * the cases that are deliberately the client's fault. For instance,
135 * a timeout or connection reset is not counted as an error. However
136 * a bad request is.
137 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200138 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200139 if (htx->flags & HTX_FL_UPGRADE)
140 goto failed_keep_alive;
141
Christopher Faulet9768c262018-10-22 09:34:31 +0200142 /* 1: have we encountered a read error ? */
143 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200144 if (!(s->flags & SF_ERR_MASK))
145 s->flags |= SF_ERR_CLICL;
146
147 if (txn->flags & TX_WAIT_NEXT_RQ)
148 goto failed_keep_alive;
149
150 if (sess->fe->options & PR_O_IGNORE_PRB)
151 goto failed_keep_alive;
152
Christopher Faulet9768c262018-10-22 09:34:31 +0200153 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 stream_inc_http_req_ctr(s);
155 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100156 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200157 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100158 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200159
Christopher Faulet9768c262018-10-22 09:34:31 +0200160 txn->status = 400;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200161 http_reply_and_close(s, txn->status, NULL);
Christopher Faulet9768c262018-10-22 09:34:31 +0200162 req->analysers &= AN_REQ_FLT_END;
163
Christopher Faulete0768eb2018-10-03 16:38:02 +0200164 if (!(s->flags & SF_FINST_MASK))
165 s->flags |= SF_FINST_R;
166 return 0;
167 }
168
Christopher Faulet9768c262018-10-22 09:34:31 +0200169 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200170 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
171 if (!(s->flags & SF_ERR_MASK))
172 s->flags |= SF_ERR_CLITO;
173
174 if (txn->flags & TX_WAIT_NEXT_RQ)
175 goto failed_keep_alive;
176
177 if (sess->fe->options & PR_O_IGNORE_PRB)
178 goto failed_keep_alive;
179
Christopher Faulet9768c262018-10-22 09:34:31 +0200180 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200181 stream_inc_http_req_ctr(s);
182 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100183 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200184 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100185 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200186
Christopher Faulet9768c262018-10-22 09:34:31 +0200187 txn->status = 408;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200188 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200189 req->analysers &= AN_REQ_FLT_END;
190
Christopher Faulete0768eb2018-10-03 16:38:02 +0200191 if (!(s->flags & SF_FINST_MASK))
192 s->flags |= SF_FINST_R;
193 return 0;
194 }
195
Christopher Faulet9768c262018-10-22 09:34:31 +0200196 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197 else if (req->flags & CF_SHUTR) {
198 if (!(s->flags & SF_ERR_MASK))
199 s->flags |= SF_ERR_CLICL;
200
201 if (txn->flags & TX_WAIT_NEXT_RQ)
202 goto failed_keep_alive;
203
204 if (sess->fe->options & PR_O_IGNORE_PRB)
205 goto failed_keep_alive;
206
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 stream_inc_http_err_ctr(s);
208 stream_inc_http_req_ctr(s);
209 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100210 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200211 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100212 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200213
Christopher Faulet9768c262018-10-22 09:34:31 +0200214 txn->status = 400;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200215 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200216 req->analysers &= AN_REQ_FLT_END;
217
Christopher Faulete0768eb2018-10-03 16:38:02 +0200218 if (!(s->flags & SF_FINST_MASK))
219 s->flags |= SF_FINST_R;
220 return 0;
221 }
222
223 channel_dont_connect(req);
224 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
225 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100226
Christopher Faulet9768c262018-10-22 09:34:31 +0200227 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200228 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
229 /* We need more data, we have to re-enable quick-ack in case we
230 * previously disabled it, otherwise we might cause the client
231 * to delay next data.
232 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100233 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200234 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100235
Christopher Faulet47365272018-10-31 17:40:50 +0100236 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 /* If the client starts to talk, let's fall back to
238 * request timeout processing.
239 */
240 txn->flags &= ~TX_WAIT_NEXT_RQ;
241 req->analyse_exp = TICK_ETERNITY;
242 }
243
244 /* just set the request timeout once at the beginning of the request */
245 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100246 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200247 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
248 else
249 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
250 }
251
252 /* we're not ready yet */
253 return 0;
254
255 failed_keep_alive:
256 /* Here we process low-level errors for keep-alive requests. In
257 * short, if the request is not the first one and it experiences
258 * a timeout, read error or shutdown, we just silently close so
259 * that the client can try again.
260 */
261 txn->status = 0;
262 msg->msg_state = HTTP_MSG_RQBEFORE;
263 req->analysers &= AN_REQ_FLT_END;
264 s->logs.logwait = 0;
265 s->logs.level = 0;
266 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200267 http_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200268 return 0;
269 }
270
Christopher Faulet9768c262018-10-22 09:34:31 +0200271 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200272 stream_inc_http_req_ctr(s);
273 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
274
Christopher Faulet9768c262018-10-22 09:34:31 +0200275 /* kill the pending keep-alive timeout */
276 txn->flags &= ~TX_WAIT_NEXT_RQ;
277 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200278
Christopher Faulet29f17582019-05-23 11:03:26 +0200279 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200280 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100281
Christopher Faulet9768c262018-10-22 09:34:31 +0200282 /* 0: we might have to print this header in debug mode */
283 if (unlikely((global.mode & MODE_DEBUG) &&
284 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
285 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200286
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200287 http_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200288
Christopher Fauleta3f15502019-05-13 15:27:23 +0200289 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200290 struct htx_blk *blk = htx_get_blk(htx, pos);
291 enum htx_blk_type type = htx_get_blk_type(blk);
292
293 if (type == HTX_BLK_EOH)
294 break;
295 if (type != HTX_BLK_HDR)
296 continue;
297
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200298 http_debug_hdr("clihdr", s,
299 htx_get_blk_name(htx, blk),
300 htx_get_blk_value(htx, blk));
Christopher Faulet9768c262018-10-22 09:34:31 +0200301 }
302 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200303
304 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100305 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100307 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100308 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200309 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100310 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100311 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100312 if (sl->flags & HTX_SL_F_BODYLESS)
313 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /* we can make use of server redirect on GET and HEAD */
316 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
317 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200319 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 goto return_bad_req;
321 }
322
323 /*
324 * 2: check if the URI matches the monitor_uri.
325 * We have to do this for every request which gets in, because
326 * the monitor-uri is defined by the frontend.
327 */
328 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /*
331 * We have found the monitor URI
332 */
333 struct acl_cond *cond;
334
335 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100336 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200337
338 /* Check if we want to fail this monitor request or not */
339 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
340 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
341
342 ret = acl_pass(ret);
343 if (cond->pol == ACL_COND_UNLESS)
344 ret = !ret;
345
346 if (ret) {
347 /* we fail this request, let's return 503 service unavail */
348 txn->status = 503;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200349 if (!(s->flags & SF_ERR_MASK))
350 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
351 goto return_prx_cond;
352 }
353 }
354
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800355 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200356 txn->status = 200;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200357 if (!(s->flags & SF_ERR_MASK))
358 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
359 goto return_prx_cond;
360 }
361
362 /*
363 * 3: Maybe we have to copy the original REQURI for the logs ?
364 * Note: we cannot log anymore if the request has been
365 * classified as invalid.
366 */
367 if (unlikely(s->logs.logwait & LW_REQ)) {
368 /* we have a complete HTTP request that we must log */
369 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200370 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200371
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200372 len = http_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
Christopher Faulet9768c262018-10-22 09:34:31 +0200373 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200374
375 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
376 s->do_log(s);
377 } else {
378 ha_alert("HTTP logging : out of memory.\n");
379 }
380 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200381
Christopher Faulete0768eb2018-10-03 16:38:02 +0200382 /* if the frontend has "option http-use-proxy-header", we'll check if
383 * we have what looks like a proxied connection instead of a connection,
384 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
385 * Note that this is *not* RFC-compliant, however browsers and proxies
386 * happen to do that despite being non-standard :-(
387 * We consider that a request not beginning with either '/' or '*' is
388 * a proxied connection, which covers both "scheme://location" and
389 * CONNECT ip:port.
390 */
391 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100392 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200393 txn->flags |= TX_USE_PX_CONN;
394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* 5: we may need to capture headers */
396 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200397 http_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398
Christopher Faulete0768eb2018-10-03 16:38:02 +0200399 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200400 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200401 req->analysers |= AN_REQ_HTTP_BODY;
402
403 /*
404 * RFC7234#4:
405 * A cache MUST write through requests with methods
406 * that are unsafe (Section 4.2.1 of [RFC7231]) to
407 * the origin server; i.e., a cache is not allowed
408 * to generate a reply to such a request before
409 * having forwarded the request and having received
410 * a corresponding response.
411 *
412 * RFC7231#4.2.1:
413 * Of the request methods defined by this
414 * specification, the GET, HEAD, OPTIONS, and TRACE
415 * methods are defined to be safe.
416 */
417 if (likely(txn->meth == HTTP_METH_GET ||
418 txn->meth == HTTP_METH_HEAD ||
419 txn->meth == HTTP_METH_OPTIONS ||
420 txn->meth == HTTP_METH_TRACE))
421 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
422
423 /* end of job, return OK */
424 req->analysers &= ~an_bit;
425 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200426
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 return 1;
428
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200429 return_int_err:
430 txn->status = 500;
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200431 if (!(s->flags & SF_ERR_MASK))
432 s->flags |= SF_ERR_INTERNAL;
433 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
434 if (sess->listener->counters)
435 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
436 goto return_prx_cond;
437
Christopher Faulete0768eb2018-10-03 16:38:02 +0200438 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200439 txn->status = 400;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100440 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200441 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200443 /* fall through */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200444
445 return_prx_cond:
Christopher Fauletb9a92f32019-09-09 10:15:21 +0200446 http_reply_and_close(s, txn->status, http_error_message(s));
447
Christopher Faulete0768eb2018-10-03 16:38:02 +0200448 if (!(s->flags & SF_ERR_MASK))
449 s->flags |= SF_ERR_PRXCOND;
450 if (!(s->flags & SF_FINST_MASK))
451 s->flags |= SF_FINST_R;
452
453 req->analysers &= AN_REQ_FLT_END;
454 req->analyse_exp = TICK_ETERNITY;
455 return 0;
456}
457
458
459/* This stream analyser runs all HTTP request processing which is common to
460 * frontends and backends, which means blocking ACLs, filters, connection-close,
461 * reqadd, stats and redirects. This is performed for the designated proxy.
462 * It returns 1 if the processing can continue on next analysers, or zero if it
463 * either needs more data or wants to immediately abort the request (eg: deny,
464 * error, ...).
465 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200466int http_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200467{
468 struct session *sess = s->sess;
469 struct http_txn *txn = s->txn;
470 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200471 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200472 struct redirect_rule *rule;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200500 verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200543 if (!s->target && http_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200548 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200556 http_handle_stats(s, req);
557 verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
Christopher Faulet2571bc62019-03-01 11:44:26 +0100567 /* Proceed with the applets now. */
568 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200569 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100570 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200571
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200572 if (http_handle_expect_hdr(s, htx, msg) == -1)
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100573 goto return_bad_req;
574
Christopher Faulete0768eb2018-10-03 16:38:02 +0200575 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
576 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
577 if (!(s->flags & SF_FINST_MASK))
578 s->flags |= SF_FINST_R;
579
580 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
581 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
582 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
583 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100584
585 req->flags |= CF_SEND_DONTWAIT;
586 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200587 goto done;
588 }
589
590 /* check whether we have some ACLs set to redirect this request */
591 list_for_each_entry(rule, &px->redirect_rules, list) {
592 if (rule->cond) {
593 int ret;
594
595 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
596 ret = acl_pass(ret);
597 if (rule->cond->pol == ACL_COND_UNLESS)
598 ret = !ret;
599 if (!ret)
600 continue;
601 }
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200602 if (!http_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200603 goto return_bad_req;
604 goto done;
605 }
606
607 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
608 * If this happens, then the data will not come immediately, so we must
609 * send all what we have without waiting. Note that due to the small gain
610 * in waiting for the body of the request, it's easier to simply put the
611 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
612 * itself once used.
613 */
614 req->flags |= CF_SEND_DONTWAIT;
615
616 done: /* done with this analyser, continue with next ones that the calling
617 * points will have set, if any.
618 */
619 req->analyse_exp = TICK_ETERNITY;
620 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
621 req->analysers &= ~an_bit;
622 return 1;
623
624 tarpit:
625 /* Allow cookie logging
626 */
627 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200628 http_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200629
630 /* When a connection is tarpitted, we use the tarpit timeout,
631 * which may be the same as the connect timeout if unspecified.
632 * If unset, then set it to zero because we really want it to
633 * eventually expire. We build the tarpit as an analyser.
634 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100635 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200636
637 /* wipe the request out so that we can drop the connection early
638 * if the client closes first.
639 */
640 channel_dont_connect(req);
641
642 txn->status = http_err_codes[deny_status];
643
644 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
645 req->analysers |= AN_REQ_HTTP_TARPIT;
646 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
647 if (!req->analyse_exp)
648 req->analyse_exp = tick_add(now_ms, 0);
649 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100650 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200651 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100652 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200653 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100654 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200655 goto done_without_exp;
656
657 deny: /* this request was blocked (denied) */
658
659 /* Allow cookie logging
660 */
661 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200662 http_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200663
664 txn->flags |= TX_CLDENY;
665 txn->status = http_err_codes[deny_status];
666 s->logs.tv_request = now;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200667 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200668 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100669 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200670 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100671 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200672 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100673 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200674 goto return_prx_cond;
675
676 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200677 txn->status = 400;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200678 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200679
Olivier Houcharda798bf52019-03-08 18:52:00 +0100680 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200681 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100682 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683
684 return_prx_cond:
685 if (!(s->flags & SF_ERR_MASK))
686 s->flags |= SF_ERR_PRXCOND;
687 if (!(s->flags & SF_FINST_MASK))
688 s->flags |= SF_FINST_R;
689
690 req->analysers &= AN_REQ_FLT_END;
691 req->analyse_exp = TICK_ETERNITY;
692 return 0;
693
694 return_prx_yield:
695 channel_dont_connect(req);
696 return 0;
697}
698
699/* This function performs all the processing enabled for the current request.
700 * It returns 1 if the processing can continue on next analysers, or zero if it
701 * needs more data, encounters an error, or wants to immediately abort the
702 * request. It relies on buffers flags, and updates s->req.analysers.
703 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200704int http_process_request(struct stream *s, struct channel *req, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705{
706 struct session *sess = s->sess;
707 struct http_txn *txn = s->txn;
708 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200709 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
711
712 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
713 /* we need more data */
714 channel_dont_connect(req);
715 return 0;
716 }
717
718 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
719 now_ms, __FUNCTION__,
720 s,
721 req,
722 req->rex, req->wex,
723 req->flags,
724 ci_data(req),
725 req->analysers);
726
727 /*
728 * Right now, we know that we have processed the entire headers
729 * and that unwanted requests have been filtered out. We can do
730 * whatever we want with the remaining request. Also, now we
731 * may have separate values for ->fe, ->be.
732 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100733 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200734
735 /*
736 * If HTTP PROXY is set we simply get remote server address parsing
Willy Tarreau1c8d32b2019-07-18 15:47:45 +0200737 * incoming request.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200738 */
739 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100740 struct htx_sl *sl;
741 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200742
Willy Tarreau1c8d32b2019-07-18 15:47:45 +0200743 if (!sockaddr_alloc(&s->target_addr)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200744 txn->status = 500;
745 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200746 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200747
748 if (!(s->flags & SF_ERR_MASK))
749 s->flags |= SF_ERR_RESOURCE;
750 if (!(s->flags & SF_FINST_MASK))
751 s->flags |= SF_FINST_R;
752
753 return 0;
754 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200755 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100756 uri = htx_sl_req_uri(sl);
757 path = http_get_path(uri);
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200758
Willy Tarreau1c8d32b2019-07-18 15:47:45 +0200759 if (url2sa(uri.ptr, uri.len - path.len, s->target_addr, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200760 goto return_bad_req;
761
Willy Tarreau1c8d32b2019-07-18 15:47:45 +0200762 s->target = &s->be->obj_type;
763 s->flags |= SF_ADDR_SET | SF_ASSIGNED;
764
Christopher Faulete0768eb2018-10-03 16:38:02 +0200765 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200766 * uri.ptr and path.ptr (excluded). If it was not found, we need
767 * to replace from all the uri by a single "/".
768 *
769 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100770 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200771 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200772 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100773 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200774 }
775
776 /*
777 * 7: Now we can work with the cookies.
778 * Note that doing so might move headers in the request, but
779 * the fields will stay coherent and the URI will not move.
780 * This should only be performed in the backend.
781 */
782 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200783 http_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200784
785 /* add unique-id if "header-unique-id" is specified */
786
787 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
788 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
789 goto return_bad_req;
790 s->unique_id[0] = '\0';
791 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
792 }
793
794 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200795 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
796 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
797
798 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200799 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200800 }
801
802 /*
803 * 9: add X-Forwarded-For if either the frontend or the backend
804 * asks for it.
805 */
806 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200807 struct http_hdr_ctx ctx = { .blk = NULL };
808 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
809 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
810
Christopher Faulete0768eb2018-10-03 16:38:02 +0200811 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200812 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 /* The header is set to be added only if none is present
814 * and we found it, so don't do anything.
815 */
816 }
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200817 else if (cli_conn && conn_get_src(cli_conn) && cli_conn->src->ss_family == AF_INET) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818 /* Add an X-Forwarded-For header unless the source IP is
819 * in the 'except' network range.
820 */
821 if ((!sess->fe->except_mask.s_addr ||
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200822 (((struct sockaddr_in *)cli_conn->src)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200823 != sess->fe->except_net.s_addr) &&
824 (!s->be->except_mask.s_addr ||
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200825 (((struct sockaddr_in *)cli_conn->src)->sin_addr.s_addr & s->be->except_mask.s_addr)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200826 != s->be->except_net.s_addr)) {
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200827 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)cli_conn->src)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200828
829 /* Note: we rely on the backend to get the header name to be used for
830 * x-forwarded-for, because the header is really meant for the backends.
831 * However, if the backend did not specify any option, we have to rely
832 * on the frontend's header name.
833 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200834 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
835 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200836 goto return_bad_req;
837 }
838 }
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200839 else if (cli_conn && conn_get_src(cli_conn) && cli_conn->src->ss_family == AF_INET6) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200840 /* FIXME: for the sake of completeness, we should also support
841 * 'except' here, although it is mostly useless in this case.
842 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200843 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200844
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 inet_ntop(AF_INET6,
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200846 (const void *)&((struct sockaddr_in6 *)(cli_conn->src))->sin6_addr,
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 pn, sizeof(pn));
848
849 /* Note: we rely on the backend to get the header name to be used for
850 * x-forwarded-for, because the header is really meant for the backends.
851 * However, if the backend did not specify any option, we have to rely
852 * on the frontend's header name.
853 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200854 chunk_printf(&trash, "%s", pn);
855 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200856 goto return_bad_req;
857 }
858 }
859
860 /*
861 * 10: add X-Original-To if either the frontend or the backend
862 * asks for it.
863 */
864 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
865
866 /* FIXME: don't know if IPv6 can handle that case too. */
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200867 if (cli_conn && conn_get_src(cli_conn) && cli_conn->src->ss_family == AF_INET && conn_get_dst(cli_conn)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200868 /* Add an X-Original-To header unless the destination IP is
869 * in the 'except' network range.
870 */
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200871 if (cli_conn->dst->ss_family == AF_INET &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200872 ((!sess->fe->except_mask_to.s_addr ||
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200873 (((struct sockaddr_in *)cli_conn->dst)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200874 != sess->fe->except_to.s_addr) &&
875 (!s->be->except_mask_to.s_addr ||
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200876 (((struct sockaddr_in *)cli_conn->dst)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200877 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200878 struct ist hdr;
Willy Tarreaua48f4b32019-07-17 15:11:59 +0200879 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)cli_conn->dst)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200880
881 /* Note: we rely on the backend to get the header name to be used for
882 * x-original-to, because the header is really meant for the backends.
883 * However, if the backend did not specify any option, we have to rely
884 * on the frontend's header name.
885 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200886 if (s->be->orgto_hdr_len)
887 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
888 else
889 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200891 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
892 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200893 goto return_bad_req;
894 }
895 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200896 }
897
Christopher Faulete0768eb2018-10-03 16:38:02 +0200898 /* If we have no server assigned yet and we're balancing on url_param
899 * with a POST request, we may be interested in checking the body for
900 * that parameter. This will be done in another analyser.
901 */
902 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100903 s->txn->meth == HTTP_METH_POST &&
904 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200905 channel_dont_connect(req);
906 req->analysers |= AN_REQ_HTTP_BODY;
907 }
908
909 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
910 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100911
Christopher Faulete0768eb2018-10-03 16:38:02 +0200912 /* We expect some data from the client. Unless we know for sure
913 * we already have a full request, we have to re-enable quick-ack
914 * in case we previously disabled it, otherwise we might cause
915 * the client to delay further data.
916 */
917 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200918 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100919 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200920
921 /*************************************************************
922 * OK, that's finished for the headers. We have done what we *
923 * could. Let's switch to the DATA state. *
924 ************************************************************/
925 req->analyse_exp = TICK_ETERNITY;
926 req->analysers &= ~an_bit;
927
928 s->logs.tv_request = now;
929 /* OK let's go on with the BODY now */
930 return 1;
931
932 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 txn->status = 400;
934 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200935 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200936
Olivier Houcharda798bf52019-03-08 18:52:00 +0100937 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100939 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940
941 if (!(s->flags & SF_ERR_MASK))
942 s->flags |= SF_ERR_PRXCOND;
943 if (!(s->flags & SF_FINST_MASK))
944 s->flags |= SF_FINST_R;
945 return 0;
946}
947
948/* This function is an analyser which processes the HTTP tarpit. It always
949 * returns zero, at the beginning because it prevents any other processing
950 * from occurring, and at the end because it terminates the request.
951 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200952int http_process_tarpit(struct stream *s, struct channel *req, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200953{
954 struct http_txn *txn = s->txn;
955
956 /* This connection is being tarpitted. The CLIENT side has
957 * already set the connect expiration date to the right
958 * timeout. We just have to check that the client is still
959 * there and that the timeout has not expired.
960 */
961 channel_dont_connect(req);
962 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
963 !tick_is_expired(req->analyse_exp, now_ms))
964 return 0;
965
966 /* We will set the queue timer to the time spent, just for
967 * logging purposes. We fake a 500 server error, so that the
968 * attacker will not suspect his connection has been tarpitted.
969 * It will not cause trouble to the logs because we can exclude
970 * the tarpitted connections by filtering on the 'PT' status flags.
971 */
972 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
973
974 if (!(req->flags & CF_READ_ERROR))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200975 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976
977 req->analysers &= AN_REQ_FLT_END;
978 req->analyse_exp = TICK_ETERNITY;
979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_T;
984 return 0;
985}
986
987/* This function is an analyser which waits for the HTTP request body. It waits
988 * for either the buffer to be full, or the full advertised contents to have
989 * reached the buffer. It must only be called after the standard HTTP request
990 * processing has occurred, because it expects the request to be parsed and will
991 * look for the Expect header. It may send a 100-Continue interim response. It
992 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
993 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
994 * needs to read more data, or 1 once it has completed its analysis.
995 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200996int http_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200997{
998 struct session *sess = s->sess;
999 struct http_txn *txn = s->txn;
1000 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001001 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001002
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001003
1004 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1005 now_ms, __FUNCTION__,
1006 s,
1007 req,
1008 req->rex, req->wex,
1009 req->flags,
1010 ci_data(req),
1011 req->analysers);
1012
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001013 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001014
Willy Tarreau4236f032019-03-05 10:43:32 +01001015 if (htx->flags & HTX_FL_PARSING_ERROR)
1016 goto return_bad_req;
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001017 if (htx->flags & HTX_FL_PROCESSING_ERROR)
1018 goto return_int_err;
Willy Tarreau4236f032019-03-05 10:43:32 +01001019
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001020 if (msg->msg_state < HTTP_MSG_BODY)
1021 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001022
Christopher Faulete0768eb2018-10-03 16:38:02 +02001023 /* We have to parse the HTTP request body to find any required data.
1024 * "balance url_param check_post" should have been the only way to get
1025 * into this. We were brought here after HTTP header analysis, so all
1026 * related structures are ready.
1027 */
1028
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001029 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001030 if (http_handle_expect_hdr(s, htx, msg) == -1)
Christopher Faulet4a28a532019-03-01 11:19:40 +01001031 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001032 }
1033
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001034 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001035
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001036 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1037 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001038 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001039 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001040 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001041 goto http_end;
1042
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001043 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001044 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1045 txn->status = 408;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001046
1047 if (!(s->flags & SF_ERR_MASK))
1048 s->flags |= SF_ERR_CLITO;
1049 if (!(s->flags & SF_FINST_MASK))
1050 s->flags |= SF_FINST_D;
1051 goto return_err_msg;
1052 }
1053
1054 /* we get here if we need to wait for more data */
1055 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1056 /* Not enough data. We'll re-use the http-request
1057 * timeout here. Ideally, we should set the timeout
1058 * relative to the accept() date. We just set the
1059 * request timeout once at the beginning of the
1060 * request.
1061 */
1062 channel_dont_connect(req);
1063 if (!tick_isset(req->analyse_exp))
1064 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1065 return 0;
1066 }
1067
1068 http_end:
1069 /* The situation will not evolve, so let's give up on the analysis. */
1070 s->logs.tv_request = now; /* update the request timer to reflect full request */
1071 req->analysers &= ~an_bit;
1072 req->analyse_exp = TICK_ETERNITY;
1073 return 1;
1074
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001075 return_int_err:
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001076 txn->status = 500;
1077
1078 if (!(s->flags & SF_ERR_MASK))
1079 s->flags |= SF_ERR_INTERNAL;
1080 if (!(s->flags & SF_FINST_MASK))
1081 s->flags |= SF_FINST_R;
1082 goto return_err_msg;
1083
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001085 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086
1087 if (!(s->flags & SF_ERR_MASK))
1088 s->flags |= SF_ERR_PRXCOND;
1089 if (!(s->flags & SF_FINST_MASK))
1090 s->flags |= SF_FINST_R;
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001091 /* fall through */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001092
1093 return_err_msg:
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001094 http_reply_and_close(s, txn->status, http_error_message(s));
1095
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001097 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001098 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001099 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001100 return 0;
1101}
1102
1103/* This function is an analyser which forwards request body (including chunk
1104 * sizes if any). It is called as soon as we must forward, even if we forward
1105 * zero byte. The only situation where it must not be called is when we're in
1106 * tunnel mode and we want to forward till the close. It's used both to forward
1107 * remaining data and to resync after end of body. It expects the msg_state to
1108 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1109 * read more data, or 1 once we can go on with next request or end the stream.
1110 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1111 * bytes of pending data + the headers if not already done.
1112 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001113int http_request_forward_body(struct stream *s, struct channel *req, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001114{
1115 struct session *sess = s->sess;
1116 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001117 struct http_msg *msg = &txn->req;
1118 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001119 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001120 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001121
1122 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1123 now_ms, __FUNCTION__,
1124 s,
1125 req,
1126 req->rex, req->wex,
1127 req->flags,
1128 ci_data(req),
1129 req->analysers);
1130
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001131 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001132
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001133 if (htx->flags & HTX_FL_PARSING_ERROR)
1134 goto return_bad_req;
1135 if (htx->flags & HTX_FL_PROCESSING_ERROR)
1136 goto return_int_err;
1137
Christopher Faulete0768eb2018-10-03 16:38:02 +02001138 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1139 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1140 /* Output closed while we were sending data. We must abort and
1141 * wake the other side up.
1142 */
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001143
Olivier Houchard29cac3c2019-07-12 15:48:58 +02001144 /* Don't abort yet if we had L7 retries activated and it
1145 * was a write error, we may recover.
1146 */
1147 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1148 (s->si[1].flags & SI_FL_L7_RETRY))
1149 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001150 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001151 http_end_request(s);
1152 http_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001153 return 1;
1154 }
1155
1156 /* Note that we don't have to send 100-continue back because we don't
1157 * need the data to complete our job, and it's up to the server to
1158 * decide whether to return 100, 417 or anything else in return of
1159 * an "Expect: 100-continue" header.
1160 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001161 if (msg->msg_state == HTTP_MSG_BODY)
1162 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001163
Christopher Faulete0768eb2018-10-03 16:38:02 +02001164 /* in most states, we should abort in case of early close */
1165 channel_auto_close(req);
1166
1167 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001168 if (req->to_forward == CHN_INFINITE_FORWARD) {
1169 if (req->flags & (CF_SHUTR|CF_EOI)) {
1170 msg->msg_state = HTTP_MSG_DONE;
1171 req->to_forward = 0;
1172 goto done;
1173 }
1174 }
1175 else {
1176 /* We can't process the buffer's contents yet */
1177 req->flags |= CF_WAKE_WRITE;
1178 goto missing_data_or_waiting;
1179 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001180 }
1181
Christopher Faulet9768c262018-10-22 09:34:31 +02001182 if (msg->msg_state >= HTTP_MSG_DONE)
1183 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001184 /* Forward input data. We get it by removing all outgoing data not
1185 * forwarded yet from HTX data size. If there are some data filters, we
1186 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001187 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001188 if (HAS_REQ_DATA_FILTERS(s)) {
1189 ret = flt_http_payload(s, msg, htx->data);
1190 if (ret < 0)
1191 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001192 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001193 }
1194 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001195 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001196 if (msg->flags & HTTP_MSGF_XFER_LEN)
1197 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001198 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001199
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001200 if (txn->meth == HTTP_METH_CONNECT) {
1201 msg->msg_state = HTTP_MSG_TUNNEL;
1202 goto done;
1203 }
1204
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001205
Christopher Faulet9768c262018-10-22 09:34:31 +02001206 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001207 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1208 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001209 */
1210 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1211 goto missing_data_or_waiting;
1212
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001213 msg->msg_state = HTTP_MSG_ENDING;
1214 if (htx->data != co_data(req))
1215 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001216 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001217 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001218
1219 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001220 /* other states, DONE...TUNNEL */
1221 /* we don't want to forward closes on DONE except in tunnel mode. */
Christopher Fauletc41547b2019-07-16 14:32:23 +02001222 if (!(txn->flags & TX_CON_WANT_TUN))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001223 channel_dont_close(req);
1224
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001225 if (HAS_REQ_DATA_FILTERS(s)) {
1226 ret = flt_http_end(s, msg);
1227 if (ret <= 0) {
1228 if (!ret)
1229 goto missing_data_or_waiting;
1230 goto return_bad_req;
1231 }
1232 }
1233
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001234 http_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001235 if (!(req->analysers & an_bit)) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001236 http_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001237 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1238 if (req->flags & CF_SHUTW) {
1239 /* request errors are most likely due to the
1240 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001241 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001242 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243 goto return_bad_req;
1244 }
1245 return 1;
1246 }
1247
1248 /* If "option abortonclose" is set on the backend, we want to monitor
1249 * the client's connection and forward any shutdown notification to the
1250 * server, which will decide whether to close or to go on processing the
1251 * request. We only do that in tunnel mode, and not in other modes since
1252 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001253 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001254 channel_auto_read(req);
Christopher Fauletc41547b2019-07-16 14:32:23 +02001255 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) && !(txn->flags & TX_CON_WANT_TUN))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001256 s->si[1].flags |= SI_FL_NOLINGER;
1257 channel_auto_close(req);
1258 }
1259 else if (s->txn->meth == HTTP_METH_POST) {
1260 /* POST requests may require to read extra CRLF sent by broken
1261 * browsers and which could cause an RST to be sent upon close
1262 * on some systems (eg: Linux). */
1263 channel_auto_read(req);
1264 }
1265 return 0;
1266
1267 missing_data_or_waiting:
1268 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001269 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001270 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271
1272 waiting:
1273 /* waiting for the last bits to leave the buffer */
1274 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001275 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276
1277 /* When TE: chunked is used, we need to get there again to parse remaining
1278 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1279 * And when content-length is used, we never want to let the possible
1280 * shutdown be forwarded to the other side, as the state machine will
1281 * take care of it once the client responds. It's also important to
1282 * prevent TIME_WAITs from accumulating on the backend side, and for
1283 * HTTP/2 where the last frame comes with a shutdown.
1284 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001285 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 channel_dont_close(req);
1287
1288 /* We know that more data are expected, but we couldn't send more that
1289 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1290 * system knows it must not set a PUSH on this first part. Interactive
1291 * modes are already handled by the stream sock layer. We must not do
1292 * this in content-length mode because it could present the MSG_MORE
1293 * flag with the last block of forwarded data, which would cause an
1294 * additional delay to be observed by the receiver.
1295 */
1296 if (msg->flags & HTTP_MSGF_TE_CHNK)
1297 req->flags |= CF_EXPECT_MORE;
1298
1299 return 0;
1300
Christopher Faulet93e02d82019-03-08 14:18:50 +01001301 return_cli_abort:
1302 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1303 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1304 if (objt_server(s->target))
1305 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1306 if (!(s->flags & SF_ERR_MASK))
1307 s->flags |= SF_ERR_CLICL;
1308 status = 400;
1309 goto return_error;
1310
1311 return_srv_abort:
1312 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1313 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1314 if (objt_server(s->target))
1315 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1316 if (!(s->flags & SF_ERR_MASK))
1317 s->flags |= SF_ERR_SRVCL;
1318 status = 502;
1319 goto return_error;
1320
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001321 return_int_err:
1322 if (!(s->flags & SF_ERR_MASK))
1323 s->flags |= SF_ERR_INTERNAL;
1324 status = 500;
1325 goto return_error;
1326
Christopher Faulet93e02d82019-03-08 14:18:50 +01001327 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001328 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001330 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001331 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001332 s->flags |= SF_ERR_CLICL;
1333 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001334
Christopher Faulet93e02d82019-03-08 14:18:50 +01001335 return_error:
Christopher Faulet9768c262018-10-22 09:34:31 +02001336 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001337 /* Note: we don't send any error if some data were already sent */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001338 http_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001339 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001340 txn->status = status;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001341 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001342 }
1343 req->analysers &= AN_REQ_FLT_END;
1344 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 +01001345 if (!(s->flags & SF_FINST_MASK))
1346 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001347 return 0;
1348}
1349
Olivier Houcharda254a372019-04-05 15:30:12 +02001350/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1351/* Returns 0 if we can attempt to retry, -1 otherwise */
1352static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1353{
1354 struct channel *req, *res;
1355 int co_data;
1356
1357 si->conn_retries--;
1358 if (si->conn_retries < 0)
1359 return -1;
1360
Willy Tarreau223995e2019-05-04 10:38:31 +02001361 if (objt_server(s->target))
1362 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1363 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1364
Olivier Houcharda254a372019-04-05 15:30:12 +02001365 req = &s->req;
1366 res = &s->res;
1367 /* Remove any write error from the request, and read error from the response */
1368 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1369 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1370 res->analysers = 0;
1371 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard4bd58672019-07-12 16:16:59 +02001372 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001373 si->exp = TICK_ETERNITY;
1374 res->rex = TICK_ETERNITY;
1375 res->to_forward = 0;
1376 res->analyse_exp = TICK_ETERNITY;
1377 res->total = 0;
Olivier Houchard4bd58672019-07-12 16:16:59 +02001378 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001379 si_release_endpoint(&s->si[1]);
1380 b_free(&req->buf);
1381 /* Swap the L7 buffer with the channel buffer */
1382 /* We know we stored the co_data as b_data, so get it there */
1383 co_data = b_data(&si->l7_buffer);
1384 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1385 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1386
1387 co_set_data(req, co_data);
1388 b_reset(&res->buf);
1389 co_set_data(res, 0);
1390 return 0;
1391}
1392
Christopher Faulete0768eb2018-10-03 16:38:02 +02001393/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1394 * processing can continue on next analysers, or zero if it either needs more
1395 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1396 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1397 * when it has nothing left to do, and may remove any analyser when it wants to
1398 * abort.
1399 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001400int http_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001401{
Christopher Faulet9768c262018-10-22 09:34:31 +02001402 /*
1403 * We will analyze a complete HTTP response to check the its syntax.
1404 *
1405 * Once the start line and all headers are received, we may perform a
1406 * capture of the error (if any), and we will set a few fields. We also
1407 * logging and finally headers capture.
1408 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001409 struct session *sess = s->sess;
1410 struct http_txn *txn = s->txn;
1411 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001412 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001413 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001414 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001415 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001416 int n;
1417
1418 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1419 now_ms, __FUNCTION__,
1420 s,
1421 rep,
1422 rep->rex, rep->wex,
1423 rep->flags,
1424 ci_data(rep),
1425 rep->analysers);
1426
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001427 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428
Willy Tarreau4236f032019-03-05 10:43:32 +01001429 /* Parsing errors are caught here */
1430 if (htx->flags & HTX_FL_PARSING_ERROR)
1431 goto return_bad_res;
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001432 if (htx->flags & HTX_FL_PROCESSING_ERROR)
1433 goto return_int_err;
Willy Tarreau4236f032019-03-05 10:43:32 +01001434
Christopher Faulete0768eb2018-10-03 16:38:02 +02001435 /*
1436 * Now we quickly check if we have found a full valid response.
1437 * If not so, we check the FD and buffer states before leaving.
1438 * A full response is indicated by the fact that we have seen
1439 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1440 * responses are checked first.
1441 *
1442 * Depending on whether the client is still there or not, we
1443 * may send an error response back or not. Note that normally
1444 * we should only check for HTTP status there, and check I/O
1445 * errors somewhere else.
1446 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001447 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001448 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001449 /* 1: have we encountered a read error ? */
1450 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001451 struct connection *conn = NULL;
1452
Olivier Houchard865d8392019-05-03 22:46:27 +02001453 if (objt_cs(s->si[1].end))
1454 conn = objt_cs(s->si[1].end)->conn;
1455
1456 if (si_b->flags & SI_FL_L7_RETRY &&
1457 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001458 /* If we arrive here, then CF_READ_ERROR was
1459 * set by si_cs_recv() because we matched a
1460 * status, overwise it would have removed
1461 * the SI_FL_L7_RETRY flag, so it's ok not
1462 * to check s->be->retry_type.
1463 */
1464 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1465 return 0;
1466 }
1467
Olivier Houchard6db16992019-05-17 15:40:49 +02001468 if (txn->flags & TX_NOT_FIRST)
1469 goto abort_keep_alive;
1470
Olivier Houcharda798bf52019-03-08 18:52:00 +01001471 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001473 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001474 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001475 }
1476
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477 rep->analysers &= AN_RES_FLT_END;
1478 txn->status = 502;
1479
1480 /* Check to see if the server refused the early data.
1481 * If so, just send a 425
1482 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001483 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1484 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001485 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001486 do_l7_retry(s, si_b) == 0)
1487 return 0;
1488 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001489 }
1490
1491 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001492 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001493
1494 if (!(s->flags & SF_ERR_MASK))
1495 s->flags |= SF_ERR_SRVCL;
1496 if (!(s->flags & SF_FINST_MASK))
1497 s->flags |= SF_FINST_H;
1498 return 0;
1499 }
1500
Christopher Faulet9768c262018-10-22 09:34:31 +02001501 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001502 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001503 if ((si_b->flags & SI_FL_L7_RETRY) &&
1504 (s->be->retry_type & PR_RE_TIMEOUT)) {
1505 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1506 return 0;
1507 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001508 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001510 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001511 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512 }
1513
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 rep->analysers &= AN_RES_FLT_END;
1515 txn->status = 504;
1516 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001517 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518
1519 if (!(s->flags & SF_ERR_MASK))
1520 s->flags |= SF_ERR_SRVTO;
1521 if (!(s->flags & SF_FINST_MASK))
1522 s->flags |= SF_FINST_H;
1523 return 0;
1524 }
1525
Christopher Faulet9768c262018-10-22 09:34:31 +02001526 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001528 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1529 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001531 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532
1533 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 txn->status = 400;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001535 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536
1537 if (!(s->flags & SF_ERR_MASK))
1538 s->flags |= SF_ERR_CLICL;
1539 if (!(s->flags & SF_FINST_MASK))
1540 s->flags |= SF_FINST_H;
1541
1542 /* process_stream() will take care of the error */
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001548 if ((si_b->flags & SI_FL_L7_RETRY) &&
1549 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1550 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1551 return 0;
1552 }
1553
Olivier Houchard6db16992019-05-17 15:40:49 +02001554 if (txn->flags & TX_NOT_FIRST)
1555 goto abort_keep_alive;
1556
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001559 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001560 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 }
1562
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563 rep->analysers &= AN_RES_FLT_END;
1564 txn->status = 502;
1565 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001566 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001567
1568 if (!(s->flags & SF_ERR_MASK))
1569 s->flags |= SF_ERR_SRVCL;
1570 if (!(s->flags & SF_FINST_MASK))
1571 s->flags |= SF_FINST_H;
1572 return 0;
1573 }
1574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001577 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578 goto abort_keep_alive;
1579
Olivier Houcharda798bf52019-03-08 18:52:00 +01001580 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001581 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001582
1583 if (!(s->flags & SF_ERR_MASK))
1584 s->flags |= SF_ERR_CLICL;
1585 if (!(s->flags & SF_FINST_MASK))
1586 s->flags |= SF_FINST_H;
1587
1588 /* process_stream() will take care of the error */
1589 return 0;
1590 }
1591
1592 channel_dont_close(rep);
1593 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1594 return 0;
1595 }
1596
1597 /* More interesting part now : we know that we have a complete
1598 * response which at least looks like HTTP. We have an indicator
1599 * of each header's length, so we can parse them quickly.
1600 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001602 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001603 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604
Christopher Faulet9768c262018-10-22 09:34:31 +02001605 /* 0: we might have to print this header in debug mode */
1606 if (unlikely((global.mode & MODE_DEBUG) &&
1607 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1608 int32_t pos;
1609
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001610 http_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001611
Christopher Fauleta3f15502019-05-13 15:27:23 +02001612 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001613 struct htx_blk *blk = htx_get_blk(htx, pos);
1614 enum htx_blk_type type = htx_get_blk_type(blk);
1615
1616 if (type == HTX_BLK_EOH)
1617 break;
1618 if (type != HTX_BLK_HDR)
1619 continue;
1620
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001621 http_debug_hdr("srvhdr", s,
1622 htx_get_blk_name(htx, blk),
1623 htx_get_blk_value(htx, blk));
Christopher Faulet9768c262018-10-22 09:34:31 +02001624 }
1625 }
1626
Christopher Faulet03599112018-11-27 11:21:21 +01001627 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001628 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001629 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001630 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001631 if (sl->flags & HTX_SL_F_XFER_LEN) {
1632 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001633 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001634 if (sl->flags & HTX_SL_F_BODYLESS)
1635 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001636 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001637
1638 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639 if (n < 1 || n > 5)
1640 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001641
Christopher Faulete0768eb2018-10-03 16:38:02 +02001642 /* when the client triggers a 4xx from the server, it's most often due
1643 * to a missing object or permission. These events should be tracked
1644 * because if they happen often, it may indicate a brute force or a
1645 * vulnerability scan.
1646 */
1647 if (n == 4)
1648 stream_inc_http_err_ctr(s);
1649
1650 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001651 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001652
Christopher Faulete0768eb2018-10-03 16:38:02 +02001653 /* Adjust server's health based on status code. Note: status codes 501
1654 * and 505 are triggered on demand by client request, so we must not
1655 * count them as server failures.
1656 */
1657 if (objt_server(s->target)) {
1658 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001659 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001660 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001661 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001662 }
1663
1664 /*
1665 * We may be facing a 100-continue response, or any other informational
1666 * 1xx response which is non-final, in which case this is not the right
1667 * response, and we're waiting for the next one. Let's allow this response
1668 * to go to the client and wait for the next one. There's an exception for
1669 * 101 which is used later in the code to switch protocols.
1670 */
1671 if (txn->status < 200 &&
1672 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001673 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001674 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet3499f622019-09-03 15:23:54 +02001676 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001677 txn->status = 0;
1678 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001679 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001680 }
1681
1682 /*
1683 * 2: check for cacheability.
1684 */
1685
1686 switch (txn->status) {
1687 case 200:
1688 case 203:
1689 case 204:
1690 case 206:
1691 case 300:
1692 case 301:
1693 case 404:
1694 case 405:
1695 case 410:
1696 case 414:
1697 case 501:
1698 break;
1699 default:
1700 /* RFC7231#6.1:
1701 * Responses with status codes that are defined as
1702 * cacheable by default (e.g., 200, 203, 204, 206,
1703 * 300, 301, 404, 405, 410, 414, and 501 in this
1704 * specification) can be reused by a cache with
1705 * heuristic expiration unless otherwise indicated
1706 * by the method definition or explicit cache
1707 * controls [RFC7234]; all other status codes are
1708 * not cacheable by default.
1709 */
1710 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1711 break;
1712 }
1713
1714 /*
1715 * 3: we may need to capture headers
1716 */
1717 s->logs.logwait &= ~LW_RESP;
1718 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001719 http_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720
Christopher Faulet9768c262018-10-22 09:34:31 +02001721 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001722 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1723 txn->status == 101)) {
1724 /* Either we've established an explicit tunnel, or we're
1725 * switching the protocol. In both cases, we're very unlikely
1726 * to understand the next protocols. We have to switch to tunnel
1727 * mode, so that we transfer the request and responses then let
1728 * this protocol pass unmodified. When we later implement specific
1729 * parsers for such protocols, we'll want to check the Upgrade
1730 * header which contains information about that protocol for
1731 * responses with status 101 (eg: see RFC2817 about TLS).
1732 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02001733 txn->flags |= TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001734 }
1735
Christopher Faulet61608322018-11-23 16:23:45 +01001736 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1737 * 407 (Proxy-Authenticate) responses and set the connection to private
1738 */
1739 srv_conn = cs_conn(objt_cs(s->si[1].end));
1740 if (srv_conn) {
1741 struct ist hdr;
1742 struct http_hdr_ctx ctx;
1743
1744 if (txn->status == 401)
1745 hdr = ist("WWW-Authenticate");
1746 else if (txn->status == 407)
1747 hdr = ist("Proxy-Authenticate");
1748 else
1749 goto end;
1750
1751 ctx.blk = NULL;
1752 while (http_find_header(htx, hdr, &ctx, 0)) {
1753 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001754 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1755 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001756 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001757 }
Christopher Faulet61608322018-11-23 16:23:45 +01001758 }
1759 }
1760
1761 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001762 /* we want to have the response time before we start processing it */
1763 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1764
1765 /* end of job, return OK */
1766 rep->analysers &= ~an_bit;
1767 rep->analyse_exp = TICK_ETERNITY;
1768 channel_auto_close(rep);
1769 return 1;
1770
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001771 return_int_err:
1772 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1773 txn->status = 500;
1774 if (!(s->flags & SF_ERR_MASK))
1775 s->flags |= SF_ERR_INTERNAL;
1776 goto return_error;
1777
1778 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001779 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001780 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001781 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001782 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001783 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001784 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001785 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001786 do_l7_retry(s, si_b) == 0)
1787 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001788 txn->status = 502;
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001789 /* fall through */
1790
1791 return_error:
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001792 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001793
1794 if (!(s->flags & SF_ERR_MASK))
1795 s->flags |= SF_ERR_PRXCOND;
1796 if (!(s->flags & SF_FINST_MASK))
1797 s->flags |= SF_FINST_H;
Christopher Fauletb9a92f32019-09-09 10:15:21 +02001798
1799 s->si[1].flags |= SI_FL_NOLINGER;
1800 rep->analysers &= AN_RES_FLT_END;
1801 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001802 return 0;
1803
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 abort_keep_alive:
1805 /* A keep-alive request to the server failed on a network error.
1806 * The client is required to retry. We need to close without returning
1807 * any other information so that the client retries.
1808 */
1809 txn->status = 0;
1810 rep->analysers &= AN_RES_FLT_END;
1811 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001812 s->logs.logwait = 0;
1813 s->logs.level = 0;
1814 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001815 http_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001816 return 0;
1817}
1818
1819/* This function performs all the processing enabled for the current response.
1820 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1821 * and updates s->res.analysers. It might make sense to explode it into several
1822 * other functions. It works like process_request (see indications above).
1823 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001824int http_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001825{
1826 struct session *sess = s->sess;
1827 struct http_txn *txn = s->txn;
1828 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001829 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001830 struct proxy *cur_proxy;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001831 enum rule_result ret = HTTP_RULE_RES_CONT;
1832
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001833 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1834 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001835
Christopher Faulete0768eb2018-10-03 16:38:02 +02001836 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1837 now_ms, __FUNCTION__,
1838 s,
1839 rep,
1840 rep->rex, rep->wex,
1841 rep->flags,
1842 ci_data(rep),
1843 rep->analysers);
1844
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001845 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001846
1847 /* The stats applet needs to adjust the Connection header but we don't
1848 * apply any filter there.
1849 */
1850 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1851 rep->analysers &= ~an_bit;
1852 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001853 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001854 }
1855
1856 /*
1857 * We will have to evaluate the filters.
1858 * As opposed to version 1.2, now they will be evaluated in the
1859 * filters order and not in the header order. This means that
1860 * each filter has to be validated among all headers.
1861 *
1862 * Filters are tried with ->be first, then with ->fe if it is
1863 * different from ->be.
1864 *
1865 * Maybe we are in resume condiion. In this case I choose the
1866 * "struct proxy" which contains the rule list matching the resume
1867 * pointer. If none of theses "struct proxy" match, I initialise
1868 * the process with the first one.
1869 *
1870 * In fact, I check only correspondance betwwen the current list
1871 * pointer and the ->fe rule list. If it doesn't match, I initialize
1872 * the loop with the ->be.
1873 */
1874 if (s->current_rule_list == &sess->fe->http_res_rules)
1875 cur_proxy = sess->fe;
1876 else
1877 cur_proxy = s->be;
1878 while (1) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879 /* evaluate http-response rules */
1880 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001881 ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001882
1883 if (ret == HTTP_RULE_RES_BADREQ)
1884 goto return_srv_prx_502;
1885
1886 if (ret == HTTP_RULE_RES_DONE) {
1887 rep->analysers &= ~an_bit;
1888 rep->analyse_exp = TICK_ETERNITY;
1889 return 1;
1890 }
1891 }
1892
1893 /* we need to be called again. */
1894 if (ret == HTTP_RULE_RES_YIELD) {
1895 channel_dont_close(rep);
1896 return 0;
1897 }
1898
Christopher Faulete0768eb2018-10-03 16:38:02 +02001899 /* has the response been denied ? */
1900 if (txn->flags & TX_SVDENY) {
1901 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001902 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001903
Olivier Houcharda798bf52019-03-08 18:52:00 +01001904 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1905 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001906 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001907 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001908 goto return_srv_prx_502;
1909 }
1910
Christopher Faulete0768eb2018-10-03 16:38:02 +02001911 /* check whether we're already working on the frontend */
1912 if (cur_proxy == sess->fe)
1913 break;
1914 cur_proxy = sess->fe;
1915 }
1916
1917 /* After this point, this anayzer can't return yield, so we can
1918 * remove the bit corresponding to this analyzer from the list.
1919 *
1920 * Note that the intermediate returns and goto found previously
1921 * reset the analyzers.
1922 */
1923 rep->analysers &= ~an_bit;
1924 rep->analyse_exp = TICK_ETERNITY;
1925
1926 /* OK that's all we can do for 1xx responses */
1927 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001928 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001929
1930 /*
1931 * Now check for a server cookie.
1932 */
1933 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001934 http_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001935
1936 /*
1937 * Check for cache-control or pragma headers if required.
1938 */
1939 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001940 http_check_response_for_cacheability(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001941
1942 /*
1943 * Add server cookie in the response if needed
1944 */
1945 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1946 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1947 (!(s->flags & SF_DIRECT) ||
1948 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1949 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1950 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1951 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1952 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1953 !(s->flags & SF_IGNORE_PRST)) {
1954 /* the server is known, it's not the one the client requested, or the
1955 * cookie's last seen date needs to be refreshed. We have to
1956 * insert a set-cookie here, except if we want to insert only on POST
1957 * requests and this one isn't. Note that servers which don't have cookies
1958 * (eg: some backup servers) will return a full cookie removal request.
1959 */
1960 if (!objt_server(s->target)->cookie) {
1961 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001962 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001963 s->be->cookie_name);
1964 }
1965 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001966 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967
1968 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1969 /* emit last_date, which is mandatory */
1970 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1971 s30tob64((date.tv_sec+3) >> 2,
1972 trash.area + trash.data);
1973 trash.data += 5;
1974
1975 if (s->be->cookie_maxlife) {
1976 /* emit first_date, which is either the original one or
1977 * the current date.
1978 */
1979 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1980 s30tob64(txn->cookie_first_date ?
1981 txn->cookie_first_date >> 2 :
1982 (date.tv_sec+3) >> 2,
1983 trash.area + trash.data);
1984 trash.data += 5;
1985 }
1986 }
1987 chunk_appendf(&trash, "; path=/");
1988 }
1989
1990 if (s->be->cookie_domain)
1991 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1992
1993 if (s->be->ck_opts & PR_CK_HTTPONLY)
1994 chunk_appendf(&trash, "; HttpOnly");
1995
1996 if (s->be->ck_opts & PR_CK_SECURE)
1997 chunk_appendf(&trash, "; Secure");
1998
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001999 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002000 goto return_bad_resp;
2001
2002 txn->flags &= ~TX_SCK_MASK;
2003 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2004 /* the server did not change, only the date was updated */
2005 txn->flags |= TX_SCK_UPDATED;
2006 else
2007 txn->flags |= TX_SCK_INSERTED;
2008
2009 /* Here, we will tell an eventual cache on the client side that we don't
2010 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2011 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2012 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2013 */
2014 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2015
2016 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2017
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002018 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019 goto return_bad_resp;
2020 }
2021 }
2022
2023 /*
2024 * Check if result will be cacheable with a cookie.
2025 * We'll block the response if security checks have caught
2026 * nasty things such as a cacheable cookie.
2027 */
2028 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2029 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2030 (s->be->options & PR_O_CHK_CACHE)) {
2031 /* we're in presence of a cacheable response containing
2032 * a set-cookie header. We'll block it as requested by
2033 * the 'checkcache' option, and send an alert.
2034 */
2035 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002036 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002037
Olivier Houcharda798bf52019-03-08 18:52:00 +01002038 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2039 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002040 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002041 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002042
2043 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2044 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2045 send_log(s->be, LOG_ALERT,
2046 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2047 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2048 goto return_srv_prx_502;
2049 }
2050
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002051 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002052 /* Always enter in the body analyzer */
2053 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2054 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2055
2056 /* if the user wants to log as soon as possible, without counting
2057 * bytes from the server, then this is the right moment. We have
2058 * to temporarily assign bytes_out to log what we currently have.
2059 */
2060 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2061 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002063 s->do_log(s);
2064 s->logs.bytes_out = 0;
2065 }
2066 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002067
2068 return_bad_resp:
2069 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002070 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002071 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002072 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002073 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002074
2075 return_srv_prx_502:
2076 rep->analysers &= AN_RES_FLT_END;
2077 txn->status = 502;
2078 s->logs.t_data = -1; /* was not a valid response */
2079 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002080 http_reply_and_close(s, txn->status, http_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002081 if (!(s->flags & SF_ERR_MASK))
2082 s->flags |= SF_ERR_PRXCOND;
2083 if (!(s->flags & SF_FINST_MASK))
2084 s->flags |= SF_FINST_H;
2085 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002086}
2087
2088/* This function is an analyser which forwards response body (including chunk
2089 * sizes if any). It is called as soon as we must forward, even if we forward
2090 * zero byte. The only situation where it must not be called is when we're in
2091 * tunnel mode and we want to forward till the close. It's used both to forward
2092 * remaining data and to resync after end of body. It expects the msg_state to
2093 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2094 * read more data, or 1 once we can go on with next request or end the stream.
2095 *
2096 * It is capable of compressing response data both in content-length mode and
2097 * in chunked mode. The state machines follows different flows depending on
2098 * whether content-length and chunked modes are used, since there are no
2099 * trailers in content-length :
2100 *
2101 * chk-mode cl-mode
2102 * ,----- BODY -----.
2103 * / \
2104 * V size > 0 V chk-mode
2105 * .--> SIZE -------------> DATA -------------> CRLF
2106 * | | size == 0 | last byte |
2107 * | v final crlf v inspected |
2108 * | TRAILERS -----------> DONE |
2109 * | |
2110 * `----------------------------------------------'
2111 *
2112 * Compression only happens in the DATA state, and must be flushed in final
2113 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2114 * is performed at once on final states for all bytes parsed, or when leaving
2115 * on missing data.
2116 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002117int http_response_forward_body(struct stream *s, struct channel *res, int an_bit)
Christopher Faulete0768eb2018-10-03 16:38:02 +02002118{
2119 struct session *sess = s->sess;
2120 struct http_txn *txn = s->txn;
2121 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002122 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002123 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124
2125 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2126 now_ms, __FUNCTION__,
2127 s,
2128 res,
2129 res->rex, res->wex,
2130 res->flags,
2131 ci_data(res),
2132 res->analysers);
2133
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002134 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002135
Christopher Fauletb9a92f32019-09-09 10:15:21 +02002136 if (htx->flags & HTX_FL_PARSING_ERROR)
2137 goto return_bad_res;
2138 if (htx->flags & HTX_FL_PROCESSING_ERROR)
2139 goto return_int_err;
2140
Christopher Faulete0768eb2018-10-03 16:38:02 +02002141 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002142 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002143 /* Output closed while we were sending data. We must abort and
2144 * wake the other side up.
2145 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02002146 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002147 http_end_response(s);
2148 http_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 return 1;
2150 }
2151
Christopher Faulet9768c262018-10-22 09:34:31 +02002152 if (msg->msg_state == HTTP_MSG_BODY)
2153 msg->msg_state = HTTP_MSG_DATA;
2154
Christopher Faulete0768eb2018-10-03 16:38:02 +02002155 /* in most states, we should abort in case of early close */
2156 channel_auto_close(res);
2157
Christopher Faulete0768eb2018-10-03 16:38:02 +02002158 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002159 if (res->to_forward == CHN_INFINITE_FORWARD) {
2160 if (res->flags & (CF_SHUTR|CF_EOI)) {
2161 msg->msg_state = HTTP_MSG_DONE;
2162 res->to_forward = 0;
2163 goto done;
2164 }
2165 }
2166 else {
2167 /* We can't process the buffer's contents yet */
2168 res->flags |= CF_WAKE_WRITE;
2169 goto missing_data_or_waiting;
2170 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002171 }
2172
Christopher Faulet9768c262018-10-22 09:34:31 +02002173 if (msg->msg_state >= HTTP_MSG_DONE)
2174 goto done;
2175
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002176 /* Forward input data. We get it by removing all outgoing data not
2177 * forwarded yet from HTX data size. If there are some data filters, we
2178 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002179 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002180 if (HAS_RSP_DATA_FILTERS(s)) {
2181 ret = flt_http_payload(s, msg, htx->data);
2182 if (ret < 0)
2183 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002184 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002185 }
2186 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002187 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002188 if (msg->flags & HTTP_MSGF_XFER_LEN)
2189 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002190 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002191
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002192 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2193 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2194 msg->msg_state = HTTP_MSG_TUNNEL;
2195 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 }
2197
Christopher Faulet9768c262018-10-22 09:34:31 +02002198 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002199 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2200 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002201 */
2202 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2203 goto missing_data_or_waiting;
2204
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002205 msg->msg_state = HTTP_MSG_ENDING;
2206 if (htx->data != co_data(res))
2207 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002208 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002209 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002210
2211 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002213 channel_dont_close(res);
2214
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002215 if (HAS_RSP_DATA_FILTERS(s)) {
2216 ret = flt_http_end(s, msg);
2217 if (ret <= 0) {
2218 if (!ret)
2219 goto missing_data_or_waiting;
2220 goto return_bad_res;
2221 }
2222 }
2223
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002224 http_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 if (!(res->analysers & an_bit)) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002226 http_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2228 if (res->flags & CF_SHUTW) {
2229 /* response errors are most likely due to the
2230 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002231 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002233 goto return_bad_res;
2234 }
2235 return 1;
2236 }
2237 return 0;
2238
2239 missing_data_or_waiting:
2240 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002241 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242
2243 /* stop waiting for data if the input is closed before the end. If the
2244 * client side was already closed, it means that the client has aborted,
2245 * so we don't want to count this as a server abort. Otherwise it's a
2246 * server abort.
2247 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002248 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002249 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002250 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002252 if (htx_is_empty(htx))
2253 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002254 }
2255
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 /* When TE: chunked is used, we need to get there again to parse
2257 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002258 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2259 * are filters registered on the stream, we don't want to forward a
2260 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002262 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 channel_dont_close(res);
2264
2265 /* We know that more data are expected, but we couldn't send more that
2266 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2267 * system knows it must not set a PUSH on this first part. Interactive
2268 * modes are already handled by the stream sock layer. We must not do
2269 * this in content-length mode because it could present the MSG_MORE
2270 * flag with the last block of forwarded data, which would cause an
2271 * additional delay to be observed by the receiver.
2272 */
2273 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2274 res->flags |= CF_EXPECT_MORE;
2275
2276 /* the stream handler will take care of timeouts and errors */
2277 return 0;
2278
Christopher Faulet93e02d82019-03-08 14:18:50 +01002279 return_srv_abort:
2280 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2281 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002283 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2284 if (!(s->flags & SF_ERR_MASK))
2285 s->flags |= SF_ERR_SRVCL;
2286 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002287
Christopher Faulet93e02d82019-03-08 14:18:50 +01002288 return_cli_abort:
2289 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2290 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002291 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002292 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2293 if (!(s->flags & SF_ERR_MASK))
2294 s->flags |= SF_ERR_CLICL;
2295 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296
Christopher Fauletb9a92f32019-09-09 10:15:21 +02002297 return_int_err:
2298 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2299 if (!(s->flags & SF_ERR_MASK))
2300 s->flags |= SF_ERR_INTERNAL;
2301 goto return_error;
2302
Christopher Faulet93e02d82019-03-08 14:18:50 +01002303 return_bad_res:
2304 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2305 if (objt_server(s->target)) {
2306 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2307 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2308 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002309 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002310 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002311
Christopher Faulet93e02d82019-03-08 14:18:50 +01002312 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002313 /* don't send any error message as we're in the body */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002314 http_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002315 res->analysers &= AN_RES_FLT_END;
2316 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 +02002317 if (!(s->flags & SF_FINST_MASK))
2318 s->flags |= SF_FINST_D;
2319 return 0;
2320}
2321
Christopher Fauletf2824e62018-10-01 12:12:37 +02002322/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002323 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002324 * as too large a request to build a valid response.
2325 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002326int http_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327{
Christopher Faulet99daf282018-11-28 22:58:13 +01002328 struct channel *req = &s->req;
2329 struct channel *res = &s->res;
2330 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002331 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002332 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002333 struct ist status, reason, location;
2334 unsigned int flags;
2335 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002336 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002337
2338 chunk = alloc_trash_chunk();
2339 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002341
Christopher Faulet99daf282018-11-28 22:58:13 +01002342 /*
2343 * Create the location
2344 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002345 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002346 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002347 case REDIRECT_TYPE_SCHEME: {
2348 struct http_hdr_ctx ctx;
2349 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002350
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 host = ist("");
2352 ctx.blk = NULL;
2353 if (http_find_header(htx, ist("Host"), &ctx, 0))
2354 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355
Christopher Faulet297fbb42019-05-13 14:41:27 +02002356 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 path = http_get_path(htx_sl_req_uri(sl));
2358 /* build message using path */
2359 if (path.ptr) {
2360 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2361 int qs = 0;
2362 while (qs < path.len) {
2363 if (*(path.ptr + qs) == '?') {
2364 path.len = qs;
2365 break;
2366 }
2367 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369 }
2370 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002371 else
2372 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373
Christopher Faulet99daf282018-11-28 22:58:13 +01002374 if (rule->rdr_str) { /* this is an old "redirect" rule */
2375 /* add scheme */
2376 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2377 goto fail;
2378 }
2379 else {
2380 /* add scheme with executing log format */
2381 chunk->data += build_logline(s, chunk->area + chunk->data,
2382 chunk->size - chunk->data,
2383 &rule->rdr_fmt);
2384 }
2385 /* add "://" + host + path */
2386 if (!chunk_memcat(chunk, "://", 3) ||
2387 !chunk_memcat(chunk, host.ptr, host.len) ||
2388 !chunk_memcat(chunk, path.ptr, path.len))
2389 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 /* append a slash at the end of the location if needed and missing */
2392 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2393 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2394 if (chunk->data + 1 >= chunk->size)
2395 goto fail;
2396 chunk->area[chunk->data++] = '/';
2397 }
2398 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002399 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400
Christopher Faulet99daf282018-11-28 22:58:13 +01002401 case REDIRECT_TYPE_PREFIX: {
2402 struct ist path;
2403
Christopher Faulet297fbb42019-05-13 14:41:27 +02002404 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 path = http_get_path(htx_sl_req_uri(sl));
2406 /* build message using path */
2407 if (path.ptr) {
2408 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2409 int qs = 0;
2410 while (qs < path.len) {
2411 if (*(path.ptr + qs) == '?') {
2412 path.len = qs;
2413 break;
2414 }
2415 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417 }
2418 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 else
2420 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002421
Christopher Faulet99daf282018-11-28 22:58:13 +01002422 if (rule->rdr_str) { /* this is an old "redirect" rule */
2423 /* add prefix. Note that if prefix == "/", we don't want to
2424 * add anything, otherwise it makes it hard for the user to
2425 * configure a self-redirection.
2426 */
2427 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2428 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2429 goto fail;
2430 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002431 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002432 else {
2433 /* add prefix with executing log format */
2434 chunk->data += build_logline(s, chunk->area + chunk->data,
2435 chunk->size - chunk->data,
2436 &rule->rdr_fmt);
2437 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438
Christopher Faulet99daf282018-11-28 22:58:13 +01002439 /* add path */
2440 if (!chunk_memcat(chunk, path.ptr, path.len))
2441 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 /* append a slash at the end of the location if needed and missing */
2444 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2445 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2446 if (chunk->data + 1 >= chunk->size)
2447 goto fail;
2448 chunk->area[chunk->data++] = '/';
2449 }
2450 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 case REDIRECT_TYPE_LOCATION:
2453 default:
2454 if (rule->rdr_str) { /* this is an old "redirect" rule */
2455 /* add location */
2456 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2457 goto fail;
2458 }
2459 else {
2460 /* add location with executing log format */
2461 chunk->data += build_logline(s, chunk->area + chunk->data,
2462 chunk->size - chunk->data,
2463 &rule->rdr_fmt);
2464 }
2465 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002467 location = ist2(chunk->area, chunk->data);
2468
2469 /*
2470 * Create the 30x response
2471 */
2472 switch (rule->code) {
2473 case 308:
2474 status = ist("308");
2475 reason = ist("Permanent Redirect");
2476 break;
2477 case 307:
2478 status = ist("307");
2479 reason = ist("Temporary Redirect");
2480 break;
2481 case 303:
2482 status = ist("303");
2483 reason = ist("See Other");
2484 break;
2485 case 301:
2486 status = ist("301");
2487 reason = ist("Moved Permanently");
2488 break;
2489 case 302:
2490 default:
2491 status = ist("302");
2492 reason = ist("Found");
2493 break;
2494 }
2495
Christopher Faulet08e66462019-05-23 16:44:59 +02002496 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2497 close = 1;
2498
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 htx = htx_from_buf(&res->buf);
2500 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2501 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2502 if (!sl)
2503 goto fail;
2504 sl->info.res.status = rule->code;
2505 s->txn->status = rule->code;
2506
Christopher Faulet08e66462019-05-23 16:44:59 +02002507 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2508 goto fail;
2509
2510 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002511 !htx_add_header(htx, ist("Location"), location))
2512 goto fail;
2513
2514 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2515 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2516 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002517 }
2518
2519 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2521 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002522 }
2523
Christopher Faulet99daf282018-11-28 22:58:13 +01002524 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2525 goto fail;
2526
Christopher Fauletf2824e62018-10-01 12:12:37 +02002527 /* let's log the request time */
2528 s->logs.tv_request = now;
2529
Christopher Faulet06511812019-10-16 09:38:27 +02002530 htx->flags |= HTX_FL_PROXY_RESP;
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 c_adv(res, data);
2533 res->total += data;
2534
2535 channel_auto_read(req);
2536 channel_abort(req);
2537 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002538 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002539
2540 res->wex = tick_add_ifset(now_ms, res->wto);
2541 channel_auto_read(res);
2542 channel_auto_close(res);
2543 channel_shutr_now(res);
2544
2545 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002546
2547 if (!(s->flags & SF_ERR_MASK))
2548 s->flags |= SF_ERR_LOCAL;
2549 if (!(s->flags & SF_FINST_MASK))
2550 s->flags |= SF_FINST_R;
2551
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 free_trash_chunk(chunk);
2553 return 1;
2554
2555 fail:
2556 /* If an error occurred, remove the incomplete HTTP response from the
2557 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002558 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002559 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002560 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002561}
2562
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002563int http_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2564 struct ist name, const char *str, struct my_regex *re, int action)
Christopher Faulet72333522018-10-24 11:25:02 +02002565{
2566 struct http_hdr_ctx ctx;
2567 struct buffer *output = get_trash_chunk();
2568
2569 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2570 ctx.blk = NULL;
2571 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2572 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2573 continue;
2574
2575 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2576 if (output->data == -1)
2577 return -1;
2578 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2579 return -1;
2580 }
2581 return 0;
2582}
2583
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002584static int http_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2585 const struct ist name, struct list *fmt, struct my_regex *re, int action)
Christopher Faulet72333522018-10-24 11:25:02 +02002586{
2587 struct buffer *replace;
2588 int ret = -1;
2589
2590 replace = alloc_trash_chunk();
2591 if (!replace)
2592 goto leave;
2593
2594 replace->data = build_logline(s, replace->area, replace->size, fmt);
2595 if (replace->data >= replace->size - 1)
2596 goto leave;
2597
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002598 ret = http_transform_header_str(s, chn, htx, name, replace->area, re, action);
Christopher Faulet72333522018-10-24 11:25:02 +02002599
2600 leave:
2601 free_trash_chunk(replace);
2602 return ret;
2603}
2604
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002605
2606/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2607 * on success and -1 on error. The response channel is updated accordingly.
2608 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002609static int http_reply_103_early_hints(struct channel *res)
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002610{
2611 struct htx *htx = htx_from_buf(&res->buf);
2612 size_t data;
2613
Christopher Faulet1d5ec092019-06-26 14:23:54 +02002614 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002615 /* If an error occurred during an Early-hint rule,
2616 * remove the incomplete HTTP 103 response from the
2617 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002618 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002619 return -1;
2620 }
2621
2622 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002623 c_adv(res, data);
2624 res->total += data;
2625 return 0;
2626}
2627
Christopher Faulet6eb92892018-11-15 16:39:29 +01002628/*
2629 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2630 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002631 * If <early_hints> is 0, it is starts a new response by adding the start
2632 * line. If an error occurred -1 is returned. On success 0 is returned. The
2633 * channel is not updated here. It must be done calling the function
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002634 * http_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002635 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002636static int http_add_early_hint_header(struct stream *s, int early_hints, const struct ist name, struct list *fmt)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002637{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 struct channel *res = &s->res;
2639 struct htx *htx = htx_from_buf(&res->buf);
2640 struct buffer *value = alloc_trash_chunk();
2641
Christopher Faulet6eb92892018-11-15 16:39:29 +01002642 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 struct htx_sl *sl;
2644 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2645 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2646
2647 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2648 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2649 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002650 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002652 }
2653
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2655 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002656 goto fail;
2657
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002659 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002660
2661 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 /* If an error occurred during an Early-hint rule, remove the incomplete
2663 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002664 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 free_trash_chunk(value);
2666 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667}
2668
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002669/* This function executes one of the set-{method,path,query,uri} actions. It
2670 * takes the string from the variable 'replace' with length 'len', then modifies
2671 * the relevant part of the request line accordingly. Then it updates various
2672 * pointers to the next elements which were moved, and the total buffer length.
2673 * It finds the action to be performed in p[2], previously filled by function
2674 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2675 * error, though this can be revisited when this code is finally exploited.
2676 *
2677 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2678 * query string and 3 to replace uri.
2679 *
2680 * In query string case, the mark question '?' must be set at the start of the
2681 * string by the caller, event if the replacement query string is empty.
2682 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002683int http_req_replace_stline(int action, const char *replace, int len,
2684 struct proxy *px, struct stream *s)
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002685{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002686 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002687
2688 switch (action) {
2689 case 0: // method
2690 if (!http_replace_req_meth(htx, ist2(replace, len)))
2691 return -1;
2692 break;
2693
2694 case 1: // path
2695 if (!http_replace_req_path(htx, ist2(replace, len)))
2696 return -1;
2697 break;
2698
2699 case 2: // query
2700 if (!http_replace_req_query(htx, ist2(replace, len)))
2701 return -1;
2702 break;
2703
2704 case 3: // uri
2705 if (!http_replace_req_uri(htx, ist2(replace, len)))
2706 return -1;
2707 break;
2708
2709 default:
2710 return -1;
2711 }
2712 return 0;
2713}
2714
2715/* This function replace the HTTP status code and the associated message. The
2716 * variable <status> contains the new status code. This function never fails.
2717 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002718void http_res_set_status(unsigned int status, const char *reason, struct stream *s)
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002719{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002720 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002721 char *res;
2722
2723 chunk_reset(&trash);
2724 res = ultoa_o(status, trash.area, trash.size);
2725 trash.data = res - trash.area;
2726
2727 /* Do we have a custom reason format string? */
2728 if (reason == NULL)
2729 reason = http_get_reason(status);
2730
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002731 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002732 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2733}
2734
Christopher Faulet3e964192018-10-24 11:39:23 +02002735/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2736 * transaction <txn>. Returns the verdict of the first rule that prevents
2737 * further processing of the request (auth, deny, ...), and defaults to
2738 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2739 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2740 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2741 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2742 * status.
2743 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002744static enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules,
2745 struct stream *s, int *deny_status)
Christopher Faulet3e964192018-10-24 11:39:23 +02002746{
2747 struct session *sess = strm_sess(s);
2748 struct http_txn *txn = s->txn;
2749 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002750 struct act_rule *rule;
2751 struct http_hdr_ctx ctx;
2752 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002753 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2754 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002755 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002756
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002757 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002758
2759 /* If "the current_rule_list" match the executed rule list, we are in
2760 * resume condition. If a resume is needed it is always in the action
2761 * and never in the ACL or converters. In this case, we initialise the
2762 * current rule, and go to the action execution point.
2763 */
2764 if (s->current_rule) {
2765 rule = s->current_rule;
2766 s->current_rule = NULL;
2767 if (s->current_rule_list == rules)
2768 goto resume_execution;
2769 }
2770 s->current_rule_list = rules;
2771
2772 list_for_each_entry(rule, rules, list) {
2773 /* check optional condition */
2774 if (rule->cond) {
2775 int ret;
2776
2777 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2778 ret = acl_pass(ret);
2779
2780 if (rule->cond->pol == ACL_COND_UNLESS)
2781 ret = !ret;
2782
2783 if (!ret) /* condition not matched */
2784 continue;
2785 }
2786
2787 act_flags |= ACT_FLAG_FIRST;
2788 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002789 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2790 early_hints = 0;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002791 if (http_reply_103_early_hints(&s->res) == -1) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002792 rule_ret = HTTP_RULE_RES_BADREQ;
2793 goto end;
2794 }
2795 }
2796
Christopher Faulet3e964192018-10-24 11:39:23 +02002797 switch (rule->action) {
2798 case ACT_ACTION_ALLOW:
2799 rule_ret = HTTP_RULE_RES_STOP;
2800 goto end;
2801
2802 case ACT_ACTION_DENY:
2803 if (deny_status)
2804 *deny_status = rule->deny_status;
2805 rule_ret = HTTP_RULE_RES_DENY;
2806 goto end;
2807
2808 case ACT_HTTP_REQ_TARPIT:
2809 txn->flags |= TX_CLTARPIT;
2810 if (deny_status)
2811 *deny_status = rule->deny_status;
2812 rule_ret = HTTP_RULE_RES_DENY;
2813 goto end;
2814
2815 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002816 /* Auth might be performed on regular http-req rules as well as on stats */
2817 auth_realm = rule->arg.auth.realm;
2818 if (!auth_realm) {
2819 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2820 auth_realm = STATS_DEFAULT_REALM;
2821 else
2822 auth_realm = px->id;
2823 }
2824 /* send 401/407 depending on whether we use a proxy or not. We still
2825 * count one error, because normal browsing won't significantly
2826 * increase the counter but brute force attempts will.
2827 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002829 if (http_reply_40x_unauthorized(s, auth_realm) == -1)
Christopher Faulet12c51e22018-11-28 15:59:42 +01002830 rule_ret = HTTP_RULE_RES_BADREQ;
2831 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002832 goto end;
2833
2834 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002835 rule_ret = HTTP_RULE_RES_DONE;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002836 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02002837 rule_ret = HTTP_RULE_RES_BADREQ;
2838 goto end;
2839
2840 case ACT_HTTP_SET_NICE:
2841 s->task->nice = rule->arg.nice;
2842 break;
2843
2844 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002845 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002846 break;
2847
2848 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002849 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002850 break;
2851
2852 case ACT_HTTP_SET_LOGL:
2853 s->logs.level = rule->arg.loglevel;
2854 break;
2855
2856 case ACT_HTTP_REPLACE_HDR:
2857 case ACT_HTTP_REPLACE_VAL:
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002858 if (http_transform_header(s, &s->req, htx,
2859 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2860 &rule->arg.hdr_add.fmt,
2861 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 rule_ret = HTTP_RULE_RES_BADREQ;
2863 goto end;
2864 }
2865 break;
2866
2867 case ACT_HTTP_DEL_HDR:
2868 /* remove all occurrences of the header */
2869 ctx.blk = NULL;
2870 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2871 http_remove_header(htx, &ctx);
2872 break;
2873
2874 case ACT_HTTP_SET_HDR:
2875 case ACT_HTTP_ADD_HDR: {
2876 /* The scope of the trash buffer must be limited to this function. The
2877 * build_logline() function can execute a lot of other function which
2878 * can use the trash buffer. So for limiting the scope of this global
2879 * buffer, we build first the header value using build_logline, and
2880 * after we store the header name.
2881 */
2882 struct buffer *replace;
2883 struct ist n, v;
2884
2885 replace = alloc_trash_chunk();
2886 if (!replace) {
2887 rule_ret = HTTP_RULE_RES_BADREQ;
2888 goto end;
2889 }
2890
2891 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2892 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2893 v = ist2(replace->area, replace->data);
2894
2895 if (rule->action == ACT_HTTP_SET_HDR) {
2896 /* remove all occurrences of the header */
2897 ctx.blk = NULL;
2898 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2899 http_remove_header(htx, &ctx);
2900 }
2901
2902 if (!http_add_header(htx, n, v)) {
2903 static unsigned char rate_limit = 0;
2904
2905 if ((rate_limit++ & 255) == 0) {
2906 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);
2907 }
2908
Olivier Houcharda798bf52019-03-08 18:52:00 +01002909 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002910 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002911 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002912 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002913 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002914 }
2915 free_trash_chunk(replace);
2916 break;
2917 }
2918
2919 case ACT_HTTP_DEL_ACL:
2920 case ACT_HTTP_DEL_MAP: {
2921 struct pat_ref *ref;
2922 struct buffer *key;
2923
2924 /* collect reference */
2925 ref = pat_ref_lookup(rule->arg.map.ref);
2926 if (!ref)
2927 continue;
2928
2929 /* allocate key */
2930 key = alloc_trash_chunk();
2931 if (!key) {
2932 rule_ret = HTTP_RULE_RES_BADREQ;
2933 goto end;
2934 }
2935
2936 /* collect key */
2937 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2938 key->area[key->data] = '\0';
2939
2940 /* perform update */
2941 /* returned code: 1=ok, 0=ko */
2942 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2943 pat_ref_delete(ref, key->area);
2944 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2945
2946 free_trash_chunk(key);
2947 break;
2948 }
2949
2950 case ACT_HTTP_ADD_ACL: {
2951 struct pat_ref *ref;
2952 struct buffer *key;
2953
2954 /* collect reference */
2955 ref = pat_ref_lookup(rule->arg.map.ref);
2956 if (!ref)
2957 continue;
2958
2959 /* allocate key */
2960 key = alloc_trash_chunk();
2961 if (!key) {
2962 rule_ret = HTTP_RULE_RES_BADREQ;
2963 goto end;
2964 }
2965
2966 /* collect key */
2967 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2968 key->area[key->data] = '\0';
2969
2970 /* perform update */
2971 /* add entry only if it does not already exist */
2972 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2973 if (pat_ref_find_elt(ref, key->area) == NULL)
2974 pat_ref_add(ref, key->area, NULL, NULL);
2975 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2976
2977 free_trash_chunk(key);
2978 break;
2979 }
2980
2981 case ACT_HTTP_SET_MAP: {
2982 struct pat_ref *ref;
2983 struct buffer *key, *value;
2984
2985 /* collect reference */
2986 ref = pat_ref_lookup(rule->arg.map.ref);
2987 if (!ref)
2988 continue;
2989
2990 /* allocate key */
2991 key = alloc_trash_chunk();
2992 if (!key) {
2993 rule_ret = HTTP_RULE_RES_BADREQ;
2994 goto end;
2995 }
2996
2997 /* allocate value */
2998 value = alloc_trash_chunk();
2999 if (!value) {
3000 free_trash_chunk(key);
3001 rule_ret = HTTP_RULE_RES_BADREQ;
3002 goto end;
3003 }
3004
3005 /* collect key */
3006 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3007 key->area[key->data] = '\0';
3008
3009 /* collect value */
3010 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3011 value->area[value->data] = '\0';
3012
3013 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003014 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003015 if (pat_ref_find_elt(ref, key->area) != NULL)
3016 /* update entry if it exists */
3017 pat_ref_set(ref, key->area, value->area, NULL);
3018 else
3019 /* insert a new entry */
3020 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003021 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003022 free_trash_chunk(key);
3023 free_trash_chunk(value);
3024 break;
3025 }
3026
3027 case ACT_HTTP_EARLY_HINT:
3028 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3029 break;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003030 early_hints = http_add_early_hint_header(s, early_hints,
3031 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
3032 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003033 if (early_hints == -1) {
3034 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003035 goto end;
3036 }
3037 break;
3038
3039 case ACT_CUSTOM:
3040 if ((s->req.flags & CF_READ_ERROR) ||
3041 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003042 (px->options & PR_O_ABRT_CLOSE)))
3043 act_flags |= ACT_FLAG_FINAL;
3044
3045 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3046 case ACT_RET_ERR:
3047 case ACT_RET_CONT:
3048 break;
3049 case ACT_RET_STOP:
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003050 rule_ret = HTTP_RULE_RES_STOP;
3051 goto end;
3052 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003053 rule_ret = HTTP_RULE_RES_DONE;
3054 goto end;
3055 case ACT_RET_YIELD:
3056 s->current_rule = rule;
3057 rule_ret = HTTP_RULE_RES_YIELD;
3058 goto end;
3059 }
3060 break;
3061
3062 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3063 /* Note: only the first valid tracking parameter of each
3064 * applies.
3065 */
3066
3067 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3068 struct stktable *t;
3069 struct stksess *ts;
3070 struct stktable_key *key;
3071 void *ptr1, *ptr2;
3072
3073 t = rule->arg.trk_ctr.table.t;
3074 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3075 rule->arg.trk_ctr.expr, NULL);
3076
3077 if (key && (ts = stktable_get_entry(t, key))) {
3078 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3079
3080 /* let's count a new HTTP request as it's the first time we do it */
3081 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3082 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3083 if (ptr1 || ptr2) {
3084 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3085
3086 if (ptr1)
3087 stktable_data_cast(ptr1, http_req_cnt)++;
3088
3089 if (ptr2)
3090 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3091 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3092
3093 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3094
3095 /* If data was modified, we need to touch to re-schedule sync */
3096 stktable_touch_local(t, ts, 0);
3097 }
3098
3099 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3100 if (sess->fe != s->be)
3101 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3102 }
3103 }
3104 break;
3105
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003106 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003107 default:
3108 break;
3109 }
3110 }
3111
3112 end:
3113 if (early_hints) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003114 if (http_reply_103_early_hints(&s->res) == -1)
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003115 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003116 }
3117
3118 /* we reached the end of the rules, nothing to report */
3119 return rule_ret;
3120}
3121
3122/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3123 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3124 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3125 * is returned, the process can continue the evaluation of next rule list. If
3126 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3127 * is returned, it means the operation could not be processed and a server error
3128 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3129 * deny rule. If *YIELD is returned, the caller must call again the function
3130 * with the same context.
3131 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003132static enum rule_result http_res_get_intercept_rule(struct proxy *px, struct list *rules,
3133 struct stream *s)
Christopher Faulet3e964192018-10-24 11:39:23 +02003134{
3135 struct session *sess = strm_sess(s);
3136 struct http_txn *txn = s->txn;
3137 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003138 struct act_rule *rule;
3139 struct http_hdr_ctx ctx;
3140 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3141 int act_flags = 0;
3142
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003143 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003144
3145 /* If "the current_rule_list" match the executed rule list, we are in
3146 * resume condition. If a resume is needed it is always in the action
3147 * and never in the ACL or converters. In this case, we initialise the
3148 * current rule, and go to the action execution point.
3149 */
3150 if (s->current_rule) {
3151 rule = s->current_rule;
3152 s->current_rule = NULL;
3153 if (s->current_rule_list == rules)
3154 goto resume_execution;
3155 }
3156 s->current_rule_list = rules;
3157
3158 list_for_each_entry(rule, rules, list) {
3159 /* check optional condition */
3160 if (rule->cond) {
3161 int ret;
3162
3163 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3164 ret = acl_pass(ret);
3165
3166 if (rule->cond->pol == ACL_COND_UNLESS)
3167 ret = !ret;
3168
3169 if (!ret) /* condition not matched */
3170 continue;
3171 }
3172
3173 act_flags |= ACT_FLAG_FIRST;
3174resume_execution:
3175 switch (rule->action) {
3176 case ACT_ACTION_ALLOW:
3177 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3178 goto end;
3179
3180 case ACT_ACTION_DENY:
3181 txn->flags |= TX_SVDENY;
3182 rule_ret = HTTP_RULE_RES_STOP;
3183 goto end;
3184
3185 case ACT_HTTP_SET_NICE:
3186 s->task->nice = rule->arg.nice;
3187 break;
3188
3189 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003190 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003191 break;
3192
3193 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003194 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003195 break;
3196
3197 case ACT_HTTP_SET_LOGL:
3198 s->logs.level = rule->arg.loglevel;
3199 break;
3200
3201 case ACT_HTTP_REPLACE_HDR:
3202 case ACT_HTTP_REPLACE_VAL:
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003203 if (http_transform_header(s, &s->res, htx,
3204 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3205 &rule->arg.hdr_add.fmt,
3206 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003207 rule_ret = HTTP_RULE_RES_BADREQ;
3208 goto end;
3209 }
3210 break;
3211
3212 case ACT_HTTP_DEL_HDR:
3213 /* remove all occurrences of the header */
3214 ctx.blk = NULL;
3215 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3216 http_remove_header(htx, &ctx);
3217 break;
3218
3219 case ACT_HTTP_SET_HDR:
3220 case ACT_HTTP_ADD_HDR: {
3221 struct buffer *replace;
3222 struct ist n, v;
3223
3224 replace = alloc_trash_chunk();
3225 if (!replace) {
3226 rule_ret = HTTP_RULE_RES_BADREQ;
3227 goto end;
3228 }
3229
3230 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3231 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3232 v = ist2(replace->area, replace->data);
3233
3234 if (rule->action == ACT_HTTP_SET_HDR) {
3235 /* remove all occurrences of the header */
3236 ctx.blk = NULL;
3237 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3238 http_remove_header(htx, &ctx);
3239 }
3240
3241 if (!http_add_header(htx, n, v)) {
3242 static unsigned char rate_limit = 0;
3243
3244 if ((rate_limit++ & 255) == 0) {
3245 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);
3246 }
3247
Olivier Houcharda798bf52019-03-08 18:52:00 +01003248 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003249 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003250 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003251 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003252 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003253 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003254 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003255 }
3256 free_trash_chunk(replace);
3257 break;
3258 }
3259
3260 case ACT_HTTP_DEL_ACL:
3261 case ACT_HTTP_DEL_MAP: {
3262 struct pat_ref *ref;
3263 struct buffer *key;
3264
3265 /* collect reference */
3266 ref = pat_ref_lookup(rule->arg.map.ref);
3267 if (!ref)
3268 continue;
3269
3270 /* allocate key */
3271 key = alloc_trash_chunk();
3272 if (!key) {
3273 rule_ret = HTTP_RULE_RES_BADREQ;
3274 goto end;
3275 }
3276
3277 /* collect key */
3278 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3279 key->area[key->data] = '\0';
3280
3281 /* perform update */
3282 /* returned code: 1=ok, 0=ko */
3283 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3284 pat_ref_delete(ref, key->area);
3285 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3286
3287 free_trash_chunk(key);
3288 break;
3289 }
3290
3291 case ACT_HTTP_ADD_ACL: {
3292 struct pat_ref *ref;
3293 struct buffer *key;
3294
3295 /* collect reference */
3296 ref = pat_ref_lookup(rule->arg.map.ref);
3297 if (!ref)
3298 continue;
3299
3300 /* allocate key */
3301 key = alloc_trash_chunk();
3302 if (!key) {
3303 rule_ret = HTTP_RULE_RES_BADREQ;
3304 goto end;
3305 }
3306
3307 /* collect key */
3308 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3309 key->area[key->data] = '\0';
3310
3311 /* perform update */
3312 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003313 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003314 if (pat_ref_find_elt(ref, key->area) == NULL)
3315 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003316 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003317 free_trash_chunk(key);
3318 break;
3319 }
3320
3321 case ACT_HTTP_SET_MAP: {
3322 struct pat_ref *ref;
3323 struct buffer *key, *value;
3324
3325 /* collect reference */
3326 ref = pat_ref_lookup(rule->arg.map.ref);
3327 if (!ref)
3328 continue;
3329
3330 /* allocate key */
3331 key = alloc_trash_chunk();
3332 if (!key) {
3333 rule_ret = HTTP_RULE_RES_BADREQ;
3334 goto end;
3335 }
3336
3337 /* allocate value */
3338 value = alloc_trash_chunk();
3339 if (!value) {
3340 free_trash_chunk(key);
3341 rule_ret = HTTP_RULE_RES_BADREQ;
3342 goto end;
3343 }
3344
3345 /* collect key */
3346 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3347 key->area[key->data] = '\0';
3348
3349 /* collect value */
3350 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3351 value->area[value->data] = '\0';
3352
3353 /* perform update */
3354 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3355 if (pat_ref_find_elt(ref, key->area) != NULL)
3356 /* update entry if it exists */
3357 pat_ref_set(ref, key->area, value->area, NULL);
3358 else
3359 /* insert a new entry */
3360 pat_ref_add(ref, key->area, value->area, NULL);
3361 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3362 free_trash_chunk(key);
3363 free_trash_chunk(value);
3364 break;
3365 }
3366
3367 case ACT_HTTP_REDIR:
3368 rule_ret = HTTP_RULE_RES_DONE;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003369 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02003370 rule_ret = HTTP_RULE_RES_BADREQ;
3371 goto end;
3372
3373 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3374 /* Note: only the first valid tracking parameter of each
3375 * applies.
3376 */
3377 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3378 struct stktable *t;
3379 struct stksess *ts;
3380 struct stktable_key *key;
3381 void *ptr;
3382
3383 t = rule->arg.trk_ctr.table.t;
3384 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3385 rule->arg.trk_ctr.expr, NULL);
3386
3387 if (key && (ts = stktable_get_entry(t, key))) {
3388 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3389
3390 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3391
3392 /* let's count a new HTTP request as it's the first time we do it */
3393 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3394 if (ptr)
3395 stktable_data_cast(ptr, http_req_cnt)++;
3396
3397 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3398 if (ptr)
3399 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3400 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3401
3402 /* When the client triggers a 4xx from the server, it's most often due
3403 * to a missing object or permission. These events should be tracked
3404 * because if they happen often, it may indicate a brute force or a
3405 * vulnerability scan. Normally this is done when receiving the response
3406 * but here we're tracking after this ought to have been done so we have
3407 * to do it on purpose.
3408 */
3409 if ((unsigned)(txn->status - 400) < 100) {
3410 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3411 if (ptr)
3412 stktable_data_cast(ptr, http_err_cnt)++;
3413
3414 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3415 if (ptr)
3416 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3417 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3418 }
3419
3420 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3421
3422 /* If data was modified, we need to touch to re-schedule sync */
3423 stktable_touch_local(t, ts, 0);
3424
3425 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3426 if (sess->fe != s->be)
3427 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3428 }
3429 }
3430 break;
3431
3432 case ACT_CUSTOM:
3433 if ((s->req.flags & CF_READ_ERROR) ||
3434 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003435 (px->options & PR_O_ABRT_CLOSE)))
3436 act_flags |= ACT_FLAG_FINAL;
3437
3438 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3439 case ACT_RET_ERR:
3440 case ACT_RET_CONT:
3441 break;
3442 case ACT_RET_STOP:
3443 rule_ret = HTTP_RULE_RES_STOP;
3444 goto end;
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003445 case ACT_RET_DONE:
3446 rule_ret = HTTP_RULE_RES_DONE;
3447 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003448 case ACT_RET_YIELD:
3449 s->current_rule = rule;
3450 rule_ret = HTTP_RULE_RES_YIELD;
3451 goto end;
3452 }
3453 break;
3454
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003455 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003456 default:
3457 break;
3458 }
3459 }
3460
3461 end:
3462 /* we reached the end of the rules, nothing to report */
3463 return rule_ret;
3464}
3465
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003466/*
3467 * Manage client-side cookie. It can impact performance by about 2% so it is
3468 * desirable to call it only when needed. This code is quite complex because
3469 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3470 * highly recommended not to touch this part without a good reason !
3471 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003472static void http_manage_client_side_cookies(struct stream *s, struct channel *req)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003473{
3474 struct session *sess = s->sess;
3475 struct http_txn *txn = s->txn;
3476 struct htx *htx;
3477 struct http_hdr_ctx ctx;
3478 char *hdr_beg, *hdr_end, *del_from;
3479 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3480 int preserve_hdr;
3481
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003482 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003483 ctx.blk = NULL;
3484 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardf0f42382019-07-22 17:43:46 +02003485 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003486 del_from = NULL; /* nothing to be deleted */
3487 preserve_hdr = 0; /* assume we may kill the whole header */
3488
3489 /* Now look for cookies. Conforming to RFC2109, we have to support
3490 * attributes whose name begin with a '$', and associate them with
3491 * the right cookie, if we want to delete this cookie.
3492 * So there are 3 cases for each cookie read :
3493 * 1) it's a special attribute, beginning with a '$' : ignore it.
3494 * 2) it's a server id cookie that we *MAY* want to delete : save
3495 * some pointers on it (last semi-colon, beginning of cookie...)
3496 * 3) it's an application cookie : we *MAY* have to delete a previous
3497 * "special" cookie.
3498 * At the end of loop, if a "special" cookie remains, we may have to
3499 * remove it. If no application cookie persists in the header, we
3500 * *MUST* delete it.
3501 *
3502 * Note: RFC2965 is unclear about the processing of spaces around
3503 * the equal sign in the ATTR=VALUE form. A careful inspection of
3504 * the RFC explicitly allows spaces before it, and not within the
3505 * tokens (attrs or values). An inspection of RFC2109 allows that
3506 * too but section 10.1.3 lets one think that spaces may be allowed
3507 * after the equal sign too, resulting in some (rare) buggy
3508 * implementations trying to do that. So let's do what servers do.
3509 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3510 * allowed quoted strings in values, with any possible character
3511 * after a backslash, including control chars and delimitors, which
3512 * causes parsing to become ambiguous. Browsers also allow spaces
3513 * within values even without quotes.
3514 *
3515 * We have to keep multiple pointers in order to support cookie
3516 * removal at the beginning, middle or end of header without
3517 * corrupting the header. All of these headers are valid :
3518 *
3519 * hdr_beg hdr_end
3520 * | |
3521 * v |
3522 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3523 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3524 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3525 * | | | | | | |
3526 * | | | | | | |
3527 * | | | | | | +--> next
3528 * | | | | | +----> val_end
3529 * | | | | +-----------> val_beg
3530 * | | | +--------------> equal
3531 * | | +----------------> att_end
3532 * | +---------------------> att_beg
3533 * +--------------------------> prev
3534 *
3535 */
3536 hdr_beg = ctx.value.ptr;
3537 hdr_end = hdr_beg + ctx.value.len;
3538 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3539 /* Iterate through all cookies on this line */
3540
3541 /* find att_beg */
3542 att_beg = prev;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003543 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003544 att_beg++;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003545 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003546
3547 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3548 att_beg++;
3549
3550 /* find att_end : this is the first character after the last non
3551 * space before the equal. It may be equal to hdr_end.
3552 */
3553 equal = att_end = att_beg;
3554 while (equal < hdr_end) {
3555 if (*equal == '=' || *equal == ',' || *equal == ';')
3556 break;
3557 if (HTTP_IS_SPHT(*equal++))
3558 continue;
3559 att_end = equal;
3560 }
3561
3562 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3563 * is between <att_beg> and <equal>, both may be identical.
3564 */
3565 /* look for end of cookie if there is an equal sign */
3566 if (equal < hdr_end && *equal == '=') {
3567 /* look for the beginning of the value */
3568 val_beg = equal + 1;
3569 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3570 val_beg++;
3571
3572 /* find the end of the value, respecting quotes */
3573 next = http_find_cookie_value_end(val_beg, hdr_end);
3574
3575 /* make val_end point to the first white space or delimitor after the value */
3576 val_end = next;
3577 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3578 val_end--;
3579 }
3580 else
3581 val_beg = val_end = next = equal;
3582
3583 /* We have nothing to do with attributes beginning with
3584 * '$'. However, they will automatically be removed if a
3585 * header before them is removed, since they're supposed
3586 * to be linked together.
3587 */
3588 if (*att_beg == '$')
3589 continue;
3590
3591 /* Ignore cookies with no equal sign */
3592 if (equal == next) {
3593 /* This is not our cookie, so we must preserve it. But if we already
3594 * scheduled another cookie for removal, we cannot remove the
3595 * complete header, but we can remove the previous block itself.
3596 */
3597 preserve_hdr = 1;
3598 if (del_from != NULL) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003599 int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003600 val_end += delta;
3601 next += delta;
3602 hdr_end += delta;
3603 prev = del_from;
3604 del_from = NULL;
3605 }
3606 continue;
3607 }
3608
3609 /* if there are spaces around the equal sign, we need to
3610 * strip them otherwise we'll get trouble for cookie captures,
3611 * or even for rewrites. Since this happens extremely rarely,
3612 * it does not hurt performance.
3613 */
3614 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3615 int stripped_before = 0;
3616 int stripped_after = 0;
3617
3618 if (att_end != equal) {
3619 memmove(att_end, equal, hdr_end - equal);
3620 stripped_before = (att_end - equal);
3621 equal += stripped_before;
3622 val_beg += stripped_before;
3623 }
3624
3625 if (val_beg > equal + 1) {
3626 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3627 stripped_after = (equal + 1) - val_beg;
3628 val_beg += stripped_after;
3629 stripped_before += stripped_after;
3630 }
3631
3632 val_end += stripped_before;
3633 next += stripped_before;
3634 hdr_end += stripped_before;
3635 }
3636 /* now everything is as on the diagram above */
3637
3638 /* First, let's see if we want to capture this cookie. We check
3639 * that we don't already have a client side cookie, because we
3640 * can only capture one. Also as an optimisation, we ignore
3641 * cookies shorter than the declared name.
3642 */
3643 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
3644 (val_end - att_beg >= sess->fe->capture_namelen) &&
3645 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
3646 int log_len = val_end - att_beg;
3647
3648 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
3649 ha_alert("HTTP logging : out of memory.\n");
3650 } else {
3651 if (log_len > sess->fe->capture_len)
3652 log_len = sess->fe->capture_len;
3653 memcpy(txn->cli_cookie, att_beg, log_len);
3654 txn->cli_cookie[log_len] = 0;
3655 }
3656 }
3657
3658 /* Persistence cookies in passive, rewrite or insert mode have the
3659 * following form :
3660 *
3661 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
3662 *
3663 * For cookies in prefix mode, the form is :
3664 *
3665 * Cookie: NAME=SRV~VALUE
3666 */
3667 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
3668 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
3669 struct server *srv = s->be->srv;
3670 char *delim;
3671
3672 /* if we're in cookie prefix mode, we'll search the delimitor so that we
3673 * have the server ID between val_beg and delim, and the original cookie between
3674 * delim+1 and val_end. Otherwise, delim==val_end :
3675 *
3676 * hdr_beg
3677 * |
3678 * v
3679 * NAME=SRV; # in all but prefix modes
3680 * NAME=SRV~OPAQUE ; # in prefix mode
3681 * || || | |+-> next
3682 * || || | +--> val_end
3683 * || || +---------> delim
3684 * || |+------------> val_beg
3685 * || +-------------> att_end = equal
3686 * |+-----------------> att_beg
3687 * +------------------> prev
3688 *
3689 */
3690 if (s->be->ck_opts & PR_CK_PFX) {
3691 for (delim = val_beg; delim < val_end; delim++)
3692 if (*delim == COOKIE_DELIM)
3693 break;
3694 }
3695 else {
3696 char *vbar1;
3697 delim = val_end;
3698 /* Now check if the cookie contains a date field, which would
3699 * appear after a vertical bar ('|') just after the server name
3700 * and before the delimiter.
3701 */
3702 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
3703 if (vbar1) {
3704 /* OK, so left of the bar is the server's cookie and
3705 * right is the last seen date. It is a base64 encoded
3706 * 30-bit value representing the UNIX date since the
3707 * epoch in 4-second quantities.
3708 */
3709 int val;
3710 delim = vbar1++;
3711 if (val_end - vbar1 >= 5) {
3712 val = b64tos30(vbar1);
3713 if (val > 0)
3714 txn->cookie_last_date = val << 2;
3715 }
3716 /* look for a second vertical bar */
3717 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
3718 if (vbar1 && (val_end - vbar1 > 5)) {
3719 val = b64tos30(vbar1 + 1);
3720 if (val > 0)
3721 txn->cookie_first_date = val << 2;
3722 }
3723 }
3724 }
3725
3726 /* if the cookie has an expiration date and the proxy wants to check
3727 * it, then we do that now. We first check if the cookie is too old,
3728 * then only if it has expired. We detect strict overflow because the
3729 * time resolution here is not great (4 seconds). Cookies with dates
3730 * in the future are ignored if their offset is beyond one day. This
3731 * allows an admin to fix timezone issues without expiring everyone
3732 * and at the same time avoids keeping unwanted side effects for too
3733 * long.
3734 */
3735 if (txn->cookie_first_date && s->be->cookie_maxlife &&
3736 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
3737 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
3738 txn->flags &= ~TX_CK_MASK;
3739 txn->flags |= TX_CK_OLD;
3740 delim = val_beg; // let's pretend we have not found the cookie
3741 txn->cookie_first_date = 0;
3742 txn->cookie_last_date = 0;
3743 }
3744 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
3745 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
3746 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
3747 txn->flags &= ~TX_CK_MASK;
3748 txn->flags |= TX_CK_EXPIRED;
3749 delim = val_beg; // let's pretend we have not found the cookie
3750 txn->cookie_first_date = 0;
3751 txn->cookie_last_date = 0;
3752 }
3753
3754 /* Here, we'll look for the first running server which supports the cookie.
3755 * This allows to share a same cookie between several servers, for example
3756 * to dedicate backup servers to specific servers only.
3757 * However, to prevent clients from sticking to cookie-less backup server
3758 * when they have incidentely learned an empty cookie, we simply ignore
3759 * empty cookies and mark them as invalid.
3760 * The same behaviour is applied when persistence must be ignored.
3761 */
3762 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3763 srv = NULL;
3764
3765 while (srv) {
3766 if (srv->cookie && (srv->cklen == delim - val_beg) &&
3767 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
3768 if ((srv->cur_state != SRV_ST_STOPPED) ||
3769 (s->be->options & PR_O_PERSIST) ||
3770 (s->flags & SF_FORCE_PRST)) {
3771 /* we found the server and we can use it */
3772 txn->flags &= ~TX_CK_MASK;
3773 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
3774 s->flags |= SF_DIRECT | SF_ASSIGNED;
3775 s->target = &srv->obj_type;
3776 break;
3777 } else {
3778 /* we found a server, but it's down,
3779 * mark it as such and go on in case
3780 * another one is available.
3781 */
3782 txn->flags &= ~TX_CK_MASK;
3783 txn->flags |= TX_CK_DOWN;
3784 }
3785 }
3786 srv = srv->next;
3787 }
3788
3789 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
3790 /* no server matched this cookie or we deliberately skipped it */
3791 txn->flags &= ~TX_CK_MASK;
3792 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3793 txn->flags |= TX_CK_UNUSED;
3794 else
3795 txn->flags |= TX_CK_INVALID;
3796 }
3797
3798 /* depending on the cookie mode, we may have to either :
3799 * - delete the complete cookie if we're in insert+indirect mode, so that
3800 * the server never sees it ;
3801 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08003802 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003803 * if we're in cookie prefix mode
3804 */
3805 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
3806 int delta; /* negative */
3807
3808 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
3809 delta = val_beg - (delim + 1);
3810 val_end += delta;
3811 next += delta;
3812 hdr_end += delta;
3813 del_from = NULL;
3814 preserve_hdr = 1; /* we want to keep this cookie */
3815 }
3816 else if (del_from == NULL &&
3817 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
3818 del_from = prev;
3819 }
3820 }
3821 else {
3822 /* This is not our cookie, so we must preserve it. But if we already
3823 * scheduled another cookie for removal, we cannot remove the
3824 * complete header, but we can remove the previous block itself.
3825 */
3826 preserve_hdr = 1;
3827
3828 if (del_from != NULL) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003829 int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003830 if (att_beg >= del_from)
3831 att_beg += delta;
3832 if (att_end >= del_from)
3833 att_end += delta;
3834 val_beg += delta;
3835 val_end += delta;
3836 next += delta;
3837 hdr_end += delta;
3838 prev = del_from;
3839 del_from = NULL;
3840 }
3841 }
3842
3843 /* continue with next cookie on this header line */
3844 att_beg = next;
3845 } /* for each cookie */
3846
3847
3848 /* There are no more cookies on this line.
3849 * We may still have one (or several) marked for deletion at the
3850 * end of the line. We must do this now in two ways :
3851 * - if some cookies must be preserved, we only delete from the
3852 * mark to the end of line ;
3853 * - if nothing needs to be preserved, simply delete the whole header
3854 */
3855 if (del_from) {
3856 hdr_end = (preserve_hdr ? del_from : hdr_beg);
3857 }
3858 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet3e2638e2019-06-18 09:49:16 +02003859 if (hdr_beg != hdr_end)
3860 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003861 else
3862 http_remove_header(htx, &ctx);
3863 }
3864 } /* for each "Cookie header */
3865}
3866
3867/*
3868 * Manage server-side cookies. It can impact performance by about 2% so it is
3869 * desirable to call it only when needed. This function is also used when we
3870 * just need to know if there is a cookie (eg: for check-cache).
3871 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003872static void http_manage_server_side_cookies(struct stream *s, struct channel *res)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003873{
3874 struct session *sess = s->sess;
3875 struct http_txn *txn = s->txn;
3876 struct htx *htx;
3877 struct http_hdr_ctx ctx;
3878 struct server *srv;
3879 char *hdr_beg, *hdr_end;
3880 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02003881 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003882
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003883 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003884
3885 ctx.blk = NULL;
3886 while (1) {
Olivier Houchardf0f42382019-07-22 17:43:46 +02003887 int is_first = 1;
3888
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003889 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
3890 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
3891 break;
3892 is_cookie2 = 1;
3893 }
3894
3895 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
3896 * <prev> points to the colon.
3897 */
3898 txn->flags |= TX_SCK_PRESENT;
3899
3900 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
3901 * check-cache is enabled) and we are not interested in checking
3902 * them. Warning, the cookie capture is declared in the frontend.
3903 */
3904 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
3905 break;
3906
3907 /* OK so now we know we have to process this response cookie.
3908 * The format of the Set-Cookie header is slightly different
3909 * from the format of the Cookie header in that it does not
3910 * support the comma as a cookie delimiter (thus the header
3911 * cannot be folded) because the Expires attribute described in
3912 * the original Netscape's spec may contain an unquoted date
3913 * with a comma inside. We have to live with this because
3914 * many browsers don't support Max-Age and some browsers don't
3915 * support quoted strings. However the Set-Cookie2 header is
3916 * clean.
3917 *
3918 * We have to keep multiple pointers in order to support cookie
3919 * removal at the beginning, middle or end of header without
3920 * corrupting the header (in case of set-cookie2). A special
3921 * pointer, <scav> points to the beginning of the set-cookie-av
3922 * fields after the first semi-colon. The <next> pointer points
3923 * either to the end of line (set-cookie) or next unquoted comma
3924 * (set-cookie2). All of these headers are valid :
3925 *
3926 * hdr_beg hdr_end
3927 * | |
3928 * v |
3929 * NAME1 = VALUE 1 ; Secure; Path="/" |
3930 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
3931 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
3932 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
3933 * | | | | | | | |
3934 * | | | | | | | +-> next
3935 * | | | | | | +------------> scav
3936 * | | | | | +--------------> val_end
3937 * | | | | +--------------------> val_beg
3938 * | | | +----------------------> equal
3939 * | | +------------------------> att_end
3940 * | +----------------------------> att_beg
3941 * +------------------------------> prev
3942 * -------------------------------> hdr_beg
3943 */
3944 hdr_beg = ctx.value.ptr;
3945 hdr_end = hdr_beg + ctx.value.len;
3946 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3947
3948 /* Iterate through all cookies on this line */
3949
3950 /* find att_beg */
3951 att_beg = prev;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003952 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003953 att_beg++;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003954 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003955
3956 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3957 att_beg++;
3958
3959 /* find att_end : this is the first character after the last non
3960 * space before the equal. It may be equal to hdr_end.
3961 */
3962 equal = att_end = att_beg;
3963
3964 while (equal < hdr_end) {
3965 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
3966 break;
3967 if (HTTP_IS_SPHT(*equal++))
3968 continue;
3969 att_end = equal;
3970 }
3971
3972 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3973 * is between <att_beg> and <equal>, both may be identical.
3974 */
3975
3976 /* look for end of cookie if there is an equal sign */
3977 if (equal < hdr_end && *equal == '=') {
3978 /* look for the beginning of the value */
3979 val_beg = equal + 1;
3980 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3981 val_beg++;
3982
3983 /* find the end of the value, respecting quotes */
3984 next = http_find_cookie_value_end(val_beg, hdr_end);
3985
3986 /* make val_end point to the first white space or delimitor after the value */
3987 val_end = next;
3988 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3989 val_end--;
3990 }
3991 else {
3992 /* <equal> points to next comma, semi-colon or EOL */
3993 val_beg = val_end = next = equal;
3994 }
3995
3996 if (next < hdr_end) {
3997 /* Set-Cookie2 supports multiple cookies, and <next> points to
3998 * a colon or semi-colon before the end. So skip all attr-value
3999 * pairs and look for the next comma. For Set-Cookie, since
4000 * commas are permitted in values, skip to the end.
4001 */
4002 if (is_cookie2)
4003 next = http_find_hdr_value_end(next, hdr_end);
4004 else
4005 next = hdr_end;
4006 }
4007
4008 /* Now everything is as on the diagram above */
4009
4010 /* Ignore cookies with no equal sign */
4011 if (equal == val_end)
4012 continue;
4013
4014 /* If there are spaces around the equal sign, we need to
4015 * strip them otherwise we'll get trouble for cookie captures,
4016 * or even for rewrites. Since this happens extremely rarely,
4017 * it does not hurt performance.
4018 */
4019 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4020 int stripped_before = 0;
4021 int stripped_after = 0;
4022
4023 if (att_end != equal) {
4024 memmove(att_end, equal, hdr_end - equal);
4025 stripped_before = (att_end - equal);
4026 equal += stripped_before;
4027 val_beg += stripped_before;
4028 }
4029
4030 if (val_beg > equal + 1) {
4031 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4032 stripped_after = (equal + 1) - val_beg;
4033 val_beg += stripped_after;
4034 stripped_before += stripped_after;
4035 }
4036
4037 val_end += stripped_before;
4038 next += stripped_before;
4039 hdr_end += stripped_before;
4040
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004041 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004042 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004043 }
4044
4045 /* First, let's see if we want to capture this cookie. We check
4046 * that we don't already have a server side cookie, because we
4047 * can only capture one. Also as an optimisation, we ignore
4048 * cookies shorter than the declared name.
4049 */
4050 if (sess->fe->capture_name != NULL &&
4051 txn->srv_cookie == NULL &&
4052 (val_end - att_beg >= sess->fe->capture_namelen) &&
4053 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4054 int log_len = val_end - att_beg;
4055 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4056 ha_alert("HTTP logging : out of memory.\n");
4057 }
4058 else {
4059 if (log_len > sess->fe->capture_len)
4060 log_len = sess->fe->capture_len;
4061 memcpy(txn->srv_cookie, att_beg, log_len);
4062 txn->srv_cookie[log_len] = 0;
4063 }
4064 }
4065
4066 srv = objt_server(s->target);
4067 /* now check if we need to process it for persistence */
4068 if (!(s->flags & SF_IGNORE_PRST) &&
4069 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4070 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4071 /* assume passive cookie by default */
4072 txn->flags &= ~TX_SCK_MASK;
4073 txn->flags |= TX_SCK_FOUND;
4074
4075 /* If the cookie is in insert mode on a known server, we'll delete
4076 * this occurrence because we'll insert another one later.
4077 * We'll delete it too if the "indirect" option is set and we're in
4078 * a direct access.
4079 */
4080 if (s->be->ck_opts & PR_CK_PSV) {
4081 /* The "preserve" flag was set, we don't want to touch the
4082 * server's cookie.
4083 */
4084 }
4085 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4086 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4087 /* this cookie must be deleted */
4088 if (prev == hdr_beg && next == hdr_end) {
4089 /* whole header */
4090 http_remove_header(htx, &ctx);
4091 /* note: while both invalid now, <next> and <hdr_end>
4092 * are still equal, so the for() will stop as expected.
4093 */
4094 } else {
4095 /* just remove the value */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004096 int delta = http_del_hdr_value(hdr_beg, hdr_end, &prev, next);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004097 next = prev;
4098 hdr_end += delta;
4099 }
4100 txn->flags &= ~TX_SCK_MASK;
4101 txn->flags |= TX_SCK_DELETED;
4102 /* and go on with next cookie */
4103 }
4104 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4105 /* replace bytes val_beg->val_end with the cookie name associated
4106 * with this server since we know it.
4107 */
4108 int sliding, delta;
4109
4110 ctx.value = ist2(val_beg, val_end - val_beg);
4111 ctx.lws_before = ctx.lws_after = 0;
4112 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4113 delta = srv->cklen - (val_end - val_beg);
4114 sliding = (ctx.value.ptr - val_beg);
4115 hdr_beg += sliding;
4116 val_beg += sliding;
4117 next += sliding + delta;
4118 hdr_end += sliding + delta;
4119
4120 txn->flags &= ~TX_SCK_MASK;
4121 txn->flags |= TX_SCK_REPLACED;
4122 }
4123 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4124 /* insert the cookie name associated with this server
4125 * before existing cookie, and insert a delimiter between them..
4126 */
4127 int sliding, delta;
4128 ctx.value = ist2(val_beg, 0);
4129 ctx.lws_before = ctx.lws_after = 0;
4130 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4131 delta = srv->cklen + 1;
4132 sliding = (ctx.value.ptr - val_beg);
4133 hdr_beg += sliding;
4134 val_beg += sliding;
4135 next += sliding + delta;
4136 hdr_end += sliding + delta;
4137
4138 val_beg[srv->cklen] = COOKIE_DELIM;
4139 txn->flags &= ~TX_SCK_MASK;
4140 txn->flags |= TX_SCK_REPLACED;
4141 }
4142 }
4143 /* that's done for this cookie, check the next one on the same
4144 * line when next != hdr_end (only if is_cookie2).
4145 */
4146 }
4147 }
4148}
4149
Christopher Faulet25a02f62018-10-24 12:00:25 +02004150/*
4151 * Parses the Cache-Control and Pragma request header fields to determine if
4152 * the request may be served from the cache and/or if it is cacheable. Updates
4153 * s->txn->flags.
4154 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004155void http_check_request_for_cacheability(struct stream *s, struct channel *req)
Christopher Faulet25a02f62018-10-24 12:00:25 +02004156{
4157 struct http_txn *txn = s->txn;
4158 struct htx *htx;
4159 int32_t pos;
4160 int pragma_found, cc_found, i;
4161
4162 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4163 return; /* nothing more to do here */
4164
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004165 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004166 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004167 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004168 struct htx_blk *blk = htx_get_blk(htx, pos);
4169 enum htx_blk_type type = htx_get_blk_type(blk);
4170 struct ist n, v;
4171
4172 if (type == HTX_BLK_EOH)
4173 break;
4174 if (type != HTX_BLK_HDR)
4175 continue;
4176
4177 n = htx_get_blk_name(htx, blk);
4178 v = htx_get_blk_value(htx, blk);
4179
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004180 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004181 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4182 pragma_found = 1;
4183 continue;
4184 }
4185 }
4186
4187 /* Don't use the cache and don't try to store if we found the
4188 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004189 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004190 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4191 txn->flags |= TX_CACHE_IGNORE;
4192 continue;
4193 }
4194
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004195 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004196 continue;
4197
4198 /* OK, right now we know we have a cache-control header */
4199 cc_found = 1;
4200 if (!v.len) /* no info */
4201 continue;
4202
4203 i = 0;
4204 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4205 !isspace((unsigned char)*(v.ptr+i)))
4206 i++;
4207
4208 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4209 * values after max-age, max-stale nor min-fresh, we simply don't
4210 * use the cache when they're specified.
4211 */
4212 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4213 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4214 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4215 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4216 txn->flags |= TX_CACHE_IGNORE;
4217 continue;
4218 }
4219
4220 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4221 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4222 continue;
4223 }
4224 }
4225
4226 /* RFC7234#5.4:
4227 * When the Cache-Control header field is also present and
4228 * understood in a request, Pragma is ignored.
4229 * When the Cache-Control header field is not present in a
4230 * request, caches MUST consider the no-cache request
4231 * pragma-directive as having the same effect as if
4232 * "Cache-Control: no-cache" were present.
4233 */
4234 if (!cc_found && pragma_found)
4235 txn->flags |= TX_CACHE_IGNORE;
4236}
4237
4238/*
4239 * Check if response is cacheable or not. Updates s->txn->flags.
4240 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004241void http_check_response_for_cacheability(struct stream *s, struct channel *res)
Christopher Faulet25a02f62018-10-24 12:00:25 +02004242{
4243 struct http_txn *txn = s->txn;
4244 struct htx *htx;
4245 int32_t pos;
4246 int i;
4247
4248 if (txn->status < 200) {
4249 /* do not try to cache interim responses! */
4250 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4251 return;
4252 }
4253
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004254 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004255 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004256 struct htx_blk *blk = htx_get_blk(htx, pos);
4257 enum htx_blk_type type = htx_get_blk_type(blk);
4258 struct ist n, v;
4259
4260 if (type == HTX_BLK_EOH)
4261 break;
4262 if (type != HTX_BLK_HDR)
4263 continue;
4264
4265 n = htx_get_blk_name(htx, blk);
4266 v = htx_get_blk_value(htx, blk);
4267
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004268 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004269 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4270 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4271 return;
4272 }
4273 }
4274
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004275 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004276 continue;
4277
4278 /* OK, right now we know we have a cache-control header */
4279 if (!v.len) /* no info */
4280 continue;
4281
4282 i = 0;
4283 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4284 !isspace((unsigned char)*(v.ptr+i)))
4285 i++;
4286
4287 /* we have a complete value between v.ptr and (v.ptr+i) */
4288 if (i < v.len && *(v.ptr + i) == '=') {
4289 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4290 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4291 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4292 continue;
4293 }
4294
4295 /* we have something of the form no-cache="set-cookie" */
4296 if ((v.len >= 21) &&
4297 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4298 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4299 txn->flags &= ~TX_CACHE_COOK;
4300 continue;
4301 }
4302
4303 /* OK, so we know that either p2 points to the end of string or to a comma */
4304 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4305 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4306 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4307 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4308 return;
4309 }
4310
4311 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4312 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4313 continue;
4314 }
4315 }
4316}
4317
Christopher Faulet377c5a52018-10-24 21:21:30 +02004318/*
4319 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4320 * for the current backend.
4321 *
4322 * It is assumed that the request is either a HEAD, GET, or POST and that the
4323 * uri_auth field is valid.
4324 *
4325 * Returns 1 if stats should be provided, otherwise 0.
4326 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004327static int http_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004328{
4329 struct uri_auth *uri_auth = backend->uri_auth;
4330 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004331 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004332 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004333
4334 if (!uri_auth)
4335 return 0;
4336
4337 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4338 return 0;
4339
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004340 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004341 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004342 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004343
4344 /* check URI size */
4345 if (uri_auth->uri_len > uri.len)
4346 return 0;
4347
4348 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4349 return 0;
4350
4351 return 1;
4352}
4353
4354/* This function prepares an applet to handle the stats. It can deal with the
4355 * "100-continue" expectation, check that admin rules are met for POST requests,
4356 * and program a response message if something was unexpected. It cannot fail
4357 * and always relies on the stats applet to complete the job. It does not touch
4358 * analysers nor counters, which are left to the caller. It does not touch
4359 * s->target which is supposed to already point to the stats applet. The caller
4360 * is expected to have already assigned an appctx to the stream.
4361 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004362static int http_handle_stats(struct stream *s, struct channel *req)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004363{
4364 struct stats_admin_rule *stats_admin_rule;
4365 struct stream_interface *si = &s->si[1];
4366 struct session *sess = s->sess;
4367 struct http_txn *txn = s->txn;
4368 struct http_msg *msg = &txn->req;
4369 struct uri_auth *uri_auth = s->be->uri_auth;
4370 const char *h, *lookup, *end;
4371 struct appctx *appctx;
4372 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004373 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004374
4375 appctx = si_appctx(si);
4376 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4377 appctx->st1 = appctx->st2 = 0;
4378 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
Willy Tarreau676c29e2019-10-09 10:50:01 +02004379 appctx->ctx.stats.flags |= uri_auth->flags;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004380 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4381 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4382 appctx->ctx.stats.flags |= STAT_CHUNKED;
4383
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004384 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004385 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004386 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4387 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004388
4389 for (h = lookup; h <= end - 3; h++) {
4390 if (memcmp(h, ";up", 3) == 0) {
4391 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4392 break;
4393 }
4394 }
4395
4396 if (uri_auth->refresh) {
4397 for (h = lookup; h <= end - 10; h++) {
4398 if (memcmp(h, ";norefresh", 10) == 0) {
4399 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4400 break;
4401 }
4402 }
4403 }
4404
4405 for (h = lookup; h <= end - 4; h++) {
4406 if (memcmp(h, ";csv", 4) == 0) {
Christopher Faulet6338a082019-09-09 15:50:54 +02004407 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004408 break;
4409 }
4410 }
4411
4412 for (h = lookup; h <= end - 6; h++) {
4413 if (memcmp(h, ";typed", 6) == 0) {
Christopher Faulet6338a082019-09-09 15:50:54 +02004414 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004415 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4416 break;
4417 }
4418 }
4419
Christopher Faulet6338a082019-09-09 15:50:54 +02004420 for (h = lookup; h <= end - 5; h++) {
4421 if (memcmp(h, ";json", 5) == 0) {
4422 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
4423 appctx->ctx.stats.flags |= STAT_FMT_JSON;
4424 break;
4425 }
4426 }
4427
4428 for (h = lookup; h <= end - 12; h++) {
4429 if (memcmp(h, ";json-schema", 12) == 0) {
4430 appctx->ctx.stats.flags &= ~STAT_FMT_MASK;
4431 appctx->ctx.stats.flags |= STAT_JSON_SCHM;
4432 break;
4433 }
4434 }
4435
Christopher Faulet377c5a52018-10-24 21:21:30 +02004436 for (h = lookup; h <= end - 8; h++) {
4437 if (memcmp(h, ";st=", 4) == 0) {
4438 int i;
4439 h += 4;
4440 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4441 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4442 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4443 appctx->ctx.stats.st_code = i;
4444 break;
4445 }
4446 }
4447 break;
4448 }
4449 }
4450
4451 appctx->ctx.stats.scope_str = 0;
4452 appctx->ctx.stats.scope_len = 0;
4453 for (h = lookup; h <= end - 8; h++) {
4454 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4455 int itx = 0;
4456 const char *h2;
4457 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4458 const char *err;
4459
4460 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4461 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004462 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4463 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004464 if (*h == ';' || *h == '&' || *h == ' ')
4465 break;
4466 itx++;
4467 h++;
4468 }
4469
4470 if (itx > STAT_SCOPE_TXT_MAXLEN)
4471 itx = STAT_SCOPE_TXT_MAXLEN;
4472 appctx->ctx.stats.scope_len = itx;
4473
4474 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4475 memcpy(scope_txt, h2, itx);
4476 scope_txt[itx] = '\0';
4477 err = invalid_char(scope_txt);
4478 if (err) {
4479 /* bad char in search text => clear scope */
4480 appctx->ctx.stats.scope_str = 0;
4481 appctx->ctx.stats.scope_len = 0;
4482 }
4483 break;
4484 }
4485 }
4486
4487 /* now check whether we have some admin rules for this request */
4488 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4489 int ret = 1;
4490
4491 if (stats_admin_rule->cond) {
4492 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4493 ret = acl_pass(ret);
4494 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4495 ret = !ret;
4496 }
4497
4498 if (ret) {
4499 /* no rule, or the rule matches */
4500 appctx->ctx.stats.flags |= STAT_ADMIN;
4501 break;
4502 }
4503 }
4504
Christopher Faulet5d45e382019-02-27 15:15:23 +01004505 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4506 appctx->st0 = STAT_HTTP_HEAD;
4507 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbd9e8422019-08-15 22:26:48 +02004508 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004509 appctx->st0 = STAT_HTTP_POST;
Christopher Fauletbd9e8422019-08-15 22:26:48 +02004510 if (msg->msg_state < HTTP_MSG_DATA)
4511 req->analysers |= AN_REQ_HTTP_BODY;
4512 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02004513 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004514 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004515 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4516 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4517 appctx->st0 = STAT_HTTP_LAST;
4518 }
4519 }
4520 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004521 /* Unsupported method */
4522 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4523 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4524 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004525 }
4526
4527 s->task->nice = -32; /* small boost for HTTP statistics */
4528 return 1;
4529}
4530
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004531void http_perform_server_redirect(struct stream *s, struct stream_interface *si)
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004532{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004533 struct channel *req = &s->req;
4534 struct channel *res = &s->res;
4535 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004536 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004537 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004538 struct ist path, location;
4539 unsigned int flags;
4540 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004541
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004542 /*
4543 * Create the location
4544 */
4545 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004546
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004547 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004548 /* special prefix "/" means don't change URL */
4549 srv = __objt_server(s->target);
4550 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4551 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4552 return;
4553 }
4554
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004555 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004556 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004557 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004558 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004559 if (!path.ptr)
4560 return;
4561
4562 if (!chunk_memcat(&trash, path.ptr, path.len))
4563 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004564 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004565
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004566 /*
4567 * Create the 302 respone
4568 */
4569 htx = htx_from_buf(&res->buf);
4570 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4571 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4572 ist("HTTP/1.1"), ist("302"), ist("Found"));
4573 if (!sl)
4574 goto fail;
4575 sl->info.res.status = 302;
4576 s->txn->status = 302;
4577
4578 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4579 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4580 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4581 !htx_add_header(htx, ist("Location"), location))
4582 goto fail;
4583
4584 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4585 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004586
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004587 /*
4588 * Send the message
4589 */
4590 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004591 c_adv(res, data);
4592 res->total += data;
4593
4594 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004595 si_shutr(si);
4596 si_shutw(si);
4597 si->err_type = SI_ET_NONE;
4598 si->state = SI_ST_CLO;
4599
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004600 channel_auto_read(req);
4601 channel_abort(req);
4602 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004603 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004604 channel_auto_read(res);
4605 channel_auto_close(res);
4606
4607 if (!(s->flags & SF_ERR_MASK))
4608 s->flags |= SF_ERR_LOCAL;
4609 if (!(s->flags & SF_FINST_MASK))
4610 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004611
4612 /* FIXME: we should increase a counter of redirects per server and per backend. */
4613 srv_inc_sess_ctr(srv);
4614 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004615 return;
4616
4617 fail:
4618 /* If an error occurred, remove the incomplete HTTP response from the
4619 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004620 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004621}
4622
Christopher Fauletf2824e62018-10-01 12:12:37 +02004623/* This function terminates the request because it was completly analyzed or
4624 * because an error was triggered during the body forwarding.
4625 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004626static void http_end_request(struct stream *s)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004627{
4628 struct channel *chn = &s->req;
4629 struct http_txn *txn = s->txn;
4630
4631 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4632 now_ms, __FUNCTION__, s,
4633 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4634 s->req.analysers, s->res.analysers);
4635
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004636 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4637 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004638 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004639 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02004640 goto end;
4641 }
4642
4643 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4644 return;
4645
4646 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004647 /* No need to read anymore, the request was completely parsed.
4648 * We can shut the read side unless we want to abort_on_close,
4649 * or we have a POST request. The issue with POST requests is
4650 * that some browsers still send a CRLF after the request, and
4651 * this CRLF must be read so that it does not remain in the kernel
4652 * buffers, otherwise a close could cause an RST on some systems
4653 * (eg: Linux).
4654 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01004655 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004656 channel_dont_read(chn);
4657
4658 /* if the server closes the connection, we want to immediately react
4659 * and close the socket to save packets and syscalls.
4660 */
4661 s->si[1].flags |= SI_FL_NOHALF;
4662
4663 /* In any case we've finished parsing the request so we must
4664 * disable Nagle when sending data because 1) we're not going
4665 * to shut this side, and 2) the server is waiting for us to
4666 * send pending data.
4667 */
4668 chn->flags |= CF_NEVER_WAIT;
4669
Christopher Fauletd01ce402019-01-02 17:44:13 +01004670 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4671 /* The server has not finished to respond, so we
4672 * don't want to move in order not to upset it.
4673 */
4674 return;
4675 }
4676
Christopher Fauletf2824e62018-10-01 12:12:37 +02004677 /* When we get here, it means that both the request and the
4678 * response have finished receiving. Depending on the connection
4679 * mode, we'll have to wait for the last bytes to leave in either
4680 * direction, and sometimes for a close to be effective.
4681 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02004682 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004683 /* Tunnel mode will not have any analyser so it needs to
4684 * poll for reads.
4685 */
4686 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02004687 if (b_data(&chn->buf))
4688 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004689 txn->req.msg_state = HTTP_MSG_TUNNEL;
4690 }
4691 else {
4692 /* we're not expecting any new data to come for this
4693 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02004694 *
4695 * However, there is an exception if the response
4696 * length is undefined. In this case, we need to wait
4697 * the close from the server. The response will be
4698 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02004699 */
4700 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
4701 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02004702 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004703
4704 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4705 channel_shutr_now(chn);
4706 channel_shutw_now(chn);
4707 }
4708 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02004709 goto check_channel_flags;
4710 }
4711
4712 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
4713 http_msg_closing:
4714 /* nothing else to forward, just waiting for the output buffer
4715 * to be empty and for the shutw_now to take effect.
4716 */
4717 if (channel_is_empty(chn)) {
4718 txn->req.msg_state = HTTP_MSG_CLOSED;
4719 goto http_msg_closed;
4720 }
4721 else if (chn->flags & CF_SHUTW) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004722 txn->req.msg_state = HTTP_MSG_ERROR;
4723 goto end;
4724 }
4725 return;
4726 }
4727
4728 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
4729 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02004730 /* if we don't know whether the server will close, we need to hard close */
4731 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
4732 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02004733 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01004734 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02004735 channel_dont_read(chn);
4736 goto end;
4737 }
4738
4739 check_channel_flags:
4740 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4741 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4742 /* if we've just closed an output, let's switch */
4743 txn->req.msg_state = HTTP_MSG_CLOSING;
4744 goto http_msg_closing;
4745 }
4746
4747 end:
4748 chn->analysers &= AN_REQ_FLT_END;
4749 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
4750 chn->analysers |= AN_REQ_FLT_XFER_DATA;
4751 channel_auto_close(chn);
4752 channel_auto_read(chn);
4753}
4754
4755
4756/* This function terminates the response because it was completly analyzed or
4757 * because an error was triggered during the body forwarding.
4758 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004759static void http_end_response(struct stream *s)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004760{
4761 struct channel *chn = &s->res;
4762 struct http_txn *txn = s->txn;
4763
4764 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4765 now_ms, __FUNCTION__, s,
4766 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4767 s->req.analysers, s->res.analysers);
4768
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004769 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4770 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004771 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02004772 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004773 goto end;
4774 }
4775
4776 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
4777 return;
4778
4779 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
4780 /* In theory, we don't need to read anymore, but we must
4781 * still monitor the server connection for a possible close
4782 * while the request is being uploaded, so we don't disable
4783 * reading.
4784 */
4785 /* channel_dont_read(chn); */
4786
4787 if (txn->req.msg_state < HTTP_MSG_DONE) {
4788 /* The client seems to still be sending data, probably
4789 * because we got an error response during an upload.
4790 * We have the choice of either breaking the connection
4791 * or letting it pass through. Let's do the later.
4792 */
4793 return;
4794 }
4795
4796 /* When we get here, it means that both the request and the
4797 * response have finished receiving. Depending on the connection
4798 * mode, we'll have to wait for the last bytes to leave in either
4799 * direction, and sometimes for a close to be effective.
4800 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02004801 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004802 channel_auto_read(chn);
4803 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02004804 if (b_data(&chn->buf))
4805 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004806 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
4807 }
4808 else {
4809 /* we're not expecting any new data to come for this
4810 * transaction, so we can close it.
4811 */
4812 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4813 channel_shutr_now(chn);
4814 channel_shutw_now(chn);
4815 }
4816 }
4817 goto check_channel_flags;
4818 }
4819
4820 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
4821 http_msg_closing:
4822 /* nothing else to forward, just waiting for the output buffer
4823 * to be empty and for the shutw_now to take effect.
4824 */
4825 if (channel_is_empty(chn)) {
4826 txn->rsp.msg_state = HTTP_MSG_CLOSED;
4827 goto http_msg_closed;
4828 }
4829 else if (chn->flags & CF_SHUTW) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004830 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01004831 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004832 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01004833 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004834 goto end;
4835 }
4836 return;
4837 }
4838
4839 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
4840 http_msg_closed:
4841 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004842 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02004843 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004844 goto end;
4845 }
4846
4847 check_channel_flags:
4848 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4849 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4850 /* if we've just closed an output, let's switch */
4851 txn->rsp.msg_state = HTTP_MSG_CLOSING;
4852 goto http_msg_closing;
4853 }
4854
4855 end:
4856 chn->analysers &= AN_RES_FLT_END;
4857 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
4858 chn->analysers |= AN_RES_FLT_XFER_DATA;
4859 channel_auto_close(chn);
4860 channel_auto_read(chn);
4861}
4862
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004863void http_server_error(struct stream *s, struct stream_interface *si, int err,
4864 int finst, const struct buffer *msg)
Christopher Faulet0f226952018-10-22 09:29:56 +02004865{
4866 channel_auto_read(si_oc(si));
4867 channel_abort(si_oc(si));
4868 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004869 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02004870 channel_auto_close(si_ic(si));
4871 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004872
4873 /* <msg> is an HTX structure. So we copy it in the response's
4874 * channel */
Christopher Faulet9f5839c2019-07-22 16:41:43 +02004875 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02004876 struct channel *chn = si_ic(si);
4877 struct htx *htx;
4878
Christopher Fauletaed82cf2018-11-30 22:22:32 +01004879 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004880 chn->buf.data = msg->data;
4881 memcpy(chn->buf.area, msg->area, msg->data);
4882 htx = htx_from_buf(&chn->buf);
Christopher Faulet06511812019-10-16 09:38:27 +02004883 htx->flags |= HTX_FL_PROXY_RESP;
Christopher Faulet0f226952018-10-22 09:29:56 +02004884 c_adv(chn, htx->data);
4885 chn->total += htx->data;
4886 }
4887 if (!(s->flags & SF_ERR_MASK))
4888 s->flags |= err;
4889 if (!(s->flags & SF_FINST_MASK))
4890 s->flags |= finst;
4891}
4892
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004893void http_reply_and_close(struct stream *s, short status, struct buffer *msg)
Christopher Faulet0f226952018-10-22 09:29:56 +02004894{
4895 channel_auto_read(&s->req);
4896 channel_abort(&s->req);
4897 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004898 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
4899 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02004900
4901 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004902
4903 /* <msg> is an HTX structure. So we copy it in the response's
4904 * channel */
4905 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet9f5839c2019-07-22 16:41:43 +02004906 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02004907 struct channel *chn = &s->res;
4908 struct htx *htx;
4909
Christopher Fauletaed82cf2018-11-30 22:22:32 +01004910 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004911 chn->buf.data = msg->data;
4912 memcpy(chn->buf.area, msg->area, msg->data);
4913 htx = htx_from_buf(&chn->buf);
Christopher Faulet06511812019-10-16 09:38:27 +02004914 htx->flags |= HTX_FL_PROXY_RESP;
Christopher Faulet0f226952018-10-22 09:29:56 +02004915 c_adv(chn, htx->data);
4916 chn->total += htx->data;
4917 }
4918
4919 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
4920 channel_auto_read(&s->res);
4921 channel_auto_close(&s->res);
4922 channel_shutr_now(&s->res);
4923}
4924
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004925struct buffer *http_error_message(struct stream *s)
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004926{
4927 const int msgnum = http_get_status_idx(s->txn->status);
4928
4929 if (s->be->errmsg[msgnum].area)
4930 return &s->be->errmsg[msgnum];
4931 else if (strm_fe(s)->errmsg[msgnum].area)
4932 return &strm_fe(s)->errmsg[msgnum];
4933 else
Christopher Fauletf7346382019-07-17 22:02:08 +02004934 return &http_err_chunks[msgnum];
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004935}
4936
Christopher Faulet304cc402019-07-15 15:46:28 +02004937/* Return the error message corresponding to si->err_type. It is assumed
4938 * that the server side is closed. Note that err_type is actually a
4939 * bitmask, where almost only aborts may be cumulated with other
4940 * values. We consider that aborted operations are more important
4941 * than timeouts or errors due to the fact that nobody else in the
4942 * logs might explain incomplete retries. All others should avoid
4943 * being cumulated. It should normally not be possible to have multiple
4944 * aborts at once, but just in case, the first one in sequence is reported.
4945 * Note that connection errors appearing on the second request of a keep-alive
4946 * connection are not reported since this allows the client to retry.
4947 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004948void http_return_srv_error(struct stream *s, struct stream_interface *si)
Christopher Faulet304cc402019-07-15 15:46:28 +02004949{
4950 int err_type = si->err_type;
4951
4952 /* set s->txn->status for http_error_message(s) */
4953 s->txn->status = 503;
4954
4955 if (err_type & SI_ET_QUEUE_ABRT)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004956 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
4957 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004958 else if (err_type & SI_ET_CONN_ABRT)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004959 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
4960 (s->txn->flags & TX_NOT_FIRST) ? NULL :
4961 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004962 else if (err_type & SI_ET_QUEUE_TO)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004963 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
4964 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004965 else if (err_type & SI_ET_QUEUE_ERR)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004966 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
4967 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004968 else if (err_type & SI_ET_CONN_TO)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004969 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
4970 (s->txn->flags & TX_NOT_FIRST) ? NULL :
4971 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004972 else if (err_type & SI_ET_CONN_ERR)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004973 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
4974 (s->flags & SF_SRV_REUSED) ? NULL :
4975 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004976 else if (err_type & SI_ET_CONN_RES)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004977 http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
4978 (s->txn->flags & TX_NOT_FIRST) ? NULL :
4979 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004980 else { /* SI_ET_CONN_OTHER and others */
4981 s->txn->status = 500;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004982 http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
4983 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004984 }
4985}
4986
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004987
Christopher Faulet4a28a532019-03-01 11:19:40 +01004988/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
4989 * on success and -1 on error.
4990 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004991static int http_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
Christopher Faulet4a28a532019-03-01 11:19:40 +01004992{
4993 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
4994 * then we must send an HTTP/1.1 100 Continue intermediate response.
4995 */
4996 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
4997 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
4998 struct ist hdr = { .ptr = "Expect", .len = 6 };
4999 struct http_hdr_ctx ctx;
5000
5001 ctx.blk = NULL;
5002 /* Expect is allowed in 1.1, look for it */
5003 if (http_find_header(htx, hdr, &ctx, 0) &&
5004 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005005 if (http_reply_100_continue(s) == -1)
Christopher Faulet4a28a532019-03-01 11:19:40 +01005006 return -1;
5007 http_remove_header(htx, &ctx);
5008 }
5009 }
5010 return 0;
5011}
5012
Christopher Faulet23a3c792018-11-28 10:01:23 +01005013/* Send a 100-Continue response to the client. It returns 0 on success and -1
5014 * on error. The response channel is updated accordingly.
5015 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005016static int http_reply_100_continue(struct stream *s)
Christopher Faulet23a3c792018-11-28 10:01:23 +01005017{
5018 struct channel *res = &s->res;
5019 struct htx *htx = htx_from_buf(&res->buf);
5020 struct htx_sl *sl;
5021 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5022 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5023 size_t data;
5024
5025 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5026 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5027 if (!sl)
5028 goto fail;
5029 sl->info.res.status = 100;
5030
Christopher Faulet1d5ec092019-06-26 14:23:54 +02005031 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005032 goto fail;
5033
5034 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005035 c_adv(res, data);
5036 res->total += data;
5037 return 0;
5038
5039 fail:
5040 /* If an error occurred, remove the incomplete HTTP response from the
5041 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005042 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005043 return -1;
5044}
5045
Christopher Faulet12c51e22018-11-28 15:59:42 +01005046
5047/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5048 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5049 * error. The response channel is updated accordingly.
5050 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005051static int http_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
Christopher Faulet12c51e22018-11-28 15:59:42 +01005052{
5053 struct channel *res = &s->res;
5054 struct htx *htx = htx_from_buf(&res->buf);
5055 struct htx_sl *sl;
5056 struct ist code, body;
5057 int status;
5058 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5059 size_t data;
5060
5061 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5062 status = 401;
5063 code = ist("401");
5064 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5065 "You need a valid user and password to access this content.\n"
5066 "</body></html>\n");
5067 }
5068 else {
5069 status = 407;
5070 code = ist("407");
5071 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5072 "You need a valid user and password to access this content.\n"
5073 "</body></html>\n");
5074 }
5075
5076 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5077 ist("HTTP/1.1"), code, ist("Unauthorized"));
5078 if (!sl)
5079 goto fail;
5080 sl->info.res.status = status;
5081 s->txn->status = status;
5082
5083 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5084 goto fail;
5085
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005086 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5087 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005088 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005089 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5090 goto fail;
5091 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5092 goto fail;
5093 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005094 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005095 if (!htx_add_endof(htx, HTX_BLK_EOH))
5096 goto fail;
5097
5098 while (body.len) {
5099 size_t sent = htx_add_data(htx, body);
5100 if (!sent)
5101 goto fail;
5102 body.ptr += sent;
5103 body.len -= sent;
5104 }
5105
5106 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005107 goto fail;
5108
Christopher Faulet06511812019-10-16 09:38:27 +02005109 htx->flags |= HTX_FL_PROXY_RESP;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005110 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005111 c_adv(res, data);
5112 res->total += data;
5113
5114 channel_auto_read(&s->req);
5115 channel_abort(&s->req);
5116 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005117 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005118
5119 res->wex = tick_add_ifset(now_ms, res->wto);
5120 channel_auto_read(res);
5121 channel_auto_close(res);
5122 channel_shutr_now(res);
5123 return 0;
5124
5125 fail:
5126 /* If an error occurred, remove the incomplete HTTP response from the
5127 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005128 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005129 return -1;
5130}
5131
Christopher Faulet0f226952018-10-22 09:29:56 +02005132/*
5133 * Capture headers from message <htx> according to header list <cap_hdr>, and
5134 * fill the <cap> pointers appropriately.
5135 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005136static void http_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
Christopher Faulet0f226952018-10-22 09:29:56 +02005137{
5138 struct cap_hdr *h;
5139 int32_t pos;
5140
Christopher Fauleta3f15502019-05-13 15:27:23 +02005141 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005142 struct htx_blk *blk = htx_get_blk(htx, pos);
5143 enum htx_blk_type type = htx_get_blk_type(blk);
5144 struct ist n, v;
5145
5146 if (type == HTX_BLK_EOH)
5147 break;
5148 if (type != HTX_BLK_HDR)
5149 continue;
5150
5151 n = htx_get_blk_name(htx, blk);
5152
5153 for (h = cap_hdr; h; h = h->next) {
5154 if (h->namelen && (h->namelen == n.len) &&
5155 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5156 if (cap[h->index] == NULL)
5157 cap[h->index] =
5158 pool_alloc(h->pool);
5159
5160 if (cap[h->index] == NULL) {
5161 ha_alert("HTTP capture : out of memory.\n");
5162 break;
5163 }
5164
5165 v = htx_get_blk_value(htx, blk);
5166 if (v.len > h->len)
5167 v.len = h->len;
5168
5169 memcpy(cap[h->index], v.ptr, v.len);
5170 cap[h->index][v.len]=0;
5171 }
5172 }
5173 }
5174}
5175
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005176/* Delete a value in a header between delimiters <from> and <next>. The header
5177 * itself is delimited by <start> and <end> pointers. The number of characters
5178 * displaced is returned, and the pointer to the first delimiter is updated if
5179 * required. The function tries as much as possible to respect the following
5180 * principles :
5181 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5182 * in which case <next> is simply removed
5183 * - set exactly one space character after the new first delimiter, unless there
5184 * are not enough characters in the block being moved to do so.
5185 * - remove unneeded spaces before the previous delimiter and after the new
5186 * one.
5187 *
5188 * It is the caller's responsibility to ensure that :
5189 * - <from> points to a valid delimiter or <start> ;
5190 * - <next> points to a valid delimiter or <end> ;
5191 * - there are non-space chars before <from>.
5192 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005193static int http_del_hdr_value(char *start, char *end, char **from, char *next)
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005194{
5195 char *prev = *from;
5196
5197 if (prev == start) {
5198 /* We're removing the first value. eat the semicolon, if <next>
5199 * is lower than <end> */
5200 if (next < end)
5201 next++;
5202
5203 while (next < end && HTTP_IS_SPHT(*next))
5204 next++;
5205 }
5206 else {
5207 /* Remove useless spaces before the old delimiter. */
5208 while (HTTP_IS_SPHT(*(prev-1)))
5209 prev--;
5210 *from = prev;
5211
5212 /* copy the delimiter and if possible a space if we're
5213 * not at the end of the line.
5214 */
5215 if (next < end) {
5216 *prev++ = *next++;
5217 if (prev + 1 < next)
5218 *prev++ = ' ';
5219 while (next < end && HTTP_IS_SPHT(*next))
5220 next++;
5221 }
5222 }
5223 memmove(prev, next, end - next);
5224 return (prev - next);
5225}
5226
Christopher Faulet0f226952018-10-22 09:29:56 +02005227
5228/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005229 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005230 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005231static size_t http_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005232{
5233 struct ist dst = ist2(str, 0);
5234
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005235 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005236 goto end;
5237 if (dst.len + 1 > len)
5238 goto end;
5239 dst.ptr[dst.len++] = ' ';
5240
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005241 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005242 goto end;
5243 if (dst.len + 1 > len)
5244 goto end;
5245 dst.ptr[dst.len++] = ' ';
5246
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005247 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005248 end:
5249 return dst.len;
5250}
5251
5252/*
5253 * Print a debug line with a start line.
5254 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005255static void http_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005256{
5257 struct session *sess = strm_sess(s);
5258 int max;
5259
5260 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5261 dir,
5262 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5263 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5264
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005265 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005266 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005267 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005268 trash.area[trash.data++] = ' ';
5269
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005270 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005271 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005272 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005273 trash.area[trash.data++] = ' ';
5274
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005275 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005276 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005277 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005278 trash.area[trash.data++] = '\n';
5279
5280 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5281}
5282
5283/*
5284 * Print a debug line with a header.
5285 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005286static void http_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
Christopher Faulet0f226952018-10-22 09:29:56 +02005287{
5288 struct session *sess = strm_sess(s);
5289 int max;
5290
5291 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5292 dir,
5293 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5294 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5295
5296 max = n.len;
5297 UBOUND(max, trash.size - trash.data - 3);
5298 chunk_memcat(&trash, n.ptr, max);
5299 trash.area[trash.data++] = ':';
5300 trash.area[trash.data++] = ' ';
5301
5302 max = v.len;
5303 UBOUND(max, trash.size - trash.data - 1);
5304 chunk_memcat(&trash, v.ptr, max);
5305 trash.area[trash.data++] = '\n';
5306
5307 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5308}
5309
Christopher Fauleta8a46e22019-07-16 14:53:09 +02005310/* Allocate a new HTTP transaction for stream <s> unless there is one already.
5311 * In case of allocation failure, everything allocated is freed and NULL is
5312 * returned. Otherwise the new transaction is assigned to the stream and
5313 * returned.
5314 */
5315struct http_txn *http_alloc_txn(struct stream *s)
5316{
5317 struct http_txn *txn = s->txn;
5318
5319 if (txn)
5320 return txn;
5321
5322 txn = pool_alloc(pool_head_http_txn);
5323 if (!txn)
5324 return txn;
5325
5326 s->txn = txn;
5327 return txn;
5328}
5329
5330void http_txn_reset_req(struct http_txn *txn)
5331{
5332 txn->req.flags = 0;
5333 txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */
5334}
5335
5336void http_txn_reset_res(struct http_txn *txn)
5337{
5338 txn->rsp.flags = 0;
5339 txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */
5340}
5341
5342/*
5343 * Initialize a new HTTP transaction for stream <s>. It is assumed that all
5344 * the required fields are properly allocated and that we only need to (re)init
5345 * them. This should be used before processing any new request.
5346 */
5347void http_init_txn(struct stream *s)
5348{
5349 struct http_txn *txn = s->txn;
5350 struct conn_stream *cs = objt_cs(s->si[0].end);
5351
5352 txn->flags = ((cs && cs->flags & CS_FL_NOT_FIRST)
5353 ? (TX_NOT_FIRST|TX_WAIT_NEXT_RQ)
5354 : 0);
5355 txn->status = -1;
5356 *(unsigned int *)txn->cache_hash = 0;
5357
5358 txn->cookie_first_date = 0;
5359 txn->cookie_last_date = 0;
5360
5361 txn->srv_cookie = NULL;
5362 txn->cli_cookie = NULL;
5363 txn->uri = NULL;
5364
5365 http_txn_reset_req(txn);
5366 http_txn_reset_res(txn);
5367
5368 txn->req.chn = &s->req;
5369 txn->rsp.chn = &s->res;
5370
5371 txn->auth.method = HTTP_AUTH_UNKNOWN;
5372
5373 vars_init(&s->vars_txn, SCOPE_TXN);
5374 vars_init(&s->vars_reqres, SCOPE_REQ);
5375}
5376
5377/* to be used at the end of a transaction */
5378void http_end_txn(struct stream *s)
5379{
5380 struct http_txn *txn = s->txn;
5381 struct proxy *fe = strm_fe(s);
5382
5383 /* these ones will have been dynamically allocated */
5384 pool_free(pool_head_requri, txn->uri);
5385 pool_free(pool_head_capture, txn->cli_cookie);
5386 pool_free(pool_head_capture, txn->srv_cookie);
5387 pool_free(pool_head_uniqueid, s->unique_id);
5388
5389 s->unique_id = NULL;
5390 txn->uri = NULL;
5391 txn->srv_cookie = NULL;
5392 txn->cli_cookie = NULL;
5393
5394 if (s->req_cap) {
5395 struct cap_hdr *h;
5396 for (h = fe->req_cap; h; h = h->next)
5397 pool_free(h->pool, s->req_cap[h->index]);
5398 memset(s->req_cap, 0, fe->nb_req_cap * sizeof(void *));
5399 }
5400
5401 if (s->res_cap) {
5402 struct cap_hdr *h;
5403 for (h = fe->rsp_cap; h; h = h->next)
5404 pool_free(h->pool, s->res_cap[h->index]);
5405 memset(s->res_cap, 0, fe->nb_rsp_cap * sizeof(void *));
5406 }
5407
5408 if (!LIST_ISEMPTY(&s->vars_txn.head))
5409 vars_prune(&s->vars_txn, s->sess, s);
5410 if (!LIST_ISEMPTY(&s->vars_reqres.head))
5411 vars_prune(&s->vars_reqres, s->sess, s);
5412}
5413
5414/* to be used at the end of a transaction to prepare a new one */
5415void http_reset_txn(struct stream *s)
5416{
5417 http_end_txn(s);
5418 http_init_txn(s);
5419
5420 /* reinitialise the current rule list pointer to NULL. We are sure that
5421 * any rulelist match the NULL pointer.
5422 */
5423 s->current_rule_list = NULL;
5424
5425 s->be = strm_fe(s);
5426 s->logs.logwait = strm_fe(s)->to_log;
5427 s->logs.level = 0;
5428 stream_del_srv_conn(s);
5429 s->target = NULL;
5430 /* re-init store persistence */
5431 s->store_count = 0;
5432 s->uniq_id = _HA_ATOMIC_XADD(&global.req_count, 1);
5433
5434 s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
5435
5436 /* We must trim any excess data from the response buffer, because we
5437 * may have blocked an invalid response from a server that we don't
5438 * want to accidently forward once we disable the analysers, nor do
5439 * we want those data to come along with next response. A typical
5440 * example of such data would be from a buggy server responding to
5441 * a HEAD with some data, or sending more than the advertised
5442 * content-length.
5443 */
5444 if (unlikely(ci_data(&s->res)))
5445 b_set_data(&s->res.buf, co_data(&s->res));
5446
5447 /* Now we can realign the response buffer */
5448 c_realign_if_empty(&s->res);
5449
5450 s->req.rto = strm_fe(s)->timeout.client;
5451 s->req.wto = TICK_ETERNITY;
5452
5453 s->res.rto = TICK_ETERNITY;
5454 s->res.wto = strm_fe(s)->timeout.client;
5455
5456 s->req.rex = TICK_ETERNITY;
5457 s->req.wex = TICK_ETERNITY;
5458 s->req.analyse_exp = TICK_ETERNITY;
5459 s->res.rex = TICK_ETERNITY;
5460 s->res.wex = TICK_ETERNITY;
5461 s->res.analyse_exp = TICK_ETERNITY;
5462 s->si[1].hcto = TICK_ETERNITY;
5463}
5464
5465
5466DECLARE_POOL(pool_head_http_txn, "http_txn", sizeof(struct http_txn));
5467DECLARE_POOL(pool_head_uniqueid, "uniqueid", UNIQUEID_LEN);
Christopher Faulet0f226952018-10-22 09:29:56 +02005468
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005469__attribute__((constructor))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005470static void __http_protocol_init(void)
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005471{
5472}
5473
5474
5475/*
5476 * Local variables:
5477 * c-indent-level: 8
5478 * c-basic-offset: 8
5479 * End:
5480 */