blob: b5089d11bf8e3a43005a868c64dbbc6655f85562 [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 Faulet99daf282018-11-28 22:58:13 +01002530 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 c_adv(res, data);
2532 res->total += data;
2533
2534 channel_auto_read(req);
2535 channel_abort(req);
2536 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002537 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002538
2539 res->wex = tick_add_ifset(now_ms, res->wto);
2540 channel_auto_read(res);
2541 channel_auto_close(res);
2542 channel_shutr_now(res);
2543
2544 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002545
2546 if (!(s->flags & SF_ERR_MASK))
2547 s->flags |= SF_ERR_LOCAL;
2548 if (!(s->flags & SF_FINST_MASK))
2549 s->flags |= SF_FINST_R;
2550
Christopher Faulet99daf282018-11-28 22:58:13 +01002551 free_trash_chunk(chunk);
2552 return 1;
2553
2554 fail:
2555 /* If an error occurred, remove the incomplete HTTP response from the
2556 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002557 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002558 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002559 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002560}
2561
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002562int http_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2563 struct ist name, const char *str, struct my_regex *re, int action)
Christopher Faulet72333522018-10-24 11:25:02 +02002564{
2565 struct http_hdr_ctx ctx;
2566 struct buffer *output = get_trash_chunk();
2567
2568 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2569 ctx.blk = NULL;
2570 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2571 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2572 continue;
2573
2574 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2575 if (output->data == -1)
2576 return -1;
2577 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2578 return -1;
2579 }
2580 return 0;
2581}
2582
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002583static int http_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2584 const struct ist name, struct list *fmt, struct my_regex *re, int action)
Christopher Faulet72333522018-10-24 11:25:02 +02002585{
2586 struct buffer *replace;
2587 int ret = -1;
2588
2589 replace = alloc_trash_chunk();
2590 if (!replace)
2591 goto leave;
2592
2593 replace->data = build_logline(s, replace->area, replace->size, fmt);
2594 if (replace->data >= replace->size - 1)
2595 goto leave;
2596
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002597 ret = http_transform_header_str(s, chn, htx, name, replace->area, re, action);
Christopher Faulet72333522018-10-24 11:25:02 +02002598
2599 leave:
2600 free_trash_chunk(replace);
2601 return ret;
2602}
2603
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002604
2605/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2606 * on success and -1 on error. The response channel is updated accordingly.
2607 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002608static int http_reply_103_early_hints(struct channel *res)
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002609{
2610 struct htx *htx = htx_from_buf(&res->buf);
2611 size_t data;
2612
Christopher Faulet1d5ec092019-06-26 14:23:54 +02002613 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002614 /* If an error occurred during an Early-hint rule,
2615 * remove the incomplete HTTP 103 response from the
2616 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002617 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002618 return -1;
2619 }
2620
2621 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 c_adv(res, data);
2623 res->total += data;
2624 return 0;
2625}
2626
Christopher Faulet6eb92892018-11-15 16:39:29 +01002627/*
2628 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2629 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002630 * If <early_hints> is 0, it is starts a new response by adding the start
2631 * line. If an error occurred -1 is returned. On success 0 is returned. The
2632 * channel is not updated here. It must be done calling the function
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002633 * http_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002635static 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 +01002636{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637 struct channel *res = &s->res;
2638 struct htx *htx = htx_from_buf(&res->buf);
2639 struct buffer *value = alloc_trash_chunk();
2640
Christopher Faulet6eb92892018-11-15 16:39:29 +01002641 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 struct htx_sl *sl;
2643 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2644 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2645
2646 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2647 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2648 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002649 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002651 }
2652
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002653 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2654 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002655 goto fail;
2656
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002657 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002659
2660 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 /* If an error occurred during an Early-hint rule, remove the incomplete
2662 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002663 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002664 free_trash_chunk(value);
2665 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002666}
2667
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002668/* This function executes one of the set-{method,path,query,uri} actions. It
2669 * takes the string from the variable 'replace' with length 'len', then modifies
2670 * the relevant part of the request line accordingly. Then it updates various
2671 * pointers to the next elements which were moved, and the total buffer length.
2672 * It finds the action to be performed in p[2], previously filled by function
2673 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2674 * error, though this can be revisited when this code is finally exploited.
2675 *
2676 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2677 * query string and 3 to replace uri.
2678 *
2679 * In query string case, the mark question '?' must be set at the start of the
2680 * string by the caller, event if the replacement query string is empty.
2681 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002682int http_req_replace_stline(int action, const char *replace, int len,
2683 struct proxy *px, struct stream *s)
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002684{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002685 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002686
2687 switch (action) {
2688 case 0: // method
2689 if (!http_replace_req_meth(htx, ist2(replace, len)))
2690 return -1;
2691 break;
2692
2693 case 1: // path
2694 if (!http_replace_req_path(htx, ist2(replace, len)))
2695 return -1;
2696 break;
2697
2698 case 2: // query
2699 if (!http_replace_req_query(htx, ist2(replace, len)))
2700 return -1;
2701 break;
2702
2703 case 3: // uri
2704 if (!http_replace_req_uri(htx, ist2(replace, len)))
2705 return -1;
2706 break;
2707
2708 default:
2709 return -1;
2710 }
2711 return 0;
2712}
2713
2714/* This function replace the HTTP status code and the associated message. The
2715 * variable <status> contains the new status code. This function never fails.
2716 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002717void http_res_set_status(unsigned int status, const char *reason, struct stream *s)
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002718{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002719 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002720 char *res;
2721
2722 chunk_reset(&trash);
2723 res = ultoa_o(status, trash.area, trash.size);
2724 trash.data = res - trash.area;
2725
2726 /* Do we have a custom reason format string? */
2727 if (reason == NULL)
2728 reason = http_get_reason(status);
2729
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002730 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002731 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2732}
2733
Christopher Faulet3e964192018-10-24 11:39:23 +02002734/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2735 * transaction <txn>. Returns the verdict of the first rule that prevents
2736 * further processing of the request (auth, deny, ...), and defaults to
2737 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2738 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2739 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2740 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2741 * status.
2742 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002743static enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules,
2744 struct stream *s, int *deny_status)
Christopher Faulet3e964192018-10-24 11:39:23 +02002745{
2746 struct session *sess = strm_sess(s);
2747 struct http_txn *txn = s->txn;
2748 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002749 struct act_rule *rule;
2750 struct http_hdr_ctx ctx;
2751 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002752 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2753 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002754 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002755
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002756 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002757
2758 /* If "the current_rule_list" match the executed rule list, we are in
2759 * resume condition. If a resume is needed it is always in the action
2760 * and never in the ACL or converters. In this case, we initialise the
2761 * current rule, and go to the action execution point.
2762 */
2763 if (s->current_rule) {
2764 rule = s->current_rule;
2765 s->current_rule = NULL;
2766 if (s->current_rule_list == rules)
2767 goto resume_execution;
2768 }
2769 s->current_rule_list = rules;
2770
2771 list_for_each_entry(rule, rules, list) {
2772 /* check optional condition */
2773 if (rule->cond) {
2774 int ret;
2775
2776 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2777 ret = acl_pass(ret);
2778
2779 if (rule->cond->pol == ACL_COND_UNLESS)
2780 ret = !ret;
2781
2782 if (!ret) /* condition not matched */
2783 continue;
2784 }
2785
2786 act_flags |= ACT_FLAG_FIRST;
2787 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002788 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2789 early_hints = 0;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002790 if (http_reply_103_early_hints(&s->res) == -1) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002791 rule_ret = HTTP_RULE_RES_BADREQ;
2792 goto end;
2793 }
2794 }
2795
Christopher Faulet3e964192018-10-24 11:39:23 +02002796 switch (rule->action) {
2797 case ACT_ACTION_ALLOW:
2798 rule_ret = HTTP_RULE_RES_STOP;
2799 goto end;
2800
2801 case ACT_ACTION_DENY:
2802 if (deny_status)
2803 *deny_status = rule->deny_status;
2804 rule_ret = HTTP_RULE_RES_DENY;
2805 goto end;
2806
2807 case ACT_HTTP_REQ_TARPIT:
2808 txn->flags |= TX_CLTARPIT;
2809 if (deny_status)
2810 *deny_status = rule->deny_status;
2811 rule_ret = HTTP_RULE_RES_DENY;
2812 goto end;
2813
2814 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002815 /* Auth might be performed on regular http-req rules as well as on stats */
2816 auth_realm = rule->arg.auth.realm;
2817 if (!auth_realm) {
2818 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2819 auth_realm = STATS_DEFAULT_REALM;
2820 else
2821 auth_realm = px->id;
2822 }
2823 /* send 401/407 depending on whether we use a proxy or not. We still
2824 * count one error, because normal browsing won't significantly
2825 * increase the counter but brute force attempts will.
2826 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002827 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002828 if (http_reply_40x_unauthorized(s, auth_realm) == -1)
Christopher Faulet12c51e22018-11-28 15:59:42 +01002829 rule_ret = HTTP_RULE_RES_BADREQ;
2830 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002831 goto end;
2832
2833 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002834 rule_ret = HTTP_RULE_RES_DONE;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002835 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02002836 rule_ret = HTTP_RULE_RES_BADREQ;
2837 goto end;
2838
2839 case ACT_HTTP_SET_NICE:
2840 s->task->nice = rule->arg.nice;
2841 break;
2842
2843 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002844 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002845 break;
2846
2847 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002848 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002849 break;
2850
2851 case ACT_HTTP_SET_LOGL:
2852 s->logs.level = rule->arg.loglevel;
2853 break;
2854
2855 case ACT_HTTP_REPLACE_HDR:
2856 case ACT_HTTP_REPLACE_VAL:
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02002857 if (http_transform_header(s, &s->req, htx,
2858 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2859 &rule->arg.hdr_add.fmt,
2860 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002861 rule_ret = HTTP_RULE_RES_BADREQ;
2862 goto end;
2863 }
2864 break;
2865
2866 case ACT_HTTP_DEL_HDR:
2867 /* remove all occurrences of the header */
2868 ctx.blk = NULL;
2869 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2870 http_remove_header(htx, &ctx);
2871 break;
2872
2873 case ACT_HTTP_SET_HDR:
2874 case ACT_HTTP_ADD_HDR: {
2875 /* The scope of the trash buffer must be limited to this function. The
2876 * build_logline() function can execute a lot of other function which
2877 * can use the trash buffer. So for limiting the scope of this global
2878 * buffer, we build first the header value using build_logline, and
2879 * after we store the header name.
2880 */
2881 struct buffer *replace;
2882 struct ist n, v;
2883
2884 replace = alloc_trash_chunk();
2885 if (!replace) {
2886 rule_ret = HTTP_RULE_RES_BADREQ;
2887 goto end;
2888 }
2889
2890 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2891 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2892 v = ist2(replace->area, replace->data);
2893
2894 if (rule->action == ACT_HTTP_SET_HDR) {
2895 /* remove all occurrences of the header */
2896 ctx.blk = NULL;
2897 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2898 http_remove_header(htx, &ctx);
2899 }
2900
2901 if (!http_add_header(htx, n, v)) {
2902 static unsigned char rate_limit = 0;
2903
2904 if ((rate_limit++ & 255) == 0) {
2905 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);
2906 }
2907
Olivier Houcharda798bf52019-03-08 18:52:00 +01002908 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002909 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002910 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002911 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002912 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002913 }
2914 free_trash_chunk(replace);
2915 break;
2916 }
2917
2918 case ACT_HTTP_DEL_ACL:
2919 case ACT_HTTP_DEL_MAP: {
2920 struct pat_ref *ref;
2921 struct buffer *key;
2922
2923 /* collect reference */
2924 ref = pat_ref_lookup(rule->arg.map.ref);
2925 if (!ref)
2926 continue;
2927
2928 /* allocate key */
2929 key = alloc_trash_chunk();
2930 if (!key) {
2931 rule_ret = HTTP_RULE_RES_BADREQ;
2932 goto end;
2933 }
2934
2935 /* collect key */
2936 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2937 key->area[key->data] = '\0';
2938
2939 /* perform update */
2940 /* returned code: 1=ok, 0=ko */
2941 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2942 pat_ref_delete(ref, key->area);
2943 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2944
2945 free_trash_chunk(key);
2946 break;
2947 }
2948
2949 case ACT_HTTP_ADD_ACL: {
2950 struct pat_ref *ref;
2951 struct buffer *key;
2952
2953 /* collect reference */
2954 ref = pat_ref_lookup(rule->arg.map.ref);
2955 if (!ref)
2956 continue;
2957
2958 /* allocate key */
2959 key = alloc_trash_chunk();
2960 if (!key) {
2961 rule_ret = HTTP_RULE_RES_BADREQ;
2962 goto end;
2963 }
2964
2965 /* collect key */
2966 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2967 key->area[key->data] = '\0';
2968
2969 /* perform update */
2970 /* add entry only if it does not already exist */
2971 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2972 if (pat_ref_find_elt(ref, key->area) == NULL)
2973 pat_ref_add(ref, key->area, NULL, NULL);
2974 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2975
2976 free_trash_chunk(key);
2977 break;
2978 }
2979
2980 case ACT_HTTP_SET_MAP: {
2981 struct pat_ref *ref;
2982 struct buffer *key, *value;
2983
2984 /* collect reference */
2985 ref = pat_ref_lookup(rule->arg.map.ref);
2986 if (!ref)
2987 continue;
2988
2989 /* allocate key */
2990 key = alloc_trash_chunk();
2991 if (!key) {
2992 rule_ret = HTTP_RULE_RES_BADREQ;
2993 goto end;
2994 }
2995
2996 /* allocate value */
2997 value = alloc_trash_chunk();
2998 if (!value) {
2999 free_trash_chunk(key);
3000 rule_ret = HTTP_RULE_RES_BADREQ;
3001 goto end;
3002 }
3003
3004 /* collect key */
3005 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3006 key->area[key->data] = '\0';
3007
3008 /* collect value */
3009 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3010 value->area[value->data] = '\0';
3011
3012 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003013 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003014 if (pat_ref_find_elt(ref, key->area) != NULL)
3015 /* update entry if it exists */
3016 pat_ref_set(ref, key->area, value->area, NULL);
3017 else
3018 /* insert a new entry */
3019 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003020 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003021 free_trash_chunk(key);
3022 free_trash_chunk(value);
3023 break;
3024 }
3025
3026 case ACT_HTTP_EARLY_HINT:
3027 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3028 break;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003029 early_hints = http_add_early_hint_header(s, early_hints,
3030 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
3031 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003032 if (early_hints == -1) {
3033 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003034 goto end;
3035 }
3036 break;
3037
3038 case ACT_CUSTOM:
3039 if ((s->req.flags & CF_READ_ERROR) ||
3040 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003041 (px->options & PR_O_ABRT_CLOSE)))
3042 act_flags |= ACT_FLAG_FINAL;
3043
3044 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3045 case ACT_RET_ERR:
3046 case ACT_RET_CONT:
3047 break;
3048 case ACT_RET_STOP:
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003049 rule_ret = HTTP_RULE_RES_STOP;
3050 goto end;
3051 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003052 rule_ret = HTTP_RULE_RES_DONE;
3053 goto end;
3054 case ACT_RET_YIELD:
3055 s->current_rule = rule;
3056 rule_ret = HTTP_RULE_RES_YIELD;
3057 goto end;
3058 }
3059 break;
3060
3061 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3062 /* Note: only the first valid tracking parameter of each
3063 * applies.
3064 */
3065
3066 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3067 struct stktable *t;
3068 struct stksess *ts;
3069 struct stktable_key *key;
3070 void *ptr1, *ptr2;
3071
3072 t = rule->arg.trk_ctr.table.t;
3073 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3074 rule->arg.trk_ctr.expr, NULL);
3075
3076 if (key && (ts = stktable_get_entry(t, key))) {
3077 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3078
3079 /* let's count a new HTTP request as it's the first time we do it */
3080 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3081 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3082 if (ptr1 || ptr2) {
3083 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3084
3085 if (ptr1)
3086 stktable_data_cast(ptr1, http_req_cnt)++;
3087
3088 if (ptr2)
3089 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3090 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3091
3092 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3093
3094 /* If data was modified, we need to touch to re-schedule sync */
3095 stktable_touch_local(t, ts, 0);
3096 }
3097
3098 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3099 if (sess->fe != s->be)
3100 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3101 }
3102 }
3103 break;
3104
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003105 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003106 default:
3107 break;
3108 }
3109 }
3110
3111 end:
3112 if (early_hints) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003113 if (http_reply_103_early_hints(&s->res) == -1)
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003114 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003115 }
3116
3117 /* we reached the end of the rules, nothing to report */
3118 return rule_ret;
3119}
3120
3121/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3122 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3123 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3124 * is returned, the process can continue the evaluation of next rule list. If
3125 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3126 * is returned, it means the operation could not be processed and a server error
3127 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3128 * deny rule. If *YIELD is returned, the caller must call again the function
3129 * with the same context.
3130 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003131static enum rule_result http_res_get_intercept_rule(struct proxy *px, struct list *rules,
3132 struct stream *s)
Christopher Faulet3e964192018-10-24 11:39:23 +02003133{
3134 struct session *sess = strm_sess(s);
3135 struct http_txn *txn = s->txn;
3136 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003137 struct act_rule *rule;
3138 struct http_hdr_ctx ctx;
3139 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3140 int act_flags = 0;
3141
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003142 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003143
3144 /* If "the current_rule_list" match the executed rule list, we are in
3145 * resume condition. If a resume is needed it is always in the action
3146 * and never in the ACL or converters. In this case, we initialise the
3147 * current rule, and go to the action execution point.
3148 */
3149 if (s->current_rule) {
3150 rule = s->current_rule;
3151 s->current_rule = NULL;
3152 if (s->current_rule_list == rules)
3153 goto resume_execution;
3154 }
3155 s->current_rule_list = rules;
3156
3157 list_for_each_entry(rule, rules, list) {
3158 /* check optional condition */
3159 if (rule->cond) {
3160 int ret;
3161
3162 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3163 ret = acl_pass(ret);
3164
3165 if (rule->cond->pol == ACL_COND_UNLESS)
3166 ret = !ret;
3167
3168 if (!ret) /* condition not matched */
3169 continue;
3170 }
3171
3172 act_flags |= ACT_FLAG_FIRST;
3173resume_execution:
3174 switch (rule->action) {
3175 case ACT_ACTION_ALLOW:
3176 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3177 goto end;
3178
3179 case ACT_ACTION_DENY:
3180 txn->flags |= TX_SVDENY;
3181 rule_ret = HTTP_RULE_RES_STOP;
3182 goto end;
3183
3184 case ACT_HTTP_SET_NICE:
3185 s->task->nice = rule->arg.nice;
3186 break;
3187
3188 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003189 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003190 break;
3191
3192 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003193 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003194 break;
3195
3196 case ACT_HTTP_SET_LOGL:
3197 s->logs.level = rule->arg.loglevel;
3198 break;
3199
3200 case ACT_HTTP_REPLACE_HDR:
3201 case ACT_HTTP_REPLACE_VAL:
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003202 if (http_transform_header(s, &s->res, htx,
3203 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3204 &rule->arg.hdr_add.fmt,
3205 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003206 rule_ret = HTTP_RULE_RES_BADREQ;
3207 goto end;
3208 }
3209 break;
3210
3211 case ACT_HTTP_DEL_HDR:
3212 /* remove all occurrences of the header */
3213 ctx.blk = NULL;
3214 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3215 http_remove_header(htx, &ctx);
3216 break;
3217
3218 case ACT_HTTP_SET_HDR:
3219 case ACT_HTTP_ADD_HDR: {
3220 struct buffer *replace;
3221 struct ist n, v;
3222
3223 replace = alloc_trash_chunk();
3224 if (!replace) {
3225 rule_ret = HTTP_RULE_RES_BADREQ;
3226 goto end;
3227 }
3228
3229 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3230 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3231 v = ist2(replace->area, replace->data);
3232
3233 if (rule->action == ACT_HTTP_SET_HDR) {
3234 /* remove all occurrences of the header */
3235 ctx.blk = NULL;
3236 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3237 http_remove_header(htx, &ctx);
3238 }
3239
3240 if (!http_add_header(htx, n, v)) {
3241 static unsigned char rate_limit = 0;
3242
3243 if ((rate_limit++ & 255) == 0) {
3244 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);
3245 }
3246
Olivier Houcharda798bf52019-03-08 18:52:00 +01003247 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003248 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003249 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003250 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003251 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003252 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003253 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003254 }
3255 free_trash_chunk(replace);
3256 break;
3257 }
3258
3259 case ACT_HTTP_DEL_ACL:
3260 case ACT_HTTP_DEL_MAP: {
3261 struct pat_ref *ref;
3262 struct buffer *key;
3263
3264 /* collect reference */
3265 ref = pat_ref_lookup(rule->arg.map.ref);
3266 if (!ref)
3267 continue;
3268
3269 /* allocate key */
3270 key = alloc_trash_chunk();
3271 if (!key) {
3272 rule_ret = HTTP_RULE_RES_BADREQ;
3273 goto end;
3274 }
3275
3276 /* collect key */
3277 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3278 key->area[key->data] = '\0';
3279
3280 /* perform update */
3281 /* returned code: 1=ok, 0=ko */
3282 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3283 pat_ref_delete(ref, key->area);
3284 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3285
3286 free_trash_chunk(key);
3287 break;
3288 }
3289
3290 case ACT_HTTP_ADD_ACL: {
3291 struct pat_ref *ref;
3292 struct buffer *key;
3293
3294 /* collect reference */
3295 ref = pat_ref_lookup(rule->arg.map.ref);
3296 if (!ref)
3297 continue;
3298
3299 /* allocate key */
3300 key = alloc_trash_chunk();
3301 if (!key) {
3302 rule_ret = HTTP_RULE_RES_BADREQ;
3303 goto end;
3304 }
3305
3306 /* collect key */
3307 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3308 key->area[key->data] = '\0';
3309
3310 /* perform update */
3311 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003312 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003313 if (pat_ref_find_elt(ref, key->area) == NULL)
3314 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003315 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003316 free_trash_chunk(key);
3317 break;
3318 }
3319
3320 case ACT_HTTP_SET_MAP: {
3321 struct pat_ref *ref;
3322 struct buffer *key, *value;
3323
3324 /* collect reference */
3325 ref = pat_ref_lookup(rule->arg.map.ref);
3326 if (!ref)
3327 continue;
3328
3329 /* allocate key */
3330 key = alloc_trash_chunk();
3331 if (!key) {
3332 rule_ret = HTTP_RULE_RES_BADREQ;
3333 goto end;
3334 }
3335
3336 /* allocate value */
3337 value = alloc_trash_chunk();
3338 if (!value) {
3339 free_trash_chunk(key);
3340 rule_ret = HTTP_RULE_RES_BADREQ;
3341 goto end;
3342 }
3343
3344 /* collect key */
3345 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3346 key->area[key->data] = '\0';
3347
3348 /* collect value */
3349 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3350 value->area[value->data] = '\0';
3351
3352 /* perform update */
3353 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3354 if (pat_ref_find_elt(ref, key->area) != NULL)
3355 /* update entry if it exists */
3356 pat_ref_set(ref, key->area, value->area, NULL);
3357 else
3358 /* insert a new entry */
3359 pat_ref_add(ref, key->area, value->area, NULL);
3360 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3361 free_trash_chunk(key);
3362 free_trash_chunk(value);
3363 break;
3364 }
3365
3366 case ACT_HTTP_REDIR:
3367 rule_ret = HTTP_RULE_RES_DONE;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003368 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02003369 rule_ret = HTTP_RULE_RES_BADREQ;
3370 goto end;
3371
3372 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3373 /* Note: only the first valid tracking parameter of each
3374 * applies.
3375 */
3376 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3377 struct stktable *t;
3378 struct stksess *ts;
3379 struct stktable_key *key;
3380 void *ptr;
3381
3382 t = rule->arg.trk_ctr.table.t;
3383 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3384 rule->arg.trk_ctr.expr, NULL);
3385
3386 if (key && (ts = stktable_get_entry(t, key))) {
3387 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3388
3389 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3390
3391 /* let's count a new HTTP request as it's the first time we do it */
3392 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3393 if (ptr)
3394 stktable_data_cast(ptr, http_req_cnt)++;
3395
3396 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3397 if (ptr)
3398 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3399 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3400
3401 /* When the client triggers a 4xx from the server, it's most often due
3402 * to a missing object or permission. These events should be tracked
3403 * because if they happen often, it may indicate a brute force or a
3404 * vulnerability scan. Normally this is done when receiving the response
3405 * but here we're tracking after this ought to have been done so we have
3406 * to do it on purpose.
3407 */
3408 if ((unsigned)(txn->status - 400) < 100) {
3409 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3410 if (ptr)
3411 stktable_data_cast(ptr, http_err_cnt)++;
3412
3413 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3414 if (ptr)
3415 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3416 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3417 }
3418
3419 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3420
3421 /* If data was modified, we need to touch to re-schedule sync */
3422 stktable_touch_local(t, ts, 0);
3423
3424 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3425 if (sess->fe != s->be)
3426 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3427 }
3428 }
3429 break;
3430
3431 case ACT_CUSTOM:
3432 if ((s->req.flags & CF_READ_ERROR) ||
3433 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003434 (px->options & PR_O_ABRT_CLOSE)))
3435 act_flags |= ACT_FLAG_FINAL;
3436
3437 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3438 case ACT_RET_ERR:
3439 case ACT_RET_CONT:
3440 break;
3441 case ACT_RET_STOP:
3442 rule_ret = HTTP_RULE_RES_STOP;
3443 goto end;
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003444 case ACT_RET_DONE:
3445 rule_ret = HTTP_RULE_RES_DONE;
3446 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003447 case ACT_RET_YIELD:
3448 s->current_rule = rule;
3449 rule_ret = HTTP_RULE_RES_YIELD;
3450 goto end;
3451 }
3452 break;
3453
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003454 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003455 default:
3456 break;
3457 }
3458 }
3459
3460 end:
3461 /* we reached the end of the rules, nothing to report */
3462 return rule_ret;
3463}
3464
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003465/*
3466 * Manage client-side cookie. It can impact performance by about 2% so it is
3467 * desirable to call it only when needed. This code is quite complex because
3468 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3469 * highly recommended not to touch this part without a good reason !
3470 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003471static void http_manage_client_side_cookies(struct stream *s, struct channel *req)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003472{
3473 struct session *sess = s->sess;
3474 struct http_txn *txn = s->txn;
3475 struct htx *htx;
3476 struct http_hdr_ctx ctx;
3477 char *hdr_beg, *hdr_end, *del_from;
3478 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3479 int preserve_hdr;
3480
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003481 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003482 ctx.blk = NULL;
3483 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardf0f42382019-07-22 17:43:46 +02003484 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003485 del_from = NULL; /* nothing to be deleted */
3486 preserve_hdr = 0; /* assume we may kill the whole header */
3487
3488 /* Now look for cookies. Conforming to RFC2109, we have to support
3489 * attributes whose name begin with a '$', and associate them with
3490 * the right cookie, if we want to delete this cookie.
3491 * So there are 3 cases for each cookie read :
3492 * 1) it's a special attribute, beginning with a '$' : ignore it.
3493 * 2) it's a server id cookie that we *MAY* want to delete : save
3494 * some pointers on it (last semi-colon, beginning of cookie...)
3495 * 3) it's an application cookie : we *MAY* have to delete a previous
3496 * "special" cookie.
3497 * At the end of loop, if a "special" cookie remains, we may have to
3498 * remove it. If no application cookie persists in the header, we
3499 * *MUST* delete it.
3500 *
3501 * Note: RFC2965 is unclear about the processing of spaces around
3502 * the equal sign in the ATTR=VALUE form. A careful inspection of
3503 * the RFC explicitly allows spaces before it, and not within the
3504 * tokens (attrs or values). An inspection of RFC2109 allows that
3505 * too but section 10.1.3 lets one think that spaces may be allowed
3506 * after the equal sign too, resulting in some (rare) buggy
3507 * implementations trying to do that. So let's do what servers do.
3508 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3509 * allowed quoted strings in values, with any possible character
3510 * after a backslash, including control chars and delimitors, which
3511 * causes parsing to become ambiguous. Browsers also allow spaces
3512 * within values even without quotes.
3513 *
3514 * We have to keep multiple pointers in order to support cookie
3515 * removal at the beginning, middle or end of header without
3516 * corrupting the header. All of these headers are valid :
3517 *
3518 * hdr_beg hdr_end
3519 * | |
3520 * v |
3521 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3522 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3523 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3524 * | | | | | | |
3525 * | | | | | | |
3526 * | | | | | | +--> next
3527 * | | | | | +----> val_end
3528 * | | | | +-----------> val_beg
3529 * | | | +--------------> equal
3530 * | | +----------------> att_end
3531 * | +---------------------> att_beg
3532 * +--------------------------> prev
3533 *
3534 */
3535 hdr_beg = ctx.value.ptr;
3536 hdr_end = hdr_beg + ctx.value.len;
3537 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3538 /* Iterate through all cookies on this line */
3539
3540 /* find att_beg */
3541 att_beg = prev;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003542 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003543 att_beg++;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003544 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003545
3546 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3547 att_beg++;
3548
3549 /* find att_end : this is the first character after the last non
3550 * space before the equal. It may be equal to hdr_end.
3551 */
3552 equal = att_end = att_beg;
3553 while (equal < hdr_end) {
3554 if (*equal == '=' || *equal == ',' || *equal == ';')
3555 break;
3556 if (HTTP_IS_SPHT(*equal++))
3557 continue;
3558 att_end = equal;
3559 }
3560
3561 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3562 * is between <att_beg> and <equal>, both may be identical.
3563 */
3564 /* look for end of cookie if there is an equal sign */
3565 if (equal < hdr_end && *equal == '=') {
3566 /* look for the beginning of the value */
3567 val_beg = equal + 1;
3568 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3569 val_beg++;
3570
3571 /* find the end of the value, respecting quotes */
3572 next = http_find_cookie_value_end(val_beg, hdr_end);
3573
3574 /* make val_end point to the first white space or delimitor after the value */
3575 val_end = next;
3576 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3577 val_end--;
3578 }
3579 else
3580 val_beg = val_end = next = equal;
3581
3582 /* We have nothing to do with attributes beginning with
3583 * '$'. However, they will automatically be removed if a
3584 * header before them is removed, since they're supposed
3585 * to be linked together.
3586 */
3587 if (*att_beg == '$')
3588 continue;
3589
3590 /* Ignore cookies with no equal sign */
3591 if (equal == next) {
3592 /* This is not our cookie, so we must preserve it. But if we already
3593 * scheduled another cookie for removal, we cannot remove the
3594 * complete header, but we can remove the previous block itself.
3595 */
3596 preserve_hdr = 1;
3597 if (del_from != NULL) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003598 int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003599 val_end += delta;
3600 next += delta;
3601 hdr_end += delta;
3602 prev = del_from;
3603 del_from = NULL;
3604 }
3605 continue;
3606 }
3607
3608 /* if there are spaces around the equal sign, we need to
3609 * strip them otherwise we'll get trouble for cookie captures,
3610 * or even for rewrites. Since this happens extremely rarely,
3611 * it does not hurt performance.
3612 */
3613 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3614 int stripped_before = 0;
3615 int stripped_after = 0;
3616
3617 if (att_end != equal) {
3618 memmove(att_end, equal, hdr_end - equal);
3619 stripped_before = (att_end - equal);
3620 equal += stripped_before;
3621 val_beg += stripped_before;
3622 }
3623
3624 if (val_beg > equal + 1) {
3625 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3626 stripped_after = (equal + 1) - val_beg;
3627 val_beg += stripped_after;
3628 stripped_before += stripped_after;
3629 }
3630
3631 val_end += stripped_before;
3632 next += stripped_before;
3633 hdr_end += stripped_before;
3634 }
3635 /* now everything is as on the diagram above */
3636
3637 /* First, let's see if we want to capture this cookie. We check
3638 * that we don't already have a client side cookie, because we
3639 * can only capture one. Also as an optimisation, we ignore
3640 * cookies shorter than the declared name.
3641 */
3642 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
3643 (val_end - att_beg >= sess->fe->capture_namelen) &&
3644 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
3645 int log_len = val_end - att_beg;
3646
3647 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
3648 ha_alert("HTTP logging : out of memory.\n");
3649 } else {
3650 if (log_len > sess->fe->capture_len)
3651 log_len = sess->fe->capture_len;
3652 memcpy(txn->cli_cookie, att_beg, log_len);
3653 txn->cli_cookie[log_len] = 0;
3654 }
3655 }
3656
3657 /* Persistence cookies in passive, rewrite or insert mode have the
3658 * following form :
3659 *
3660 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
3661 *
3662 * For cookies in prefix mode, the form is :
3663 *
3664 * Cookie: NAME=SRV~VALUE
3665 */
3666 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
3667 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
3668 struct server *srv = s->be->srv;
3669 char *delim;
3670
3671 /* if we're in cookie prefix mode, we'll search the delimitor so that we
3672 * have the server ID between val_beg and delim, and the original cookie between
3673 * delim+1 and val_end. Otherwise, delim==val_end :
3674 *
3675 * hdr_beg
3676 * |
3677 * v
3678 * NAME=SRV; # in all but prefix modes
3679 * NAME=SRV~OPAQUE ; # in prefix mode
3680 * || || | |+-> next
3681 * || || | +--> val_end
3682 * || || +---------> delim
3683 * || |+------------> val_beg
3684 * || +-------------> att_end = equal
3685 * |+-----------------> att_beg
3686 * +------------------> prev
3687 *
3688 */
3689 if (s->be->ck_opts & PR_CK_PFX) {
3690 for (delim = val_beg; delim < val_end; delim++)
3691 if (*delim == COOKIE_DELIM)
3692 break;
3693 }
3694 else {
3695 char *vbar1;
3696 delim = val_end;
3697 /* Now check if the cookie contains a date field, which would
3698 * appear after a vertical bar ('|') just after the server name
3699 * and before the delimiter.
3700 */
3701 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
3702 if (vbar1) {
3703 /* OK, so left of the bar is the server's cookie and
3704 * right is the last seen date. It is a base64 encoded
3705 * 30-bit value representing the UNIX date since the
3706 * epoch in 4-second quantities.
3707 */
3708 int val;
3709 delim = vbar1++;
3710 if (val_end - vbar1 >= 5) {
3711 val = b64tos30(vbar1);
3712 if (val > 0)
3713 txn->cookie_last_date = val << 2;
3714 }
3715 /* look for a second vertical bar */
3716 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
3717 if (vbar1 && (val_end - vbar1 > 5)) {
3718 val = b64tos30(vbar1 + 1);
3719 if (val > 0)
3720 txn->cookie_first_date = val << 2;
3721 }
3722 }
3723 }
3724
3725 /* if the cookie has an expiration date and the proxy wants to check
3726 * it, then we do that now. We first check if the cookie is too old,
3727 * then only if it has expired. We detect strict overflow because the
3728 * time resolution here is not great (4 seconds). Cookies with dates
3729 * in the future are ignored if their offset is beyond one day. This
3730 * allows an admin to fix timezone issues without expiring everyone
3731 * and at the same time avoids keeping unwanted side effects for too
3732 * long.
3733 */
3734 if (txn->cookie_first_date && s->be->cookie_maxlife &&
3735 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
3736 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
3737 txn->flags &= ~TX_CK_MASK;
3738 txn->flags |= TX_CK_OLD;
3739 delim = val_beg; // let's pretend we have not found the cookie
3740 txn->cookie_first_date = 0;
3741 txn->cookie_last_date = 0;
3742 }
3743 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
3744 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
3745 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
3746 txn->flags &= ~TX_CK_MASK;
3747 txn->flags |= TX_CK_EXPIRED;
3748 delim = val_beg; // let's pretend we have not found the cookie
3749 txn->cookie_first_date = 0;
3750 txn->cookie_last_date = 0;
3751 }
3752
3753 /* Here, we'll look for the first running server which supports the cookie.
3754 * This allows to share a same cookie between several servers, for example
3755 * to dedicate backup servers to specific servers only.
3756 * However, to prevent clients from sticking to cookie-less backup server
3757 * when they have incidentely learned an empty cookie, we simply ignore
3758 * empty cookies and mark them as invalid.
3759 * The same behaviour is applied when persistence must be ignored.
3760 */
3761 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3762 srv = NULL;
3763
3764 while (srv) {
3765 if (srv->cookie && (srv->cklen == delim - val_beg) &&
3766 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
3767 if ((srv->cur_state != SRV_ST_STOPPED) ||
3768 (s->be->options & PR_O_PERSIST) ||
3769 (s->flags & SF_FORCE_PRST)) {
3770 /* we found the server and we can use it */
3771 txn->flags &= ~TX_CK_MASK;
3772 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
3773 s->flags |= SF_DIRECT | SF_ASSIGNED;
3774 s->target = &srv->obj_type;
3775 break;
3776 } else {
3777 /* we found a server, but it's down,
3778 * mark it as such and go on in case
3779 * another one is available.
3780 */
3781 txn->flags &= ~TX_CK_MASK;
3782 txn->flags |= TX_CK_DOWN;
3783 }
3784 }
3785 srv = srv->next;
3786 }
3787
3788 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
3789 /* no server matched this cookie or we deliberately skipped it */
3790 txn->flags &= ~TX_CK_MASK;
3791 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
3792 txn->flags |= TX_CK_UNUSED;
3793 else
3794 txn->flags |= TX_CK_INVALID;
3795 }
3796
3797 /* depending on the cookie mode, we may have to either :
3798 * - delete the complete cookie if we're in insert+indirect mode, so that
3799 * the server never sees it ;
3800 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08003801 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003802 * if we're in cookie prefix mode
3803 */
3804 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
3805 int delta; /* negative */
3806
3807 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
3808 delta = val_beg - (delim + 1);
3809 val_end += delta;
3810 next += delta;
3811 hdr_end += delta;
3812 del_from = NULL;
3813 preserve_hdr = 1; /* we want to keep this cookie */
3814 }
3815 else if (del_from == NULL &&
3816 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
3817 del_from = prev;
3818 }
3819 }
3820 else {
3821 /* This is not our cookie, so we must preserve it. But if we already
3822 * scheduled another cookie for removal, we cannot remove the
3823 * complete header, but we can remove the previous block itself.
3824 */
3825 preserve_hdr = 1;
3826
3827 if (del_from != NULL) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003828 int delta = http_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003829 if (att_beg >= del_from)
3830 att_beg += delta;
3831 if (att_end >= del_from)
3832 att_end += delta;
3833 val_beg += delta;
3834 val_end += delta;
3835 next += delta;
3836 hdr_end += delta;
3837 prev = del_from;
3838 del_from = NULL;
3839 }
3840 }
3841
3842 /* continue with next cookie on this header line */
3843 att_beg = next;
3844 } /* for each cookie */
3845
3846
3847 /* There are no more cookies on this line.
3848 * We may still have one (or several) marked for deletion at the
3849 * end of the line. We must do this now in two ways :
3850 * - if some cookies must be preserved, we only delete from the
3851 * mark to the end of line ;
3852 * - if nothing needs to be preserved, simply delete the whole header
3853 */
3854 if (del_from) {
3855 hdr_end = (preserve_hdr ? del_from : hdr_beg);
3856 }
3857 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet3e2638e2019-06-18 09:49:16 +02003858 if (hdr_beg != hdr_end)
3859 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003860 else
3861 http_remove_header(htx, &ctx);
3862 }
3863 } /* for each "Cookie header */
3864}
3865
3866/*
3867 * Manage server-side cookies. It can impact performance by about 2% so it is
3868 * desirable to call it only when needed. This function is also used when we
3869 * just need to know if there is a cookie (eg: for check-cache).
3870 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02003871static void http_manage_server_side_cookies(struct stream *s, struct channel *res)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003872{
3873 struct session *sess = s->sess;
3874 struct http_txn *txn = s->txn;
3875 struct htx *htx;
3876 struct http_hdr_ctx ctx;
3877 struct server *srv;
3878 char *hdr_beg, *hdr_end;
3879 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02003880 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003881
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003882 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003883
3884 ctx.blk = NULL;
3885 while (1) {
Olivier Houchardf0f42382019-07-22 17:43:46 +02003886 int is_first = 1;
3887
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003888 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
3889 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
3890 break;
3891 is_cookie2 = 1;
3892 }
3893
3894 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
3895 * <prev> points to the colon.
3896 */
3897 txn->flags |= TX_SCK_PRESENT;
3898
3899 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
3900 * check-cache is enabled) and we are not interested in checking
3901 * them. Warning, the cookie capture is declared in the frontend.
3902 */
3903 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
3904 break;
3905
3906 /* OK so now we know we have to process this response cookie.
3907 * The format of the Set-Cookie header is slightly different
3908 * from the format of the Cookie header in that it does not
3909 * support the comma as a cookie delimiter (thus the header
3910 * cannot be folded) because the Expires attribute described in
3911 * the original Netscape's spec may contain an unquoted date
3912 * with a comma inside. We have to live with this because
3913 * many browsers don't support Max-Age and some browsers don't
3914 * support quoted strings. However the Set-Cookie2 header is
3915 * clean.
3916 *
3917 * We have to keep multiple pointers in order to support cookie
3918 * removal at the beginning, middle or end of header without
3919 * corrupting the header (in case of set-cookie2). A special
3920 * pointer, <scav> points to the beginning of the set-cookie-av
3921 * fields after the first semi-colon. The <next> pointer points
3922 * either to the end of line (set-cookie) or next unquoted comma
3923 * (set-cookie2). All of these headers are valid :
3924 *
3925 * hdr_beg hdr_end
3926 * | |
3927 * v |
3928 * NAME1 = VALUE 1 ; Secure; Path="/" |
3929 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
3930 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
3931 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
3932 * | | | | | | | |
3933 * | | | | | | | +-> next
3934 * | | | | | | +------------> scav
3935 * | | | | | +--------------> val_end
3936 * | | | | +--------------------> val_beg
3937 * | | | +----------------------> equal
3938 * | | +------------------------> att_end
3939 * | +----------------------------> att_beg
3940 * +------------------------------> prev
3941 * -------------------------------> hdr_beg
3942 */
3943 hdr_beg = ctx.value.ptr;
3944 hdr_end = hdr_beg + ctx.value.len;
3945 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3946
3947 /* Iterate through all cookies on this line */
3948
3949 /* find att_beg */
3950 att_beg = prev;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003951 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003952 att_beg++;
Olivier Houchardf0f42382019-07-22 17:43:46 +02003953 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003954
3955 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3956 att_beg++;
3957
3958 /* find att_end : this is the first character after the last non
3959 * space before the equal. It may be equal to hdr_end.
3960 */
3961 equal = att_end = att_beg;
3962
3963 while (equal < hdr_end) {
3964 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
3965 break;
3966 if (HTTP_IS_SPHT(*equal++))
3967 continue;
3968 att_end = equal;
3969 }
3970
3971 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3972 * is between <att_beg> and <equal>, both may be identical.
3973 */
3974
3975 /* look for end of cookie if there is an equal sign */
3976 if (equal < hdr_end && *equal == '=') {
3977 /* look for the beginning of the value */
3978 val_beg = equal + 1;
3979 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3980 val_beg++;
3981
3982 /* find the end of the value, respecting quotes */
3983 next = http_find_cookie_value_end(val_beg, hdr_end);
3984
3985 /* make val_end point to the first white space or delimitor after the value */
3986 val_end = next;
3987 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3988 val_end--;
3989 }
3990 else {
3991 /* <equal> points to next comma, semi-colon or EOL */
3992 val_beg = val_end = next = equal;
3993 }
3994
3995 if (next < hdr_end) {
3996 /* Set-Cookie2 supports multiple cookies, and <next> points to
3997 * a colon or semi-colon before the end. So skip all attr-value
3998 * pairs and look for the next comma. For Set-Cookie, since
3999 * commas are permitted in values, skip to the end.
4000 */
4001 if (is_cookie2)
4002 next = http_find_hdr_value_end(next, hdr_end);
4003 else
4004 next = hdr_end;
4005 }
4006
4007 /* Now everything is as on the diagram above */
4008
4009 /* Ignore cookies with no equal sign */
4010 if (equal == val_end)
4011 continue;
4012
4013 /* If there are spaces around the equal sign, we need to
4014 * strip them otherwise we'll get trouble for cookie captures,
4015 * or even for rewrites. Since this happens extremely rarely,
4016 * it does not hurt performance.
4017 */
4018 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4019 int stripped_before = 0;
4020 int stripped_after = 0;
4021
4022 if (att_end != equal) {
4023 memmove(att_end, equal, hdr_end - equal);
4024 stripped_before = (att_end - equal);
4025 equal += stripped_before;
4026 val_beg += stripped_before;
4027 }
4028
4029 if (val_beg > equal + 1) {
4030 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4031 stripped_after = (equal + 1) - val_beg;
4032 val_beg += stripped_after;
4033 stripped_before += stripped_after;
4034 }
4035
4036 val_end += stripped_before;
4037 next += stripped_before;
4038 hdr_end += stripped_before;
4039
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004040 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004041 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004042 }
4043
4044 /* First, let's see if we want to capture this cookie. We check
4045 * that we don't already have a server side cookie, because we
4046 * can only capture one. Also as an optimisation, we ignore
4047 * cookies shorter than the declared name.
4048 */
4049 if (sess->fe->capture_name != NULL &&
4050 txn->srv_cookie == NULL &&
4051 (val_end - att_beg >= sess->fe->capture_namelen) &&
4052 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4053 int log_len = val_end - att_beg;
4054 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4055 ha_alert("HTTP logging : out of memory.\n");
4056 }
4057 else {
4058 if (log_len > sess->fe->capture_len)
4059 log_len = sess->fe->capture_len;
4060 memcpy(txn->srv_cookie, att_beg, log_len);
4061 txn->srv_cookie[log_len] = 0;
4062 }
4063 }
4064
4065 srv = objt_server(s->target);
4066 /* now check if we need to process it for persistence */
4067 if (!(s->flags & SF_IGNORE_PRST) &&
4068 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4069 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4070 /* assume passive cookie by default */
4071 txn->flags &= ~TX_SCK_MASK;
4072 txn->flags |= TX_SCK_FOUND;
4073
4074 /* If the cookie is in insert mode on a known server, we'll delete
4075 * this occurrence because we'll insert another one later.
4076 * We'll delete it too if the "indirect" option is set and we're in
4077 * a direct access.
4078 */
4079 if (s->be->ck_opts & PR_CK_PSV) {
4080 /* The "preserve" flag was set, we don't want to touch the
4081 * server's cookie.
4082 */
4083 }
4084 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4085 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4086 /* this cookie must be deleted */
4087 if (prev == hdr_beg && next == hdr_end) {
4088 /* whole header */
4089 http_remove_header(htx, &ctx);
4090 /* note: while both invalid now, <next> and <hdr_end>
4091 * are still equal, so the for() will stop as expected.
4092 */
4093 } else {
4094 /* just remove the value */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004095 int delta = http_del_hdr_value(hdr_beg, hdr_end, &prev, next);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004096 next = prev;
4097 hdr_end += delta;
4098 }
4099 txn->flags &= ~TX_SCK_MASK;
4100 txn->flags |= TX_SCK_DELETED;
4101 /* and go on with next cookie */
4102 }
4103 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4104 /* replace bytes val_beg->val_end with the cookie name associated
4105 * with this server since we know it.
4106 */
4107 int sliding, delta;
4108
4109 ctx.value = ist2(val_beg, val_end - val_beg);
4110 ctx.lws_before = ctx.lws_after = 0;
4111 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4112 delta = srv->cklen - (val_end - val_beg);
4113 sliding = (ctx.value.ptr - val_beg);
4114 hdr_beg += sliding;
4115 val_beg += sliding;
4116 next += sliding + delta;
4117 hdr_end += sliding + delta;
4118
4119 txn->flags &= ~TX_SCK_MASK;
4120 txn->flags |= TX_SCK_REPLACED;
4121 }
4122 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4123 /* insert the cookie name associated with this server
4124 * before existing cookie, and insert a delimiter between them..
4125 */
4126 int sliding, delta;
4127 ctx.value = ist2(val_beg, 0);
4128 ctx.lws_before = ctx.lws_after = 0;
4129 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4130 delta = srv->cklen + 1;
4131 sliding = (ctx.value.ptr - val_beg);
4132 hdr_beg += sliding;
4133 val_beg += sliding;
4134 next += sliding + delta;
4135 hdr_end += sliding + delta;
4136
4137 val_beg[srv->cklen] = COOKIE_DELIM;
4138 txn->flags &= ~TX_SCK_MASK;
4139 txn->flags |= TX_SCK_REPLACED;
4140 }
4141 }
4142 /* that's done for this cookie, check the next one on the same
4143 * line when next != hdr_end (only if is_cookie2).
4144 */
4145 }
4146 }
4147}
4148
Christopher Faulet25a02f62018-10-24 12:00:25 +02004149/*
4150 * Parses the Cache-Control and Pragma request header fields to determine if
4151 * the request may be served from the cache and/or if it is cacheable. Updates
4152 * s->txn->flags.
4153 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004154void http_check_request_for_cacheability(struct stream *s, struct channel *req)
Christopher Faulet25a02f62018-10-24 12:00:25 +02004155{
4156 struct http_txn *txn = s->txn;
4157 struct htx *htx;
4158 int32_t pos;
4159 int pragma_found, cc_found, i;
4160
4161 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4162 return; /* nothing more to do here */
4163
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004164 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004165 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004166 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004167 struct htx_blk *blk = htx_get_blk(htx, pos);
4168 enum htx_blk_type type = htx_get_blk_type(blk);
4169 struct ist n, v;
4170
4171 if (type == HTX_BLK_EOH)
4172 break;
4173 if (type != HTX_BLK_HDR)
4174 continue;
4175
4176 n = htx_get_blk_name(htx, blk);
4177 v = htx_get_blk_value(htx, blk);
4178
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004179 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004180 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4181 pragma_found = 1;
4182 continue;
4183 }
4184 }
4185
4186 /* Don't use the cache and don't try to store if we found the
4187 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004188 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004189 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4190 txn->flags |= TX_CACHE_IGNORE;
4191 continue;
4192 }
4193
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004194 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004195 continue;
4196
4197 /* OK, right now we know we have a cache-control header */
4198 cc_found = 1;
4199 if (!v.len) /* no info */
4200 continue;
4201
4202 i = 0;
4203 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4204 !isspace((unsigned char)*(v.ptr+i)))
4205 i++;
4206
4207 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4208 * values after max-age, max-stale nor min-fresh, we simply don't
4209 * use the cache when they're specified.
4210 */
4211 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4212 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4213 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4214 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4215 txn->flags |= TX_CACHE_IGNORE;
4216 continue;
4217 }
4218
4219 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4220 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4221 continue;
4222 }
4223 }
4224
4225 /* RFC7234#5.4:
4226 * When the Cache-Control header field is also present and
4227 * understood in a request, Pragma is ignored.
4228 * When the Cache-Control header field is not present in a
4229 * request, caches MUST consider the no-cache request
4230 * pragma-directive as having the same effect as if
4231 * "Cache-Control: no-cache" were present.
4232 */
4233 if (!cc_found && pragma_found)
4234 txn->flags |= TX_CACHE_IGNORE;
4235}
4236
4237/*
4238 * Check if response is cacheable or not. Updates s->txn->flags.
4239 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004240void http_check_response_for_cacheability(struct stream *s, struct channel *res)
Christopher Faulet25a02f62018-10-24 12:00:25 +02004241{
4242 struct http_txn *txn = s->txn;
4243 struct htx *htx;
4244 int32_t pos;
4245 int i;
4246
4247 if (txn->status < 200) {
4248 /* do not try to cache interim responses! */
4249 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4250 return;
4251 }
4252
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004253 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004254 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004255 struct htx_blk *blk = htx_get_blk(htx, pos);
4256 enum htx_blk_type type = htx_get_blk_type(blk);
4257 struct ist n, v;
4258
4259 if (type == HTX_BLK_EOH)
4260 break;
4261 if (type != HTX_BLK_HDR)
4262 continue;
4263
4264 n = htx_get_blk_name(htx, blk);
4265 v = htx_get_blk_value(htx, blk);
4266
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004267 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004268 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4269 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4270 return;
4271 }
4272 }
4273
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004274 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004275 continue;
4276
4277 /* OK, right now we know we have a cache-control header */
4278 if (!v.len) /* no info */
4279 continue;
4280
4281 i = 0;
4282 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4283 !isspace((unsigned char)*(v.ptr+i)))
4284 i++;
4285
4286 /* we have a complete value between v.ptr and (v.ptr+i) */
4287 if (i < v.len && *(v.ptr + i) == '=') {
4288 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4289 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4290 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4291 continue;
4292 }
4293
4294 /* we have something of the form no-cache="set-cookie" */
4295 if ((v.len >= 21) &&
4296 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4297 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4298 txn->flags &= ~TX_CACHE_COOK;
4299 continue;
4300 }
4301
4302 /* OK, so we know that either p2 points to the end of string or to a comma */
4303 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4304 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4305 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4306 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4307 return;
4308 }
4309
4310 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4311 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4312 continue;
4313 }
4314 }
4315}
4316
Christopher Faulet64159df2018-10-24 21:15:35 +02004317/* send a server's name with an outgoing request over an established connection.
4318 * Note: this function is designed to be called once the request has been
4319 * scheduled for being forwarded. This is the reason why the number of forwarded
4320 * bytes have to be adjusted.
4321 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004322int http_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
Christopher Faulet64159df2018-10-24 21:15:35 +02004323{
4324 struct htx *htx;
4325 struct http_hdr_ctx ctx;
4326 struct ist hdr;
4327 uint32_t data;
4328
4329 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004330 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004331 data = htx->data;
4332
4333 ctx.blk = NULL;
4334 while (http_find_header(htx, hdr, &ctx, 1))
4335 http_remove_header(htx, &ctx);
4336 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4337
4338 if (co_data(&s->req)) {
4339 if (data >= htx->data)
4340 c_rew(&s->req, data - htx->data);
4341 else
4342 c_adv(&s->req, htx->data - data);
4343 }
4344 return 0;
4345}
4346
Christopher Faulet377c5a52018-10-24 21:21:30 +02004347/*
4348 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4349 * for the current backend.
4350 *
4351 * It is assumed that the request is either a HEAD, GET, or POST and that the
4352 * uri_auth field is valid.
4353 *
4354 * Returns 1 if stats should be provided, otherwise 0.
4355 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004356static int http_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004357{
4358 struct uri_auth *uri_auth = backend->uri_auth;
4359 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004360 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004361 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004362
4363 if (!uri_auth)
4364 return 0;
4365
4366 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4367 return 0;
4368
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004369 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004370 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004371 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004372
4373 /* check URI size */
4374 if (uri_auth->uri_len > uri.len)
4375 return 0;
4376
4377 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4378 return 0;
4379
4380 return 1;
4381}
4382
4383/* This function prepares an applet to handle the stats. It can deal with the
4384 * "100-continue" expectation, check that admin rules are met for POST requests,
4385 * and program a response message if something was unexpected. It cannot fail
4386 * and always relies on the stats applet to complete the job. It does not touch
4387 * analysers nor counters, which are left to the caller. It does not touch
4388 * s->target which is supposed to already point to the stats applet. The caller
4389 * is expected to have already assigned an appctx to the stream.
4390 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004391static int http_handle_stats(struct stream *s, struct channel *req)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004392{
4393 struct stats_admin_rule *stats_admin_rule;
4394 struct stream_interface *si = &s->si[1];
4395 struct session *sess = s->sess;
4396 struct http_txn *txn = s->txn;
4397 struct http_msg *msg = &txn->req;
4398 struct uri_auth *uri_auth = s->be->uri_auth;
4399 const char *h, *lookup, *end;
4400 struct appctx *appctx;
4401 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004402 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004403
4404 appctx = si_appctx(si);
4405 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4406 appctx->st1 = appctx->st2 = 0;
4407 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4408 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4409 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4410 appctx->ctx.stats.flags |= STAT_CHUNKED;
4411
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004412 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004413 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004414 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4415 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004416
4417 for (h = lookup; h <= end - 3; h++) {
4418 if (memcmp(h, ";up", 3) == 0) {
4419 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4420 break;
4421 }
4422 }
4423
4424 if (uri_auth->refresh) {
4425 for (h = lookup; h <= end - 10; h++) {
4426 if (memcmp(h, ";norefresh", 10) == 0) {
4427 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4428 break;
4429 }
4430 }
4431 }
4432
4433 for (h = lookup; h <= end - 4; h++) {
4434 if (memcmp(h, ";csv", 4) == 0) {
Christopher Faulet6338a082019-09-09 15:50:54 +02004435 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004436 break;
4437 }
4438 }
4439
4440 for (h = lookup; h <= end - 6; h++) {
4441 if (memcmp(h, ";typed", 6) == 0) {
Christopher Faulet6338a082019-09-09 15:50:54 +02004442 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004443 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4444 break;
4445 }
4446 }
4447
Christopher Faulet6338a082019-09-09 15:50:54 +02004448 for (h = lookup; h <= end - 5; h++) {
4449 if (memcmp(h, ";json", 5) == 0) {
4450 appctx->ctx.stats.flags &= ~(STAT_FMT_MASK|STAT_JSON_SCHM);
4451 appctx->ctx.stats.flags |= STAT_FMT_JSON;
4452 break;
4453 }
4454 }
4455
4456 for (h = lookup; h <= end - 12; h++) {
4457 if (memcmp(h, ";json-schema", 12) == 0) {
4458 appctx->ctx.stats.flags &= ~STAT_FMT_MASK;
4459 appctx->ctx.stats.flags |= STAT_JSON_SCHM;
4460 break;
4461 }
4462 }
4463
Christopher Faulet377c5a52018-10-24 21:21:30 +02004464 for (h = lookup; h <= end - 8; h++) {
4465 if (memcmp(h, ";st=", 4) == 0) {
4466 int i;
4467 h += 4;
4468 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4469 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4470 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4471 appctx->ctx.stats.st_code = i;
4472 break;
4473 }
4474 }
4475 break;
4476 }
4477 }
4478
4479 appctx->ctx.stats.scope_str = 0;
4480 appctx->ctx.stats.scope_len = 0;
4481 for (h = lookup; h <= end - 8; h++) {
4482 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4483 int itx = 0;
4484 const char *h2;
4485 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4486 const char *err;
4487
4488 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4489 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004490 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4491 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004492 if (*h == ';' || *h == '&' || *h == ' ')
4493 break;
4494 itx++;
4495 h++;
4496 }
4497
4498 if (itx > STAT_SCOPE_TXT_MAXLEN)
4499 itx = STAT_SCOPE_TXT_MAXLEN;
4500 appctx->ctx.stats.scope_len = itx;
4501
4502 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4503 memcpy(scope_txt, h2, itx);
4504 scope_txt[itx] = '\0';
4505 err = invalid_char(scope_txt);
4506 if (err) {
4507 /* bad char in search text => clear scope */
4508 appctx->ctx.stats.scope_str = 0;
4509 appctx->ctx.stats.scope_len = 0;
4510 }
4511 break;
4512 }
4513 }
4514
4515 /* now check whether we have some admin rules for this request */
4516 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4517 int ret = 1;
4518
4519 if (stats_admin_rule->cond) {
4520 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4521 ret = acl_pass(ret);
4522 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4523 ret = !ret;
4524 }
4525
4526 if (ret) {
4527 /* no rule, or the rule matches */
4528 appctx->ctx.stats.flags |= STAT_ADMIN;
4529 break;
4530 }
4531 }
4532
Christopher Faulet5d45e382019-02-27 15:15:23 +01004533 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4534 appctx->st0 = STAT_HTTP_HEAD;
4535 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbd9e8422019-08-15 22:26:48 +02004536 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004537 appctx->st0 = STAT_HTTP_POST;
Christopher Fauletbd9e8422019-08-15 22:26:48 +02004538 if (msg->msg_state < HTTP_MSG_DATA)
4539 req->analysers |= AN_REQ_HTTP_BODY;
4540 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02004541 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004542 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004543 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4544 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4545 appctx->st0 = STAT_HTTP_LAST;
4546 }
4547 }
4548 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004549 /* Unsupported method */
4550 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4551 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4552 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004553 }
4554
4555 s->task->nice = -32; /* small boost for HTTP statistics */
4556 return 1;
4557}
4558
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004559void http_perform_server_redirect(struct stream *s, struct stream_interface *si)
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004560{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004561 struct channel *req = &s->req;
4562 struct channel *res = &s->res;
4563 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004564 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004565 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004566 struct ist path, location;
4567 unsigned int flags;
4568 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004569
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004570 /*
4571 * Create the location
4572 */
4573 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004574
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004575 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004576 /* special prefix "/" means don't change URL */
4577 srv = __objt_server(s->target);
4578 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4579 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4580 return;
4581 }
4582
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004583 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004584 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004585 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004586 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004587 if (!path.ptr)
4588 return;
4589
4590 if (!chunk_memcat(&trash, path.ptr, path.len))
4591 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004592 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004593
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004594 /*
4595 * Create the 302 respone
4596 */
4597 htx = htx_from_buf(&res->buf);
4598 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4599 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4600 ist("HTTP/1.1"), ist("302"), ist("Found"));
4601 if (!sl)
4602 goto fail;
4603 sl->info.res.status = 302;
4604 s->txn->status = 302;
4605
4606 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4607 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4608 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4609 !htx_add_header(htx, ist("Location"), location))
4610 goto fail;
4611
4612 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4613 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004614
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004615 /*
4616 * Send the message
4617 */
4618 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004619 c_adv(res, data);
4620 res->total += data;
4621
4622 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004623 si_shutr(si);
4624 si_shutw(si);
4625 si->err_type = SI_ET_NONE;
4626 si->state = SI_ST_CLO;
4627
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004628 channel_auto_read(req);
4629 channel_abort(req);
4630 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004631 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004632 channel_auto_read(res);
4633 channel_auto_close(res);
4634
4635 if (!(s->flags & SF_ERR_MASK))
4636 s->flags |= SF_ERR_LOCAL;
4637 if (!(s->flags & SF_FINST_MASK))
4638 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004639
4640 /* FIXME: we should increase a counter of redirects per server and per backend. */
4641 srv_inc_sess_ctr(srv);
4642 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004643 return;
4644
4645 fail:
4646 /* If an error occurred, remove the incomplete HTTP response from the
4647 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004648 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004649}
4650
Christopher Fauletf2824e62018-10-01 12:12:37 +02004651/* This function terminates the request because it was completly analyzed or
4652 * because an error was triggered during the body forwarding.
4653 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004654static void http_end_request(struct stream *s)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004655{
4656 struct channel *chn = &s->req;
4657 struct http_txn *txn = s->txn;
4658
4659 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4660 now_ms, __FUNCTION__, s,
4661 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4662 s->req.analysers, s->res.analysers);
4663
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004664 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4665 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004666 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004667 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02004668 goto end;
4669 }
4670
4671 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4672 return;
4673
4674 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004675 /* No need to read anymore, the request was completely parsed.
4676 * We can shut the read side unless we want to abort_on_close,
4677 * or we have a POST request. The issue with POST requests is
4678 * that some browsers still send a CRLF after the request, and
4679 * this CRLF must be read so that it does not remain in the kernel
4680 * buffers, otherwise a close could cause an RST on some systems
4681 * (eg: Linux).
4682 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01004683 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004684 channel_dont_read(chn);
4685
4686 /* if the server closes the connection, we want to immediately react
4687 * and close the socket to save packets and syscalls.
4688 */
4689 s->si[1].flags |= SI_FL_NOHALF;
4690
4691 /* In any case we've finished parsing the request so we must
4692 * disable Nagle when sending data because 1) we're not going
4693 * to shut this side, and 2) the server is waiting for us to
4694 * send pending data.
4695 */
4696 chn->flags |= CF_NEVER_WAIT;
4697
Christopher Fauletd01ce402019-01-02 17:44:13 +01004698 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4699 /* The server has not finished to respond, so we
4700 * don't want to move in order not to upset it.
4701 */
4702 return;
4703 }
4704
Christopher Fauletf2824e62018-10-01 12:12:37 +02004705 /* When we get here, it means that both the request and the
4706 * response have finished receiving. Depending on the connection
4707 * mode, we'll have to wait for the last bytes to leave in either
4708 * direction, and sometimes for a close to be effective.
4709 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02004710 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004711 /* Tunnel mode will not have any analyser so it needs to
4712 * poll for reads.
4713 */
4714 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02004715 if (b_data(&chn->buf))
4716 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004717 txn->req.msg_state = HTTP_MSG_TUNNEL;
4718 }
4719 else {
4720 /* we're not expecting any new data to come for this
4721 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02004722 *
4723 * However, there is an exception if the response
4724 * length is undefined. In this case, we need to wait
4725 * the close from the server. The response will be
4726 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02004727 */
4728 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
4729 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02004730 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004731
4732 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4733 channel_shutr_now(chn);
4734 channel_shutw_now(chn);
4735 }
4736 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02004737 goto check_channel_flags;
4738 }
4739
4740 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
4741 http_msg_closing:
4742 /* nothing else to forward, just waiting for the output buffer
4743 * to be empty and for the shutw_now to take effect.
4744 */
4745 if (channel_is_empty(chn)) {
4746 txn->req.msg_state = HTTP_MSG_CLOSED;
4747 goto http_msg_closed;
4748 }
4749 else if (chn->flags & CF_SHUTW) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004750 txn->req.msg_state = HTTP_MSG_ERROR;
4751 goto end;
4752 }
4753 return;
4754 }
4755
4756 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
4757 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02004758 /* if we don't know whether the server will close, we need to hard close */
4759 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
4760 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02004761 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01004762 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02004763 channel_dont_read(chn);
4764 goto end;
4765 }
4766
4767 check_channel_flags:
4768 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4769 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4770 /* if we've just closed an output, let's switch */
4771 txn->req.msg_state = HTTP_MSG_CLOSING;
4772 goto http_msg_closing;
4773 }
4774
4775 end:
4776 chn->analysers &= AN_REQ_FLT_END;
4777 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
4778 chn->analysers |= AN_REQ_FLT_XFER_DATA;
4779 channel_auto_close(chn);
4780 channel_auto_read(chn);
4781}
4782
4783
4784/* This function terminates the response because it was completly analyzed or
4785 * because an error was triggered during the body forwarding.
4786 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004787static void http_end_response(struct stream *s)
Christopher Fauletf2824e62018-10-01 12:12:37 +02004788{
4789 struct channel *chn = &s->res;
4790 struct http_txn *txn = s->txn;
4791
4792 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4793 now_ms, __FUNCTION__, s,
4794 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4795 s->req.analysers, s->res.analysers);
4796
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004797 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4798 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004799 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02004800 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004801 goto end;
4802 }
4803
4804 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
4805 return;
4806
4807 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
4808 /* In theory, we don't need to read anymore, but we must
4809 * still monitor the server connection for a possible close
4810 * while the request is being uploaded, so we don't disable
4811 * reading.
4812 */
4813 /* channel_dont_read(chn); */
4814
4815 if (txn->req.msg_state < HTTP_MSG_DONE) {
4816 /* The client seems to still be sending data, probably
4817 * because we got an error response during an upload.
4818 * We have the choice of either breaking the connection
4819 * or letting it pass through. Let's do the later.
4820 */
4821 return;
4822 }
4823
4824 /* When we get here, it means that both the request and the
4825 * response have finished receiving. Depending on the connection
4826 * mode, we'll have to wait for the last bytes to leave in either
4827 * direction, and sometimes for a close to be effective.
4828 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02004829 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004830 channel_auto_read(chn);
4831 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02004832 if (b_data(&chn->buf))
4833 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02004834 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
4835 }
4836 else {
4837 /* we're not expecting any new data to come for this
4838 * transaction, so we can close it.
4839 */
4840 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
4841 channel_shutr_now(chn);
4842 channel_shutw_now(chn);
4843 }
4844 }
4845 goto check_channel_flags;
4846 }
4847
4848 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
4849 http_msg_closing:
4850 /* nothing else to forward, just waiting for the output buffer
4851 * to be empty and for the shutw_now to take effect.
4852 */
4853 if (channel_is_empty(chn)) {
4854 txn->rsp.msg_state = HTTP_MSG_CLOSED;
4855 goto http_msg_closed;
4856 }
4857 else if (chn->flags & CF_SHUTW) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004858 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01004859 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004860 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01004861 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004862 goto end;
4863 }
4864 return;
4865 }
4866
4867 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
4868 http_msg_closed:
4869 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004870 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02004871 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02004872 goto end;
4873 }
4874
4875 check_channel_flags:
4876 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
4877 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
4878 /* if we've just closed an output, let's switch */
4879 txn->rsp.msg_state = HTTP_MSG_CLOSING;
4880 goto http_msg_closing;
4881 }
4882
4883 end:
4884 chn->analysers &= AN_RES_FLT_END;
4885 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
4886 chn->analysers |= AN_RES_FLT_XFER_DATA;
4887 channel_auto_close(chn);
4888 channel_auto_read(chn);
4889}
4890
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004891void http_server_error(struct stream *s, struct stream_interface *si, int err,
4892 int finst, const struct buffer *msg)
Christopher Faulet0f226952018-10-22 09:29:56 +02004893{
4894 channel_auto_read(si_oc(si));
4895 channel_abort(si_oc(si));
4896 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004897 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02004898 channel_auto_close(si_ic(si));
4899 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004900
4901 /* <msg> is an HTX structure. So we copy it in the response's
4902 * channel */
Christopher Faulet9f5839c2019-07-22 16:41:43 +02004903 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02004904 struct channel *chn = si_ic(si);
4905 struct htx *htx;
4906
Christopher Fauletaed82cf2018-11-30 22:22:32 +01004907 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004908 chn->buf.data = msg->data;
4909 memcpy(chn->buf.area, msg->area, msg->data);
4910 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02004911 c_adv(chn, htx->data);
4912 chn->total += htx->data;
4913 }
4914 if (!(s->flags & SF_ERR_MASK))
4915 s->flags |= err;
4916 if (!(s->flags & SF_FINST_MASK))
4917 s->flags |= finst;
4918}
4919
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004920void http_reply_and_close(struct stream *s, short status, struct buffer *msg)
Christopher Faulet0f226952018-10-22 09:29:56 +02004921{
4922 channel_auto_read(&s->req);
4923 channel_abort(&s->req);
4924 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004925 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
4926 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02004927
4928 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004929
4930 /* <msg> is an HTX structure. So we copy it in the response's
4931 * channel */
4932 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet9f5839c2019-07-22 16:41:43 +02004933 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02004934 struct channel *chn = &s->res;
4935 struct htx *htx;
4936
Christopher Fauletaed82cf2018-11-30 22:22:32 +01004937 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004938 chn->buf.data = msg->data;
4939 memcpy(chn->buf.area, msg->area, msg->data);
4940 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02004941 c_adv(chn, htx->data);
4942 chn->total += htx->data;
4943 }
4944
4945 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
4946 channel_auto_read(&s->res);
4947 channel_auto_close(&s->res);
4948 channel_shutr_now(&s->res);
4949}
4950
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004951struct buffer *http_error_message(struct stream *s)
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004952{
4953 const int msgnum = http_get_status_idx(s->txn->status);
4954
4955 if (s->be->errmsg[msgnum].area)
4956 return &s->be->errmsg[msgnum];
4957 else if (strm_fe(s)->errmsg[msgnum].area)
4958 return &strm_fe(s)->errmsg[msgnum];
4959 else
Christopher Fauletf7346382019-07-17 22:02:08 +02004960 return &http_err_chunks[msgnum];
Christopher Fauleta7b677c2018-11-29 16:48:49 +01004961}
4962
Christopher Faulet304cc402019-07-15 15:46:28 +02004963/* Return the error message corresponding to si->err_type. It is assumed
4964 * that the server side is closed. Note that err_type is actually a
4965 * bitmask, where almost only aborts may be cumulated with other
4966 * values. We consider that aborted operations are more important
4967 * than timeouts or errors due to the fact that nobody else in the
4968 * logs might explain incomplete retries. All others should avoid
4969 * being cumulated. It should normally not be possible to have multiple
4970 * aborts at once, but just in case, the first one in sequence is reported.
4971 * Note that connection errors appearing on the second request of a keep-alive
4972 * connection are not reported since this allows the client to retry.
4973 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004974void http_return_srv_error(struct stream *s, struct stream_interface *si)
Christopher Faulet304cc402019-07-15 15:46:28 +02004975{
4976 int err_type = si->err_type;
4977
4978 /* set s->txn->status for http_error_message(s) */
4979 s->txn->status = 503;
4980
4981 if (err_type & SI_ET_QUEUE_ABRT)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004982 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
4983 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004984 else if (err_type & SI_ET_CONN_ABRT)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004985 http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
4986 (s->txn->flags & TX_NOT_FIRST) ? NULL :
4987 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004988 else if (err_type & SI_ET_QUEUE_TO)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004989 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
4990 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004991 else if (err_type & SI_ET_QUEUE_ERR)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004992 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
4993 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004994 else if (err_type & SI_ET_CONN_TO)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004995 http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
4996 (s->txn->flags & TX_NOT_FIRST) ? NULL :
4997 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02004998 else if (err_type & SI_ET_CONN_ERR)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004999 http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
5000 (s->flags & SF_SRV_REUSED) ? NULL :
5001 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02005002 else if (err_type & SI_ET_CONN_RES)
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005003 http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
5004 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5005 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02005006 else { /* SI_ET_CONN_OTHER and others */
5007 s->txn->status = 500;
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005008 http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
5009 http_error_message(s));
Christopher Faulet304cc402019-07-15 15:46:28 +02005010 }
5011}
5012
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005013
Christopher Faulet4a28a532019-03-01 11:19:40 +01005014/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5015 * on success and -1 on error.
5016 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005017static int http_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
Christopher Faulet4a28a532019-03-01 11:19:40 +01005018{
5019 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5020 * then we must send an HTTP/1.1 100 Continue intermediate response.
5021 */
5022 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5023 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5024 struct ist hdr = { .ptr = "Expect", .len = 6 };
5025 struct http_hdr_ctx ctx;
5026
5027 ctx.blk = NULL;
5028 /* Expect is allowed in 1.1, look for it */
5029 if (http_find_header(htx, hdr, &ctx, 0) &&
5030 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005031 if (http_reply_100_continue(s) == -1)
Christopher Faulet4a28a532019-03-01 11:19:40 +01005032 return -1;
5033 http_remove_header(htx, &ctx);
5034 }
5035 }
5036 return 0;
5037}
5038
Christopher Faulet23a3c792018-11-28 10:01:23 +01005039/* Send a 100-Continue response to the client. It returns 0 on success and -1
5040 * on error. The response channel is updated accordingly.
5041 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005042static int http_reply_100_continue(struct stream *s)
Christopher Faulet23a3c792018-11-28 10:01:23 +01005043{
5044 struct channel *res = &s->res;
5045 struct htx *htx = htx_from_buf(&res->buf);
5046 struct htx_sl *sl;
5047 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5048 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5049 size_t data;
5050
5051 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5052 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5053 if (!sl)
5054 goto fail;
5055 sl->info.res.status = 100;
5056
Christopher Faulet1d5ec092019-06-26 14:23:54 +02005057 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005058 goto fail;
5059
5060 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005061 c_adv(res, data);
5062 res->total += data;
5063 return 0;
5064
5065 fail:
5066 /* If an error occurred, remove the incomplete HTTP response from the
5067 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005068 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005069 return -1;
5070}
5071
Christopher Faulet12c51e22018-11-28 15:59:42 +01005072
5073/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5074 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5075 * error. The response channel is updated accordingly.
5076 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005077static int http_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
Christopher Faulet12c51e22018-11-28 15:59:42 +01005078{
5079 struct channel *res = &s->res;
5080 struct htx *htx = htx_from_buf(&res->buf);
5081 struct htx_sl *sl;
5082 struct ist code, body;
5083 int status;
5084 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5085 size_t data;
5086
5087 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5088 status = 401;
5089 code = ist("401");
5090 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5091 "You need a valid user and password to access this content.\n"
5092 "</body></html>\n");
5093 }
5094 else {
5095 status = 407;
5096 code = ist("407");
5097 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5098 "You need a valid user and password to access this content.\n"
5099 "</body></html>\n");
5100 }
5101
5102 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5103 ist("HTTP/1.1"), code, ist("Unauthorized"));
5104 if (!sl)
5105 goto fail;
5106 sl->info.res.status = status;
5107 s->txn->status = status;
5108
5109 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5110 goto fail;
5111
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005112 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5113 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005114 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005115 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5116 goto fail;
5117 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5118 goto fail;
5119 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005120 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005121 if (!htx_add_endof(htx, HTX_BLK_EOH))
5122 goto fail;
5123
5124 while (body.len) {
5125 size_t sent = htx_add_data(htx, body);
5126 if (!sent)
5127 goto fail;
5128 body.ptr += sent;
5129 body.len -= sent;
5130 }
5131
5132 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005133 goto fail;
5134
5135 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005136 c_adv(res, data);
5137 res->total += data;
5138
5139 channel_auto_read(&s->req);
5140 channel_abort(&s->req);
5141 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005142 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005143
5144 res->wex = tick_add_ifset(now_ms, res->wto);
5145 channel_auto_read(res);
5146 channel_auto_close(res);
5147 channel_shutr_now(res);
5148 return 0;
5149
5150 fail:
5151 /* If an error occurred, remove the incomplete HTTP response from the
5152 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005153 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005154 return -1;
5155}
5156
Christopher Faulet0f226952018-10-22 09:29:56 +02005157/*
5158 * Capture headers from message <htx> according to header list <cap_hdr>, and
5159 * fill the <cap> pointers appropriately.
5160 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005161static void http_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
Christopher Faulet0f226952018-10-22 09:29:56 +02005162{
5163 struct cap_hdr *h;
5164 int32_t pos;
5165
Christopher Fauleta3f15502019-05-13 15:27:23 +02005166 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005167 struct htx_blk *blk = htx_get_blk(htx, pos);
5168 enum htx_blk_type type = htx_get_blk_type(blk);
5169 struct ist n, v;
5170
5171 if (type == HTX_BLK_EOH)
5172 break;
5173 if (type != HTX_BLK_HDR)
5174 continue;
5175
5176 n = htx_get_blk_name(htx, blk);
5177
5178 for (h = cap_hdr; h; h = h->next) {
5179 if (h->namelen && (h->namelen == n.len) &&
5180 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5181 if (cap[h->index] == NULL)
5182 cap[h->index] =
5183 pool_alloc(h->pool);
5184
5185 if (cap[h->index] == NULL) {
5186 ha_alert("HTTP capture : out of memory.\n");
5187 break;
5188 }
5189
5190 v = htx_get_blk_value(htx, blk);
5191 if (v.len > h->len)
5192 v.len = h->len;
5193
5194 memcpy(cap[h->index], v.ptr, v.len);
5195 cap[h->index][v.len]=0;
5196 }
5197 }
5198 }
5199}
5200
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005201/* Delete a value in a header between delimiters <from> and <next>. The header
5202 * itself is delimited by <start> and <end> pointers. The number of characters
5203 * displaced is returned, and the pointer to the first delimiter is updated if
5204 * required. The function tries as much as possible to respect the following
5205 * principles :
5206 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5207 * in which case <next> is simply removed
5208 * - set exactly one space character after the new first delimiter, unless there
5209 * are not enough characters in the block being moved to do so.
5210 * - remove unneeded spaces before the previous delimiter and after the new
5211 * one.
5212 *
5213 * It is the caller's responsibility to ensure that :
5214 * - <from> points to a valid delimiter or <start> ;
5215 * - <next> points to a valid delimiter or <end> ;
5216 * - there are non-space chars before <from>.
5217 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005218static int http_del_hdr_value(char *start, char *end, char **from, char *next)
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005219{
5220 char *prev = *from;
5221
5222 if (prev == start) {
5223 /* We're removing the first value. eat the semicolon, if <next>
5224 * is lower than <end> */
5225 if (next < end)
5226 next++;
5227
5228 while (next < end && HTTP_IS_SPHT(*next))
5229 next++;
5230 }
5231 else {
5232 /* Remove useless spaces before the old delimiter. */
5233 while (HTTP_IS_SPHT(*(prev-1)))
5234 prev--;
5235 *from = prev;
5236
5237 /* copy the delimiter and if possible a space if we're
5238 * not at the end of the line.
5239 */
5240 if (next < end) {
5241 *prev++ = *next++;
5242 if (prev + 1 < next)
5243 *prev++ = ' ';
5244 while (next < end && HTTP_IS_SPHT(*next))
5245 next++;
5246 }
5247 }
5248 memmove(prev, next, end - next);
5249 return (prev - next);
5250}
5251
Christopher Faulet0f226952018-10-22 09:29:56 +02005252
5253/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005254 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005255 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005256static size_t http_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005257{
5258 struct ist dst = ist2(str, 0);
5259
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005260 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005261 goto end;
5262 if (dst.len + 1 > len)
5263 goto end;
5264 dst.ptr[dst.len++] = ' ';
5265
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005266 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005267 goto end;
5268 if (dst.len + 1 > len)
5269 goto end;
5270 dst.ptr[dst.len++] = ' ';
5271
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005272 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005273 end:
5274 return dst.len;
5275}
5276
5277/*
5278 * Print a debug line with a start line.
5279 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005280static void http_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005281{
5282 struct session *sess = strm_sess(s);
5283 int max;
5284
5285 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5286 dir,
5287 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5288 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5289
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005290 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005291 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005292 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005293 trash.area[trash.data++] = ' ';
5294
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005295 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005296 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005297 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005298 trash.area[trash.data++] = ' ';
5299
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005300 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005301 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005302 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005303 trash.area[trash.data++] = '\n';
5304
5305 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5306}
5307
5308/*
5309 * Print a debug line with a header.
5310 */
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005311static 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 +02005312{
5313 struct session *sess = strm_sess(s);
5314 int max;
5315
5316 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5317 dir,
5318 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5319 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5320
5321 max = n.len;
5322 UBOUND(max, trash.size - trash.data - 3);
5323 chunk_memcat(&trash, n.ptr, max);
5324 trash.area[trash.data++] = ':';
5325 trash.area[trash.data++] = ' ';
5326
5327 max = v.len;
5328 UBOUND(max, trash.size - trash.data - 1);
5329 chunk_memcat(&trash, v.ptr, max);
5330 trash.area[trash.data++] = '\n';
5331
5332 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5333}
5334
Christopher Fauleta8a46e22019-07-16 14:53:09 +02005335/* Allocate a new HTTP transaction for stream <s> unless there is one already.
5336 * In case of allocation failure, everything allocated is freed and NULL is
5337 * returned. Otherwise the new transaction is assigned to the stream and
5338 * returned.
5339 */
5340struct http_txn *http_alloc_txn(struct stream *s)
5341{
5342 struct http_txn *txn = s->txn;
5343
5344 if (txn)
5345 return txn;
5346
5347 txn = pool_alloc(pool_head_http_txn);
5348 if (!txn)
5349 return txn;
5350
5351 s->txn = txn;
5352 return txn;
5353}
5354
5355void http_txn_reset_req(struct http_txn *txn)
5356{
5357 txn->req.flags = 0;
5358 txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */
5359}
5360
5361void http_txn_reset_res(struct http_txn *txn)
5362{
5363 txn->rsp.flags = 0;
5364 txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */
5365}
5366
5367/*
5368 * Initialize a new HTTP transaction for stream <s>. It is assumed that all
5369 * the required fields are properly allocated and that we only need to (re)init
5370 * them. This should be used before processing any new request.
5371 */
5372void http_init_txn(struct stream *s)
5373{
5374 struct http_txn *txn = s->txn;
5375 struct conn_stream *cs = objt_cs(s->si[0].end);
5376
5377 txn->flags = ((cs && cs->flags & CS_FL_NOT_FIRST)
5378 ? (TX_NOT_FIRST|TX_WAIT_NEXT_RQ)
5379 : 0);
5380 txn->status = -1;
5381 *(unsigned int *)txn->cache_hash = 0;
5382
5383 txn->cookie_first_date = 0;
5384 txn->cookie_last_date = 0;
5385
5386 txn->srv_cookie = NULL;
5387 txn->cli_cookie = NULL;
5388 txn->uri = NULL;
5389
5390 http_txn_reset_req(txn);
5391 http_txn_reset_res(txn);
5392
5393 txn->req.chn = &s->req;
5394 txn->rsp.chn = &s->res;
5395
5396 txn->auth.method = HTTP_AUTH_UNKNOWN;
5397
5398 vars_init(&s->vars_txn, SCOPE_TXN);
5399 vars_init(&s->vars_reqres, SCOPE_REQ);
5400}
5401
5402/* to be used at the end of a transaction */
5403void http_end_txn(struct stream *s)
5404{
5405 struct http_txn *txn = s->txn;
5406 struct proxy *fe = strm_fe(s);
5407
5408 /* these ones will have been dynamically allocated */
5409 pool_free(pool_head_requri, txn->uri);
5410 pool_free(pool_head_capture, txn->cli_cookie);
5411 pool_free(pool_head_capture, txn->srv_cookie);
5412 pool_free(pool_head_uniqueid, s->unique_id);
5413
5414 s->unique_id = NULL;
5415 txn->uri = NULL;
5416 txn->srv_cookie = NULL;
5417 txn->cli_cookie = NULL;
5418
5419 if (s->req_cap) {
5420 struct cap_hdr *h;
5421 for (h = fe->req_cap; h; h = h->next)
5422 pool_free(h->pool, s->req_cap[h->index]);
5423 memset(s->req_cap, 0, fe->nb_req_cap * sizeof(void *));
5424 }
5425
5426 if (s->res_cap) {
5427 struct cap_hdr *h;
5428 for (h = fe->rsp_cap; h; h = h->next)
5429 pool_free(h->pool, s->res_cap[h->index]);
5430 memset(s->res_cap, 0, fe->nb_rsp_cap * sizeof(void *));
5431 }
5432
5433 if (!LIST_ISEMPTY(&s->vars_txn.head))
5434 vars_prune(&s->vars_txn, s->sess, s);
5435 if (!LIST_ISEMPTY(&s->vars_reqres.head))
5436 vars_prune(&s->vars_reqres, s->sess, s);
5437}
5438
5439/* to be used at the end of a transaction to prepare a new one */
5440void http_reset_txn(struct stream *s)
5441{
5442 http_end_txn(s);
5443 http_init_txn(s);
5444
5445 /* reinitialise the current rule list pointer to NULL. We are sure that
5446 * any rulelist match the NULL pointer.
5447 */
5448 s->current_rule_list = NULL;
5449
5450 s->be = strm_fe(s);
5451 s->logs.logwait = strm_fe(s)->to_log;
5452 s->logs.level = 0;
5453 stream_del_srv_conn(s);
5454 s->target = NULL;
5455 /* re-init store persistence */
5456 s->store_count = 0;
5457 s->uniq_id = _HA_ATOMIC_XADD(&global.req_count, 1);
5458
5459 s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
5460
5461 /* We must trim any excess data from the response buffer, because we
5462 * may have blocked an invalid response from a server that we don't
5463 * want to accidently forward once we disable the analysers, nor do
5464 * we want those data to come along with next response. A typical
5465 * example of such data would be from a buggy server responding to
5466 * a HEAD with some data, or sending more than the advertised
5467 * content-length.
5468 */
5469 if (unlikely(ci_data(&s->res)))
5470 b_set_data(&s->res.buf, co_data(&s->res));
5471
5472 /* Now we can realign the response buffer */
5473 c_realign_if_empty(&s->res);
5474
5475 s->req.rto = strm_fe(s)->timeout.client;
5476 s->req.wto = TICK_ETERNITY;
5477
5478 s->res.rto = TICK_ETERNITY;
5479 s->res.wto = strm_fe(s)->timeout.client;
5480
5481 s->req.rex = TICK_ETERNITY;
5482 s->req.wex = TICK_ETERNITY;
5483 s->req.analyse_exp = TICK_ETERNITY;
5484 s->res.rex = TICK_ETERNITY;
5485 s->res.wex = TICK_ETERNITY;
5486 s->res.analyse_exp = TICK_ETERNITY;
5487 s->si[1].hcto = TICK_ETERNITY;
5488}
5489
5490
5491DECLARE_POOL(pool_head_http_txn, "http_txn", sizeof(struct http_txn));
5492DECLARE_POOL(pool_head_uniqueid, "uniqueid", UNIQUEID_LEN);
Christopher Faulet0f226952018-10-22 09:29:56 +02005493
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005494__attribute__((constructor))
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005495static void __http_protocol_init(void)
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005496{
5497}
5498
5499
5500/*
5501 * Local variables:
5502 * c-indent-level: 8
5503 * c-basic-offset: 8
5504 * End:
5505 */