blob: 3c6df30798696db5937134c5ee53e15455dbc5ef [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200148 if (htx->flags & HTX_FL_UPGRADE)
149 goto failed_keep_alive;
150
Christopher Faulet9768c262018-10-22 09:34:31 +0200151 /* 1: have we encountered a read error ? */
152 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200153 if (!(s->flags & SF_ERR_MASK))
154 s->flags |= SF_ERR_CLICL;
155
156 if (txn->flags & TX_WAIT_NEXT_RQ)
157 goto failed_keep_alive;
158
159 if (sess->fe->options & PR_O_IGNORE_PRB)
160 goto failed_keep_alive;
161
Christopher Faulet9768c262018-10-22 09:34:31 +0200162 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 stream_inc_http_req_ctr(s);
164 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100165 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200166 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100167 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168
Christopher Faulet9768c262018-10-22 09:34:31 +0200169 txn->status = 400;
170 msg->err_state = msg->msg_state;
171 msg->msg_state = HTTP_MSG_ERROR;
172 htx_reply_and_close(s, txn->status, NULL);
173 req->analysers &= AN_REQ_FLT_END;
174
Christopher Faulete0768eb2018-10-03 16:38:02 +0200175 if (!(s->flags & SF_FINST_MASK))
176 s->flags |= SF_FINST_R;
177 return 0;
178 }
179
Christopher Faulet9768c262018-10-22 09:34:31 +0200180 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200181 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
182 if (!(s->flags & SF_ERR_MASK))
183 s->flags |= SF_ERR_CLITO;
184
185 if (txn->flags & TX_WAIT_NEXT_RQ)
186 goto failed_keep_alive;
187
188 if (sess->fe->options & PR_O_IGNORE_PRB)
189 goto failed_keep_alive;
190
Christopher Faulet9768c262018-10-22 09:34:31 +0200191 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 stream_inc_http_req_ctr(s);
193 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100194 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200195 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100196 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197
Christopher Faulet9768c262018-10-22 09:34:31 +0200198 txn->status = 408;
199 msg->err_state = msg->msg_state;
200 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100201 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200202 req->analysers &= AN_REQ_FLT_END;
203
Christopher Faulete0768eb2018-10-03 16:38:02 +0200204 if (!(s->flags & SF_FINST_MASK))
205 s->flags |= SF_FINST_R;
206 return 0;
207 }
208
Christopher Faulet9768c262018-10-22 09:34:31 +0200209 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200210 else if (req->flags & CF_SHUTR) {
211 if (!(s->flags & SF_ERR_MASK))
212 s->flags |= SF_ERR_CLICL;
213
214 if (txn->flags & TX_WAIT_NEXT_RQ)
215 goto failed_keep_alive;
216
217 if (sess->fe->options & PR_O_IGNORE_PRB)
218 goto failed_keep_alive;
219
Christopher Faulete0768eb2018-10-03 16:38:02 +0200220 stream_inc_http_err_ctr(s);
221 stream_inc_http_req_ctr(s);
222 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100223 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200224 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100225 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200226
Christopher Faulet9768c262018-10-22 09:34:31 +0200227 txn->status = 400;
228 msg->err_state = msg->msg_state;
229 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100230 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200231 req->analysers &= AN_REQ_FLT_END;
232
Christopher Faulete0768eb2018-10-03 16:38:02 +0200233 if (!(s->flags & SF_FINST_MASK))
234 s->flags |= SF_FINST_R;
235 return 0;
236 }
237
238 channel_dont_connect(req);
239 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
240 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100241
Christopher Faulet9768c262018-10-22 09:34:31 +0200242 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200243 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
244 /* We need more data, we have to re-enable quick-ack in case we
245 * previously disabled it, otherwise we might cause the client
246 * to delay next data.
247 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100248 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100250
Christopher Faulet47365272018-10-31 17:40:50 +0100251 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200252 /* If the client starts to talk, let's fall back to
253 * request timeout processing.
254 */
255 txn->flags &= ~TX_WAIT_NEXT_RQ;
256 req->analyse_exp = TICK_ETERNITY;
257 }
258
259 /* just set the request timeout once at the beginning of the request */
260 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100261 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200262 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
263 else
264 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
265 }
266
267 /* we're not ready yet */
268 return 0;
269
270 failed_keep_alive:
271 /* Here we process low-level errors for keep-alive requests. In
272 * short, if the request is not the first one and it experiences
273 * a timeout, read error or shutdown, we just silently close so
274 * that the client can try again.
275 */
276 txn->status = 0;
277 msg->msg_state = HTTP_MSG_RQBEFORE;
278 req->analysers &= AN_REQ_FLT_END;
279 s->logs.logwait = 0;
280 s->logs.level = 0;
281 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200282 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200283 return 0;
284 }
285
Christopher Faulet9768c262018-10-22 09:34:31 +0200286 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200287 stream_inc_http_req_ctr(s);
288 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
289
Christopher Faulet9768c262018-10-22 09:34:31 +0200290 /* kill the pending keep-alive timeout */
291 txn->flags &= ~TX_WAIT_NEXT_RQ;
292 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200293
Christopher Faulet03599112018-11-27 11:21:21 +0100294 sl = http_find_stline(htx);
295
Christopher Faulet9768c262018-10-22 09:34:31 +0200296 /* 0: we might have to print this header in debug mode */
297 if (unlikely((global.mode & MODE_DEBUG) &&
298 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
299 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200300
Christopher Faulet03599112018-11-27 11:21:21 +0100301 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200302
303 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
304 struct htx_blk *blk = htx_get_blk(htx, pos);
305 enum htx_blk_type type = htx_get_blk_type(blk);
306
307 if (type == HTX_BLK_EOH)
308 break;
309 if (type != HTX_BLK_HDR)
310 continue;
311
312 htx_debug_hdr("clihdr", s,
313 htx_get_blk_name(htx, blk),
314 htx_get_blk_value(htx, blk));
315 }
316 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100319 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100322 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200323 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100324 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100325 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100326 if (sl->flags & HTX_SL_F_BODYLESS)
327 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200328
329 /* we can make use of server redirect on GET and HEAD */
330 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
331 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100332 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200334 goto return_bad_req;
335 }
336
337 /*
338 * 2: check if the URI matches the monitor_uri.
339 * We have to do this for every request which gets in, because
340 * the monitor-uri is defined by the frontend.
341 */
342 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100343 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200344 /*
345 * We have found the monitor URI
346 */
347 struct acl_cond *cond;
348
349 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200351
352 /* Check if we want to fail this monitor request or not */
353 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
354 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
355
356 ret = acl_pass(ret);
357 if (cond->pol == ACL_COND_UNLESS)
358 ret = !ret;
359
360 if (ret) {
361 /* we fail this request, let's return 503 service unavail */
362 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100363 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200364 if (!(s->flags & SF_ERR_MASK))
365 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
366 goto return_prx_cond;
367 }
368 }
369
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800370 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200371 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100372 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200373 if (!(s->flags & SF_ERR_MASK))
374 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
375 goto return_prx_cond;
376 }
377
378 /*
379 * 3: Maybe we have to copy the original REQURI for the logs ?
380 * Note: we cannot log anymore if the request has been
381 * classified as invalid.
382 */
383 if (unlikely(s->logs.logwait & LW_REQ)) {
384 /* we have a complete HTTP request that we must log */
385 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200386 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
Christopher Faulet9768c262018-10-22 09:34:31 +0200388 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
389 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200390
391 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
392 s->do_log(s);
393 } else {
394 ha_alert("HTTP logging : out of memory.\n");
395 }
396 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200397
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 /* if the frontend has "option http-use-proxy-header", we'll check if
399 * we have what looks like a proxied connection instead of a connection,
400 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
401 * Note that this is *not* RFC-compliant, however browsers and proxies
402 * happen to do that despite being non-standard :-(
403 * We consider that a request not beginning with either '/' or '*' is
404 * a proxied connection, which covers both "scheme://location" and
405 * CONNECT ip:port.
406 */
407 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100408 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 txn->flags |= TX_USE_PX_CONN;
410
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411 /* 5: we may need to capture headers */
412 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200413 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100415 /* by default, close the stream at the end of the transaction. */
416 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417
418 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200419 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200420 req->analysers |= AN_REQ_HTTP_BODY;
421
422 /*
423 * RFC7234#4:
424 * A cache MUST write through requests with methods
425 * that are unsafe (Section 4.2.1 of [RFC7231]) to
426 * the origin server; i.e., a cache is not allowed
427 * to generate a reply to such a request before
428 * having forwarded the request and having received
429 * a corresponding response.
430 *
431 * RFC7231#4.2.1:
432 * Of the request methods defined by this
433 * specification, the GET, HEAD, OPTIONS, and TRACE
434 * methods are defined to be safe.
435 */
436 if (likely(txn->meth == HTTP_METH_GET ||
437 txn->meth == HTTP_METH_HEAD ||
438 txn->meth == HTTP_METH_OPTIONS ||
439 txn->meth == HTTP_METH_TRACE))
440 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
441
442 /* end of job, return OK */
443 req->analysers &= ~an_bit;
444 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200445
Christopher Faulete0768eb2018-10-03 16:38:02 +0200446 return 1;
447
448 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200449 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200450 txn->req.err_state = txn->req.msg_state;
451 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100452 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100453 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200454 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100455 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200456
457 return_prx_cond:
458 if (!(s->flags & SF_ERR_MASK))
459 s->flags |= SF_ERR_PRXCOND;
460 if (!(s->flags & SF_FINST_MASK))
461 s->flags |= SF_FINST_R;
462
463 req->analysers &= AN_REQ_FLT_END;
464 req->analyse_exp = TICK_ETERNITY;
465 return 0;
466}
467
468
469/* This stream analyser runs all HTTP request processing which is common to
470 * frontends and backends, which means blocking ACLs, filters, connection-close,
471 * reqadd, stats and redirects. This is performed for the designated proxy.
472 * It returns 1 if the processing can continue on next analysers, or zero if it
473 * either needs more data or wants to immediately abort the request (eg: deny,
474 * error, ...).
475 */
476int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
477{
478 struct session *sess = s->sess;
479 struct http_txn *txn = s->txn;
480 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200481 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200482 struct redirect_rule *rule;
483 struct cond_wordlist *wl;
484 enum rule_result verdict;
485 int deny_status = HTTP_ERR_403;
486 struct connection *conn = objt_conn(sess->origin);
487
488 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
489 /* we need more data */
490 goto return_prx_yield;
491 }
492
493 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
494 now_ms, __FUNCTION__,
495 s,
496 req,
497 req->rex, req->wex,
498 req->flags,
499 ci_data(req),
500 req->analysers);
501
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100502 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200503
Christopher Faulete0768eb2018-10-03 16:38:02 +0200504 /* just in case we have some per-backend tracking */
505 stream_inc_be_http_req_ctr(s);
506
507 /* evaluate http-request rules */
508 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200509 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200510
511 switch (verdict) {
512 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
513 goto return_prx_yield;
514
515 case HTTP_RULE_RES_CONT:
516 case HTTP_RULE_RES_STOP: /* nothing to do */
517 break;
518
519 case HTTP_RULE_RES_DENY: /* deny or tarpit */
520 if (txn->flags & TX_CLTARPIT)
521 goto tarpit;
522 goto deny;
523
524 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
525 goto return_prx_cond;
526
527 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
528 goto done;
529
530 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
531 goto return_bad_req;
532 }
533 }
534
535 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
536 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200537 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200538
Christopher Fauletff2759f2018-10-24 11:13:16 +0200539 ctx.blk = NULL;
540 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
541 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200543 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 }
545
546 /* OK at this stage, we know that the request was accepted according to
547 * the http-request rules, we can check for the stats. Note that the
548 * URI is detected *before* the req* rules in order not to be affected
549 * by a possible reqrep, while they are processed *after* so that a
550 * reqdeny can still block them. This clearly needs to change in 1.6!
551 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200552 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200553 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100554 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555 txn->status = 500;
556 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100557 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558
559 if (!(s->flags & SF_ERR_MASK))
560 s->flags |= SF_ERR_RESOURCE;
561 goto return_prx_cond;
562 }
563
564 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200565 htx_handle_stats(s, req);
566 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200567 /* not all actions implemented: deny, allow, auth */
568
569 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
570 goto deny;
571
572 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
573 goto return_prx_cond;
574 }
575
576 /* evaluate the req* rules except reqadd */
577 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200578 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200579 goto return_bad_req;
580
581 if (txn->flags & TX_CLDENY)
582 goto deny;
583
584 if (txn->flags & TX_CLTARPIT) {
585 deny_status = HTTP_ERR_500;
586 goto tarpit;
587 }
588 }
589
590 /* add request headers from the rule sets in the same order */
591 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200592 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200593 if (wl->cond) {
594 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
595 ret = acl_pass(ret);
596 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
597 ret = !ret;
598 if (!ret)
599 continue;
600 }
601
Christopher Fauletff2759f2018-10-24 11:13:16 +0200602 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
603 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200604 goto return_bad_req;
605 }
606
Christopher Faulet2571bc62019-03-01 11:44:26 +0100607 /* Proceed with the applets now. */
608 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200609 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100610 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100612 if (htx_handle_expect_hdr(s, htx, msg) == -1)
613 goto return_bad_req;
614
Christopher Faulete0768eb2018-10-03 16:38:02 +0200615 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
616 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
617 if (!(s->flags & SF_FINST_MASK))
618 s->flags |= SF_FINST_R;
619
620 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
621 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
622 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
623 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100624
625 req->flags |= CF_SEND_DONTWAIT;
626 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200627 goto done;
628 }
629
630 /* check whether we have some ACLs set to redirect this request */
631 list_for_each_entry(rule, &px->redirect_rules, list) {
632 if (rule->cond) {
633 int ret;
634
635 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
636 ret = acl_pass(ret);
637 if (rule->cond->pol == ACL_COND_UNLESS)
638 ret = !ret;
639 if (!ret)
640 continue;
641 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200642 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200643 goto return_bad_req;
644 goto done;
645 }
646
647 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
648 * If this happens, then the data will not come immediately, so we must
649 * send all what we have without waiting. Note that due to the small gain
650 * in waiting for the body of the request, it's easier to simply put the
651 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
652 * itself once used.
653 */
654 req->flags |= CF_SEND_DONTWAIT;
655
656 done: /* done with this analyser, continue with next ones that the calling
657 * points will have set, if any.
658 */
659 req->analyse_exp = TICK_ETERNITY;
660 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
661 req->analysers &= ~an_bit;
662 return 1;
663
664 tarpit:
665 /* Allow cookie logging
666 */
667 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200668 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200669
670 /* When a connection is tarpitted, we use the tarpit timeout,
671 * which may be the same as the connect timeout if unspecified.
672 * If unset, then set it to zero because we really want it to
673 * eventually expire. We build the tarpit as an analyser.
674 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100675 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200676
677 /* wipe the request out so that we can drop the connection early
678 * if the client closes first.
679 */
680 channel_dont_connect(req);
681
682 txn->status = http_err_codes[deny_status];
683
684 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
685 req->analysers |= AN_REQ_HTTP_TARPIT;
686 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
687 if (!req->analyse_exp)
688 req->analyse_exp = tick_add(now_ms, 0);
689 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100690 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200691 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100692 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200693 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100694 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200695 goto done_without_exp;
696
697 deny: /* this request was blocked (denied) */
698
699 /* Allow cookie logging
700 */
701 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200702 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703
704 txn->flags |= TX_CLDENY;
705 txn->status = http_err_codes[deny_status];
706 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100707 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100709 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100711 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 goto return_prx_cond;
715
716 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 txn->req.err_state = txn->req.msg_state;
718 txn->req.msg_state = HTTP_MSG_ERROR;
719 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100720 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200721
Olivier Houcharda798bf52019-03-08 18:52:00 +0100722 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200723 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100724 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200725
726 return_prx_cond:
727 if (!(s->flags & SF_ERR_MASK))
728 s->flags |= SF_ERR_PRXCOND;
729 if (!(s->flags & SF_FINST_MASK))
730 s->flags |= SF_FINST_R;
731
732 req->analysers &= AN_REQ_FLT_END;
733 req->analyse_exp = TICK_ETERNITY;
734 return 0;
735
736 return_prx_yield:
737 channel_dont_connect(req);
738 return 0;
739}
740
741/* This function performs all the processing enabled for the current request.
742 * It returns 1 if the processing can continue on next analysers, or zero if it
743 * needs more data, encounters an error, or wants to immediately abort the
744 * request. It relies on buffers flags, and updates s->req.analysers.
745 */
746int htx_process_request(struct stream *s, struct channel *req, int an_bit)
747{
748 struct session *sess = s->sess;
749 struct http_txn *txn = s->txn;
750 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200751 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200752 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
753
754 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
755 /* we need more data */
756 channel_dont_connect(req);
757 return 0;
758 }
759
760 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
761 now_ms, __FUNCTION__,
762 s,
763 req,
764 req->rex, req->wex,
765 req->flags,
766 ci_data(req),
767 req->analysers);
768
769 /*
770 * Right now, we know that we have processed the entire headers
771 * and that unwanted requests have been filtered out. We can do
772 * whatever we want with the remaining request. Also, now we
773 * may have separate values for ->fe, ->be.
774 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100775 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200776
777 /*
778 * If HTTP PROXY is set we simply get remote server address parsing
779 * incoming request. Note that this requires that a connection is
780 * allocated on the server side.
781 */
782 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
783 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100784 struct htx_sl *sl;
785 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200786
787 /* Note that for now we don't reuse existing proxy connections */
788 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
789 txn->req.err_state = txn->req.msg_state;
790 txn->req.msg_state = HTTP_MSG_ERROR;
791 txn->status = 500;
792 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100793 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200794
795 if (!(s->flags & SF_ERR_MASK))
796 s->flags |= SF_ERR_RESOURCE;
797 if (!(s->flags & SF_FINST_MASK))
798 s->flags |= SF_FINST_R;
799
800 return 0;
801 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200802 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100803 uri = htx_sl_req_uri(sl);
804 path = http_get_path(uri);
805 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 goto return_bad_req;
807
808 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200809 * uri.ptr and path.ptr (excluded). If it was not found, we need
810 * to replace from all the uri by a single "/".
811 *
812 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100813 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200814 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200815 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100816 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200817 }
818
819 /*
820 * 7: Now we can work with the cookies.
821 * Note that doing so might move headers in the request, but
822 * the fields will stay coherent and the URI will not move.
823 * This should only be performed in the backend.
824 */
825 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100826 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200827
828 /* add unique-id if "header-unique-id" is specified */
829
830 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
831 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
832 goto return_bad_req;
833 s->unique_id[0] = '\0';
834 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
835 }
836
837 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200838 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
839 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
840
841 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200842 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200843 }
844
845 /*
846 * 9: add X-Forwarded-For if either the frontend or the backend
847 * asks for it.
848 */
849 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200850 struct http_hdr_ctx ctx = { .blk = NULL };
851 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
852 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
853
Christopher Faulete0768eb2018-10-03 16:38:02 +0200854 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200855 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200856 /* The header is set to be added only if none is present
857 * and we found it, so don't do anything.
858 */
859 }
860 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
861 /* Add an X-Forwarded-For header unless the source IP is
862 * in the 'except' network range.
863 */
864 if ((!sess->fe->except_mask.s_addr ||
865 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
866 != sess->fe->except_net.s_addr) &&
867 (!s->be->except_mask.s_addr ||
868 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
869 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200870 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200871
872 /* Note: we rely on the backend to get the header name to be used for
873 * x-forwarded-for, because the header is really meant for the backends.
874 * However, if the backend did not specify any option, we have to rely
875 * on the frontend's header name.
876 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
878 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 goto return_bad_req;
880 }
881 }
882 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
883 /* FIXME: for the sake of completeness, we should also support
884 * 'except' here, although it is mostly useless in this case.
885 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200886 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200887
Christopher Faulete0768eb2018-10-03 16:38:02 +0200888 inet_ntop(AF_INET6,
889 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
890 pn, sizeof(pn));
891
892 /* Note: we rely on the backend to get the header name to be used for
893 * x-forwarded-for, because the header is really meant for the backends.
894 * However, if the backend did not specify any option, we have to rely
895 * on the frontend's header name.
896 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200897 chunk_printf(&trash, "%s", pn);
898 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200899 goto return_bad_req;
900 }
901 }
902
903 /*
904 * 10: add X-Original-To if either the frontend or the backend
905 * asks for it.
906 */
907 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
908
909 /* FIXME: don't know if IPv6 can handle that case too. */
910 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
911 /* Add an X-Original-To header unless the destination IP is
912 * in the 'except' network range.
913 */
914 conn_get_to_addr(cli_conn);
915
916 if (cli_conn->addr.to.ss_family == AF_INET &&
917 ((!sess->fe->except_mask_to.s_addr ||
918 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
919 != sess->fe->except_to.s_addr) &&
920 (!s->be->except_mask_to.s_addr ||
921 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
922 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200923 struct ist hdr;
924 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200925
926 /* Note: we rely on the backend to get the header name to be used for
927 * x-original-to, because the header is really meant for the backends.
928 * However, if the backend did not specify any option, we have to rely
929 * on the frontend's header name.
930 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200931 if (s->be->orgto_hdr_len)
932 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
933 else
934 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200936 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
937 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938 goto return_bad_req;
939 }
940 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 }
942
Christopher Faulete0768eb2018-10-03 16:38:02 +0200943 /* If we have no server assigned yet and we're balancing on url_param
944 * with a POST request, we may be interested in checking the body for
945 * that parameter. This will be done in another analyser.
946 */
947 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100948 s->txn->meth == HTTP_METH_POST &&
949 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200950 channel_dont_connect(req);
951 req->analysers |= AN_REQ_HTTP_BODY;
952 }
953
954 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
955 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 /* We expect some data from the client. Unless we know for sure
958 * we already have a full request, we have to re-enable quick-ack
959 * in case we previously disabled it, otherwise we might cause
960 * the client to delay further data.
961 */
962 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200963 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100964 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200965
966 /*************************************************************
967 * OK, that's finished for the headers. We have done what we *
968 * could. Let's switch to the DATA state. *
969 ************************************************************/
970 req->analyse_exp = TICK_ETERNITY;
971 req->analysers &= ~an_bit;
972
973 s->logs.tv_request = now;
974 /* OK let's go on with the BODY now */
975 return 1;
976
977 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978 txn->req.err_state = txn->req.msg_state;
979 txn->req.msg_state = HTTP_MSG_ERROR;
980 txn->status = 400;
981 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100982 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200983
Olivier Houcharda798bf52019-03-08 18:52:00 +0100984 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200985 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100986 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200987
988 if (!(s->flags & SF_ERR_MASK))
989 s->flags |= SF_ERR_PRXCOND;
990 if (!(s->flags & SF_FINST_MASK))
991 s->flags |= SF_FINST_R;
992 return 0;
993}
994
995/* This function is an analyser which processes the HTTP tarpit. It always
996 * returns zero, at the beginning because it prevents any other processing
997 * from occurring, and at the end because it terminates the request.
998 */
999int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1000{
1001 struct http_txn *txn = s->txn;
1002
1003 /* This connection is being tarpitted. The CLIENT side has
1004 * already set the connect expiration date to the right
1005 * timeout. We just have to check that the client is still
1006 * there and that the timeout has not expired.
1007 */
1008 channel_dont_connect(req);
1009 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1010 !tick_is_expired(req->analyse_exp, now_ms))
1011 return 0;
1012
1013 /* We will set the queue timer to the time spent, just for
1014 * logging purposes. We fake a 500 server error, so that the
1015 * attacker will not suspect his connection has been tarpitted.
1016 * It will not cause trouble to the logs because we can exclude
1017 * the tarpitted connections by filtering on the 'PT' status flags.
1018 */
1019 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1020
1021 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001022 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001023
1024 req->analysers &= AN_REQ_FLT_END;
1025 req->analyse_exp = TICK_ETERNITY;
1026
1027 if (!(s->flags & SF_ERR_MASK))
1028 s->flags |= SF_ERR_PRXCOND;
1029 if (!(s->flags & SF_FINST_MASK))
1030 s->flags |= SF_FINST_T;
1031 return 0;
1032}
1033
1034/* This function is an analyser which waits for the HTTP request body. It waits
1035 * for either the buffer to be full, or the full advertised contents to have
1036 * reached the buffer. It must only be called after the standard HTTP request
1037 * processing has occurred, because it expects the request to be parsed and will
1038 * look for the Expect header. It may send a 100-Continue interim response. It
1039 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1040 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1041 * needs to read more data, or 1 once it has completed its analysis.
1042 */
1043int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1044{
1045 struct session *sess = s->sess;
1046 struct http_txn *txn = s->txn;
1047 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001048 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001049
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001050
1051 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1052 now_ms, __FUNCTION__,
1053 s,
1054 req,
1055 req->rex, req->wex,
1056 req->flags,
1057 ci_data(req),
1058 req->analysers);
1059
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001060 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001061
Willy Tarreau4236f032019-03-05 10:43:32 +01001062 if (htx->flags & HTX_FL_PARSING_ERROR)
1063 goto return_bad_req;
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_BODY)
1066 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001067
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 /* We have to parse the HTTP request body to find any required data.
1069 * "balance url_param check_post" should have been the only way to get
1070 * into this. We were brought here after HTTP header analysis, so all
1071 * related structures are ready.
1072 */
1073
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001074 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001075 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1076 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 }
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1082 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001084 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001085 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 goto http_end;
1087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1090 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001091 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001092
1093 if (!(s->flags & SF_ERR_MASK))
1094 s->flags |= SF_ERR_CLITO;
1095 if (!(s->flags & SF_FINST_MASK))
1096 s->flags |= SF_FINST_D;
1097 goto return_err_msg;
1098 }
1099
1100 /* we get here if we need to wait for more data */
1101 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1102 /* Not enough data. We'll re-use the http-request
1103 * timeout here. Ideally, we should set the timeout
1104 * relative to the accept() date. We just set the
1105 * request timeout once at the beginning of the
1106 * request.
1107 */
1108 channel_dont_connect(req);
1109 if (!tick_isset(req->analyse_exp))
1110 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1111 return 0;
1112 }
1113
1114 http_end:
1115 /* The situation will not evolve, so let's give up on the analysis. */
1116 s->logs.tv_request = now; /* update the request timer to reflect full request */
1117 req->analysers &= ~an_bit;
1118 req->analyse_exp = TICK_ETERNITY;
1119 return 1;
1120
1121 return_bad_req: /* let's centralize all bad requests */
1122 txn->req.err_state = txn->req.msg_state;
1123 txn->req.msg_state = HTTP_MSG_ERROR;
1124 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001125 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126
1127 if (!(s->flags & SF_ERR_MASK))
1128 s->flags |= SF_ERR_PRXCOND;
1129 if (!(s->flags & SF_FINST_MASK))
1130 s->flags |= SF_FINST_R;
1131
1132 return_err_msg:
1133 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001134 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001135 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001136 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001137 return 0;
1138}
1139
1140/* This function is an analyser which forwards request body (including chunk
1141 * sizes if any). It is called as soon as we must forward, even if we forward
1142 * zero byte. The only situation where it must not be called is when we're in
1143 * tunnel mode and we want to forward till the close. It's used both to forward
1144 * remaining data and to resync after end of body. It expects the msg_state to
1145 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1146 * read more data, or 1 once we can go on with next request or end the stream.
1147 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1148 * bytes of pending data + the headers if not already done.
1149 */
1150int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1151{
1152 struct session *sess = s->sess;
1153 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001154 struct http_msg *msg = &txn->req;
1155 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001156 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001157 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001158
1159 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1160 now_ms, __FUNCTION__,
1161 s,
1162 req,
1163 req->rex, req->wex,
1164 req->flags,
1165 ci_data(req),
1166 req->analysers);
1167
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001168 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001169
1170 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1171 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1172 /* Output closed while we were sending data. We must abort and
1173 * wake the other side up.
1174 */
1175 msg->err_state = msg->msg_state;
1176 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001177 htx_end_request(s);
1178 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001179 return 1;
1180 }
1181
1182 /* Note that we don't have to send 100-continue back because we don't
1183 * need the data to complete our job, and it's up to the server to
1184 * decide whether to return 100, 417 or anything else in return of
1185 * an "Expect: 100-continue" header.
1186 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001187 if (msg->msg_state == HTTP_MSG_BODY)
1188 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001189
1190 /* Some post-connect processing might want us to refrain from starting to
1191 * forward data. Currently, the only reason for this is "balance url_param"
1192 * whichs need to parse/process the request after we've enabled forwarding.
1193 */
1194 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1195 if (!(s->res.flags & CF_READ_ATTACHED)) {
1196 channel_auto_connect(req);
1197 req->flags |= CF_WAKE_CONNECT;
1198 channel_dont_close(req); /* don't fail on early shutr */
1199 goto waiting;
1200 }
1201 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1202 }
1203
1204 /* in most states, we should abort in case of early close */
1205 channel_auto_close(req);
1206
1207 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001208 if (req->to_forward == CHN_INFINITE_FORWARD) {
1209 if (req->flags & (CF_SHUTR|CF_EOI)) {
1210 msg->msg_state = HTTP_MSG_DONE;
1211 req->to_forward = 0;
1212 goto done;
1213 }
1214 }
1215 else {
1216 /* We can't process the buffer's contents yet */
1217 req->flags |= CF_WAKE_WRITE;
1218 goto missing_data_or_waiting;
1219 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001220 }
1221
Christopher Faulet9768c262018-10-22 09:34:31 +02001222 if (msg->msg_state >= HTTP_MSG_DONE)
1223 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 /* Forward input data. We get it by removing all outgoing data not
1225 * forwarded yet from HTX data size. If there are some data filters, we
1226 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 if (HAS_REQ_DATA_FILTERS(s)) {
1229 ret = flt_http_payload(s, msg, htx->data);
1230 if (ret < 0)
1231 goto return_bad_req;
1232 c_adv(req, ret);
1233 if (htx->data != co_data(req) || htx->extra)
1234 goto missing_data_or_waiting;
1235 }
1236 else {
1237 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001238 if (msg->flags & HTTP_MSGF_XFER_LEN)
1239 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001240 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001241
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001242 if (txn->meth == HTTP_METH_CONNECT) {
1243 msg->msg_state = HTTP_MSG_TUNNEL;
1244 goto done;
1245 }
1246
Christopher Faulet9768c262018-10-22 09:34:31 +02001247 /* Check if the end-of-message is reached and if so, switch the message
1248 * in HTTP_MSG_DONE state.
1249 */
1250 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1251 goto missing_data_or_waiting;
1252
1253 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001254 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001255
1256 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001257 /* other states, DONE...TUNNEL */
1258 /* we don't want to forward closes on DONE except in tunnel mode. */
1259 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1260 channel_dont_close(req);
1261
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001262 if (HAS_REQ_DATA_FILTERS(s)) {
1263 ret = flt_http_end(s, msg);
1264 if (ret <= 0) {
1265 if (!ret)
1266 goto missing_data_or_waiting;
1267 goto return_bad_req;
1268 }
1269 }
1270
Christopher Fauletf2824e62018-10-01 12:12:37 +02001271 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001272 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1275 if (req->flags & CF_SHUTW) {
1276 /* request errors are most likely due to the
1277 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001278 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001279 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 goto return_bad_req;
1281 }
1282 return 1;
1283 }
1284
1285 /* If "option abortonclose" is set on the backend, we want to monitor
1286 * the client's connection and forward any shutdown notification to the
1287 * server, which will decide whether to close or to go on processing the
1288 * request. We only do that in tunnel mode, and not in other modes since
1289 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001290 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001291 channel_auto_read(req);
1292 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1293 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1294 s->si[1].flags |= SI_FL_NOLINGER;
1295 channel_auto_close(req);
1296 }
1297 else if (s->txn->meth == HTTP_METH_POST) {
1298 /* POST requests may require to read extra CRLF sent by broken
1299 * browsers and which could cause an RST to be sent upon close
1300 * on some systems (eg: Linux). */
1301 channel_auto_read(req);
1302 }
1303 return 0;
1304
1305 missing_data_or_waiting:
1306 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001307 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1308 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001309
1310 waiting:
1311 /* waiting for the last bits to leave the buffer */
1312 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001313 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001314
Christopher Faulet47365272018-10-31 17:40:50 +01001315 if (htx->flags & HTX_FL_PARSING_ERROR)
1316 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001317
Christopher Faulete0768eb2018-10-03 16:38:02 +02001318 /* When TE: chunked is used, we need to get there again to parse remaining
1319 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1320 * And when content-length is used, we never want to let the possible
1321 * shutdown be forwarded to the other side, as the state machine will
1322 * take care of it once the client responds. It's also important to
1323 * prevent TIME_WAITs from accumulating on the backend side, and for
1324 * HTTP/2 where the last frame comes with a shutdown.
1325 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001326 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001327 channel_dont_close(req);
1328
1329 /* We know that more data are expected, but we couldn't send more that
1330 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1331 * system knows it must not set a PUSH on this first part. Interactive
1332 * modes are already handled by the stream sock layer. We must not do
1333 * this in content-length mode because it could present the MSG_MORE
1334 * flag with the last block of forwarded data, which would cause an
1335 * additional delay to be observed by the receiver.
1336 */
1337 if (msg->flags & HTTP_MSGF_TE_CHNK)
1338 req->flags |= CF_EXPECT_MORE;
1339
1340 return 0;
1341
Christopher Faulet93e02d82019-03-08 14:18:50 +01001342 return_cli_abort:
1343 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1344 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1345 if (objt_server(s->target))
1346 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1347 if (!(s->flags & SF_ERR_MASK))
1348 s->flags |= SF_ERR_CLICL;
1349 status = 400;
1350 goto return_error;
1351
1352 return_srv_abort:
1353 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1354 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1355 if (objt_server(s->target))
1356 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1357 if (!(s->flags & SF_ERR_MASK))
1358 s->flags |= SF_ERR_SRVCL;
1359 status = 502;
1360 goto return_error;
1361
1362 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001363 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001364 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001365 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001367 s->flags |= SF_ERR_CLICL;
1368 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001369
Christopher Faulet93e02d82019-03-08 14:18:50 +01001370 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 txn->req.err_state = txn->req.msg_state;
1372 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001373 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001375 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001377 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001378 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001379 }
1380 req->analysers &= AN_REQ_FLT_END;
1381 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 +01001382 if (!(s->flags & SF_FINST_MASK))
1383 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001384 return 0;
1385}
1386
1387/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1388 * processing can continue on next analysers, or zero if it either needs more
1389 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1390 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1391 * when it has nothing left to do, and may remove any analyser when it wants to
1392 * abort.
1393 */
1394int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1395{
Christopher Faulet9768c262018-10-22 09:34:31 +02001396 /*
1397 * We will analyze a complete HTTP response to check the its syntax.
1398 *
1399 * Once the start line and all headers are received, we may perform a
1400 * capture of the error (if any), and we will set a few fields. We also
1401 * logging and finally headers capture.
1402 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001403 struct session *sess = s->sess;
1404 struct http_txn *txn = s->txn;
1405 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001406 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001407 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001408 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001409 int n;
1410
1411 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1412 now_ms, __FUNCTION__,
1413 s,
1414 rep,
1415 rep->rex, rep->wex,
1416 rep->flags,
1417 ci_data(rep),
1418 rep->analysers);
1419
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001420 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001421
Willy Tarreau4236f032019-03-05 10:43:32 +01001422 /* Parsing errors are caught here */
1423 if (htx->flags & HTX_FL_PARSING_ERROR)
1424 goto return_bad_res;
1425
Christopher Faulete0768eb2018-10-03 16:38:02 +02001426 /*
1427 * Now we quickly check if we have found a full valid response.
1428 * If not so, we check the FD and buffer states before leaving.
1429 * A full response is indicated by the fact that we have seen
1430 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1431 * responses are checked first.
1432 *
1433 * Depending on whether the client is still there or not, we
1434 * may send an error response back or not. Note that normally
1435 * we should only check for HTTP status there, and check I/O
1436 * errors somewhere else.
1437 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001438 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001439 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001440 * First catch invalid response because of a parsing error or
1441 * because only part of headers have been transfered.
1442 * Multiplexers have the responsibility to emit all headers at
1443 * once. We must be sure to have forwarded all outgoing data
1444 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001445 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001446 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001447 goto return_bad_res;
1448
Christopher Faulet9768c262018-10-22 09:34:31 +02001449 /* 1: have we encountered a read error ? */
1450 if (rep->flags & CF_READ_ERROR) {
1451 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452 goto abort_keep_alive;
1453
Olivier Houcharda798bf52019-03-08 18:52:00 +01001454 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001455 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001456 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001457 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001458 }
1459
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 rep->analysers &= AN_RES_FLT_END;
1461 txn->status = 502;
1462
1463 /* Check to see if the server refused the early data.
1464 * If so, just send a 425
1465 */
1466 if (objt_cs(s->si[1].end)) {
1467 struct connection *conn = objt_cs(s->si[1].end)->conn;
1468
1469 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1470 txn->status = 425;
1471 }
1472
1473 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001474 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001475
1476 if (!(s->flags & SF_ERR_MASK))
1477 s->flags |= SF_ERR_SRVCL;
1478 if (!(s->flags & SF_FINST_MASK))
1479 s->flags |= SF_FINST_H;
1480 return 0;
1481 }
1482
Christopher Faulet9768c262018-10-22 09:34:31 +02001483 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001484 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001485 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001486 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001487 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001488 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001489 }
1490
Christopher Faulete0768eb2018-10-03 16:38:02 +02001491 rep->analysers &= AN_RES_FLT_END;
1492 txn->status = 504;
1493 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001494 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001495
1496 if (!(s->flags & SF_ERR_MASK))
1497 s->flags |= SF_ERR_SRVTO;
1498 if (!(s->flags & SF_FINST_MASK))
1499 s->flags |= SF_FINST_H;
1500 return 0;
1501 }
1502
Christopher Faulet9768c262018-10-22 09:34:31 +02001503 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001504 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001505 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1506 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001508 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509
1510 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001512 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513
1514 if (!(s->flags & SF_ERR_MASK))
1515 s->flags |= SF_ERR_CLICL;
1516 if (!(s->flags & SF_FINST_MASK))
1517 s->flags |= SF_FINST_H;
1518
1519 /* process_stream() will take care of the error */
1520 return 0;
1521 }
1522
Christopher Faulet9768c262018-10-22 09:34:31 +02001523 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001525 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 goto abort_keep_alive;
1527
Olivier Houcharda798bf52019-03-08 18:52:00 +01001528 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001530 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001531 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532 }
1533
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 rep->analysers &= AN_RES_FLT_END;
1535 txn->status = 502;
1536 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_SRVCL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 goto abort_keep_alive;
1550
Olivier Houcharda798bf52019-03-08 18:52:00 +01001551 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001552 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553
1554 if (!(s->flags & SF_ERR_MASK))
1555 s->flags |= SF_ERR_CLICL;
1556 if (!(s->flags & SF_FINST_MASK))
1557 s->flags |= SF_FINST_H;
1558
1559 /* process_stream() will take care of the error */
1560 return 0;
1561 }
1562
1563 channel_dont_close(rep);
1564 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1565 return 0;
1566 }
1567
1568 /* More interesting part now : we know that we have a complete
1569 * response which at least looks like HTTP. We have an indicator
1570 * of each header's length, so we can parse them quickly.
1571 */
1572
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001574 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001575
Christopher Faulet9768c262018-10-22 09:34:31 +02001576 /* 0: we might have to print this header in debug mode */
1577 if (unlikely((global.mode & MODE_DEBUG) &&
1578 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1579 int32_t pos;
1580
Christopher Faulet03599112018-11-27 11:21:21 +01001581 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001582
1583 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1584 struct htx_blk *blk = htx_get_blk(htx, pos);
1585 enum htx_blk_type type = htx_get_blk_type(blk);
1586
1587 if (type == HTX_BLK_EOH)
1588 break;
1589 if (type != HTX_BLK_HDR)
1590 continue;
1591
1592 htx_debug_hdr("srvhdr", s,
1593 htx_get_blk_name(htx, blk),
1594 htx_get_blk_value(htx, blk));
1595 }
1596 }
1597
Christopher Faulet03599112018-11-27 11:21:21 +01001598 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001599 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001600 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001602 if (sl->flags & HTX_SL_F_XFER_LEN) {
1603 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001604 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001605 if (sl->flags & HTX_SL_F_BODYLESS)
1606 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001607 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001608
1609 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610 if (n < 1 || n > 5)
1611 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001612
Christopher Faulete0768eb2018-10-03 16:38:02 +02001613 /* when the client triggers a 4xx from the server, it's most often due
1614 * to a missing object or permission. These events should be tracked
1615 * because if they happen often, it may indicate a brute force or a
1616 * vulnerability scan.
1617 */
1618 if (n == 4)
1619 stream_inc_http_err_ctr(s);
1620
1621 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001622 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624 /* Adjust server's health based on status code. Note: status codes 501
1625 * and 505 are triggered on demand by client request, so we must not
1626 * count them as server failures.
1627 */
1628 if (objt_server(s->target)) {
1629 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001630 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001632 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001633 }
1634
1635 /*
1636 * We may be facing a 100-continue response, or any other informational
1637 * 1xx response which is non-final, in which case this is not the right
1638 * response, and we're waiting for the next one. Let's allow this response
1639 * to go to the client and wait for the next one. There's an exception for
1640 * 101 which is used later in the code to switch protocols.
1641 */
1642 if (txn->status < 200 &&
1643 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001644 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001645 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001646 msg->msg_state = HTTP_MSG_RPBEFORE;
1647 txn->status = 0;
1648 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001649 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001650 }
1651
1652 /*
1653 * 2: check for cacheability.
1654 */
1655
1656 switch (txn->status) {
1657 case 200:
1658 case 203:
1659 case 204:
1660 case 206:
1661 case 300:
1662 case 301:
1663 case 404:
1664 case 405:
1665 case 410:
1666 case 414:
1667 case 501:
1668 break;
1669 default:
1670 /* RFC7231#6.1:
1671 * Responses with status codes that are defined as
1672 * cacheable by default (e.g., 200, 203, 204, 206,
1673 * 300, 301, 404, 405, 410, 414, and 501 in this
1674 * specification) can be reused by a cache with
1675 * heuristic expiration unless otherwise indicated
1676 * by the method definition or explicit cache
1677 * controls [RFC7234]; all other status codes are
1678 * not cacheable by default.
1679 */
1680 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1681 break;
1682 }
1683
1684 /*
1685 * 3: we may need to capture headers
1686 */
1687 s->logs.logwait &= ~LW_RESP;
1688 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001689 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001690
Christopher Faulet9768c262018-10-22 09:34:31 +02001691 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1693 txn->status == 101)) {
1694 /* Either we've established an explicit tunnel, or we're
1695 * switching the protocol. In both cases, we're very unlikely
1696 * to understand the next protocols. We have to switch to tunnel
1697 * mode, so that we transfer the request and responses then let
1698 * this protocol pass unmodified. When we later implement specific
1699 * parsers for such protocols, we'll want to check the Upgrade
1700 * header which contains information about that protocol for
1701 * responses with status 101 (eg: see RFC2817 about TLS).
1702 */
1703 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001704 }
1705
Christopher Faulet61608322018-11-23 16:23:45 +01001706 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1707 * 407 (Proxy-Authenticate) responses and set the connection to private
1708 */
1709 srv_conn = cs_conn(objt_cs(s->si[1].end));
1710 if (srv_conn) {
1711 struct ist hdr;
1712 struct http_hdr_ctx ctx;
1713
1714 if (txn->status == 401)
1715 hdr = ist("WWW-Authenticate");
1716 else if (txn->status == 407)
1717 hdr = ist("Proxy-Authenticate");
1718 else
1719 goto end;
1720
1721 ctx.blk = NULL;
1722 while (http_find_header(htx, hdr, &ctx, 0)) {
1723 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1724 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1725 srv_conn->flags |= CO_FL_PRIVATE;
1726 }
1727 }
1728
1729 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001730 /* we want to have the response time before we start processing it */
1731 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1732
1733 /* end of job, return OK */
1734 rep->analysers &= ~an_bit;
1735 rep->analyse_exp = TICK_ETERNITY;
1736 channel_auto_close(rep);
1737 return 1;
1738
Christopher Faulet47365272018-10-31 17:40:50 +01001739 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001740 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001741 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001742 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001743 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001744 }
1745 txn->status = 502;
1746 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001747 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001748 rep->analysers &= AN_RES_FLT_END;
1749
1750 if (!(s->flags & SF_ERR_MASK))
1751 s->flags |= SF_ERR_PRXCOND;
1752 if (!(s->flags & SF_FINST_MASK))
1753 s->flags |= SF_FINST_H;
1754 return 0;
1755
Christopher Faulete0768eb2018-10-03 16:38:02 +02001756 abort_keep_alive:
1757 /* A keep-alive request to the server failed on a network error.
1758 * The client is required to retry. We need to close without returning
1759 * any other information so that the client retries.
1760 */
1761 txn->status = 0;
1762 rep->analysers &= AN_RES_FLT_END;
1763 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001764 s->logs.logwait = 0;
1765 s->logs.level = 0;
1766 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001767 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001768 return 0;
1769}
1770
1771/* This function performs all the processing enabled for the current response.
1772 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1773 * and updates s->res.analysers. It might make sense to explode it into several
1774 * other functions. It works like process_request (see indications above).
1775 */
1776int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1777{
1778 struct session *sess = s->sess;
1779 struct http_txn *txn = s->txn;
1780 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001781 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001782 struct proxy *cur_proxy;
1783 struct cond_wordlist *wl;
1784 enum rule_result ret = HTTP_RULE_RES_CONT;
1785
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001786 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1787 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001788
Christopher Faulete0768eb2018-10-03 16:38:02 +02001789 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1790 now_ms, __FUNCTION__,
1791 s,
1792 rep,
1793 rep->rex, rep->wex,
1794 rep->flags,
1795 ci_data(rep),
1796 rep->analysers);
1797
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001798 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001799
1800 /* The stats applet needs to adjust the Connection header but we don't
1801 * apply any filter there.
1802 */
1803 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1804 rep->analysers &= ~an_bit;
1805 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001806 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001807 }
1808
1809 /*
1810 * We will have to evaluate the filters.
1811 * As opposed to version 1.2, now they will be evaluated in the
1812 * filters order and not in the header order. This means that
1813 * each filter has to be validated among all headers.
1814 *
1815 * Filters are tried with ->be first, then with ->fe if it is
1816 * different from ->be.
1817 *
1818 * Maybe we are in resume condiion. In this case I choose the
1819 * "struct proxy" which contains the rule list matching the resume
1820 * pointer. If none of theses "struct proxy" match, I initialise
1821 * the process with the first one.
1822 *
1823 * In fact, I check only correspondance betwwen the current list
1824 * pointer and the ->fe rule list. If it doesn't match, I initialize
1825 * the loop with the ->be.
1826 */
1827 if (s->current_rule_list == &sess->fe->http_res_rules)
1828 cur_proxy = sess->fe;
1829 else
1830 cur_proxy = s->be;
1831 while (1) {
1832 struct proxy *rule_set = cur_proxy;
1833
1834 /* evaluate http-response rules */
1835 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001836 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001837
1838 if (ret == HTTP_RULE_RES_BADREQ)
1839 goto return_srv_prx_502;
1840
1841 if (ret == HTTP_RULE_RES_DONE) {
1842 rep->analysers &= ~an_bit;
1843 rep->analyse_exp = TICK_ETERNITY;
1844 return 1;
1845 }
1846 }
1847
1848 /* we need to be called again. */
1849 if (ret == HTTP_RULE_RES_YIELD) {
1850 channel_dont_close(rep);
1851 return 0;
1852 }
1853
1854 /* try headers filters */
1855 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001856 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1857 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001858 }
1859
1860 /* has the response been denied ? */
1861 if (txn->flags & TX_SVDENY) {
1862 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001863 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001864
Olivier Houcharda798bf52019-03-08 18:52:00 +01001865 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1866 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001868 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 goto return_srv_prx_502;
1870 }
1871
1872 /* add response headers from the rule sets in the same order */
1873 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001874 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001875 if (txn->status < 200 && txn->status != 101)
1876 break;
1877 if (wl->cond) {
1878 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1879 ret = acl_pass(ret);
1880 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1881 ret = !ret;
1882 if (!ret)
1883 continue;
1884 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001885
1886 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1887 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001888 goto return_bad_resp;
1889 }
1890
1891 /* check whether we're already working on the frontend */
1892 if (cur_proxy == sess->fe)
1893 break;
1894 cur_proxy = sess->fe;
1895 }
1896
1897 /* After this point, this anayzer can't return yield, so we can
1898 * remove the bit corresponding to this analyzer from the list.
1899 *
1900 * Note that the intermediate returns and goto found previously
1901 * reset the analyzers.
1902 */
1903 rep->analysers &= ~an_bit;
1904 rep->analyse_exp = TICK_ETERNITY;
1905
1906 /* OK that's all we can do for 1xx responses */
1907 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001908 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001909
1910 /*
1911 * Now check for a server cookie.
1912 */
1913 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001914 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001915
1916 /*
1917 * Check for cache-control or pragma headers if required.
1918 */
1919 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1920 check_response_for_cacheability(s, rep);
1921
1922 /*
1923 * Add server cookie in the response if needed
1924 */
1925 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1926 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1927 (!(s->flags & SF_DIRECT) ||
1928 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1929 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1930 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1931 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1932 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1933 !(s->flags & SF_IGNORE_PRST)) {
1934 /* the server is known, it's not the one the client requested, or the
1935 * cookie's last seen date needs to be refreshed. We have to
1936 * insert a set-cookie here, except if we want to insert only on POST
1937 * requests and this one isn't. Note that servers which don't have cookies
1938 * (eg: some backup servers) will return a full cookie removal request.
1939 */
1940 if (!objt_server(s->target)->cookie) {
1941 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001942 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001943 s->be->cookie_name);
1944 }
1945 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001946 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001947
1948 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1949 /* emit last_date, which is mandatory */
1950 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1951 s30tob64((date.tv_sec+3) >> 2,
1952 trash.area + trash.data);
1953 trash.data += 5;
1954
1955 if (s->be->cookie_maxlife) {
1956 /* emit first_date, which is either the original one or
1957 * the current date.
1958 */
1959 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1960 s30tob64(txn->cookie_first_date ?
1961 txn->cookie_first_date >> 2 :
1962 (date.tv_sec+3) >> 2,
1963 trash.area + trash.data);
1964 trash.data += 5;
1965 }
1966 }
1967 chunk_appendf(&trash, "; path=/");
1968 }
1969
1970 if (s->be->cookie_domain)
1971 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1972
1973 if (s->be->ck_opts & PR_CK_HTTPONLY)
1974 chunk_appendf(&trash, "; HttpOnly");
1975
1976 if (s->be->ck_opts & PR_CK_SECURE)
1977 chunk_appendf(&trash, "; Secure");
1978
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001979 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001980 goto return_bad_resp;
1981
1982 txn->flags &= ~TX_SCK_MASK;
1983 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1984 /* the server did not change, only the date was updated */
1985 txn->flags |= TX_SCK_UPDATED;
1986 else
1987 txn->flags |= TX_SCK_INSERTED;
1988
1989 /* Here, we will tell an eventual cache on the client side that we don't
1990 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1991 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1992 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1993 */
1994 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1995
1996 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1997
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001998 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001999 goto return_bad_resp;
2000 }
2001 }
2002
2003 /*
2004 * Check if result will be cacheable with a cookie.
2005 * We'll block the response if security checks have caught
2006 * nasty things such as a cacheable cookie.
2007 */
2008 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2009 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2010 (s->be->options & PR_O_CHK_CACHE)) {
2011 /* we're in presence of a cacheable response containing
2012 * a set-cookie header. We'll block it as requested by
2013 * the 'checkcache' option, and send an alert.
2014 */
2015 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002016 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002017
Olivier Houcharda798bf52019-03-08 18:52:00 +01002018 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2019 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002020 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002021 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022
2023 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2024 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2025 send_log(s->be, LOG_ALERT,
2026 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2027 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2028 goto return_srv_prx_502;
2029 }
2030
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002031 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002032 /* Always enter in the body analyzer */
2033 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2034 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2035
2036 /* if the user wants to log as soon as possible, without counting
2037 * bytes from the server, then this is the right moment. We have
2038 * to temporarily assign bytes_out to log what we currently have.
2039 */
2040 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2041 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002042 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002043 s->do_log(s);
2044 s->logs.bytes_out = 0;
2045 }
2046 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002047
2048 return_bad_resp:
2049 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002050 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002051 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002052 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002053 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002054
2055 return_srv_prx_502:
2056 rep->analysers &= AN_RES_FLT_END;
2057 txn->status = 502;
2058 s->logs.t_data = -1; /* was not a valid response */
2059 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002060 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002061 if (!(s->flags & SF_ERR_MASK))
2062 s->flags |= SF_ERR_PRXCOND;
2063 if (!(s->flags & SF_FINST_MASK))
2064 s->flags |= SF_FINST_H;
2065 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002066}
2067
2068/* This function is an analyser which forwards response body (including chunk
2069 * sizes if any). It is called as soon as we must forward, even if we forward
2070 * zero byte. The only situation where it must not be called is when we're in
2071 * tunnel mode and we want to forward till the close. It's used both to forward
2072 * remaining data and to resync after end of body. It expects the msg_state to
2073 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2074 * read more data, or 1 once we can go on with next request or end the stream.
2075 *
2076 * It is capable of compressing response data both in content-length mode and
2077 * in chunked mode. The state machines follows different flows depending on
2078 * whether content-length and chunked modes are used, since there are no
2079 * trailers in content-length :
2080 *
2081 * chk-mode cl-mode
2082 * ,----- BODY -----.
2083 * / \
2084 * V size > 0 V chk-mode
2085 * .--> SIZE -------------> DATA -------------> CRLF
2086 * | | size == 0 | last byte |
2087 * | v final crlf v inspected |
2088 * | TRAILERS -----------> DONE |
2089 * | |
2090 * `----------------------------------------------'
2091 *
2092 * Compression only happens in the DATA state, and must be flushed in final
2093 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2094 * is performed at once on final states for all bytes parsed, or when leaving
2095 * on missing data.
2096 */
2097int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2098{
2099 struct session *sess = s->sess;
2100 struct http_txn *txn = s->txn;
2101 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002102 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002103 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002104
2105 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2106 now_ms, __FUNCTION__,
2107 s,
2108 res,
2109 res->rex, res->wex,
2110 res->flags,
2111 ci_data(res),
2112 res->analysers);
2113
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002114 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002115
2116 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002117 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002118 /* Output closed while we were sending data. We must abort and
2119 * wake the other side up.
2120 */
2121 msg->err_state = msg->msg_state;
2122 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002123 htx_end_response(s);
2124 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002125 return 1;
2126 }
2127
Christopher Faulet9768c262018-10-22 09:34:31 +02002128 if (msg->msg_state == HTTP_MSG_BODY)
2129 msg->msg_state = HTTP_MSG_DATA;
2130
Christopher Faulete0768eb2018-10-03 16:38:02 +02002131 /* in most states, we should abort in case of early close */
2132 channel_auto_close(res);
2133
Christopher Faulete0768eb2018-10-03 16:38:02 +02002134 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002135 if (res->to_forward == CHN_INFINITE_FORWARD) {
2136 if (res->flags & (CF_SHUTR|CF_EOI)) {
2137 msg->msg_state = HTTP_MSG_DONE;
2138 res->to_forward = 0;
2139 goto done;
2140 }
2141 }
2142 else {
2143 /* We can't process the buffer's contents yet */
2144 res->flags |= CF_WAKE_WRITE;
2145 goto missing_data_or_waiting;
2146 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002147 }
2148
Christopher Faulet9768c262018-10-22 09:34:31 +02002149 if (msg->msg_state >= HTTP_MSG_DONE)
2150 goto done;
2151
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002152 /* Forward input data. We get it by removing all outgoing data not
2153 * forwarded yet from HTX data size. If there are some data filters, we
2154 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002155 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002156 if (HAS_RSP_DATA_FILTERS(s)) {
2157 ret = flt_http_payload(s, msg, htx->data);
2158 if (ret < 0)
2159 goto return_bad_res;
2160 c_adv(res, ret);
2161 if (htx->data != co_data(res) || htx->extra)
2162 goto missing_data_or_waiting;
2163 }
2164 else {
2165 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002166 if (msg->flags & HTTP_MSGF_XFER_LEN)
2167 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002169
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002170 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2171 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2172 msg->msg_state = HTTP_MSG_TUNNEL;
2173 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002174 }
2175
Christopher Faulet9768c262018-10-22 09:34:31 +02002176 /* Check if the end-of-message is reached and if so, switch the message
2177 * in HTTP_MSG_DONE state.
2178 */
2179 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2180 goto missing_data_or_waiting;
2181
2182 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002183 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002184
2185 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002186 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002187 channel_dont_close(res);
2188
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002189 if (HAS_RSP_DATA_FILTERS(s)) {
2190 ret = flt_http_end(s, msg);
2191 if (ret <= 0) {
2192 if (!ret)
2193 goto missing_data_or_waiting;
2194 goto return_bad_res;
2195 }
2196 }
2197
Christopher Fauletf2824e62018-10-01 12:12:37 +02002198 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002199 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002200 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2202 if (res->flags & CF_SHUTW) {
2203 /* response errors are most likely due to the
2204 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002205 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002206 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 goto return_bad_res;
2208 }
2209 return 1;
2210 }
2211 return 0;
2212
2213 missing_data_or_waiting:
2214 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002215 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002216
Christopher Faulet47365272018-10-31 17:40:50 +01002217 if (htx->flags & HTX_FL_PARSING_ERROR)
2218 goto return_bad_res;
2219
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 /* stop waiting for data if the input is closed before the end. If the
2221 * client side was already closed, it means that the client has aborted,
2222 * so we don't want to count this as a server abort. Otherwise it's a
2223 * server abort.
2224 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002225 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002227 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002229 if (htx_is_empty(htx))
2230 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002231 }
2232
Christopher Faulete0768eb2018-10-03 16:38:02 +02002233 /* When TE: chunked is used, we need to get there again to parse
2234 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002235 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2236 * are filters registered on the stream, we don't want to forward a
2237 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002238 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002239 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002240 channel_dont_close(res);
2241
2242 /* We know that more data are expected, but we couldn't send more that
2243 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2244 * system knows it must not set a PUSH on this first part. Interactive
2245 * modes are already handled by the stream sock layer. We must not do
2246 * this in content-length mode because it could present the MSG_MORE
2247 * flag with the last block of forwarded data, which would cause an
2248 * additional delay to be observed by the receiver.
2249 */
2250 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2251 res->flags |= CF_EXPECT_MORE;
2252
2253 /* the stream handler will take care of timeouts and errors */
2254 return 0;
2255
Christopher Faulet93e02d82019-03-08 14:18:50 +01002256 return_srv_abort:
2257 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2258 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002260 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2261 if (!(s->flags & SF_ERR_MASK))
2262 s->flags |= SF_ERR_SRVCL;
2263 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002264
Christopher Faulet93e02d82019-03-08 14:18:50 +01002265 return_cli_abort:
2266 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2267 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002269 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2270 if (!(s->flags & SF_ERR_MASK))
2271 s->flags |= SF_ERR_CLICL;
2272 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002273
Christopher Faulet93e02d82019-03-08 14:18:50 +01002274 return_bad_res:
2275 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2276 if (objt_server(s->target)) {
2277 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2278 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2279 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002281 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282
Christopher Faulet93e02d82019-03-08 14:18:50 +01002283 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 txn->rsp.err_state = txn->rsp.msg_state;
2285 txn->rsp.msg_state = HTTP_MSG_ERROR;
2286 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002287 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 res->analysers &= AN_RES_FLT_END;
2289 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 +02002290 if (!(s->flags & SF_FINST_MASK))
2291 s->flags |= SF_FINST_D;
2292 return 0;
2293}
2294
Christopher Fauletf2824e62018-10-01 12:12:37 +02002295/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002296 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002297 * as too large a request to build a valid response.
2298 */
2299int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2300{
Christopher Faulet99daf282018-11-28 22:58:13 +01002301 struct channel *req = &s->req;
2302 struct channel *res = &s->res;
2303 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002304 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002305 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002306 struct ist status, reason, location;
2307 unsigned int flags;
2308 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002309
2310 chunk = alloc_trash_chunk();
2311 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002312 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002313
Christopher Faulet99daf282018-11-28 22:58:13 +01002314 /*
2315 * Create the location
2316 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002317 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002318 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002319 case REDIRECT_TYPE_SCHEME: {
2320 struct http_hdr_ctx ctx;
2321 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002322
Christopher Faulet99daf282018-11-28 22:58:13 +01002323 host = ist("");
2324 ctx.blk = NULL;
2325 if (http_find_header(htx, ist("Host"), &ctx, 0))
2326 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327
Christopher Faulet99daf282018-11-28 22:58:13 +01002328 sl = http_find_stline(htx);
2329 path = http_get_path(htx_sl_req_uri(sl));
2330 /* build message using path */
2331 if (path.ptr) {
2332 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2333 int qs = 0;
2334 while (qs < path.len) {
2335 if (*(path.ptr + qs) == '?') {
2336 path.len = qs;
2337 break;
2338 }
2339 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002340 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002341 }
2342 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002343 else
2344 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002345
Christopher Faulet99daf282018-11-28 22:58:13 +01002346 if (rule->rdr_str) { /* this is an old "redirect" rule */
2347 /* add scheme */
2348 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2349 goto fail;
2350 }
2351 else {
2352 /* add scheme with executing log format */
2353 chunk->data += build_logline(s, chunk->area + chunk->data,
2354 chunk->size - chunk->data,
2355 &rule->rdr_fmt);
2356 }
2357 /* add "://" + host + path */
2358 if (!chunk_memcat(chunk, "://", 3) ||
2359 !chunk_memcat(chunk, host.ptr, host.len) ||
2360 !chunk_memcat(chunk, path.ptr, path.len))
2361 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002362
Christopher Faulet99daf282018-11-28 22:58:13 +01002363 /* append a slash at the end of the location if needed and missing */
2364 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2365 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2366 if (chunk->data + 1 >= chunk->size)
2367 goto fail;
2368 chunk->area[chunk->data++] = '/';
2369 }
2370 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002371 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 case REDIRECT_TYPE_PREFIX: {
2374 struct ist path;
2375
2376 sl = http_find_stline(htx);
2377 path = http_get_path(htx_sl_req_uri(sl));
2378 /* build message using path */
2379 if (path.ptr) {
2380 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2381 int qs = 0;
2382 while (qs < path.len) {
2383 if (*(path.ptr + qs) == '?') {
2384 path.len = qs;
2385 break;
2386 }
2387 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002389 }
2390 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 else
2392 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002393
Christopher Faulet99daf282018-11-28 22:58:13 +01002394 if (rule->rdr_str) { /* this is an old "redirect" rule */
2395 /* add prefix. Note that if prefix == "/", we don't want to
2396 * add anything, otherwise it makes it hard for the user to
2397 * configure a self-redirection.
2398 */
2399 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2400 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2401 goto fail;
2402 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002403 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 else {
2405 /* add prefix with executing log format */
2406 chunk->data += build_logline(s, chunk->area + chunk->data,
2407 chunk->size - chunk->data,
2408 &rule->rdr_fmt);
2409 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410
Christopher Faulet99daf282018-11-28 22:58:13 +01002411 /* add path */
2412 if (!chunk_memcat(chunk, path.ptr, path.len))
2413 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414
Christopher Faulet99daf282018-11-28 22:58:13 +01002415 /* append a slash at the end of the location if needed and missing */
2416 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2417 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2418 if (chunk->data + 1 >= chunk->size)
2419 goto fail;
2420 chunk->area[chunk->data++] = '/';
2421 }
2422 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 case REDIRECT_TYPE_LOCATION:
2425 default:
2426 if (rule->rdr_str) { /* this is an old "redirect" rule */
2427 /* add location */
2428 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2429 goto fail;
2430 }
2431 else {
2432 /* add location with executing log format */
2433 chunk->data += build_logline(s, chunk->area + chunk->data,
2434 chunk->size - chunk->data,
2435 &rule->rdr_fmt);
2436 }
2437 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002439 location = ist2(chunk->area, chunk->data);
2440
2441 /*
2442 * Create the 30x response
2443 */
2444 switch (rule->code) {
2445 case 308:
2446 status = ist("308");
2447 reason = ist("Permanent Redirect");
2448 break;
2449 case 307:
2450 status = ist("307");
2451 reason = ist("Temporary Redirect");
2452 break;
2453 case 303:
2454 status = ist("303");
2455 reason = ist("See Other");
2456 break;
2457 case 301:
2458 status = ist("301");
2459 reason = ist("Moved Permanently");
2460 break;
2461 case 302:
2462 default:
2463 status = ist("302");
2464 reason = ist("Found");
2465 break;
2466 }
2467
2468 htx = htx_from_buf(&res->buf);
2469 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2470 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2471 if (!sl)
2472 goto fail;
2473 sl->info.res.status = rule->code;
2474 s->txn->status = rule->code;
2475
2476 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2477 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2478 !htx_add_header(htx, ist("Location"), location))
2479 goto fail;
2480
2481 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2482 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2483 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002484 }
2485
2486 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002487 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2488 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489 }
2490
Christopher Faulet99daf282018-11-28 22:58:13 +01002491 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2492 goto fail;
2493
Christopher Fauletf2824e62018-10-01 12:12:37 +02002494 /* let's log the request time */
2495 s->logs.tv_request = now;
2496
Christopher Faulet99daf282018-11-28 22:58:13 +01002497 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002498 c_adv(res, data);
2499 res->total += data;
2500
2501 channel_auto_read(req);
2502 channel_abort(req);
2503 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002504 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002505
2506 res->wex = tick_add_ifset(now_ms, res->wto);
2507 channel_auto_read(res);
2508 channel_auto_close(res);
2509 channel_shutr_now(res);
2510
2511 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002512
2513 if (!(s->flags & SF_ERR_MASK))
2514 s->flags |= SF_ERR_LOCAL;
2515 if (!(s->flags & SF_FINST_MASK))
2516 s->flags |= SF_FINST_R;
2517
Christopher Faulet99daf282018-11-28 22:58:13 +01002518 free_trash_chunk(chunk);
2519 return 1;
2520
2521 fail:
2522 /* If an error occurred, remove the incomplete HTTP response from the
2523 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002524 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002525 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002526 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002527}
2528
Christopher Faulet72333522018-10-24 11:25:02 +02002529int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2530 struct ist name, const char *str, struct my_regex *re, int action)
2531{
2532 struct http_hdr_ctx ctx;
2533 struct buffer *output = get_trash_chunk();
2534
2535 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2536 ctx.blk = NULL;
2537 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2538 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2539 continue;
2540
2541 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2542 if (output->data == -1)
2543 return -1;
2544 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2545 return -1;
2546 }
2547 return 0;
2548}
2549
2550static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2551 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2552{
2553 struct buffer *replace;
2554 int ret = -1;
2555
2556 replace = alloc_trash_chunk();
2557 if (!replace)
2558 goto leave;
2559
2560 replace->data = build_logline(s, replace->area, replace->size, fmt);
2561 if (replace->data >= replace->size - 1)
2562 goto leave;
2563
2564 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2565
2566 leave:
2567 free_trash_chunk(replace);
2568 return ret;
2569}
2570
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002571
2572/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2573 * on success and -1 on error. The response channel is updated accordingly.
2574 */
2575static int htx_reply_103_early_hints(struct channel *res)
2576{
2577 struct htx *htx = htx_from_buf(&res->buf);
2578 size_t data;
2579
2580 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2581 /* If an error occurred during an Early-hint rule,
2582 * remove the incomplete HTTP 103 response from the
2583 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002584 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002585 return -1;
2586 }
2587
2588 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002589 c_adv(res, data);
2590 res->total += data;
2591 return 0;
2592}
2593
Christopher Faulet6eb92892018-11-15 16:39:29 +01002594/*
2595 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2596 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002597 * If <early_hints> is 0, it is starts a new response by adding the start
2598 * line. If an error occurred -1 is returned. On success 0 is returned. The
2599 * channel is not updated here. It must be done calling the function
2600 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002601 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002602static int htx_add_early_hint_header(struct stream *s, int early_hints, const struct ist name, struct list *fmt)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002603{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002604 struct channel *res = &s->res;
2605 struct htx *htx = htx_from_buf(&res->buf);
2606 struct buffer *value = alloc_trash_chunk();
2607
Christopher Faulet6eb92892018-11-15 16:39:29 +01002608 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002609 struct htx_sl *sl;
2610 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2611 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2612
2613 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2614 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2615 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002616 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002617 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002618 }
2619
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002620 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2621 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002622 goto fail;
2623
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002624 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002625 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002626
2627 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002628 /* If an error occurred during an Early-hint rule, remove the incomplete
2629 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002630 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002631 free_trash_chunk(value);
2632 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002633}
2634
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002635/* This function executes one of the set-{method,path,query,uri} actions. It
2636 * takes the string from the variable 'replace' with length 'len', then modifies
2637 * the relevant part of the request line accordingly. Then it updates various
2638 * pointers to the next elements which were moved, and the total buffer length.
2639 * It finds the action to be performed in p[2], previously filled by function
2640 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2641 * error, though this can be revisited when this code is finally exploited.
2642 *
2643 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2644 * query string and 3 to replace uri.
2645 *
2646 * In query string case, the mark question '?' must be set at the start of the
2647 * string by the caller, event if the replacement query string is empty.
2648 */
2649int htx_req_replace_stline(int action, const char *replace, int len,
2650 struct proxy *px, struct stream *s)
2651{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002652 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002653
2654 switch (action) {
2655 case 0: // method
2656 if (!http_replace_req_meth(htx, ist2(replace, len)))
2657 return -1;
2658 break;
2659
2660 case 1: // path
2661 if (!http_replace_req_path(htx, ist2(replace, len)))
2662 return -1;
2663 break;
2664
2665 case 2: // query
2666 if (!http_replace_req_query(htx, ist2(replace, len)))
2667 return -1;
2668 break;
2669
2670 case 3: // uri
2671 if (!http_replace_req_uri(htx, ist2(replace, len)))
2672 return -1;
2673 break;
2674
2675 default:
2676 return -1;
2677 }
2678 return 0;
2679}
2680
2681/* This function replace the HTTP status code and the associated message. The
2682 * variable <status> contains the new status code. This function never fails.
2683 */
2684void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2685{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002686 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002687 char *res;
2688
2689 chunk_reset(&trash);
2690 res = ultoa_o(status, trash.area, trash.size);
2691 trash.data = res - trash.area;
2692
2693 /* Do we have a custom reason format string? */
2694 if (reason == NULL)
2695 reason = http_get_reason(status);
2696
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002697 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002698 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2699}
2700
Christopher Faulet3e964192018-10-24 11:39:23 +02002701/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2702 * transaction <txn>. Returns the verdict of the first rule that prevents
2703 * further processing of the request (auth, deny, ...), and defaults to
2704 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2705 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2706 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2707 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2708 * status.
2709 */
2710static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2711 struct stream *s, int *deny_status)
2712{
2713 struct session *sess = strm_sess(s);
2714 struct http_txn *txn = s->txn;
2715 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002716 struct act_rule *rule;
2717 struct http_hdr_ctx ctx;
2718 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002719 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2720 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002721 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002722
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002723 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002724
2725 /* If "the current_rule_list" match the executed rule list, we are in
2726 * resume condition. If a resume is needed it is always in the action
2727 * and never in the ACL or converters. In this case, we initialise the
2728 * current rule, and go to the action execution point.
2729 */
2730 if (s->current_rule) {
2731 rule = s->current_rule;
2732 s->current_rule = NULL;
2733 if (s->current_rule_list == rules)
2734 goto resume_execution;
2735 }
2736 s->current_rule_list = rules;
2737
2738 list_for_each_entry(rule, rules, list) {
2739 /* check optional condition */
2740 if (rule->cond) {
2741 int ret;
2742
2743 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2744 ret = acl_pass(ret);
2745
2746 if (rule->cond->pol == ACL_COND_UNLESS)
2747 ret = !ret;
2748
2749 if (!ret) /* condition not matched */
2750 continue;
2751 }
2752
2753 act_flags |= ACT_FLAG_FIRST;
2754 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002755 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2756 early_hints = 0;
2757 if (htx_reply_103_early_hints(&s->res) == -1) {
2758 rule_ret = HTTP_RULE_RES_BADREQ;
2759 goto end;
2760 }
2761 }
2762
Christopher Faulet3e964192018-10-24 11:39:23 +02002763 switch (rule->action) {
2764 case ACT_ACTION_ALLOW:
2765 rule_ret = HTTP_RULE_RES_STOP;
2766 goto end;
2767
2768 case ACT_ACTION_DENY:
2769 if (deny_status)
2770 *deny_status = rule->deny_status;
2771 rule_ret = HTTP_RULE_RES_DENY;
2772 goto end;
2773
2774 case ACT_HTTP_REQ_TARPIT:
2775 txn->flags |= TX_CLTARPIT;
2776 if (deny_status)
2777 *deny_status = rule->deny_status;
2778 rule_ret = HTTP_RULE_RES_DENY;
2779 goto end;
2780
2781 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002782 /* Auth might be performed on regular http-req rules as well as on stats */
2783 auth_realm = rule->arg.auth.realm;
2784 if (!auth_realm) {
2785 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2786 auth_realm = STATS_DEFAULT_REALM;
2787 else
2788 auth_realm = px->id;
2789 }
2790 /* send 401/407 depending on whether we use a proxy or not. We still
2791 * count one error, because normal browsing won't significantly
2792 * increase the counter but brute force attempts will.
2793 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002794 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002795 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2796 rule_ret = HTTP_RULE_RES_BADREQ;
2797 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002798 goto end;
2799
2800 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002801 rule_ret = HTTP_RULE_RES_DONE;
2802 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2803 rule_ret = HTTP_RULE_RES_BADREQ;
2804 goto end;
2805
2806 case ACT_HTTP_SET_NICE:
2807 s->task->nice = rule->arg.nice;
2808 break;
2809
2810 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002811 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002812 break;
2813
2814 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002815 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002816 break;
2817
2818 case ACT_HTTP_SET_LOGL:
2819 s->logs.level = rule->arg.loglevel;
2820 break;
2821
2822 case ACT_HTTP_REPLACE_HDR:
2823 case ACT_HTTP_REPLACE_VAL:
2824 if (htx_transform_header(s, &s->req, htx,
2825 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2826 &rule->arg.hdr_add.fmt,
2827 &rule->arg.hdr_add.re, rule->action)) {
2828 rule_ret = HTTP_RULE_RES_BADREQ;
2829 goto end;
2830 }
2831 break;
2832
2833 case ACT_HTTP_DEL_HDR:
2834 /* remove all occurrences of the header */
2835 ctx.blk = NULL;
2836 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2837 http_remove_header(htx, &ctx);
2838 break;
2839
2840 case ACT_HTTP_SET_HDR:
2841 case ACT_HTTP_ADD_HDR: {
2842 /* The scope of the trash buffer must be limited to this function. The
2843 * build_logline() function can execute a lot of other function which
2844 * can use the trash buffer. So for limiting the scope of this global
2845 * buffer, we build first the header value using build_logline, and
2846 * after we store the header name.
2847 */
2848 struct buffer *replace;
2849 struct ist n, v;
2850
2851 replace = alloc_trash_chunk();
2852 if (!replace) {
2853 rule_ret = HTTP_RULE_RES_BADREQ;
2854 goto end;
2855 }
2856
2857 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2858 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2859 v = ist2(replace->area, replace->data);
2860
2861 if (rule->action == ACT_HTTP_SET_HDR) {
2862 /* remove all occurrences of the header */
2863 ctx.blk = NULL;
2864 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2865 http_remove_header(htx, &ctx);
2866 }
2867
2868 if (!http_add_header(htx, n, v)) {
2869 static unsigned char rate_limit = 0;
2870
2871 if ((rate_limit++ & 255) == 0) {
2872 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);
2873 }
2874
Olivier Houcharda798bf52019-03-08 18:52:00 +01002875 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002876 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002877 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002878 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002879 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002880 }
2881 free_trash_chunk(replace);
2882 break;
2883 }
2884
2885 case ACT_HTTP_DEL_ACL:
2886 case ACT_HTTP_DEL_MAP: {
2887 struct pat_ref *ref;
2888 struct buffer *key;
2889
2890 /* collect reference */
2891 ref = pat_ref_lookup(rule->arg.map.ref);
2892 if (!ref)
2893 continue;
2894
2895 /* allocate key */
2896 key = alloc_trash_chunk();
2897 if (!key) {
2898 rule_ret = HTTP_RULE_RES_BADREQ;
2899 goto end;
2900 }
2901
2902 /* collect key */
2903 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2904 key->area[key->data] = '\0';
2905
2906 /* perform update */
2907 /* returned code: 1=ok, 0=ko */
2908 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2909 pat_ref_delete(ref, key->area);
2910 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2911
2912 free_trash_chunk(key);
2913 break;
2914 }
2915
2916 case ACT_HTTP_ADD_ACL: {
2917 struct pat_ref *ref;
2918 struct buffer *key;
2919
2920 /* collect reference */
2921 ref = pat_ref_lookup(rule->arg.map.ref);
2922 if (!ref)
2923 continue;
2924
2925 /* allocate key */
2926 key = alloc_trash_chunk();
2927 if (!key) {
2928 rule_ret = HTTP_RULE_RES_BADREQ;
2929 goto end;
2930 }
2931
2932 /* collect key */
2933 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2934 key->area[key->data] = '\0';
2935
2936 /* perform update */
2937 /* add entry only if it does not already exist */
2938 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2939 if (pat_ref_find_elt(ref, key->area) == NULL)
2940 pat_ref_add(ref, key->area, NULL, NULL);
2941 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2942
2943 free_trash_chunk(key);
2944 break;
2945 }
2946
2947 case ACT_HTTP_SET_MAP: {
2948 struct pat_ref *ref;
2949 struct buffer *key, *value;
2950
2951 /* collect reference */
2952 ref = pat_ref_lookup(rule->arg.map.ref);
2953 if (!ref)
2954 continue;
2955
2956 /* allocate key */
2957 key = alloc_trash_chunk();
2958 if (!key) {
2959 rule_ret = HTTP_RULE_RES_BADREQ;
2960 goto end;
2961 }
2962
2963 /* allocate value */
2964 value = alloc_trash_chunk();
2965 if (!value) {
2966 free_trash_chunk(key);
2967 rule_ret = HTTP_RULE_RES_BADREQ;
2968 goto end;
2969 }
2970
2971 /* collect key */
2972 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2973 key->area[key->data] = '\0';
2974
2975 /* collect value */
2976 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2977 value->area[value->data] = '\0';
2978
2979 /* perform update */
2980 if (pat_ref_find_elt(ref, key->area) != NULL)
2981 /* update entry if it exists */
2982 pat_ref_set(ref, key->area, value->area, NULL);
2983 else
2984 /* insert a new entry */
2985 pat_ref_add(ref, key->area, value->area, NULL);
2986
2987 free_trash_chunk(key);
2988 free_trash_chunk(value);
2989 break;
2990 }
2991
2992 case ACT_HTTP_EARLY_HINT:
2993 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2994 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002995 early_hints = htx_add_early_hint_header(s, early_hints,
2996 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02002997 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002998 if (early_hints == -1) {
2999 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003000 goto end;
3001 }
3002 break;
3003
3004 case ACT_CUSTOM:
3005 if ((s->req.flags & CF_READ_ERROR) ||
3006 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003007 (px->options & PR_O_ABRT_CLOSE)))
3008 act_flags |= ACT_FLAG_FINAL;
3009
3010 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3011 case ACT_RET_ERR:
3012 case ACT_RET_CONT:
3013 break;
3014 case ACT_RET_STOP:
3015 rule_ret = HTTP_RULE_RES_DONE;
3016 goto end;
3017 case ACT_RET_YIELD:
3018 s->current_rule = rule;
3019 rule_ret = HTTP_RULE_RES_YIELD;
3020 goto end;
3021 }
3022 break;
3023
3024 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3025 /* Note: only the first valid tracking parameter of each
3026 * applies.
3027 */
3028
3029 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3030 struct stktable *t;
3031 struct stksess *ts;
3032 struct stktable_key *key;
3033 void *ptr1, *ptr2;
3034
3035 t = rule->arg.trk_ctr.table.t;
3036 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3037 rule->arg.trk_ctr.expr, NULL);
3038
3039 if (key && (ts = stktable_get_entry(t, key))) {
3040 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3041
3042 /* let's count a new HTTP request as it's the first time we do it */
3043 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3044 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3045 if (ptr1 || ptr2) {
3046 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3047
3048 if (ptr1)
3049 stktable_data_cast(ptr1, http_req_cnt)++;
3050
3051 if (ptr2)
3052 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3053 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3054
3055 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3056
3057 /* If data was modified, we need to touch to re-schedule sync */
3058 stktable_touch_local(t, ts, 0);
3059 }
3060
3061 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3062 if (sess->fe != s->be)
3063 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3064 }
3065 }
3066 break;
3067
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003068 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003069 default:
3070 break;
3071 }
3072 }
3073
3074 end:
3075 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003076 if (htx_reply_103_early_hints(&s->res) == -1)
3077 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003078 }
3079
3080 /* we reached the end of the rules, nothing to report */
3081 return rule_ret;
3082}
3083
3084/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3085 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3086 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3087 * is returned, the process can continue the evaluation of next rule list. If
3088 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3089 * is returned, it means the operation could not be processed and a server error
3090 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3091 * deny rule. If *YIELD is returned, the caller must call again the function
3092 * with the same context.
3093 */
3094static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3095 struct stream *s)
3096{
3097 struct session *sess = strm_sess(s);
3098 struct http_txn *txn = s->txn;
3099 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003100 struct act_rule *rule;
3101 struct http_hdr_ctx ctx;
3102 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3103 int act_flags = 0;
3104
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003105 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003106
3107 /* If "the current_rule_list" match the executed rule list, we are in
3108 * resume condition. If a resume is needed it is always in the action
3109 * and never in the ACL or converters. In this case, we initialise the
3110 * current rule, and go to the action execution point.
3111 */
3112 if (s->current_rule) {
3113 rule = s->current_rule;
3114 s->current_rule = NULL;
3115 if (s->current_rule_list == rules)
3116 goto resume_execution;
3117 }
3118 s->current_rule_list = rules;
3119
3120 list_for_each_entry(rule, rules, list) {
3121 /* check optional condition */
3122 if (rule->cond) {
3123 int ret;
3124
3125 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3126 ret = acl_pass(ret);
3127
3128 if (rule->cond->pol == ACL_COND_UNLESS)
3129 ret = !ret;
3130
3131 if (!ret) /* condition not matched */
3132 continue;
3133 }
3134
3135 act_flags |= ACT_FLAG_FIRST;
3136resume_execution:
3137 switch (rule->action) {
3138 case ACT_ACTION_ALLOW:
3139 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3140 goto end;
3141
3142 case ACT_ACTION_DENY:
3143 txn->flags |= TX_SVDENY;
3144 rule_ret = HTTP_RULE_RES_STOP;
3145 goto end;
3146
3147 case ACT_HTTP_SET_NICE:
3148 s->task->nice = rule->arg.nice;
3149 break;
3150
3151 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003152 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003153 break;
3154
3155 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003156 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003157 break;
3158
3159 case ACT_HTTP_SET_LOGL:
3160 s->logs.level = rule->arg.loglevel;
3161 break;
3162
3163 case ACT_HTTP_REPLACE_HDR:
3164 case ACT_HTTP_REPLACE_VAL:
3165 if (htx_transform_header(s, &s->res, htx,
3166 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3167 &rule->arg.hdr_add.fmt,
3168 &rule->arg.hdr_add.re, rule->action)) {
3169 rule_ret = HTTP_RULE_RES_BADREQ;
3170 goto end;
3171 }
3172 break;
3173
3174 case ACT_HTTP_DEL_HDR:
3175 /* remove all occurrences of the header */
3176 ctx.blk = NULL;
3177 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3178 http_remove_header(htx, &ctx);
3179 break;
3180
3181 case ACT_HTTP_SET_HDR:
3182 case ACT_HTTP_ADD_HDR: {
3183 struct buffer *replace;
3184 struct ist n, v;
3185
3186 replace = alloc_trash_chunk();
3187 if (!replace) {
3188 rule_ret = HTTP_RULE_RES_BADREQ;
3189 goto end;
3190 }
3191
3192 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3193 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3194 v = ist2(replace->area, replace->data);
3195
3196 if (rule->action == ACT_HTTP_SET_HDR) {
3197 /* remove all occurrences of the header */
3198 ctx.blk = NULL;
3199 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3200 http_remove_header(htx, &ctx);
3201 }
3202
3203 if (!http_add_header(htx, n, v)) {
3204 static unsigned char rate_limit = 0;
3205
3206 if ((rate_limit++ & 255) == 0) {
3207 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);
3208 }
3209
Olivier Houcharda798bf52019-03-08 18:52:00 +01003210 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003211 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003212 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003213 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003214 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003215 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003216 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003217 }
3218 free_trash_chunk(replace);
3219 break;
3220 }
3221
3222 case ACT_HTTP_DEL_ACL:
3223 case ACT_HTTP_DEL_MAP: {
3224 struct pat_ref *ref;
3225 struct buffer *key;
3226
3227 /* collect reference */
3228 ref = pat_ref_lookup(rule->arg.map.ref);
3229 if (!ref)
3230 continue;
3231
3232 /* allocate key */
3233 key = alloc_trash_chunk();
3234 if (!key) {
3235 rule_ret = HTTP_RULE_RES_BADREQ;
3236 goto end;
3237 }
3238
3239 /* collect key */
3240 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3241 key->area[key->data] = '\0';
3242
3243 /* perform update */
3244 /* returned code: 1=ok, 0=ko */
3245 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3246 pat_ref_delete(ref, key->area);
3247 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3248
3249 free_trash_chunk(key);
3250 break;
3251 }
3252
3253 case ACT_HTTP_ADD_ACL: {
3254 struct pat_ref *ref;
3255 struct buffer *key;
3256
3257 /* collect reference */
3258 ref = pat_ref_lookup(rule->arg.map.ref);
3259 if (!ref)
3260 continue;
3261
3262 /* allocate key */
3263 key = alloc_trash_chunk();
3264 if (!key) {
3265 rule_ret = HTTP_RULE_RES_BADREQ;
3266 goto end;
3267 }
3268
3269 /* collect key */
3270 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3271 key->area[key->data] = '\0';
3272
3273 /* perform update */
3274 /* check if the entry already exists */
3275 if (pat_ref_find_elt(ref, key->area) == NULL)
3276 pat_ref_add(ref, key->area, NULL, NULL);
3277
3278 free_trash_chunk(key);
3279 break;
3280 }
3281
3282 case ACT_HTTP_SET_MAP: {
3283 struct pat_ref *ref;
3284 struct buffer *key, *value;
3285
3286 /* collect reference */
3287 ref = pat_ref_lookup(rule->arg.map.ref);
3288 if (!ref)
3289 continue;
3290
3291 /* allocate key */
3292 key = alloc_trash_chunk();
3293 if (!key) {
3294 rule_ret = HTTP_RULE_RES_BADREQ;
3295 goto end;
3296 }
3297
3298 /* allocate value */
3299 value = alloc_trash_chunk();
3300 if (!value) {
3301 free_trash_chunk(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 /* collect value */
3311 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3312 value->area[value->data] = '\0';
3313
3314 /* perform update */
3315 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3316 if (pat_ref_find_elt(ref, key->area) != NULL)
3317 /* update entry if it exists */
3318 pat_ref_set(ref, key->area, value->area, NULL);
3319 else
3320 /* insert a new entry */
3321 pat_ref_add(ref, key->area, value->area, NULL);
3322 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3323 free_trash_chunk(key);
3324 free_trash_chunk(value);
3325 break;
3326 }
3327
3328 case ACT_HTTP_REDIR:
3329 rule_ret = HTTP_RULE_RES_DONE;
3330 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3331 rule_ret = HTTP_RULE_RES_BADREQ;
3332 goto end;
3333
3334 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3335 /* Note: only the first valid tracking parameter of each
3336 * applies.
3337 */
3338 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3339 struct stktable *t;
3340 struct stksess *ts;
3341 struct stktable_key *key;
3342 void *ptr;
3343
3344 t = rule->arg.trk_ctr.table.t;
3345 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3346 rule->arg.trk_ctr.expr, NULL);
3347
3348 if (key && (ts = stktable_get_entry(t, key))) {
3349 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3350
3351 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3352
3353 /* let's count a new HTTP request as it's the first time we do it */
3354 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3355 if (ptr)
3356 stktable_data_cast(ptr, http_req_cnt)++;
3357
3358 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3359 if (ptr)
3360 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3361 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3362
3363 /* When the client triggers a 4xx from the server, it's most often due
3364 * to a missing object or permission. These events should be tracked
3365 * because if they happen often, it may indicate a brute force or a
3366 * vulnerability scan. Normally this is done when receiving the response
3367 * but here we're tracking after this ought to have been done so we have
3368 * to do it on purpose.
3369 */
3370 if ((unsigned)(txn->status - 400) < 100) {
3371 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3372 if (ptr)
3373 stktable_data_cast(ptr, http_err_cnt)++;
3374
3375 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3376 if (ptr)
3377 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3378 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3379 }
3380
3381 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3382
3383 /* If data was modified, we need to touch to re-schedule sync */
3384 stktable_touch_local(t, ts, 0);
3385
3386 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3387 if (sess->fe != s->be)
3388 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3389 }
3390 }
3391 break;
3392
3393 case ACT_CUSTOM:
3394 if ((s->req.flags & CF_READ_ERROR) ||
3395 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003396 (px->options & PR_O_ABRT_CLOSE)))
3397 act_flags |= ACT_FLAG_FINAL;
3398
3399 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3400 case ACT_RET_ERR:
3401 case ACT_RET_CONT:
3402 break;
3403 case ACT_RET_STOP:
3404 rule_ret = HTTP_RULE_RES_STOP;
3405 goto end;
3406 case ACT_RET_YIELD:
3407 s->current_rule = rule;
3408 rule_ret = HTTP_RULE_RES_YIELD;
3409 goto end;
3410 }
3411 break;
3412
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003413 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003414 default:
3415 break;
3416 }
3417 }
3418
3419 end:
3420 /* we reached the end of the rules, nothing to report */
3421 return rule_ret;
3422}
3423
Christopher Faulet33640082018-10-24 11:53:01 +02003424/* Iterate the same filter through all request headers.
3425 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3426 * Since it can manage the switch to another backend, it updates the per-proxy
3427 * DENY stats.
3428 */
3429static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3430{
3431 struct http_txn *txn = s->txn;
3432 struct htx *htx;
3433 struct buffer *hdr = get_trash_chunk();
3434 int32_t pos;
3435
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003436 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003437
3438 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3439 struct htx_blk *blk = htx_get_blk(htx, pos);
3440 enum htx_blk_type type;
3441 struct ist n, v;
3442
3443 next_hdr:
3444 type = htx_get_blk_type(blk);
3445 if (type == HTX_BLK_EOH)
3446 break;
3447 if (type != HTX_BLK_HDR)
3448 continue;
3449
3450 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3451 return 1;
3452 else if (unlikely(txn->flags & TX_CLALLOW) &&
3453 (exp->action == ACT_ALLOW ||
3454 exp->action == ACT_DENY ||
3455 exp->action == ACT_TARPIT))
3456 return 0;
3457
3458 n = htx_get_blk_name(htx, blk);
3459 v = htx_get_blk_value(htx, blk);
3460
Christopher Faulet02e771a2019-02-26 15:36:05 +01003461 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003462 hdr->area[hdr->data++] = ':';
3463 hdr->area[hdr->data++] = ' ';
3464 chunk_memcat(hdr, v.ptr, v.len);
3465
3466 /* Now we have one header in <hdr> */
3467
3468 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3469 struct http_hdr_ctx ctx;
3470 int len;
3471
3472 switch (exp->action) {
3473 case ACT_ALLOW:
3474 txn->flags |= TX_CLALLOW;
3475 goto end;
3476
3477 case ACT_DENY:
3478 txn->flags |= TX_CLDENY;
3479 goto end;
3480
3481 case ACT_TARPIT:
3482 txn->flags |= TX_CLTARPIT;
3483 goto end;
3484
3485 case ACT_REPLACE:
3486 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3487 if (len < 0)
3488 return -1;
3489
3490 http_parse_header(ist2(trash.area, len), &n, &v);
3491 ctx.blk = blk;
3492 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003493 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003494 if (!http_replace_header(htx, &ctx, n, v))
3495 return -1;
3496 if (!ctx.blk)
3497 goto end;
3498 pos = htx_get_blk_pos(htx, blk);
3499 break;
3500
3501 case ACT_REMOVE:
3502 ctx.blk = blk;
3503 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003504 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003505 if (!http_remove_header(htx, &ctx))
3506 return -1;
3507 if (!ctx.blk)
3508 goto end;
3509 pos = htx_get_blk_pos(htx, blk);
3510 goto next_hdr;
3511
3512 }
3513 }
3514 }
3515 end:
3516 return 0;
3517}
3518
3519/* Apply the filter to the request line.
3520 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3521 * or -1 if a replacement resulted in an invalid request line.
3522 * Since it can manage the switch to another backend, it updates the per-proxy
3523 * DENY stats.
3524 */
3525static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3526{
3527 struct http_txn *txn = s->txn;
3528 struct htx *htx;
3529 struct buffer *reqline = get_trash_chunk();
3530 int done;
3531
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003532 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003533
3534 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3535 return 1;
3536 else if (unlikely(txn->flags & TX_CLALLOW) &&
3537 (exp->action == ACT_ALLOW ||
3538 exp->action == ACT_DENY ||
3539 exp->action == ACT_TARPIT))
3540 return 0;
3541 else if (exp->action == ACT_REMOVE)
3542 return 0;
3543
3544 done = 0;
3545
3546 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3547
3548 /* Now we have the request line between cur_ptr and cur_end */
3549 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003550 struct htx_sl *sl = http_find_stline(htx);
3551 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003552 int len;
3553
3554 switch (exp->action) {
3555 case ACT_ALLOW:
3556 txn->flags |= TX_CLALLOW;
3557 done = 1;
3558 break;
3559
3560 case ACT_DENY:
3561 txn->flags |= TX_CLDENY;
3562 done = 1;
3563 break;
3564
3565 case ACT_TARPIT:
3566 txn->flags |= TX_CLTARPIT;
3567 done = 1;
3568 break;
3569
3570 case ACT_REPLACE:
3571 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3572 if (len < 0)
3573 return -1;
3574
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003575 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3576 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3577 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003578 return -1;
3579 done = 1;
3580 break;
3581 }
3582 }
3583 return done;
3584}
3585
3586/*
3587 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3588 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3589 * unparsable request. Since it can manage the switch to another backend, it
3590 * updates the per-proxy DENY stats.
3591 */
3592static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3593{
3594 struct session *sess = s->sess;
3595 struct http_txn *txn = s->txn;
3596 struct hdr_exp *exp;
3597
3598 for (exp = px->req_exp; exp; exp = exp->next) {
3599 int ret;
3600
3601 /*
3602 * The interleaving of transformations and verdicts
3603 * makes it difficult to decide to continue or stop
3604 * the evaluation.
3605 */
3606
3607 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3608 break;
3609
3610 if ((txn->flags & TX_CLALLOW) &&
3611 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3612 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3613 continue;
3614
3615 /* if this filter had a condition, evaluate it now and skip to
3616 * next filter if the condition does not match.
3617 */
3618 if (exp->cond) {
3619 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3620 ret = acl_pass(ret);
3621 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3622 ret = !ret;
3623
3624 if (!ret)
3625 continue;
3626 }
3627
3628 /* Apply the filter to the request line. */
3629 ret = htx_apply_filter_to_req_line(s, req, exp);
3630 if (unlikely(ret < 0))
3631 return -1;
3632
3633 if (likely(ret == 0)) {
3634 /* The filter did not match the request, it can be
3635 * iterated through all headers.
3636 */
3637 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3638 return -1;
3639 }
3640 }
3641 return 0;
3642}
3643
3644/* Iterate the same filter through all response headers contained in <res>.
3645 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3646 */
3647static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3648{
3649 struct http_txn *txn = s->txn;
3650 struct htx *htx;
3651 struct buffer *hdr = get_trash_chunk();
3652 int32_t pos;
3653
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003654 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003655
3656 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3657 struct htx_blk *blk = htx_get_blk(htx, pos);
3658 enum htx_blk_type type;
3659 struct ist n, v;
3660
3661 next_hdr:
3662 type = htx_get_blk_type(blk);
3663 if (type == HTX_BLK_EOH)
3664 break;
3665 if (type != HTX_BLK_HDR)
3666 continue;
3667
3668 if (unlikely(txn->flags & TX_SVDENY))
3669 return 1;
3670 else if (unlikely(txn->flags & TX_SVALLOW) &&
3671 (exp->action == ACT_ALLOW ||
3672 exp->action == ACT_DENY))
3673 return 0;
3674
3675 n = htx_get_blk_name(htx, blk);
3676 v = htx_get_blk_value(htx, blk);
3677
Christopher Faulet02e771a2019-02-26 15:36:05 +01003678 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003679 hdr->area[hdr->data++] = ':';
3680 hdr->area[hdr->data++] = ' ';
3681 chunk_memcat(hdr, v.ptr, v.len);
3682
3683 /* Now we have one header in <hdr> */
3684
3685 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3686 struct http_hdr_ctx ctx;
3687 int len;
3688
3689 switch (exp->action) {
3690 case ACT_ALLOW:
3691 txn->flags |= TX_SVALLOW;
3692 goto end;
3693 break;
3694
3695 case ACT_DENY:
3696 txn->flags |= TX_SVDENY;
3697 goto end;
3698 break;
3699
3700 case ACT_REPLACE:
3701 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3702 if (len < 0)
3703 return -1;
3704
3705 http_parse_header(ist2(trash.area, len), &n, &v);
3706 ctx.blk = blk;
3707 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003708 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003709 if (!http_replace_header(htx, &ctx, n, v))
3710 return -1;
3711 if (!ctx.blk)
3712 goto end;
3713 pos = htx_get_blk_pos(htx, blk);
3714 break;
3715
3716 case ACT_REMOVE:
3717 ctx.blk = blk;
3718 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003719 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003720 if (!http_remove_header(htx, &ctx))
3721 return -1;
3722 if (!ctx.blk)
3723 goto end;
3724 pos = htx_get_blk_pos(htx, blk);
3725 goto next_hdr;
3726 }
3727 }
3728
3729 }
3730 end:
3731 return 0;
3732}
3733
3734/* Apply the filter to the status line in the response buffer <res>.
3735 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3736 * or -1 if a replacement resulted in an invalid status line.
3737 */
3738static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3739{
3740 struct http_txn *txn = s->txn;
3741 struct htx *htx;
3742 struct buffer *resline = get_trash_chunk();
3743 int done;
3744
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003745 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003746
3747 if (unlikely(txn->flags & TX_SVDENY))
3748 return 1;
3749 else if (unlikely(txn->flags & TX_SVALLOW) &&
3750 (exp->action == ACT_ALLOW ||
3751 exp->action == ACT_DENY))
3752 return 0;
3753 else if (exp->action == ACT_REMOVE)
3754 return 0;
3755
3756 done = 0;
3757 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3758
3759 /* Now we have the status line between cur_ptr and cur_end */
3760 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003761 struct htx_sl *sl = http_find_stline(htx);
3762 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003763 int len;
3764
3765 switch (exp->action) {
3766 case ACT_ALLOW:
3767 txn->flags |= TX_SVALLOW;
3768 done = 1;
3769 break;
3770
3771 case ACT_DENY:
3772 txn->flags |= TX_SVDENY;
3773 done = 1;
3774 break;
3775
3776 case ACT_REPLACE:
3777 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3778 if (len < 0)
3779 return -1;
3780
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003781 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3782 sl->info.res.status = strl2ui(code.ptr, code.len);
3783 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003784 return -1;
3785
3786 done = 1;
3787 return 1;
3788 }
3789 }
3790 return done;
3791}
3792
3793/*
3794 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3795 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3796 * unparsable response.
3797 */
3798static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3799{
3800 struct session *sess = s->sess;
3801 struct http_txn *txn = s->txn;
3802 struct hdr_exp *exp;
3803
3804 for (exp = px->rsp_exp; exp; exp = exp->next) {
3805 int ret;
3806
3807 /*
3808 * The interleaving of transformations and verdicts
3809 * makes it difficult to decide to continue or stop
3810 * the evaluation.
3811 */
3812
3813 if (txn->flags & TX_SVDENY)
3814 break;
3815
3816 if ((txn->flags & TX_SVALLOW) &&
3817 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3818 exp->action == ACT_PASS)) {
3819 exp = exp->next;
3820 continue;
3821 }
3822
3823 /* if this filter had a condition, evaluate it now and skip to
3824 * next filter if the condition does not match.
3825 */
3826 if (exp->cond) {
3827 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3828 ret = acl_pass(ret);
3829 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3830 ret = !ret;
3831 if (!ret)
3832 continue;
3833 }
3834
3835 /* Apply the filter to the status line. */
3836 ret = htx_apply_filter_to_sts_line(s, res, exp);
3837 if (unlikely(ret < 0))
3838 return -1;
3839
3840 if (likely(ret == 0)) {
3841 /* The filter did not match the response, it can be
3842 * iterated through all headers.
3843 */
3844 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3845 return -1;
3846 }
3847 }
3848 return 0;
3849}
3850
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003851/*
3852 * Manage client-side cookie. It can impact performance by about 2% so it is
3853 * desirable to call it only when needed. This code is quite complex because
3854 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3855 * highly recommended not to touch this part without a good reason !
3856 */
3857static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3858{
3859 struct session *sess = s->sess;
3860 struct http_txn *txn = s->txn;
3861 struct htx *htx;
3862 struct http_hdr_ctx ctx;
3863 char *hdr_beg, *hdr_end, *del_from;
3864 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3865 int preserve_hdr;
3866
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003867 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003868 ctx.blk = NULL;
3869 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3870 del_from = NULL; /* nothing to be deleted */
3871 preserve_hdr = 0; /* assume we may kill the whole header */
3872
3873 /* Now look for cookies. Conforming to RFC2109, we have to support
3874 * attributes whose name begin with a '$', and associate them with
3875 * the right cookie, if we want to delete this cookie.
3876 * So there are 3 cases for each cookie read :
3877 * 1) it's a special attribute, beginning with a '$' : ignore it.
3878 * 2) it's a server id cookie that we *MAY* want to delete : save
3879 * some pointers on it (last semi-colon, beginning of cookie...)
3880 * 3) it's an application cookie : we *MAY* have to delete a previous
3881 * "special" cookie.
3882 * At the end of loop, if a "special" cookie remains, we may have to
3883 * remove it. If no application cookie persists in the header, we
3884 * *MUST* delete it.
3885 *
3886 * Note: RFC2965 is unclear about the processing of spaces around
3887 * the equal sign in the ATTR=VALUE form. A careful inspection of
3888 * the RFC explicitly allows spaces before it, and not within the
3889 * tokens (attrs or values). An inspection of RFC2109 allows that
3890 * too but section 10.1.3 lets one think that spaces may be allowed
3891 * after the equal sign too, resulting in some (rare) buggy
3892 * implementations trying to do that. So let's do what servers do.
3893 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3894 * allowed quoted strings in values, with any possible character
3895 * after a backslash, including control chars and delimitors, which
3896 * causes parsing to become ambiguous. Browsers also allow spaces
3897 * within values even without quotes.
3898 *
3899 * We have to keep multiple pointers in order to support cookie
3900 * removal at the beginning, middle or end of header without
3901 * corrupting the header. All of these headers are valid :
3902 *
3903 * hdr_beg hdr_end
3904 * | |
3905 * v |
3906 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3907 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3908 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3909 * | | | | | | |
3910 * | | | | | | |
3911 * | | | | | | +--> next
3912 * | | | | | +----> val_end
3913 * | | | | +-----------> val_beg
3914 * | | | +--------------> equal
3915 * | | +----------------> att_end
3916 * | +---------------------> att_beg
3917 * +--------------------------> prev
3918 *
3919 */
3920 hdr_beg = ctx.value.ptr;
3921 hdr_end = hdr_beg + ctx.value.len;
3922 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3923 /* Iterate through all cookies on this line */
3924
3925 /* find att_beg */
3926 att_beg = prev;
3927 if (prev > hdr_beg)
3928 att_beg++;
3929
3930 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3931 att_beg++;
3932
3933 /* find att_end : this is the first character after the last non
3934 * space before the equal. It may be equal to hdr_end.
3935 */
3936 equal = att_end = att_beg;
3937 while (equal < hdr_end) {
3938 if (*equal == '=' || *equal == ',' || *equal == ';')
3939 break;
3940 if (HTTP_IS_SPHT(*equal++))
3941 continue;
3942 att_end = equal;
3943 }
3944
3945 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3946 * is between <att_beg> and <equal>, both may be identical.
3947 */
3948 /* look for end of cookie if there is an equal sign */
3949 if (equal < hdr_end && *equal == '=') {
3950 /* look for the beginning of the value */
3951 val_beg = equal + 1;
3952 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3953 val_beg++;
3954
3955 /* find the end of the value, respecting quotes */
3956 next = http_find_cookie_value_end(val_beg, hdr_end);
3957
3958 /* make val_end point to the first white space or delimitor after the value */
3959 val_end = next;
3960 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3961 val_end--;
3962 }
3963 else
3964 val_beg = val_end = next = equal;
3965
3966 /* We have nothing to do with attributes beginning with
3967 * '$'. However, they will automatically be removed if a
3968 * header before them is removed, since they're supposed
3969 * to be linked together.
3970 */
3971 if (*att_beg == '$')
3972 continue;
3973
3974 /* Ignore cookies with no equal sign */
3975 if (equal == next) {
3976 /* This is not our cookie, so we must preserve it. But if we already
3977 * scheduled another cookie for removal, we cannot remove the
3978 * complete header, but we can remove the previous block itself.
3979 */
3980 preserve_hdr = 1;
3981 if (del_from != NULL) {
3982 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3983 val_end += delta;
3984 next += delta;
3985 hdr_end += delta;
3986 prev = del_from;
3987 del_from = NULL;
3988 }
3989 continue;
3990 }
3991
3992 /* if there are spaces around the equal sign, we need to
3993 * strip them otherwise we'll get trouble for cookie captures,
3994 * or even for rewrites. Since this happens extremely rarely,
3995 * it does not hurt performance.
3996 */
3997 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3998 int stripped_before = 0;
3999 int stripped_after = 0;
4000
4001 if (att_end != equal) {
4002 memmove(att_end, equal, hdr_end - equal);
4003 stripped_before = (att_end - equal);
4004 equal += stripped_before;
4005 val_beg += stripped_before;
4006 }
4007
4008 if (val_beg > equal + 1) {
4009 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4010 stripped_after = (equal + 1) - val_beg;
4011 val_beg += stripped_after;
4012 stripped_before += stripped_after;
4013 }
4014
4015 val_end += stripped_before;
4016 next += stripped_before;
4017 hdr_end += stripped_before;
4018 }
4019 /* now everything is as on the diagram above */
4020
4021 /* First, let's see if we want to capture this cookie. We check
4022 * that we don't already have a client side cookie, because we
4023 * can only capture one. Also as an optimisation, we ignore
4024 * cookies shorter than the declared name.
4025 */
4026 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4027 (val_end - att_beg >= sess->fe->capture_namelen) &&
4028 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4029 int log_len = val_end - att_beg;
4030
4031 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4032 ha_alert("HTTP logging : out of memory.\n");
4033 } else {
4034 if (log_len > sess->fe->capture_len)
4035 log_len = sess->fe->capture_len;
4036 memcpy(txn->cli_cookie, att_beg, log_len);
4037 txn->cli_cookie[log_len] = 0;
4038 }
4039 }
4040
4041 /* Persistence cookies in passive, rewrite or insert mode have the
4042 * following form :
4043 *
4044 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4045 *
4046 * For cookies in prefix mode, the form is :
4047 *
4048 * Cookie: NAME=SRV~VALUE
4049 */
4050 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4051 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4052 struct server *srv = s->be->srv;
4053 char *delim;
4054
4055 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4056 * have the server ID between val_beg and delim, and the original cookie between
4057 * delim+1 and val_end. Otherwise, delim==val_end :
4058 *
4059 * hdr_beg
4060 * |
4061 * v
4062 * NAME=SRV; # in all but prefix modes
4063 * NAME=SRV~OPAQUE ; # in prefix mode
4064 * || || | |+-> next
4065 * || || | +--> val_end
4066 * || || +---------> delim
4067 * || |+------------> val_beg
4068 * || +-------------> att_end = equal
4069 * |+-----------------> att_beg
4070 * +------------------> prev
4071 *
4072 */
4073 if (s->be->ck_opts & PR_CK_PFX) {
4074 for (delim = val_beg; delim < val_end; delim++)
4075 if (*delim == COOKIE_DELIM)
4076 break;
4077 }
4078 else {
4079 char *vbar1;
4080 delim = val_end;
4081 /* Now check if the cookie contains a date field, which would
4082 * appear after a vertical bar ('|') just after the server name
4083 * and before the delimiter.
4084 */
4085 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4086 if (vbar1) {
4087 /* OK, so left of the bar is the server's cookie and
4088 * right is the last seen date. It is a base64 encoded
4089 * 30-bit value representing the UNIX date since the
4090 * epoch in 4-second quantities.
4091 */
4092 int val;
4093 delim = vbar1++;
4094 if (val_end - vbar1 >= 5) {
4095 val = b64tos30(vbar1);
4096 if (val > 0)
4097 txn->cookie_last_date = val << 2;
4098 }
4099 /* look for a second vertical bar */
4100 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4101 if (vbar1 && (val_end - vbar1 > 5)) {
4102 val = b64tos30(vbar1 + 1);
4103 if (val > 0)
4104 txn->cookie_first_date = val << 2;
4105 }
4106 }
4107 }
4108
4109 /* if the cookie has an expiration date and the proxy wants to check
4110 * it, then we do that now. We first check if the cookie is too old,
4111 * then only if it has expired. We detect strict overflow because the
4112 * time resolution here is not great (4 seconds). Cookies with dates
4113 * in the future are ignored if their offset is beyond one day. This
4114 * allows an admin to fix timezone issues without expiring everyone
4115 * and at the same time avoids keeping unwanted side effects for too
4116 * long.
4117 */
4118 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4119 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4120 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4121 txn->flags &= ~TX_CK_MASK;
4122 txn->flags |= TX_CK_OLD;
4123 delim = val_beg; // let's pretend we have not found the cookie
4124 txn->cookie_first_date = 0;
4125 txn->cookie_last_date = 0;
4126 }
4127 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4128 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4129 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4130 txn->flags &= ~TX_CK_MASK;
4131 txn->flags |= TX_CK_EXPIRED;
4132 delim = val_beg; // let's pretend we have not found the cookie
4133 txn->cookie_first_date = 0;
4134 txn->cookie_last_date = 0;
4135 }
4136
4137 /* Here, we'll look for the first running server which supports the cookie.
4138 * This allows to share a same cookie between several servers, for example
4139 * to dedicate backup servers to specific servers only.
4140 * However, to prevent clients from sticking to cookie-less backup server
4141 * when they have incidentely learned an empty cookie, we simply ignore
4142 * empty cookies and mark them as invalid.
4143 * The same behaviour is applied when persistence must be ignored.
4144 */
4145 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4146 srv = NULL;
4147
4148 while (srv) {
4149 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4150 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4151 if ((srv->cur_state != SRV_ST_STOPPED) ||
4152 (s->be->options & PR_O_PERSIST) ||
4153 (s->flags & SF_FORCE_PRST)) {
4154 /* we found the server and we can use it */
4155 txn->flags &= ~TX_CK_MASK;
4156 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4157 s->flags |= SF_DIRECT | SF_ASSIGNED;
4158 s->target = &srv->obj_type;
4159 break;
4160 } else {
4161 /* we found a server, but it's down,
4162 * mark it as such and go on in case
4163 * another one is available.
4164 */
4165 txn->flags &= ~TX_CK_MASK;
4166 txn->flags |= TX_CK_DOWN;
4167 }
4168 }
4169 srv = srv->next;
4170 }
4171
4172 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4173 /* no server matched this cookie or we deliberately skipped it */
4174 txn->flags &= ~TX_CK_MASK;
4175 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4176 txn->flags |= TX_CK_UNUSED;
4177 else
4178 txn->flags |= TX_CK_INVALID;
4179 }
4180
4181 /* depending on the cookie mode, we may have to either :
4182 * - delete the complete cookie if we're in insert+indirect mode, so that
4183 * the server never sees it ;
4184 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004185 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004186 * if we're in cookie prefix mode
4187 */
4188 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4189 int delta; /* negative */
4190
4191 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4192 delta = val_beg - (delim + 1);
4193 val_end += delta;
4194 next += delta;
4195 hdr_end += delta;
4196 del_from = NULL;
4197 preserve_hdr = 1; /* we want to keep this cookie */
4198 }
4199 else if (del_from == NULL &&
4200 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4201 del_from = prev;
4202 }
4203 }
4204 else {
4205 /* This is not our cookie, so we must preserve it. But if we already
4206 * scheduled another cookie for removal, we cannot remove the
4207 * complete header, but we can remove the previous block itself.
4208 */
4209 preserve_hdr = 1;
4210
4211 if (del_from != NULL) {
4212 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4213 if (att_beg >= del_from)
4214 att_beg += delta;
4215 if (att_end >= del_from)
4216 att_end += delta;
4217 val_beg += delta;
4218 val_end += delta;
4219 next += delta;
4220 hdr_end += delta;
4221 prev = del_from;
4222 del_from = NULL;
4223 }
4224 }
4225
4226 /* continue with next cookie on this header line */
4227 att_beg = next;
4228 } /* for each cookie */
4229
4230
4231 /* There are no more cookies on this line.
4232 * We may still have one (or several) marked for deletion at the
4233 * end of the line. We must do this now in two ways :
4234 * - if some cookies must be preserved, we only delete from the
4235 * mark to the end of line ;
4236 * - if nothing needs to be preserved, simply delete the whole header
4237 */
4238 if (del_from) {
4239 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4240 }
4241 if ((hdr_end - hdr_beg) != ctx.value.len) {
4242 if (hdr_beg != hdr_end) {
4243 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004244 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004245 }
4246 else
4247 http_remove_header(htx, &ctx);
4248 }
4249 } /* for each "Cookie header */
4250}
4251
4252/*
4253 * Manage server-side cookies. It can impact performance by about 2% so it is
4254 * desirable to call it only when needed. This function is also used when we
4255 * just need to know if there is a cookie (eg: for check-cache).
4256 */
4257static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4258{
4259 struct session *sess = s->sess;
4260 struct http_txn *txn = s->txn;
4261 struct htx *htx;
4262 struct http_hdr_ctx ctx;
4263 struct server *srv;
4264 char *hdr_beg, *hdr_end;
4265 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4266 int is_cookie2;
4267
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004268 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004269
4270 ctx.blk = NULL;
4271 while (1) {
4272 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4273 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4274 break;
4275 is_cookie2 = 1;
4276 }
4277
4278 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4279 * <prev> points to the colon.
4280 */
4281 txn->flags |= TX_SCK_PRESENT;
4282
4283 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4284 * check-cache is enabled) and we are not interested in checking
4285 * them. Warning, the cookie capture is declared in the frontend.
4286 */
4287 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4288 break;
4289
4290 /* OK so now we know we have to process this response cookie.
4291 * The format of the Set-Cookie header is slightly different
4292 * from the format of the Cookie header in that it does not
4293 * support the comma as a cookie delimiter (thus the header
4294 * cannot be folded) because the Expires attribute described in
4295 * the original Netscape's spec may contain an unquoted date
4296 * with a comma inside. We have to live with this because
4297 * many browsers don't support Max-Age and some browsers don't
4298 * support quoted strings. However the Set-Cookie2 header is
4299 * clean.
4300 *
4301 * We have to keep multiple pointers in order to support cookie
4302 * removal at the beginning, middle or end of header without
4303 * corrupting the header (in case of set-cookie2). A special
4304 * pointer, <scav> points to the beginning of the set-cookie-av
4305 * fields after the first semi-colon. The <next> pointer points
4306 * either to the end of line (set-cookie) or next unquoted comma
4307 * (set-cookie2). All of these headers are valid :
4308 *
4309 * hdr_beg hdr_end
4310 * | |
4311 * v |
4312 * NAME1 = VALUE 1 ; Secure; Path="/" |
4313 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4314 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4315 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4316 * | | | | | | | |
4317 * | | | | | | | +-> next
4318 * | | | | | | +------------> scav
4319 * | | | | | +--------------> val_end
4320 * | | | | +--------------------> val_beg
4321 * | | | +----------------------> equal
4322 * | | +------------------------> att_end
4323 * | +----------------------------> att_beg
4324 * +------------------------------> prev
4325 * -------------------------------> hdr_beg
4326 */
4327 hdr_beg = ctx.value.ptr;
4328 hdr_end = hdr_beg + ctx.value.len;
4329 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4330
4331 /* Iterate through all cookies on this line */
4332
4333 /* find att_beg */
4334 att_beg = prev;
4335 if (prev > hdr_beg)
4336 att_beg++;
4337
4338 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4339 att_beg++;
4340
4341 /* find att_end : this is the first character after the last non
4342 * space before the equal. It may be equal to hdr_end.
4343 */
4344 equal = att_end = att_beg;
4345
4346 while (equal < hdr_end) {
4347 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4348 break;
4349 if (HTTP_IS_SPHT(*equal++))
4350 continue;
4351 att_end = equal;
4352 }
4353
4354 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4355 * is between <att_beg> and <equal>, both may be identical.
4356 */
4357
4358 /* look for end of cookie if there is an equal sign */
4359 if (equal < hdr_end && *equal == '=') {
4360 /* look for the beginning of the value */
4361 val_beg = equal + 1;
4362 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4363 val_beg++;
4364
4365 /* find the end of the value, respecting quotes */
4366 next = http_find_cookie_value_end(val_beg, hdr_end);
4367
4368 /* make val_end point to the first white space or delimitor after the value */
4369 val_end = next;
4370 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4371 val_end--;
4372 }
4373 else {
4374 /* <equal> points to next comma, semi-colon or EOL */
4375 val_beg = val_end = next = equal;
4376 }
4377
4378 if (next < hdr_end) {
4379 /* Set-Cookie2 supports multiple cookies, and <next> points to
4380 * a colon or semi-colon before the end. So skip all attr-value
4381 * pairs and look for the next comma. For Set-Cookie, since
4382 * commas are permitted in values, skip to the end.
4383 */
4384 if (is_cookie2)
4385 next = http_find_hdr_value_end(next, hdr_end);
4386 else
4387 next = hdr_end;
4388 }
4389
4390 /* Now everything is as on the diagram above */
4391
4392 /* Ignore cookies with no equal sign */
4393 if (equal == val_end)
4394 continue;
4395
4396 /* If there are spaces around the equal sign, we need to
4397 * strip them otherwise we'll get trouble for cookie captures,
4398 * or even for rewrites. Since this happens extremely rarely,
4399 * it does not hurt performance.
4400 */
4401 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4402 int stripped_before = 0;
4403 int stripped_after = 0;
4404
4405 if (att_end != equal) {
4406 memmove(att_end, equal, hdr_end - equal);
4407 stripped_before = (att_end - equal);
4408 equal += stripped_before;
4409 val_beg += stripped_before;
4410 }
4411
4412 if (val_beg > equal + 1) {
4413 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4414 stripped_after = (equal + 1) - val_beg;
4415 val_beg += stripped_after;
4416 stripped_before += stripped_after;
4417 }
4418
4419 val_end += stripped_before;
4420 next += stripped_before;
4421 hdr_end += stripped_before;
4422
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004423 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4424 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004425 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004426 }
4427
4428 /* First, let's see if we want to capture this cookie. We check
4429 * that we don't already have a server side cookie, because we
4430 * can only capture one. Also as an optimisation, we ignore
4431 * cookies shorter than the declared name.
4432 */
4433 if (sess->fe->capture_name != NULL &&
4434 txn->srv_cookie == NULL &&
4435 (val_end - att_beg >= sess->fe->capture_namelen) &&
4436 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4437 int log_len = val_end - att_beg;
4438 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4439 ha_alert("HTTP logging : out of memory.\n");
4440 }
4441 else {
4442 if (log_len > sess->fe->capture_len)
4443 log_len = sess->fe->capture_len;
4444 memcpy(txn->srv_cookie, att_beg, log_len);
4445 txn->srv_cookie[log_len] = 0;
4446 }
4447 }
4448
4449 srv = objt_server(s->target);
4450 /* now check if we need to process it for persistence */
4451 if (!(s->flags & SF_IGNORE_PRST) &&
4452 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4453 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4454 /* assume passive cookie by default */
4455 txn->flags &= ~TX_SCK_MASK;
4456 txn->flags |= TX_SCK_FOUND;
4457
4458 /* If the cookie is in insert mode on a known server, we'll delete
4459 * this occurrence because we'll insert another one later.
4460 * We'll delete it too if the "indirect" option is set and we're in
4461 * a direct access.
4462 */
4463 if (s->be->ck_opts & PR_CK_PSV) {
4464 /* The "preserve" flag was set, we don't want to touch the
4465 * server's cookie.
4466 */
4467 }
4468 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4469 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4470 /* this cookie must be deleted */
4471 if (prev == hdr_beg && next == hdr_end) {
4472 /* whole header */
4473 http_remove_header(htx, &ctx);
4474 /* note: while both invalid now, <next> and <hdr_end>
4475 * are still equal, so the for() will stop as expected.
4476 */
4477 } else {
4478 /* just remove the value */
4479 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4480 next = prev;
4481 hdr_end += delta;
4482 }
4483 txn->flags &= ~TX_SCK_MASK;
4484 txn->flags |= TX_SCK_DELETED;
4485 /* and go on with next cookie */
4486 }
4487 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4488 /* replace bytes val_beg->val_end with the cookie name associated
4489 * with this server since we know it.
4490 */
4491 int sliding, delta;
4492
4493 ctx.value = ist2(val_beg, val_end - val_beg);
4494 ctx.lws_before = ctx.lws_after = 0;
4495 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4496 delta = srv->cklen - (val_end - val_beg);
4497 sliding = (ctx.value.ptr - val_beg);
4498 hdr_beg += sliding;
4499 val_beg += sliding;
4500 next += sliding + delta;
4501 hdr_end += sliding + delta;
4502
4503 txn->flags &= ~TX_SCK_MASK;
4504 txn->flags |= TX_SCK_REPLACED;
4505 }
4506 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4507 /* insert the cookie name associated with this server
4508 * before existing cookie, and insert a delimiter between them..
4509 */
4510 int sliding, delta;
4511 ctx.value = ist2(val_beg, 0);
4512 ctx.lws_before = ctx.lws_after = 0;
4513 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4514 delta = srv->cklen + 1;
4515 sliding = (ctx.value.ptr - val_beg);
4516 hdr_beg += sliding;
4517 val_beg += sliding;
4518 next += sliding + delta;
4519 hdr_end += sliding + delta;
4520
4521 val_beg[srv->cklen] = COOKIE_DELIM;
4522 txn->flags &= ~TX_SCK_MASK;
4523 txn->flags |= TX_SCK_REPLACED;
4524 }
4525 }
4526 /* that's done for this cookie, check the next one on the same
4527 * line when next != hdr_end (only if is_cookie2).
4528 */
4529 }
4530 }
4531}
4532
Christopher Faulet25a02f62018-10-24 12:00:25 +02004533/*
4534 * Parses the Cache-Control and Pragma request header fields to determine if
4535 * the request may be served from the cache and/or if it is cacheable. Updates
4536 * s->txn->flags.
4537 */
4538void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4539{
4540 struct http_txn *txn = s->txn;
4541 struct htx *htx;
4542 int32_t pos;
4543 int pragma_found, cc_found, i;
4544
4545 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4546 return; /* nothing more to do here */
4547
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004548 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004549 pragma_found = cc_found = 0;
4550 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4551 struct htx_blk *blk = htx_get_blk(htx, pos);
4552 enum htx_blk_type type = htx_get_blk_type(blk);
4553 struct ist n, v;
4554
4555 if (type == HTX_BLK_EOH)
4556 break;
4557 if (type != HTX_BLK_HDR)
4558 continue;
4559
4560 n = htx_get_blk_name(htx, blk);
4561 v = htx_get_blk_value(htx, blk);
4562
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004563 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004564 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4565 pragma_found = 1;
4566 continue;
4567 }
4568 }
4569
4570 /* Don't use the cache and don't try to store if we found the
4571 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004572 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004573 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4574 txn->flags |= TX_CACHE_IGNORE;
4575 continue;
4576 }
4577
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004578 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004579 continue;
4580
4581 /* OK, right now we know we have a cache-control header */
4582 cc_found = 1;
4583 if (!v.len) /* no info */
4584 continue;
4585
4586 i = 0;
4587 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4588 !isspace((unsigned char)*(v.ptr+i)))
4589 i++;
4590
4591 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4592 * values after max-age, max-stale nor min-fresh, we simply don't
4593 * use the cache when they're specified.
4594 */
4595 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4596 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4597 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4598 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4599 txn->flags |= TX_CACHE_IGNORE;
4600 continue;
4601 }
4602
4603 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4604 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4605 continue;
4606 }
4607 }
4608
4609 /* RFC7234#5.4:
4610 * When the Cache-Control header field is also present and
4611 * understood in a request, Pragma is ignored.
4612 * When the Cache-Control header field is not present in a
4613 * request, caches MUST consider the no-cache request
4614 * pragma-directive as having the same effect as if
4615 * "Cache-Control: no-cache" were present.
4616 */
4617 if (!cc_found && pragma_found)
4618 txn->flags |= TX_CACHE_IGNORE;
4619}
4620
4621/*
4622 * Check if response is cacheable or not. Updates s->txn->flags.
4623 */
4624void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4625{
4626 struct http_txn *txn = s->txn;
4627 struct htx *htx;
4628 int32_t pos;
4629 int i;
4630
4631 if (txn->status < 200) {
4632 /* do not try to cache interim responses! */
4633 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4634 return;
4635 }
4636
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004637 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004638 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4639 struct htx_blk *blk = htx_get_blk(htx, pos);
4640 enum htx_blk_type type = htx_get_blk_type(blk);
4641 struct ist n, v;
4642
4643 if (type == HTX_BLK_EOH)
4644 break;
4645 if (type != HTX_BLK_HDR)
4646 continue;
4647
4648 n = htx_get_blk_name(htx, blk);
4649 v = htx_get_blk_value(htx, blk);
4650
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004651 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004652 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4653 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4654 return;
4655 }
4656 }
4657
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004658 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004659 continue;
4660
4661 /* OK, right now we know we have a cache-control header */
4662 if (!v.len) /* no info */
4663 continue;
4664
4665 i = 0;
4666 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4667 !isspace((unsigned char)*(v.ptr+i)))
4668 i++;
4669
4670 /* we have a complete value between v.ptr and (v.ptr+i) */
4671 if (i < v.len && *(v.ptr + i) == '=') {
4672 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4673 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4674 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4675 continue;
4676 }
4677
4678 /* we have something of the form no-cache="set-cookie" */
4679 if ((v.len >= 21) &&
4680 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4681 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4682 txn->flags &= ~TX_CACHE_COOK;
4683 continue;
4684 }
4685
4686 /* OK, so we know that either p2 points to the end of string or to a comma */
4687 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4688 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4689 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4690 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4691 return;
4692 }
4693
4694 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4695 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4696 continue;
4697 }
4698 }
4699}
4700
Christopher Faulet64159df2018-10-24 21:15:35 +02004701/* send a server's name with an outgoing request over an established connection.
4702 * Note: this function is designed to be called once the request has been
4703 * scheduled for being forwarded. This is the reason why the number of forwarded
4704 * bytes have to be adjusted.
4705 */
4706int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4707{
4708 struct htx *htx;
4709 struct http_hdr_ctx ctx;
4710 struct ist hdr;
4711 uint32_t data;
4712
4713 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004714 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004715 data = htx->data;
4716
4717 ctx.blk = NULL;
4718 while (http_find_header(htx, hdr, &ctx, 1))
4719 http_remove_header(htx, &ctx);
4720 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4721
4722 if (co_data(&s->req)) {
4723 if (data >= htx->data)
4724 c_rew(&s->req, data - htx->data);
4725 else
4726 c_adv(&s->req, htx->data - data);
4727 }
4728 return 0;
4729}
4730
Christopher Faulet377c5a52018-10-24 21:21:30 +02004731/*
4732 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4733 * for the current backend.
4734 *
4735 * It is assumed that the request is either a HEAD, GET, or POST and that the
4736 * uri_auth field is valid.
4737 *
4738 * Returns 1 if stats should be provided, otherwise 0.
4739 */
4740static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4741{
4742 struct uri_auth *uri_auth = backend->uri_auth;
4743 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004744 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004745 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004746
4747 if (!uri_auth)
4748 return 0;
4749
4750 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4751 return 0;
4752
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004753 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004754 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004755 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004756
4757 /* check URI size */
4758 if (uri_auth->uri_len > uri.len)
4759 return 0;
4760
4761 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4762 return 0;
4763
4764 return 1;
4765}
4766
4767/* This function prepares an applet to handle the stats. It can deal with the
4768 * "100-continue" expectation, check that admin rules are met for POST requests,
4769 * and program a response message if something was unexpected. It cannot fail
4770 * and always relies on the stats applet to complete the job. It does not touch
4771 * analysers nor counters, which are left to the caller. It does not touch
4772 * s->target which is supposed to already point to the stats applet. The caller
4773 * is expected to have already assigned an appctx to the stream.
4774 */
4775static int htx_handle_stats(struct stream *s, struct channel *req)
4776{
4777 struct stats_admin_rule *stats_admin_rule;
4778 struct stream_interface *si = &s->si[1];
4779 struct session *sess = s->sess;
4780 struct http_txn *txn = s->txn;
4781 struct http_msg *msg = &txn->req;
4782 struct uri_auth *uri_auth = s->be->uri_auth;
4783 const char *h, *lookup, *end;
4784 struct appctx *appctx;
4785 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004786 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004787
4788 appctx = si_appctx(si);
4789 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4790 appctx->st1 = appctx->st2 = 0;
4791 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4792 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4793 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4794 appctx->ctx.stats.flags |= STAT_CHUNKED;
4795
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004796 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004798 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4799 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004800
4801 for (h = lookup; h <= end - 3; h++) {
4802 if (memcmp(h, ";up", 3) == 0) {
4803 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4804 break;
4805 }
4806 }
4807
4808 if (uri_auth->refresh) {
4809 for (h = lookup; h <= end - 10; h++) {
4810 if (memcmp(h, ";norefresh", 10) == 0) {
4811 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4812 break;
4813 }
4814 }
4815 }
4816
4817 for (h = lookup; h <= end - 4; h++) {
4818 if (memcmp(h, ";csv", 4) == 0) {
4819 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4820 break;
4821 }
4822 }
4823
4824 for (h = lookup; h <= end - 6; h++) {
4825 if (memcmp(h, ";typed", 6) == 0) {
4826 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4827 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4828 break;
4829 }
4830 }
4831
4832 for (h = lookup; h <= end - 8; h++) {
4833 if (memcmp(h, ";st=", 4) == 0) {
4834 int i;
4835 h += 4;
4836 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4837 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4838 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4839 appctx->ctx.stats.st_code = i;
4840 break;
4841 }
4842 }
4843 break;
4844 }
4845 }
4846
4847 appctx->ctx.stats.scope_str = 0;
4848 appctx->ctx.stats.scope_len = 0;
4849 for (h = lookup; h <= end - 8; h++) {
4850 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4851 int itx = 0;
4852 const char *h2;
4853 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4854 const char *err;
4855
4856 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4857 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004858 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4859 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004860 if (*h == ';' || *h == '&' || *h == ' ')
4861 break;
4862 itx++;
4863 h++;
4864 }
4865
4866 if (itx > STAT_SCOPE_TXT_MAXLEN)
4867 itx = STAT_SCOPE_TXT_MAXLEN;
4868 appctx->ctx.stats.scope_len = itx;
4869
4870 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4871 memcpy(scope_txt, h2, itx);
4872 scope_txt[itx] = '\0';
4873 err = invalid_char(scope_txt);
4874 if (err) {
4875 /* bad char in search text => clear scope */
4876 appctx->ctx.stats.scope_str = 0;
4877 appctx->ctx.stats.scope_len = 0;
4878 }
4879 break;
4880 }
4881 }
4882
4883 /* now check whether we have some admin rules for this request */
4884 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4885 int ret = 1;
4886
4887 if (stats_admin_rule->cond) {
4888 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4889 ret = acl_pass(ret);
4890 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4891 ret = !ret;
4892 }
4893
4894 if (ret) {
4895 /* no rule, or the rule matches */
4896 appctx->ctx.stats.flags |= STAT_ADMIN;
4897 break;
4898 }
4899 }
4900
Christopher Faulet5d45e382019-02-27 15:15:23 +01004901 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4902 appctx->st0 = STAT_HTTP_HEAD;
4903 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004904 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004905 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004906 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004907 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004908 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4909 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4910 appctx->st0 = STAT_HTTP_LAST;
4911 }
4912 }
4913 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004914 /* Unsupported method */
4915 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4916 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4917 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004918 }
4919
4920 s->task->nice = -32; /* small boost for HTTP statistics */
4921 return 1;
4922}
4923
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004924void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4925{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004926 struct channel *req = &s->req;
4927 struct channel *res = &s->res;
4928 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004929 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004930 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004931 struct ist path, location;
4932 unsigned int flags;
4933 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004934
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004935 /*
4936 * Create the location
4937 */
4938 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004939
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004940 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004941 /* special prefix "/" means don't change URL */
4942 srv = __objt_server(s->target);
4943 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4944 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4945 return;
4946 }
4947
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004948 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004949 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004950 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004951 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004952 if (!path.ptr)
4953 return;
4954
4955 if (!chunk_memcat(&trash, path.ptr, path.len))
4956 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004957 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004958
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004959 /*
4960 * Create the 302 respone
4961 */
4962 htx = htx_from_buf(&res->buf);
4963 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4964 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4965 ist("HTTP/1.1"), ist("302"), ist("Found"));
4966 if (!sl)
4967 goto fail;
4968 sl->info.res.status = 302;
4969 s->txn->status = 302;
4970
4971 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4972 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4973 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4974 !htx_add_header(htx, ist("Location"), location))
4975 goto fail;
4976
4977 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4978 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004979
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004980 /*
4981 * Send the message
4982 */
4983 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004984 c_adv(res, data);
4985 res->total += data;
4986
4987 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004988 si_shutr(si);
4989 si_shutw(si);
4990 si->err_type = SI_ET_NONE;
4991 si->state = SI_ST_CLO;
4992
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004993 channel_auto_read(req);
4994 channel_abort(req);
4995 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004996 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 channel_auto_read(res);
4998 channel_auto_close(res);
4999
5000 if (!(s->flags & SF_ERR_MASK))
5001 s->flags |= SF_ERR_LOCAL;
5002 if (!(s->flags & SF_FINST_MASK))
5003 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005004
5005 /* FIXME: we should increase a counter of redirects per server and per backend. */
5006 srv_inc_sess_ctr(srv);
5007 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005008 return;
5009
5010 fail:
5011 /* If an error occurred, remove the incomplete HTTP response from the
5012 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005013 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005014}
5015
Christopher Fauletf2824e62018-10-01 12:12:37 +02005016/* This function terminates the request because it was completly analyzed or
5017 * because an error was triggered during the body forwarding.
5018 */
5019static void htx_end_request(struct stream *s)
5020{
5021 struct channel *chn = &s->req;
5022 struct http_txn *txn = s->txn;
5023
5024 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5025 now_ms, __FUNCTION__, s,
5026 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5027 s->req.analysers, s->res.analysers);
5028
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005029 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5030 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005031 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005032 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005033 goto end;
5034 }
5035
5036 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5037 return;
5038
5039 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005040 /* No need to read anymore, the request was completely parsed.
5041 * We can shut the read side unless we want to abort_on_close,
5042 * or we have a POST request. The issue with POST requests is
5043 * that some browsers still send a CRLF after the request, and
5044 * this CRLF must be read so that it does not remain in the kernel
5045 * buffers, otherwise a close could cause an RST on some systems
5046 * (eg: Linux).
5047 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005048 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005049 channel_dont_read(chn);
5050
5051 /* if the server closes the connection, we want to immediately react
5052 * and close the socket to save packets and syscalls.
5053 */
5054 s->si[1].flags |= SI_FL_NOHALF;
5055
5056 /* In any case we've finished parsing the request so we must
5057 * disable Nagle when sending data because 1) we're not going
5058 * to shut this side, and 2) the server is waiting for us to
5059 * send pending data.
5060 */
5061 chn->flags |= CF_NEVER_WAIT;
5062
Christopher Fauletd01ce402019-01-02 17:44:13 +01005063 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5064 /* The server has not finished to respond, so we
5065 * don't want to move in order not to upset it.
5066 */
5067 return;
5068 }
5069
Christopher Fauletf2824e62018-10-01 12:12:37 +02005070 /* When we get here, it means that both the request and the
5071 * response have finished receiving. Depending on the connection
5072 * mode, we'll have to wait for the last bytes to leave in either
5073 * direction, and sometimes for a close to be effective.
5074 */
5075 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5076 /* Tunnel mode will not have any analyser so it needs to
5077 * poll for reads.
5078 */
5079 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005080 if (b_data(&chn->buf))
5081 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005082 txn->req.msg_state = HTTP_MSG_TUNNEL;
5083 }
5084 else {
5085 /* we're not expecting any new data to come for this
5086 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005087 *
5088 * However, there is an exception if the response
5089 * length is undefined. In this case, we need to wait
5090 * the close from the server. The response will be
5091 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005092 */
5093 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5094 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005095 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005096
5097 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5098 channel_shutr_now(chn);
5099 channel_shutw_now(chn);
5100 }
5101 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005102 goto check_channel_flags;
5103 }
5104
5105 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5106 http_msg_closing:
5107 /* nothing else to forward, just waiting for the output buffer
5108 * to be empty and for the shutw_now to take effect.
5109 */
5110 if (channel_is_empty(chn)) {
5111 txn->req.msg_state = HTTP_MSG_CLOSED;
5112 goto http_msg_closed;
5113 }
5114 else if (chn->flags & CF_SHUTW) {
5115 txn->req.err_state = txn->req.msg_state;
5116 txn->req.msg_state = HTTP_MSG_ERROR;
5117 goto end;
5118 }
5119 return;
5120 }
5121
5122 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5123 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005124 /* if we don't know whether the server will close, we need to hard close */
5125 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5126 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005127 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005128 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005129 channel_dont_read(chn);
5130 goto end;
5131 }
5132
5133 check_channel_flags:
5134 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5135 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5136 /* if we've just closed an output, let's switch */
5137 txn->req.msg_state = HTTP_MSG_CLOSING;
5138 goto http_msg_closing;
5139 }
5140
5141 end:
5142 chn->analysers &= AN_REQ_FLT_END;
5143 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5144 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5145 channel_auto_close(chn);
5146 channel_auto_read(chn);
5147}
5148
5149
5150/* This function terminates the response because it was completly analyzed or
5151 * because an error was triggered during the body forwarding.
5152 */
5153static void htx_end_response(struct stream *s)
5154{
5155 struct channel *chn = &s->res;
5156 struct http_txn *txn = s->txn;
5157
5158 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5159 now_ms, __FUNCTION__, s,
5160 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5161 s->req.analysers, s->res.analysers);
5162
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005163 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5164 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005165 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005166 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005167 goto end;
5168 }
5169
5170 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5171 return;
5172
5173 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5174 /* In theory, we don't need to read anymore, but we must
5175 * still monitor the server connection for a possible close
5176 * while the request is being uploaded, so we don't disable
5177 * reading.
5178 */
5179 /* channel_dont_read(chn); */
5180
5181 if (txn->req.msg_state < HTTP_MSG_DONE) {
5182 /* The client seems to still be sending data, probably
5183 * because we got an error response during an upload.
5184 * We have the choice of either breaking the connection
5185 * or letting it pass through. Let's do the later.
5186 */
5187 return;
5188 }
5189
5190 /* When we get here, it means that both the request and the
5191 * response have finished receiving. Depending on the connection
5192 * mode, we'll have to wait for the last bytes to leave in either
5193 * direction, and sometimes for a close to be effective.
5194 */
5195 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5196 channel_auto_read(chn);
5197 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005198 if (b_data(&chn->buf))
5199 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005200 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5201 }
5202 else {
5203 /* we're not expecting any new data to come for this
5204 * transaction, so we can close it.
5205 */
5206 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5207 channel_shutr_now(chn);
5208 channel_shutw_now(chn);
5209 }
5210 }
5211 goto check_channel_flags;
5212 }
5213
5214 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5215 http_msg_closing:
5216 /* nothing else to forward, just waiting for the output buffer
5217 * to be empty and for the shutw_now to take effect.
5218 */
5219 if (channel_is_empty(chn)) {
5220 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5221 goto http_msg_closed;
5222 }
5223 else if (chn->flags & CF_SHUTW) {
5224 txn->rsp.err_state = txn->rsp.msg_state;
5225 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005226 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005227 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005228 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005229 goto end;
5230 }
5231 return;
5232 }
5233
5234 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5235 http_msg_closed:
5236 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005237 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005238 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005239 goto end;
5240 }
5241
5242 check_channel_flags:
5243 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5244 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5245 /* if we've just closed an output, let's switch */
5246 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5247 goto http_msg_closing;
5248 }
5249
5250 end:
5251 chn->analysers &= AN_RES_FLT_END;
5252 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5253 chn->analysers |= AN_RES_FLT_XFER_DATA;
5254 channel_auto_close(chn);
5255 channel_auto_read(chn);
5256}
5257
Christopher Faulet0f226952018-10-22 09:29:56 +02005258void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5259 int finst, const struct buffer *msg)
5260{
5261 channel_auto_read(si_oc(si));
5262 channel_abort(si_oc(si));
5263 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005264 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005265 channel_auto_close(si_ic(si));
5266 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005267
5268 /* <msg> is an HTX structure. So we copy it in the response's
5269 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005270 if (msg) {
5271 struct channel *chn = si_ic(si);
5272 struct htx *htx;
5273
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005274 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005275 chn->buf.data = msg->data;
5276 memcpy(chn->buf.area, msg->area, msg->data);
5277 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005278 c_adv(chn, htx->data);
5279 chn->total += htx->data;
5280 }
5281 if (!(s->flags & SF_ERR_MASK))
5282 s->flags |= err;
5283 if (!(s->flags & SF_FINST_MASK))
5284 s->flags |= finst;
5285}
5286
5287void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5288{
5289 channel_auto_read(&s->req);
5290 channel_abort(&s->req);
5291 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005292 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5293 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005294
5295 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005296
5297 /* <msg> is an HTX structure. So we copy it in the response's
5298 * channel */
5299 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005300 if (msg) {
5301 struct channel *chn = &s->res;
5302 struct htx *htx;
5303
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005304 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005305 chn->buf.data = msg->data;
5306 memcpy(chn->buf.area, msg->area, msg->data);
5307 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005308 c_adv(chn, htx->data);
5309 chn->total += htx->data;
5310 }
5311
5312 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5313 channel_auto_read(&s->res);
5314 channel_auto_close(&s->res);
5315 channel_shutr_now(&s->res);
5316}
5317
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005318struct buffer *htx_error_message(struct stream *s)
5319{
5320 const int msgnum = http_get_status_idx(s->txn->status);
5321
5322 if (s->be->errmsg[msgnum].area)
5323 return &s->be->errmsg[msgnum];
5324 else if (strm_fe(s)->errmsg[msgnum].area)
5325 return &strm_fe(s)->errmsg[msgnum];
5326 else
5327 return &htx_err_chunks[msgnum];
5328}
5329
5330
Christopher Faulet4a28a532019-03-01 11:19:40 +01005331/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5332 * on success and -1 on error.
5333 */
5334static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5335{
5336 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5337 * then we must send an HTTP/1.1 100 Continue intermediate response.
5338 */
5339 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5340 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5341 struct ist hdr = { .ptr = "Expect", .len = 6 };
5342 struct http_hdr_ctx ctx;
5343
5344 ctx.blk = NULL;
5345 /* Expect is allowed in 1.1, look for it */
5346 if (http_find_header(htx, hdr, &ctx, 0) &&
5347 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5348 if (htx_reply_100_continue(s) == -1)
5349 return -1;
5350 http_remove_header(htx, &ctx);
5351 }
5352 }
5353 return 0;
5354}
5355
Christopher Faulet23a3c792018-11-28 10:01:23 +01005356/* Send a 100-Continue response to the client. It returns 0 on success and -1
5357 * on error. The response channel is updated accordingly.
5358 */
5359static int htx_reply_100_continue(struct stream *s)
5360{
5361 struct channel *res = &s->res;
5362 struct htx *htx = htx_from_buf(&res->buf);
5363 struct htx_sl *sl;
5364 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5365 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5366 size_t data;
5367
5368 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5369 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5370 if (!sl)
5371 goto fail;
5372 sl->info.res.status = 100;
5373
5374 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5375 goto fail;
5376
5377 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005378 c_adv(res, data);
5379 res->total += data;
5380 return 0;
5381
5382 fail:
5383 /* If an error occurred, remove the incomplete HTTP response from the
5384 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005385 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005386 return -1;
5387}
5388
Christopher Faulet12c51e22018-11-28 15:59:42 +01005389
5390/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5391 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5392 * error. The response channel is updated accordingly.
5393 */
5394static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5395{
5396 struct channel *res = &s->res;
5397 struct htx *htx = htx_from_buf(&res->buf);
5398 struct htx_sl *sl;
5399 struct ist code, body;
5400 int status;
5401 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5402 size_t data;
5403
5404 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5405 status = 401;
5406 code = ist("401");
5407 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5408 "You need a valid user and password to access this content.\n"
5409 "</body></html>\n");
5410 }
5411 else {
5412 status = 407;
5413 code = ist("407");
5414 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5415 "You need a valid user and password to access this content.\n"
5416 "</body></html>\n");
5417 }
5418
5419 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5420 ist("HTTP/1.1"), code, ist("Unauthorized"));
5421 if (!sl)
5422 goto fail;
5423 sl->info.res.status = status;
5424 s->txn->status = status;
5425
5426 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5427 goto fail;
5428
5429 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5430 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005431 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5432 goto fail;
5433 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5434 goto fail;
5435 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005436 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005437 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5438 goto fail;
5439
5440 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005441 c_adv(res, data);
5442 res->total += data;
5443
5444 channel_auto_read(&s->req);
5445 channel_abort(&s->req);
5446 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005447 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005448
5449 res->wex = tick_add_ifset(now_ms, res->wto);
5450 channel_auto_read(res);
5451 channel_auto_close(res);
5452 channel_shutr_now(res);
5453 return 0;
5454
5455 fail:
5456 /* If an error occurred, remove the incomplete HTTP response from the
5457 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005458 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005459 return -1;
5460}
5461
Christopher Faulet0f226952018-10-22 09:29:56 +02005462/*
5463 * Capture headers from message <htx> according to header list <cap_hdr>, and
5464 * fill the <cap> pointers appropriately.
5465 */
5466static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5467{
5468 struct cap_hdr *h;
5469 int32_t pos;
5470
5471 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5472 struct htx_blk *blk = htx_get_blk(htx, pos);
5473 enum htx_blk_type type = htx_get_blk_type(blk);
5474 struct ist n, v;
5475
5476 if (type == HTX_BLK_EOH)
5477 break;
5478 if (type != HTX_BLK_HDR)
5479 continue;
5480
5481 n = htx_get_blk_name(htx, blk);
5482
5483 for (h = cap_hdr; h; h = h->next) {
5484 if (h->namelen && (h->namelen == n.len) &&
5485 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5486 if (cap[h->index] == NULL)
5487 cap[h->index] =
5488 pool_alloc(h->pool);
5489
5490 if (cap[h->index] == NULL) {
5491 ha_alert("HTTP capture : out of memory.\n");
5492 break;
5493 }
5494
5495 v = htx_get_blk_value(htx, blk);
5496 if (v.len > h->len)
5497 v.len = h->len;
5498
5499 memcpy(cap[h->index], v.ptr, v.len);
5500 cap[h->index][v.len]=0;
5501 }
5502 }
5503 }
5504}
5505
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005506/* Delete a value in a header between delimiters <from> and <next>. The header
5507 * itself is delimited by <start> and <end> pointers. The number of characters
5508 * displaced is returned, and the pointer to the first delimiter is updated if
5509 * required. The function tries as much as possible to respect the following
5510 * principles :
5511 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5512 * in which case <next> is simply removed
5513 * - set exactly one space character after the new first delimiter, unless there
5514 * are not enough characters in the block being moved to do so.
5515 * - remove unneeded spaces before the previous delimiter and after the new
5516 * one.
5517 *
5518 * It is the caller's responsibility to ensure that :
5519 * - <from> points to a valid delimiter or <start> ;
5520 * - <next> points to a valid delimiter or <end> ;
5521 * - there are non-space chars before <from>.
5522 */
5523static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5524{
5525 char *prev = *from;
5526
5527 if (prev == start) {
5528 /* We're removing the first value. eat the semicolon, if <next>
5529 * is lower than <end> */
5530 if (next < end)
5531 next++;
5532
5533 while (next < end && HTTP_IS_SPHT(*next))
5534 next++;
5535 }
5536 else {
5537 /* Remove useless spaces before the old delimiter. */
5538 while (HTTP_IS_SPHT(*(prev-1)))
5539 prev--;
5540 *from = prev;
5541
5542 /* copy the delimiter and if possible a space if we're
5543 * not at the end of the line.
5544 */
5545 if (next < end) {
5546 *prev++ = *next++;
5547 if (prev + 1 < next)
5548 *prev++ = ' ';
5549 while (next < end && HTTP_IS_SPHT(*next))
5550 next++;
5551 }
5552 }
5553 memmove(prev, next, end - next);
5554 return (prev - next);
5555}
5556
Christopher Faulet0f226952018-10-22 09:29:56 +02005557
5558/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005559 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005560 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005561static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005562{
5563 struct ist dst = ist2(str, 0);
5564
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005565 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005566 goto end;
5567 if (dst.len + 1 > len)
5568 goto end;
5569 dst.ptr[dst.len++] = ' ';
5570
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005571 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005572 goto end;
5573 if (dst.len + 1 > len)
5574 goto end;
5575 dst.ptr[dst.len++] = ' ';
5576
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005577 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005578 end:
5579 return dst.len;
5580}
5581
Christopher Fauletf0523542018-10-24 11:06:58 +02005582/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005583 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005584 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005586{
5587 struct ist dst = ist2(str, 0);
5588
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005589 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005590 goto end;
5591 if (dst.len + 1 > len)
5592 goto end;
5593 dst.ptr[dst.len++] = ' ';
5594
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005595 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005596 goto end;
5597 if (dst.len + 1 > len)
5598 goto end;
5599 dst.ptr[dst.len++] = ' ';
5600
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005601 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005602 end:
5603 return dst.len;
5604}
5605
5606
Christopher Faulet0f226952018-10-22 09:29:56 +02005607/*
5608 * Print a debug line with a start line.
5609 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005610static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005611{
5612 struct session *sess = strm_sess(s);
5613 int max;
5614
5615 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5616 dir,
5617 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5618 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5619
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005620 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005621 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005622 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005623 trash.area[trash.data++] = ' ';
5624
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005625 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005626 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005628 trash.area[trash.data++] = ' ';
5629
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005631 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005632 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005633 trash.area[trash.data++] = '\n';
5634
5635 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5636}
5637
5638/*
5639 * Print a debug line with a header.
5640 */
5641static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5642{
5643 struct session *sess = strm_sess(s);
5644 int max;
5645
5646 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5647 dir,
5648 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5649 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5650
5651 max = n.len;
5652 UBOUND(max, trash.size - trash.data - 3);
5653 chunk_memcat(&trash, n.ptr, max);
5654 trash.area[trash.data++] = ':';
5655 trash.area[trash.data++] = ' ';
5656
5657 max = v.len;
5658 UBOUND(max, trash.size - trash.data - 1);
5659 chunk_memcat(&trash, v.ptr, max);
5660 trash.area[trash.data++] = '\n';
5661
5662 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5663}
5664
5665
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005666__attribute__((constructor))
5667static void __htx_protocol_init(void)
5668{
5669}
5670
5671
5672/*
5673 * Local variables:
5674 * c-indent-level: 8
5675 * c-basic-offset: 8
5676 * End:
5677 */