blob: 2ec1dc4d9d12ed283dad7e1d351f7bfb90889734 [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 Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
412 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
413 * only change if both the request and the config reference something else.
414 * Option httpclose by itself sets tunnel mode where headers are mangled.
415 * However, if another mode is set, it will affect it (eg: server-close/
416 * keep-alive + httpclose = close). Note that we avoid to redo the same work
417 * if FE and BE have the same settings (common). The method consists in
418 * checking if options changed between the two calls (implying that either
419 * one is non-null, or one of them is non-null and we are there for the first
420 * time.
421 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200422 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200423 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200424
425 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200426 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 req->analysers |= AN_REQ_HTTP_BODY;
428
429 /*
430 * RFC7234#4:
431 * A cache MUST write through requests with methods
432 * that are unsafe (Section 4.2.1 of [RFC7231]) to
433 * the origin server; i.e., a cache is not allowed
434 * to generate a reply to such a request before
435 * having forwarded the request and having received
436 * a corresponding response.
437 *
438 * RFC7231#4.2.1:
439 * Of the request methods defined by this
440 * specification, the GET, HEAD, OPTIONS, and TRACE
441 * methods are defined to be safe.
442 */
443 if (likely(txn->meth == HTTP_METH_GET ||
444 txn->meth == HTTP_METH_HEAD ||
445 txn->meth == HTTP_METH_OPTIONS ||
446 txn->meth == HTTP_METH_TRACE))
447 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
448
449 /* end of job, return OK */
450 req->analysers &= ~an_bit;
451 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200452
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 return 1;
454
455 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200456 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200457 txn->req.err_state = txn->req.msg_state;
458 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100459 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100460 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200461 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100462 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200463
464 return_prx_cond:
465 if (!(s->flags & SF_ERR_MASK))
466 s->flags |= SF_ERR_PRXCOND;
467 if (!(s->flags & SF_FINST_MASK))
468 s->flags |= SF_FINST_R;
469
470 req->analysers &= AN_REQ_FLT_END;
471 req->analyse_exp = TICK_ETERNITY;
472 return 0;
473}
474
475
476/* This stream analyser runs all HTTP request processing which is common to
477 * frontends and backends, which means blocking ACLs, filters, connection-close,
478 * reqadd, stats and redirects. This is performed for the designated proxy.
479 * It returns 1 if the processing can continue on next analysers, or zero if it
480 * either needs more data or wants to immediately abort the request (eg: deny,
481 * error, ...).
482 */
483int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
484{
485 struct session *sess = s->sess;
486 struct http_txn *txn = s->txn;
487 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200489 struct redirect_rule *rule;
490 struct cond_wordlist *wl;
491 enum rule_result verdict;
492 int deny_status = HTTP_ERR_403;
493 struct connection *conn = objt_conn(sess->origin);
494
495 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
496 /* we need more data */
497 goto return_prx_yield;
498 }
499
500 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
501 now_ms, __FUNCTION__,
502 s,
503 req,
504 req->rex, req->wex,
505 req->flags,
506 ci_data(req),
507 req->analysers);
508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100509 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200510
Christopher Faulete0768eb2018-10-03 16:38:02 +0200511 /* just in case we have some per-backend tracking */
512 stream_inc_be_http_req_ctr(s);
513
514 /* evaluate http-request rules */
515 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200516 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200517
518 switch (verdict) {
519 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
520 goto return_prx_yield;
521
522 case HTTP_RULE_RES_CONT:
523 case HTTP_RULE_RES_STOP: /* nothing to do */
524 break;
525
526 case HTTP_RULE_RES_DENY: /* deny or tarpit */
527 if (txn->flags & TX_CLTARPIT)
528 goto tarpit;
529 goto deny;
530
531 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
532 goto return_prx_cond;
533
534 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
535 goto done;
536
537 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
538 goto return_bad_req;
539 }
540 }
541
542 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
543 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200544 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 ctx.blk = NULL;
547 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
548 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
552
553 /* OK at this stage, we know that the request was accepted according to
554 * the http-request rules, we can check for the stats. Note that the
555 * URI is detected *before* the req* rules in order not to be affected
556 * by a possible reqrep, while they are processed *after* so that a
557 * reqdeny can still block them. This clearly needs to change in 1.6!
558 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200559 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100561 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200562 txn->status = 500;
563 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200565
566 if (!(s->flags & SF_ERR_MASK))
567 s->flags |= SF_ERR_RESOURCE;
568 goto return_prx_cond;
569 }
570
571 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200572 htx_handle_stats(s, req);
573 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200574 /* not all actions implemented: deny, allow, auth */
575
576 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
577 goto deny;
578
579 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
580 goto return_prx_cond;
581 }
582
583 /* evaluate the req* rules except reqadd */
584 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200585 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200586 goto return_bad_req;
587
588 if (txn->flags & TX_CLDENY)
589 goto deny;
590
591 if (txn->flags & TX_CLTARPIT) {
592 deny_status = HTTP_ERR_500;
593 goto tarpit;
594 }
595 }
596
597 /* add request headers from the rule sets in the same order */
598 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (wl->cond) {
601 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
602 ret = acl_pass(ret);
603 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
604 ret = !ret;
605 if (!ret)
606 continue;
607 }
608
Christopher Fauletff2759f2018-10-24 11:13:16 +0200609 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
610 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 goto return_bad_req;
612 }
613
Christopher Faulet2571bc62019-03-01 11:44:26 +0100614 /* Proceed with the applets now. */
615 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200616 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100617 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100619 if (htx_handle_expect_hdr(s, htx, msg) == -1)
620 goto return_bad_req;
621
Christopher Faulete0768eb2018-10-03 16:38:02 +0200622 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
623 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
624 if (!(s->flags & SF_FINST_MASK))
625 s->flags |= SF_FINST_R;
626
627 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
628 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
629 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
630 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100631
632 req->flags |= CF_SEND_DONTWAIT;
633 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto done;
635 }
636
637 /* check whether we have some ACLs set to redirect this request */
638 list_for_each_entry(rule, &px->redirect_rules, list) {
639 if (rule->cond) {
640 int ret;
641
642 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
643 ret = acl_pass(ret);
644 if (rule->cond->pol == ACL_COND_UNLESS)
645 ret = !ret;
646 if (!ret)
647 continue;
648 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200649 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200650 goto return_bad_req;
651 goto done;
652 }
653
654 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
655 * If this happens, then the data will not come immediately, so we must
656 * send all what we have without waiting. Note that due to the small gain
657 * in waiting for the body of the request, it's easier to simply put the
658 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
659 * itself once used.
660 */
661 req->flags |= CF_SEND_DONTWAIT;
662
663 done: /* done with this analyser, continue with next ones that the calling
664 * points will have set, if any.
665 */
666 req->analyse_exp = TICK_ETERNITY;
667 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
668 req->analysers &= ~an_bit;
669 return 1;
670
671 tarpit:
672 /* Allow cookie logging
673 */
674 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200675 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200676
677 /* When a connection is tarpitted, we use the tarpit timeout,
678 * which may be the same as the connect timeout if unspecified.
679 * If unset, then set it to zero because we really want it to
680 * eventually expire. We build the tarpit as an analyser.
681 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100682 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683
684 /* wipe the request out so that we can drop the connection early
685 * if the client closes first.
686 */
687 channel_dont_connect(req);
688
689 txn->status = http_err_codes[deny_status];
690
691 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
692 req->analysers |= AN_REQ_HTTP_TARPIT;
693 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
694 if (!req->analyse_exp)
695 req->analyse_exp = tick_add(now_ms, 0);
696 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100697 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100699 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100701 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702 goto done_without_exp;
703
704 deny: /* this request was blocked (denied) */
705
706 /* Allow cookie logging
707 */
708 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200709 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710
711 txn->flags |= TX_CLDENY;
712 txn->status = http_err_codes[deny_status];
713 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100714 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100716 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100718 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200719 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100720 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200721 goto return_prx_cond;
722
723 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200724 txn->req.err_state = txn->req.msg_state;
725 txn->req.msg_state = HTTP_MSG_ERROR;
726 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100727 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200728
Olivier Houcharda798bf52019-03-08 18:52:00 +0100729 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200730 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100731 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200732
733 return_prx_cond:
734 if (!(s->flags & SF_ERR_MASK))
735 s->flags |= SF_ERR_PRXCOND;
736 if (!(s->flags & SF_FINST_MASK))
737 s->flags |= SF_FINST_R;
738
739 req->analysers &= AN_REQ_FLT_END;
740 req->analyse_exp = TICK_ETERNITY;
741 return 0;
742
743 return_prx_yield:
744 channel_dont_connect(req);
745 return 0;
746}
747
748/* This function performs all the processing enabled for the current request.
749 * It returns 1 if the processing can continue on next analysers, or zero if it
750 * needs more data, encounters an error, or wants to immediately abort the
751 * request. It relies on buffers flags, and updates s->req.analysers.
752 */
753int htx_process_request(struct stream *s, struct channel *req, int an_bit)
754{
755 struct session *sess = s->sess;
756 struct http_txn *txn = s->txn;
757 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200758 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200759 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
760
761 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
762 /* we need more data */
763 channel_dont_connect(req);
764 return 0;
765 }
766
767 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
768 now_ms, __FUNCTION__,
769 s,
770 req,
771 req->rex, req->wex,
772 req->flags,
773 ci_data(req),
774 req->analysers);
775
776 /*
777 * Right now, we know that we have processed the entire headers
778 * and that unwanted requests have been filtered out. We can do
779 * whatever we want with the remaining request. Also, now we
780 * may have separate values for ->fe, ->be.
781 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100782 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 /*
785 * If HTTP PROXY is set we simply get remote server address parsing
786 * incoming request. Note that this requires that a connection is
787 * allocated on the server side.
788 */
789 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
790 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100791 struct htx_sl *sl;
792 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793
794 /* Note that for now we don't reuse existing proxy connections */
795 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
796 txn->req.err_state = txn->req.msg_state;
797 txn->req.msg_state = HTTP_MSG_ERROR;
798 txn->status = 500;
799 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100800 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200801
802 if (!(s->flags & SF_ERR_MASK))
803 s->flags |= SF_ERR_RESOURCE;
804 if (!(s->flags & SF_FINST_MASK))
805 s->flags |= SF_FINST_R;
806
807 return 0;
808 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200809 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100810 uri = htx_sl_req_uri(sl);
811 path = http_get_path(uri);
812 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 goto return_bad_req;
814
815 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200816 * uri.ptr and path.ptr (excluded). If it was not found, we need
817 * to replace from all the uri by a single "/".
818 *
819 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100820 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200821 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200822 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100823 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200824 }
825
826 /*
827 * 7: Now we can work with the cookies.
828 * Note that doing so might move headers in the request, but
829 * the fields will stay coherent and the URI will not move.
830 * This should only be performed in the backend.
831 */
832 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100833 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834
835 /* add unique-id if "header-unique-id" is specified */
836
837 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
838 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
839 goto return_bad_req;
840 s->unique_id[0] = '\0';
841 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
842 }
843
844 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200845 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
846 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
847
848 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200850 }
851
852 /*
853 * 9: add X-Forwarded-For if either the frontend or the backend
854 * asks for it.
855 */
856 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200857 struct http_hdr_ctx ctx = { .blk = NULL };
858 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
859 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
860
Christopher Faulete0768eb2018-10-03 16:38:02 +0200861 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863 /* The header is set to be added only if none is present
864 * and we found it, so don't do anything.
865 */
866 }
867 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
868 /* Add an X-Forwarded-For header unless the source IP is
869 * in the 'except' network range.
870 */
871 if ((!sess->fe->except_mask.s_addr ||
872 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
873 != sess->fe->except_net.s_addr) &&
874 (!s->be->except_mask.s_addr ||
875 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
876 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878
879 /* Note: we rely on the backend to get the header name to be used for
880 * x-forwarded-for, because the header is really meant for the backends.
881 * However, if the backend did not specify any option, we have to rely
882 * on the frontend's header name.
883 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200884 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
885 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200886 goto return_bad_req;
887 }
888 }
889 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
890 /* FIXME: for the sake of completeness, we should also support
891 * 'except' here, although it is mostly useless in this case.
892 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200893 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200894
Christopher Faulete0768eb2018-10-03 16:38:02 +0200895 inet_ntop(AF_INET6,
896 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
897 pn, sizeof(pn));
898
899 /* Note: we rely on the backend to get the header name to be used for
900 * x-forwarded-for, because the header is really meant for the backends.
901 * However, if the backend did not specify any option, we have to rely
902 * on the frontend's header name.
903 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200904 chunk_printf(&trash, "%s", pn);
905 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200906 goto return_bad_req;
907 }
908 }
909
910 /*
911 * 10: add X-Original-To if either the frontend or the backend
912 * asks for it.
913 */
914 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
915
916 /* FIXME: don't know if IPv6 can handle that case too. */
917 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
918 /* Add an X-Original-To header unless the destination IP is
919 * in the 'except' network range.
920 */
921 conn_get_to_addr(cli_conn);
922
923 if (cli_conn->addr.to.ss_family == AF_INET &&
924 ((!sess->fe->except_mask_to.s_addr ||
925 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
926 != sess->fe->except_to.s_addr) &&
927 (!s->be->except_mask_to.s_addr ||
928 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
929 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200930 struct ist hdr;
931 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932
933 /* Note: we rely on the backend to get the header name to be used for
934 * x-original-to, because the header is really meant for the backends.
935 * However, if the backend did not specify any option, we have to rely
936 * on the frontend's header name.
937 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200938 if (s->be->orgto_hdr_len)
939 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
940 else
941 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200943 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
944 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 goto return_bad_req;
946 }
947 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 }
949
Christopher Faulete0768eb2018-10-03 16:38:02 +0200950 /* If we have no server assigned yet and we're balancing on url_param
951 * with a POST request, we may be interested in checking the body for
952 * that parameter. This will be done in another analyser.
953 */
954 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100955 s->txn->meth == HTTP_METH_POST &&
956 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 channel_dont_connect(req);
958 req->analysers |= AN_REQ_HTTP_BODY;
959 }
960
961 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
962 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100963
Christopher Faulete0768eb2018-10-03 16:38:02 +0200964 /* We expect some data from the client. Unless we know for sure
965 * we already have a full request, we have to re-enable quick-ack
966 * in case we previously disabled it, otherwise we might cause
967 * the client to delay further data.
968 */
969 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200970 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100971 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200972
973 /*************************************************************
974 * OK, that's finished for the headers. We have done what we *
975 * could. Let's switch to the DATA state. *
976 ************************************************************/
977 req->analyse_exp = TICK_ETERNITY;
978 req->analysers &= ~an_bit;
979
980 s->logs.tv_request = now;
981 /* OK let's go on with the BODY now */
982 return 1;
983
984 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200985 txn->req.err_state = txn->req.msg_state;
986 txn->req.msg_state = HTTP_MSG_ERROR;
987 txn->status = 400;
988 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100989 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200990
Olivier Houcharda798bf52019-03-08 18:52:00 +0100991 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200992 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100993 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200994
995 if (!(s->flags & SF_ERR_MASK))
996 s->flags |= SF_ERR_PRXCOND;
997 if (!(s->flags & SF_FINST_MASK))
998 s->flags |= SF_FINST_R;
999 return 0;
1000}
1001
1002/* This function is an analyser which processes the HTTP tarpit. It always
1003 * returns zero, at the beginning because it prevents any other processing
1004 * from occurring, and at the end because it terminates the request.
1005 */
1006int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1007{
1008 struct http_txn *txn = s->txn;
1009
1010 /* This connection is being tarpitted. The CLIENT side has
1011 * already set the connect expiration date to the right
1012 * timeout. We just have to check that the client is still
1013 * there and that the timeout has not expired.
1014 */
1015 channel_dont_connect(req);
1016 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1017 !tick_is_expired(req->analyse_exp, now_ms))
1018 return 0;
1019
1020 /* We will set the queue timer to the time spent, just for
1021 * logging purposes. We fake a 500 server error, so that the
1022 * attacker will not suspect his connection has been tarpitted.
1023 * It will not cause trouble to the logs because we can exclude
1024 * the tarpitted connections by filtering on the 'PT' status flags.
1025 */
1026 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1027
1028 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001029 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001030
1031 req->analysers &= AN_REQ_FLT_END;
1032 req->analyse_exp = TICK_ETERNITY;
1033
1034 if (!(s->flags & SF_ERR_MASK))
1035 s->flags |= SF_ERR_PRXCOND;
1036 if (!(s->flags & SF_FINST_MASK))
1037 s->flags |= SF_FINST_T;
1038 return 0;
1039}
1040
1041/* This function is an analyser which waits for the HTTP request body. It waits
1042 * for either the buffer to be full, or the full advertised contents to have
1043 * reached the buffer. It must only be called after the standard HTTP request
1044 * processing has occurred, because it expects the request to be parsed and will
1045 * look for the Expect header. It may send a 100-Continue interim response. It
1046 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1047 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1048 * needs to read more data, or 1 once it has completed its analysis.
1049 */
1050int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1051{
1052 struct session *sess = s->sess;
1053 struct http_txn *txn = s->txn;
1054 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001055 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001056
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057
1058 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1059 now_ms, __FUNCTION__,
1060 s,
1061 req,
1062 req->rex, req->wex,
1063 req->flags,
1064 ci_data(req),
1065 req->analysers);
1066
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001067 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068
Willy Tarreau4236f032019-03-05 10:43:32 +01001069 if (htx->flags & HTX_FL_PARSING_ERROR)
1070 goto return_bad_req;
1071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 if (msg->msg_state < HTTP_MSG_BODY)
1073 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001074
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075 /* We have to parse the HTTP request body to find any required data.
1076 * "balance url_param check_post" should have been the only way to get
1077 * into this. We were brought here after HTTP header analysis, so all
1078 * related structures are ready.
1079 */
1080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001082 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1083 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 }
1085
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001086 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1089 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001092 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 goto http_end;
1094
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1097 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001098 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001099
1100 if (!(s->flags & SF_ERR_MASK))
1101 s->flags |= SF_ERR_CLITO;
1102 if (!(s->flags & SF_FINST_MASK))
1103 s->flags |= SF_FINST_D;
1104 goto return_err_msg;
1105 }
1106
1107 /* we get here if we need to wait for more data */
1108 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1109 /* Not enough data. We'll re-use the http-request
1110 * timeout here. Ideally, we should set the timeout
1111 * relative to the accept() date. We just set the
1112 * request timeout once at the beginning of the
1113 * request.
1114 */
1115 channel_dont_connect(req);
1116 if (!tick_isset(req->analyse_exp))
1117 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1118 return 0;
1119 }
1120
1121 http_end:
1122 /* The situation will not evolve, so let's give up on the analysis. */
1123 s->logs.tv_request = now; /* update the request timer to reflect full request */
1124 req->analysers &= ~an_bit;
1125 req->analyse_exp = TICK_ETERNITY;
1126 return 1;
1127
1128 return_bad_req: /* let's centralize all bad requests */
1129 txn->req.err_state = txn->req.msg_state;
1130 txn->req.msg_state = HTTP_MSG_ERROR;
1131 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001132 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001133
1134 if (!(s->flags & SF_ERR_MASK))
1135 s->flags |= SF_ERR_PRXCOND;
1136 if (!(s->flags & SF_FINST_MASK))
1137 s->flags |= SF_FINST_R;
1138
1139 return_err_msg:
1140 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001141 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001142 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001143 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001144 return 0;
1145}
1146
1147/* This function is an analyser which forwards request body (including chunk
1148 * sizes if any). It is called as soon as we must forward, even if we forward
1149 * zero byte. The only situation where it must not be called is when we're in
1150 * tunnel mode and we want to forward till the close. It's used both to forward
1151 * remaining data and to resync after end of body. It expects the msg_state to
1152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1153 * read more data, or 1 once we can go on with next request or end the stream.
1154 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1155 * bytes of pending data + the headers if not already done.
1156 */
1157int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1158{
1159 struct session *sess = s->sess;
1160 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001161 struct http_msg *msg = &txn->req;
1162 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001163 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001164 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001165
1166 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1167 now_ms, __FUNCTION__,
1168 s,
1169 req,
1170 req->rex, req->wex,
1171 req->flags,
1172 ci_data(req),
1173 req->analysers);
1174
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001175 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176
1177 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1178 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1179 /* Output closed while we were sending data. We must abort and
1180 * wake the other side up.
1181 */
1182 msg->err_state = msg->msg_state;
1183 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001184 htx_end_request(s);
1185 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186 return 1;
1187 }
1188
1189 /* Note that we don't have to send 100-continue back because we don't
1190 * need the data to complete our job, and it's up to the server to
1191 * decide whether to return 100, 417 or anything else in return of
1192 * an "Expect: 100-continue" header.
1193 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001194 if (msg->msg_state == HTTP_MSG_BODY)
1195 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001196
1197 /* Some post-connect processing might want us to refrain from starting to
1198 * forward data. Currently, the only reason for this is "balance url_param"
1199 * whichs need to parse/process the request after we've enabled forwarding.
1200 */
1201 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1202 if (!(s->res.flags & CF_READ_ATTACHED)) {
1203 channel_auto_connect(req);
1204 req->flags |= CF_WAKE_CONNECT;
1205 channel_dont_close(req); /* don't fail on early shutr */
1206 goto waiting;
1207 }
1208 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1209 }
1210
1211 /* in most states, we should abort in case of early close */
1212 channel_auto_close(req);
1213
1214 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001215 if (req->to_forward == CHN_INFINITE_FORWARD) {
1216 if (req->flags & (CF_SHUTR|CF_EOI)) {
1217 msg->msg_state = HTTP_MSG_DONE;
1218 req->to_forward = 0;
1219 goto done;
1220 }
1221 }
1222 else {
1223 /* We can't process the buffer's contents yet */
1224 req->flags |= CF_WAKE_WRITE;
1225 goto missing_data_or_waiting;
1226 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001227 }
1228
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 if (msg->msg_state >= HTTP_MSG_DONE)
1230 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001231 /* Forward input data. We get it by removing all outgoing data not
1232 * forwarded yet from HTX data size. If there are some data filters, we
1233 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001234 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001235 if (HAS_REQ_DATA_FILTERS(s)) {
1236 ret = flt_http_payload(s, msg, htx->data);
1237 if (ret < 0)
1238 goto return_bad_req;
1239 c_adv(req, ret);
1240 if (htx->data != co_data(req) || htx->extra)
1241 goto missing_data_or_waiting;
1242 }
1243 else {
1244 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001245 if (msg->flags & HTTP_MSGF_XFER_LEN)
1246 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001247 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001248
Christopher Faulet9768c262018-10-22 09:34:31 +02001249 /* Check if the end-of-message is reached and if so, switch the message
1250 * in HTTP_MSG_DONE state.
1251 */
1252 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1253 goto missing_data_or_waiting;
1254
1255 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001256 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001257
1258 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001259 /* other states, DONE...TUNNEL */
1260 /* we don't want to forward closes on DONE except in tunnel mode. */
1261 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1262 channel_dont_close(req);
1263
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001264 if (HAS_REQ_DATA_FILTERS(s)) {
1265 ret = flt_http_end(s, msg);
1266 if (ret <= 0) {
1267 if (!ret)
1268 goto missing_data_or_waiting;
1269 goto return_bad_req;
1270 }
1271 }
1272
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001275 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1277 if (req->flags & CF_SHUTW) {
1278 /* request errors are most likely due to the
1279 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001280 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 goto return_bad_req;
1283 }
1284 return 1;
1285 }
1286
1287 /* If "option abortonclose" is set on the backend, we want to monitor
1288 * the client's connection and forward any shutdown notification to the
1289 * server, which will decide whether to close or to go on processing the
1290 * request. We only do that in tunnel mode, and not in other modes since
1291 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001292 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001293 channel_auto_read(req);
1294 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1295 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1296 s->si[1].flags |= SI_FL_NOLINGER;
1297 channel_auto_close(req);
1298 }
1299 else if (s->txn->meth == HTTP_METH_POST) {
1300 /* POST requests may require to read extra CRLF sent by broken
1301 * browsers and which could cause an RST to be sent upon close
1302 * on some systems (eg: Linux). */
1303 channel_auto_read(req);
1304 }
1305 return 0;
1306
1307 missing_data_or_waiting:
1308 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001309 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1310 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001311
1312 waiting:
1313 /* waiting for the last bits to leave the buffer */
1314 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316
Christopher Faulet47365272018-10-31 17:40:50 +01001317 if (htx->flags & HTX_FL_PARSING_ERROR)
1318 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001319
Christopher Faulete0768eb2018-10-03 16:38:02 +02001320 /* When TE: chunked is used, we need to get there again to parse remaining
1321 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1322 * And when content-length is used, we never want to let the possible
1323 * shutdown be forwarded to the other side, as the state machine will
1324 * take care of it once the client responds. It's also important to
1325 * prevent TIME_WAITs from accumulating on the backend side, and for
1326 * HTTP/2 where the last frame comes with a shutdown.
1327 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001328 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 channel_dont_close(req);
1330
1331 /* We know that more data are expected, but we couldn't send more that
1332 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1333 * system knows it must not set a PUSH on this first part. Interactive
1334 * modes are already handled by the stream sock layer. We must not do
1335 * this in content-length mode because it could present the MSG_MORE
1336 * flag with the last block of forwarded data, which would cause an
1337 * additional delay to be observed by the receiver.
1338 */
1339 if (msg->flags & HTTP_MSGF_TE_CHNK)
1340 req->flags |= CF_EXPECT_MORE;
1341
1342 return 0;
1343
Christopher Faulet93e02d82019-03-08 14:18:50 +01001344 return_cli_abort:
1345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1346 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1347 if (objt_server(s->target))
1348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1349 if (!(s->flags & SF_ERR_MASK))
1350 s->flags |= SF_ERR_CLICL;
1351 status = 400;
1352 goto return_error;
1353
1354 return_srv_abort:
1355 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1356 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1357 if (objt_server(s->target))
1358 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1359 if (!(s->flags & SF_ERR_MASK))
1360 s->flags |= SF_ERR_SRVCL;
1361 status = 502;
1362 goto return_error;
1363
1364 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001365 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001367 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001369 s->flags |= SF_ERR_CLICL;
1370 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371
Christopher Faulet93e02d82019-03-08 14:18:50 +01001372 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 txn->req.err_state = txn->req.msg_state;
1374 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001375 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001377 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001379 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001380 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 }
1382 req->analysers &= AN_REQ_FLT_END;
1383 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 +01001384 if (!(s->flags & SF_FINST_MASK))
1385 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 return 0;
1387}
1388
1389/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1390 * processing can continue on next analysers, or zero if it either needs more
1391 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1392 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1393 * when it has nothing left to do, and may remove any analyser when it wants to
1394 * abort.
1395 */
1396int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1397{
Christopher Faulet9768c262018-10-22 09:34:31 +02001398 /*
1399 * We will analyze a complete HTTP response to check the its syntax.
1400 *
1401 * Once the start line and all headers are received, we may perform a
1402 * capture of the error (if any), and we will set a few fields. We also
1403 * logging and finally headers capture.
1404 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001405 struct session *sess = s->sess;
1406 struct http_txn *txn = s->txn;
1407 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001408 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001409 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001410 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001411 int n;
1412
1413 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1414 now_ms, __FUNCTION__,
1415 s,
1416 rep,
1417 rep->rex, rep->wex,
1418 rep->flags,
1419 ci_data(rep),
1420 rep->analysers);
1421
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001422 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001423
Willy Tarreau4236f032019-03-05 10:43:32 +01001424 /* Parsing errors are caught here */
1425 if (htx->flags & HTX_FL_PARSING_ERROR)
1426 goto return_bad_res;
1427
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428 /*
1429 * Now we quickly check if we have found a full valid response.
1430 * If not so, we check the FD and buffer states before leaving.
1431 * A full response is indicated by the fact that we have seen
1432 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1433 * responses are checked first.
1434 *
1435 * Depending on whether the client is still there or not, we
1436 * may send an error response back or not. Note that normally
1437 * we should only check for HTTP status there, and check I/O
1438 * errors somewhere else.
1439 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001440 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001441 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001442 * First catch invalid response because of a parsing error or
1443 * because only part of headers have been transfered.
1444 * Multiplexers have the responsibility to emit all headers at
1445 * once. We must be sure to have forwarded all outgoing data
1446 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001447 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001448 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001449 goto return_bad_res;
1450
Christopher Faulet9768c262018-10-22 09:34:31 +02001451 /* 1: have we encountered a read error ? */
1452 if (rep->flags & CF_READ_ERROR) {
1453 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 goto abort_keep_alive;
1455
Olivier Houcharda798bf52019-03-08 18:52:00 +01001456 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001458 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001459 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 }
1461
Christopher Faulete0768eb2018-10-03 16:38:02 +02001462 rep->analysers &= AN_RES_FLT_END;
1463 txn->status = 502;
1464
1465 /* Check to see if the server refused the early data.
1466 * If so, just send a 425
1467 */
1468 if (objt_cs(s->si[1].end)) {
1469 struct connection *conn = objt_cs(s->si[1].end)->conn;
1470
1471 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1472 txn->status = 425;
1473 }
1474
1475 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001476 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477
1478 if (!(s->flags & SF_ERR_MASK))
1479 s->flags |= SF_ERR_SRVCL;
1480 if (!(s->flags & SF_FINST_MASK))
1481 s->flags |= SF_FINST_H;
1482 return 0;
1483 }
1484
Christopher Faulet9768c262018-10-22 09:34:31 +02001485 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001486 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001487 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001488 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001489 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001490 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001491 }
1492
Christopher Faulete0768eb2018-10-03 16:38:02 +02001493 rep->analysers &= AN_RES_FLT_END;
1494 txn->status = 504;
1495 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001496 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001497
1498 if (!(s->flags & SF_ERR_MASK))
1499 s->flags |= SF_ERR_SRVTO;
1500 if (!(s->flags & SF_FINST_MASK))
1501 s->flags |= SF_FINST_H;
1502 return 0;
1503 }
1504
Christopher Faulet9768c262018-10-22 09:34:31 +02001505 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001507 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1508 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001510 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511
1512 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001514 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515
1516 if (!(s->flags & SF_ERR_MASK))
1517 s->flags |= SF_ERR_CLICL;
1518 if (!(s->flags & SF_FINST_MASK))
1519 s->flags |= SF_FINST_H;
1520
1521 /* process_stream() will take care of the error */
1522 return 0;
1523 }
1524
Christopher Faulet9768c262018-10-22 09:34:31 +02001525 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001527 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 goto abort_keep_alive;
1529
Olivier Houcharda798bf52019-03-08 18:52:00 +01001530 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001532 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001533 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 rep->analysers &= AN_RES_FLT_END;
1537 txn->status = 502;
1538 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001539 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540
1541 if (!(s->flags & SF_ERR_MASK))
1542 s->flags |= SF_ERR_SRVCL;
1543 if (!(s->flags & SF_FINST_MASK))
1544 s->flags |= SF_FINST_H;
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001550 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 goto abort_keep_alive;
1552
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555
1556 if (!(s->flags & SF_ERR_MASK))
1557 s->flags |= SF_ERR_CLICL;
1558 if (!(s->flags & SF_FINST_MASK))
1559 s->flags |= SF_FINST_H;
1560
1561 /* process_stream() will take care of the error */
1562 return 0;
1563 }
1564
1565 channel_dont_close(rep);
1566 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1567 return 0;
1568 }
1569
1570 /* More interesting part now : we know that we have a complete
1571 * response which at least looks like HTTP. We have an indicator
1572 * of each header's length, so we can parse them quickly.
1573 */
1574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001576 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577
Christopher Faulet9768c262018-10-22 09:34:31 +02001578 /* 0: we might have to print this header in debug mode */
1579 if (unlikely((global.mode & MODE_DEBUG) &&
1580 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1581 int32_t pos;
1582
Christopher Faulet03599112018-11-27 11:21:21 +01001583 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001584
1585 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1586 struct htx_blk *blk = htx_get_blk(htx, pos);
1587 enum htx_blk_type type = htx_get_blk_type(blk);
1588
1589 if (type == HTX_BLK_EOH)
1590 break;
1591 if (type != HTX_BLK_HDR)
1592 continue;
1593
1594 htx_debug_hdr("srvhdr", s,
1595 htx_get_blk_name(htx, blk),
1596 htx_get_blk_value(htx, blk));
1597 }
1598 }
1599
Christopher Faulet03599112018-11-27 11:21:21 +01001600 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001601 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001602 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001603 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001604 if (sl->flags & HTX_SL_F_XFER_LEN) {
1605 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001606 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001607 if (sl->flags & HTX_SL_F_BODYLESS)
1608 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001609 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001610
1611 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 if (n < 1 || n > 5)
1613 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001614
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 /* when the client triggers a 4xx from the server, it's most often due
1616 * to a missing object or permission. These events should be tracked
1617 * because if they happen often, it may indicate a brute force or a
1618 * vulnerability scan.
1619 */
1620 if (n == 4)
1621 stream_inc_http_err_ctr(s);
1622
1623 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001624 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626 /* Adjust server's health based on status code. Note: status codes 501
1627 * and 505 are triggered on demand by client request, so we must not
1628 * count them as server failures.
1629 */
1630 if (objt_server(s->target)) {
1631 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001632 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001633 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001634 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 }
1636
1637 /*
1638 * We may be facing a 100-continue response, or any other informational
1639 * 1xx response which is non-final, in which case this is not the right
1640 * response, and we're waiting for the next one. Let's allow this response
1641 * to go to the client and wait for the next one. There's an exception for
1642 * 101 which is used later in the code to switch protocols.
1643 */
1644 if (txn->status < 200 &&
1645 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001646 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 msg->msg_state = HTTP_MSG_RPBEFORE;
1649 txn->status = 0;
1650 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001651 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001652 }
1653
1654 /*
1655 * 2: check for cacheability.
1656 */
1657
1658 switch (txn->status) {
1659 case 200:
1660 case 203:
1661 case 204:
1662 case 206:
1663 case 300:
1664 case 301:
1665 case 404:
1666 case 405:
1667 case 410:
1668 case 414:
1669 case 501:
1670 break;
1671 default:
1672 /* RFC7231#6.1:
1673 * Responses with status codes that are defined as
1674 * cacheable by default (e.g., 200, 203, 204, 206,
1675 * 300, 301, 404, 405, 410, 414, and 501 in this
1676 * specification) can be reused by a cache with
1677 * heuristic expiration unless otherwise indicated
1678 * by the method definition or explicit cache
1679 * controls [RFC7234]; all other status codes are
1680 * not cacheable by default.
1681 */
1682 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1683 break;
1684 }
1685
1686 /*
1687 * 3: we may need to capture headers
1688 */
1689 s->logs.logwait &= ~LW_RESP;
1690 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001691 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692
Christopher Faulet9768c262018-10-22 09:34:31 +02001693 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1695 txn->status == 101)) {
1696 /* Either we've established an explicit tunnel, or we're
1697 * switching the protocol. In both cases, we're very unlikely
1698 * to understand the next protocols. We have to switch to tunnel
1699 * mode, so that we transfer the request and responses then let
1700 * this protocol pass unmodified. When we later implement specific
1701 * parsers for such protocols, we'll want to check the Upgrade
1702 * header which contains information about that protocol for
1703 * responses with status 101 (eg: see RFC2817 about TLS).
1704 */
1705 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 }
1707
Christopher Faulet61608322018-11-23 16:23:45 +01001708 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1709 * 407 (Proxy-Authenticate) responses and set the connection to private
1710 */
1711 srv_conn = cs_conn(objt_cs(s->si[1].end));
1712 if (srv_conn) {
1713 struct ist hdr;
1714 struct http_hdr_ctx ctx;
1715
1716 if (txn->status == 401)
1717 hdr = ist("WWW-Authenticate");
1718 else if (txn->status == 407)
1719 hdr = ist("Proxy-Authenticate");
1720 else
1721 goto end;
1722
1723 ctx.blk = NULL;
1724 while (http_find_header(htx, hdr, &ctx, 0)) {
1725 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1726 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1727 srv_conn->flags |= CO_FL_PRIVATE;
1728 }
1729 }
1730
1731 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001732 /* we want to have the response time before we start processing it */
1733 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1734
1735 /* end of job, return OK */
1736 rep->analysers &= ~an_bit;
1737 rep->analyse_exp = TICK_ETERNITY;
1738 channel_auto_close(rep);
1739 return 1;
1740
Christopher Faulet47365272018-10-31 17:40:50 +01001741 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001742 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001743 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001744 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001745 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001746 }
1747 txn->status = 502;
1748 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001749 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001750 rep->analysers &= AN_RES_FLT_END;
1751
1752 if (!(s->flags & SF_ERR_MASK))
1753 s->flags |= SF_ERR_PRXCOND;
1754 if (!(s->flags & SF_FINST_MASK))
1755 s->flags |= SF_FINST_H;
1756 return 0;
1757
Christopher Faulete0768eb2018-10-03 16:38:02 +02001758 abort_keep_alive:
1759 /* A keep-alive request to the server failed on a network error.
1760 * The client is required to retry. We need to close without returning
1761 * any other information so that the client retries.
1762 */
1763 txn->status = 0;
1764 rep->analysers &= AN_RES_FLT_END;
1765 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001766 s->logs.logwait = 0;
1767 s->logs.level = 0;
1768 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001769 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001770 return 0;
1771}
1772
1773/* This function performs all the processing enabled for the current response.
1774 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1775 * and updates s->res.analysers. It might make sense to explode it into several
1776 * other functions. It works like process_request (see indications above).
1777 */
1778int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1779{
1780 struct session *sess = s->sess;
1781 struct http_txn *txn = s->txn;
1782 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001783 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 struct proxy *cur_proxy;
1785 struct cond_wordlist *wl;
1786 enum rule_result ret = HTTP_RULE_RES_CONT;
1787
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001788 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1789 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001790
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1792 now_ms, __FUNCTION__,
1793 s,
1794 rep,
1795 rep->rex, rep->wex,
1796 rep->flags,
1797 ci_data(rep),
1798 rep->analysers);
1799
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001800 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001801
1802 /* The stats applet needs to adjust the Connection header but we don't
1803 * apply any filter there.
1804 */
1805 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1806 rep->analysers &= ~an_bit;
1807 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001808 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001809 }
1810
1811 /*
1812 * We will have to evaluate the filters.
1813 * As opposed to version 1.2, now they will be evaluated in the
1814 * filters order and not in the header order. This means that
1815 * each filter has to be validated among all headers.
1816 *
1817 * Filters are tried with ->be first, then with ->fe if it is
1818 * different from ->be.
1819 *
1820 * Maybe we are in resume condiion. In this case I choose the
1821 * "struct proxy" which contains the rule list matching the resume
1822 * pointer. If none of theses "struct proxy" match, I initialise
1823 * the process with the first one.
1824 *
1825 * In fact, I check only correspondance betwwen the current list
1826 * pointer and the ->fe rule list. If it doesn't match, I initialize
1827 * the loop with the ->be.
1828 */
1829 if (s->current_rule_list == &sess->fe->http_res_rules)
1830 cur_proxy = sess->fe;
1831 else
1832 cur_proxy = s->be;
1833 while (1) {
1834 struct proxy *rule_set = cur_proxy;
1835
1836 /* evaluate http-response rules */
1837 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001838 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001839
1840 if (ret == HTTP_RULE_RES_BADREQ)
1841 goto return_srv_prx_502;
1842
1843 if (ret == HTTP_RULE_RES_DONE) {
1844 rep->analysers &= ~an_bit;
1845 rep->analyse_exp = TICK_ETERNITY;
1846 return 1;
1847 }
1848 }
1849
1850 /* we need to be called again. */
1851 if (ret == HTTP_RULE_RES_YIELD) {
1852 channel_dont_close(rep);
1853 return 0;
1854 }
1855
1856 /* try headers filters */
1857 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001858 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1859 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001860 }
1861
1862 /* has the response been denied ? */
1863 if (txn->flags & TX_SVDENY) {
1864 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001865 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866
Olivier Houcharda798bf52019-03-08 18:52:00 +01001867 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1868 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001870 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 goto return_srv_prx_502;
1872 }
1873
1874 /* add response headers from the rule sets in the same order */
1875 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001876 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001877 if (txn->status < 200 && txn->status != 101)
1878 break;
1879 if (wl->cond) {
1880 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1881 ret = acl_pass(ret);
1882 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1883 ret = !ret;
1884 if (!ret)
1885 continue;
1886 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001887
1888 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1889 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890 goto return_bad_resp;
1891 }
1892
1893 /* check whether we're already working on the frontend */
1894 if (cur_proxy == sess->fe)
1895 break;
1896 cur_proxy = sess->fe;
1897 }
1898
1899 /* After this point, this anayzer can't return yield, so we can
1900 * remove the bit corresponding to this analyzer from the list.
1901 *
1902 * Note that the intermediate returns and goto found previously
1903 * reset the analyzers.
1904 */
1905 rep->analysers &= ~an_bit;
1906 rep->analyse_exp = TICK_ETERNITY;
1907
1908 /* OK that's all we can do for 1xx responses */
1909 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001910 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001911
1912 /*
1913 * Now check for a server cookie.
1914 */
1915 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001916 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001917
1918 /*
1919 * Check for cache-control or pragma headers if required.
1920 */
1921 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1922 check_response_for_cacheability(s, rep);
1923
1924 /*
1925 * Add server cookie in the response if needed
1926 */
1927 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1928 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1929 (!(s->flags & SF_DIRECT) ||
1930 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1931 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1932 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1933 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1934 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1935 !(s->flags & SF_IGNORE_PRST)) {
1936 /* the server is known, it's not the one the client requested, or the
1937 * cookie's last seen date needs to be refreshed. We have to
1938 * insert a set-cookie here, except if we want to insert only on POST
1939 * requests and this one isn't. Note that servers which don't have cookies
1940 * (eg: some backup servers) will return a full cookie removal request.
1941 */
1942 if (!objt_server(s->target)->cookie) {
1943 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001944 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945 s->be->cookie_name);
1946 }
1947 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001948 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001949
1950 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1951 /* emit last_date, which is mandatory */
1952 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1953 s30tob64((date.tv_sec+3) >> 2,
1954 trash.area + trash.data);
1955 trash.data += 5;
1956
1957 if (s->be->cookie_maxlife) {
1958 /* emit first_date, which is either the original one or
1959 * the current date.
1960 */
1961 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1962 s30tob64(txn->cookie_first_date ?
1963 txn->cookie_first_date >> 2 :
1964 (date.tv_sec+3) >> 2,
1965 trash.area + trash.data);
1966 trash.data += 5;
1967 }
1968 }
1969 chunk_appendf(&trash, "; path=/");
1970 }
1971
1972 if (s->be->cookie_domain)
1973 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1974
1975 if (s->be->ck_opts & PR_CK_HTTPONLY)
1976 chunk_appendf(&trash, "; HttpOnly");
1977
1978 if (s->be->ck_opts & PR_CK_SECURE)
1979 chunk_appendf(&trash, "; Secure");
1980
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001981 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001982 goto return_bad_resp;
1983
1984 txn->flags &= ~TX_SCK_MASK;
1985 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1986 /* the server did not change, only the date was updated */
1987 txn->flags |= TX_SCK_UPDATED;
1988 else
1989 txn->flags |= TX_SCK_INSERTED;
1990
1991 /* Here, we will tell an eventual cache on the client side that we don't
1992 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1993 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1994 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1995 */
1996 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1997
1998 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1999
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002000 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002001 goto return_bad_resp;
2002 }
2003 }
2004
2005 /*
2006 * Check if result will be cacheable with a cookie.
2007 * We'll block the response if security checks have caught
2008 * nasty things such as a cacheable cookie.
2009 */
2010 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2011 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2012 (s->be->options & PR_O_CHK_CACHE)) {
2013 /* we're in presence of a cacheable response containing
2014 * a set-cookie header. We'll block it as requested by
2015 * the 'checkcache' option, and send an alert.
2016 */
2017 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002018 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019
Olivier Houcharda798bf52019-03-08 18:52:00 +01002020 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2021 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002023 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024
2025 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2026 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2027 send_log(s->be, LOG_ALERT,
2028 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2029 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2030 goto return_srv_prx_502;
2031 }
2032
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002033 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002034 /* Always enter in the body analyzer */
2035 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2036 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2037
2038 /* if the user wants to log as soon as possible, without counting
2039 * bytes from the server, then this is the right moment. We have
2040 * to temporarily assign bytes_out to log what we currently have.
2041 */
2042 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2043 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002044 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002045 s->do_log(s);
2046 s->logs.bytes_out = 0;
2047 }
2048 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049
2050 return_bad_resp:
2051 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002052 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002053 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002054 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002055 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056
2057 return_srv_prx_502:
2058 rep->analysers &= AN_RES_FLT_END;
2059 txn->status = 502;
2060 s->logs.t_data = -1; /* was not a valid response */
2061 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002062 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002063 if (!(s->flags & SF_ERR_MASK))
2064 s->flags |= SF_ERR_PRXCOND;
2065 if (!(s->flags & SF_FINST_MASK))
2066 s->flags |= SF_FINST_H;
2067 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002068}
2069
2070/* This function is an analyser which forwards response body (including chunk
2071 * sizes if any). It is called as soon as we must forward, even if we forward
2072 * zero byte. The only situation where it must not be called is when we're in
2073 * tunnel mode and we want to forward till the close. It's used both to forward
2074 * remaining data and to resync after end of body. It expects the msg_state to
2075 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2076 * read more data, or 1 once we can go on with next request or end the stream.
2077 *
2078 * It is capable of compressing response data both in content-length mode and
2079 * in chunked mode. The state machines follows different flows depending on
2080 * whether content-length and chunked modes are used, since there are no
2081 * trailers in content-length :
2082 *
2083 * chk-mode cl-mode
2084 * ,----- BODY -----.
2085 * / \
2086 * V size > 0 V chk-mode
2087 * .--> SIZE -------------> DATA -------------> CRLF
2088 * | | size == 0 | last byte |
2089 * | v final crlf v inspected |
2090 * | TRAILERS -----------> DONE |
2091 * | |
2092 * `----------------------------------------------'
2093 *
2094 * Compression only happens in the DATA state, and must be flushed in final
2095 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2096 * is performed at once on final states for all bytes parsed, or when leaving
2097 * on missing data.
2098 */
2099int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2100{
2101 struct session *sess = s->sess;
2102 struct http_txn *txn = s->txn;
2103 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002104 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002105 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002106
2107 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2108 now_ms, __FUNCTION__,
2109 s,
2110 res,
2111 res->rex, res->wex,
2112 res->flags,
2113 ci_data(res),
2114 res->analysers);
2115
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002116 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002117
2118 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002119 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120 /* Output closed while we were sending data. We must abort and
2121 * wake the other side up.
2122 */
2123 msg->err_state = msg->msg_state;
2124 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002125 htx_end_response(s);
2126 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002127 return 1;
2128 }
2129
Christopher Faulet9768c262018-10-22 09:34:31 +02002130 if (msg->msg_state == HTTP_MSG_BODY)
2131 msg->msg_state = HTTP_MSG_DATA;
2132
Christopher Faulete0768eb2018-10-03 16:38:02 +02002133 /* in most states, we should abort in case of early close */
2134 channel_auto_close(res);
2135
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002137 if (res->to_forward == CHN_INFINITE_FORWARD) {
2138 if (res->flags & (CF_SHUTR|CF_EOI)) {
2139 msg->msg_state = HTTP_MSG_DONE;
2140 res->to_forward = 0;
2141 goto done;
2142 }
2143 }
2144 else {
2145 /* We can't process the buffer's contents yet */
2146 res->flags |= CF_WAKE_WRITE;
2147 goto missing_data_or_waiting;
2148 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 }
2150
Christopher Faulet9768c262018-10-22 09:34:31 +02002151 if (msg->msg_state >= HTTP_MSG_DONE)
2152 goto done;
2153
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002154 /* Forward input data. We get it by removing all outgoing data not
2155 * forwarded yet from HTX data size. If there are some data filters, we
2156 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002157 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002158 if (HAS_RSP_DATA_FILTERS(s)) {
2159 ret = flt_http_payload(s, msg, htx->data);
2160 if (ret < 0)
2161 goto return_bad_res;
2162 c_adv(res, ret);
2163 if (htx->data != co_data(res) || htx->extra)
2164 goto missing_data_or_waiting;
2165 }
2166 else {
2167 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002168 if (msg->flags & HTTP_MSGF_XFER_LEN)
2169 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002170 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002171
2172 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2173 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002174 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002175 msg->msg_state = HTTP_MSG_TUNNEL;
2176 goto done;
2177 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002178 }
2179
Christopher Faulet9768c262018-10-22 09:34:31 +02002180 /* Check if the end-of-message is reached and if so, switch the message
2181 * in HTTP_MSG_DONE state.
2182 */
2183 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2184 goto missing_data_or_waiting;
2185
2186 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002187 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002188
2189 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002191 channel_dont_close(res);
2192
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002193 if (HAS_RSP_DATA_FILTERS(s)) {
2194 ret = flt_http_end(s, msg);
2195 if (ret <= 0) {
2196 if (!ret)
2197 goto missing_data_or_waiting;
2198 goto return_bad_res;
2199 }
2200 }
2201
Christopher Fauletf2824e62018-10-01 12:12:37 +02002202 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002204 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2206 if (res->flags & CF_SHUTW) {
2207 /* response errors are most likely due to the
2208 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002209 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 goto return_bad_res;
2212 }
2213 return 1;
2214 }
2215 return 0;
2216
2217 missing_data_or_waiting:
2218 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002219 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220
Christopher Faulet47365272018-10-31 17:40:50 +01002221 if (htx->flags & HTX_FL_PARSING_ERROR)
2222 goto return_bad_res;
2223
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 /* stop waiting for data if the input is closed before the end. If the
2225 * client side was already closed, it means that the client has aborted,
2226 * so we don't want to count this as a server abort. Otherwise it's a
2227 * server abort.
2228 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002229 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002231 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002233 if (htx_is_empty(htx))
2234 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002235 }
2236
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 /* When TE: chunked is used, we need to get there again to parse
2238 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2240 * are filters registered on the stream, we don't want to forward a
2241 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002243 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 channel_dont_close(res);
2245
2246 /* We know that more data are expected, but we couldn't send more that
2247 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2248 * system knows it must not set a PUSH on this first part. Interactive
2249 * modes are already handled by the stream sock layer. We must not do
2250 * this in content-length mode because it could present the MSG_MORE
2251 * flag with the last block of forwarded data, which would cause an
2252 * additional delay to be observed by the receiver.
2253 */
2254 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2255 res->flags |= CF_EXPECT_MORE;
2256
2257 /* the stream handler will take care of timeouts and errors */
2258 return 0;
2259
Christopher Faulet93e02d82019-03-08 14:18:50 +01002260 return_srv_abort:
2261 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2262 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002264 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2265 if (!(s->flags & SF_ERR_MASK))
2266 s->flags |= SF_ERR_SRVCL;
2267 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268
Christopher Faulet93e02d82019-03-08 14:18:50 +01002269 return_cli_abort:
2270 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2271 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002272 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002273 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2274 if (!(s->flags & SF_ERR_MASK))
2275 s->flags |= SF_ERR_CLICL;
2276 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002277
Christopher Faulet93e02d82019-03-08 14:18:50 +01002278 return_bad_res:
2279 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2280 if (objt_server(s->target)) {
2281 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2282 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2283 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002285 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 txn->rsp.err_state = txn->rsp.msg_state;
2289 txn->rsp.msg_state = HTTP_MSG_ERROR;
2290 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002291 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002292 res->analysers &= AN_RES_FLT_END;
2293 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 +02002294 if (!(s->flags & SF_FINST_MASK))
2295 s->flags |= SF_FINST_D;
2296 return 0;
2297}
2298
Christopher Faulet0f226952018-10-22 09:29:56 +02002299void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002300{
Christopher Fauletf2824e62018-10-01 12:12:37 +02002301 int tmp = TX_CON_WANT_CLO;
2302
Christopher Fauletf2824e62018-10-01 12:12:37 +02002303 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002304 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002305}
2306
2307/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002308 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002309 * as too large a request to build a valid response.
2310 */
2311int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2312{
Christopher Faulet99daf282018-11-28 22:58:13 +01002313 struct channel *req = &s->req;
2314 struct channel *res = &s->res;
2315 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002316 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002317 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002318 struct ist status, reason, location;
2319 unsigned int flags;
2320 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002321
2322 chunk = alloc_trash_chunk();
2323 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002324 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002325
Christopher Faulet99daf282018-11-28 22:58:13 +01002326 /*
2327 * Create the location
2328 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002329 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002330 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002331 case REDIRECT_TYPE_SCHEME: {
2332 struct http_hdr_ctx ctx;
2333 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002334
Christopher Faulet99daf282018-11-28 22:58:13 +01002335 host = ist("");
2336 ctx.blk = NULL;
2337 if (http_find_header(htx, ist("Host"), &ctx, 0))
2338 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002339
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 sl = http_find_stline(htx);
2341 path = http_get_path(htx_sl_req_uri(sl));
2342 /* build message using path */
2343 if (path.ptr) {
2344 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2345 int qs = 0;
2346 while (qs < path.len) {
2347 if (*(path.ptr + qs) == '?') {
2348 path.len = qs;
2349 break;
2350 }
2351 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002352 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353 }
2354 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002355 else
2356 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357
Christopher Faulet99daf282018-11-28 22:58:13 +01002358 if (rule->rdr_str) { /* this is an old "redirect" rule */
2359 /* add scheme */
2360 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2361 goto fail;
2362 }
2363 else {
2364 /* add scheme with executing log format */
2365 chunk->data += build_logline(s, chunk->area + chunk->data,
2366 chunk->size - chunk->data,
2367 &rule->rdr_fmt);
2368 }
2369 /* add "://" + host + path */
2370 if (!chunk_memcat(chunk, "://", 3) ||
2371 !chunk_memcat(chunk, host.ptr, host.len) ||
2372 !chunk_memcat(chunk, path.ptr, path.len))
2373 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 /* append a slash at the end of the location if needed and missing */
2376 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2377 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2378 if (chunk->data + 1 >= chunk->size)
2379 goto fail;
2380 chunk->area[chunk->data++] = '/';
2381 }
2382 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002384
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 case REDIRECT_TYPE_PREFIX: {
2386 struct ist path;
2387
2388 sl = http_find_stline(htx);
2389 path = http_get_path(htx_sl_req_uri(sl));
2390 /* build message using path */
2391 if (path.ptr) {
2392 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2393 int qs = 0;
2394 while (qs < path.len) {
2395 if (*(path.ptr + qs) == '?') {
2396 path.len = qs;
2397 break;
2398 }
2399 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 }
2402 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002403 else
2404 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405
Christopher Faulet99daf282018-11-28 22:58:13 +01002406 if (rule->rdr_str) { /* this is an old "redirect" rule */
2407 /* add prefix. Note that if prefix == "/", we don't want to
2408 * add anything, otherwise it makes it hard for the user to
2409 * configure a self-redirection.
2410 */
2411 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2412 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2413 goto fail;
2414 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002416 else {
2417 /* add prefix with executing log format */
2418 chunk->data += build_logline(s, chunk->area + chunk->data,
2419 chunk->size - chunk->data,
2420 &rule->rdr_fmt);
2421 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 /* add path */
2424 if (!chunk_memcat(chunk, path.ptr, path.len))
2425 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 /* append a slash at the end of the location if needed and missing */
2428 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2429 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2430 if (chunk->data + 1 >= chunk->size)
2431 goto fail;
2432 chunk->area[chunk->data++] = '/';
2433 }
2434 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 case REDIRECT_TYPE_LOCATION:
2437 default:
2438 if (rule->rdr_str) { /* this is an old "redirect" rule */
2439 /* add location */
2440 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2441 goto fail;
2442 }
2443 else {
2444 /* add location with executing log format */
2445 chunk->data += build_logline(s, chunk->area + chunk->data,
2446 chunk->size - chunk->data,
2447 &rule->rdr_fmt);
2448 }
2449 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002451 location = ist2(chunk->area, chunk->data);
2452
2453 /*
2454 * Create the 30x response
2455 */
2456 switch (rule->code) {
2457 case 308:
2458 status = ist("308");
2459 reason = ist("Permanent Redirect");
2460 break;
2461 case 307:
2462 status = ist("307");
2463 reason = ist("Temporary Redirect");
2464 break;
2465 case 303:
2466 status = ist("303");
2467 reason = ist("See Other");
2468 break;
2469 case 301:
2470 status = ist("301");
2471 reason = ist("Moved Permanently");
2472 break;
2473 case 302:
2474 default:
2475 status = ist("302");
2476 reason = ist("Found");
2477 break;
2478 }
2479
2480 htx = htx_from_buf(&res->buf);
2481 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2482 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2483 if (!sl)
2484 goto fail;
2485 sl->info.res.status = rule->code;
2486 s->txn->status = rule->code;
2487
2488 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2489 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2490 !htx_add_header(htx, ist("Location"), location))
2491 goto fail;
2492
2493 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2494 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2495 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002496 }
2497
2498 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2500 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002501 }
2502
Christopher Faulet99daf282018-11-28 22:58:13 +01002503 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2504 goto fail;
2505
Christopher Fauletf2824e62018-10-01 12:12:37 +02002506 /* let's log the request time */
2507 s->logs.tv_request = now;
2508
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002510 c_adv(res, data);
2511 res->total += data;
2512
2513 channel_auto_read(req);
2514 channel_abort(req);
2515 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002516 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002517
2518 res->wex = tick_add_ifset(now_ms, res->wto);
2519 channel_auto_read(res);
2520 channel_auto_close(res);
2521 channel_shutr_now(res);
2522
2523 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002524
2525 if (!(s->flags & SF_ERR_MASK))
2526 s->flags |= SF_ERR_LOCAL;
2527 if (!(s->flags & SF_FINST_MASK))
2528 s->flags |= SF_FINST_R;
2529
Christopher Faulet99daf282018-11-28 22:58:13 +01002530 free_trash_chunk(chunk);
2531 return 1;
2532
2533 fail:
2534 /* If an error occurred, remove the incomplete HTTP response from the
2535 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002536 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002537 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002538 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539}
2540
Christopher Faulet72333522018-10-24 11:25:02 +02002541int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2542 struct ist name, const char *str, struct my_regex *re, int action)
2543{
2544 struct http_hdr_ctx ctx;
2545 struct buffer *output = get_trash_chunk();
2546
2547 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2548 ctx.blk = NULL;
2549 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2550 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2551 continue;
2552
2553 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2554 if (output->data == -1)
2555 return -1;
2556 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2557 return -1;
2558 }
2559 return 0;
2560}
2561
2562static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2563 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2564{
2565 struct buffer *replace;
2566 int ret = -1;
2567
2568 replace = alloc_trash_chunk();
2569 if (!replace)
2570 goto leave;
2571
2572 replace->data = build_logline(s, replace->area, replace->size, fmt);
2573 if (replace->data >= replace->size - 1)
2574 goto leave;
2575
2576 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2577
2578 leave:
2579 free_trash_chunk(replace);
2580 return ret;
2581}
2582
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002583
2584/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2585 * on success and -1 on error. The response channel is updated accordingly.
2586 */
2587static int htx_reply_103_early_hints(struct channel *res)
2588{
2589 struct htx *htx = htx_from_buf(&res->buf);
2590 size_t data;
2591
2592 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2593 /* If an error occurred during an Early-hint rule,
2594 * remove the incomplete HTTP 103 response from the
2595 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002596 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002597 return -1;
2598 }
2599
2600 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002601 c_adv(res, data);
2602 res->total += data;
2603 return 0;
2604}
2605
Christopher Faulet6eb92892018-11-15 16:39:29 +01002606/*
2607 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2608 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002609 * If <early_hints> is 0, it is starts a new response by adding the start
2610 * line. If an error occurred -1 is returned. On success 0 is returned. The
2611 * channel is not updated here. It must be done calling the function
2612 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002613 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002614static 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 +01002615{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002616 struct channel *res = &s->res;
2617 struct htx *htx = htx_from_buf(&res->buf);
2618 struct buffer *value = alloc_trash_chunk();
2619
Christopher Faulet6eb92892018-11-15 16:39:29 +01002620 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002621 struct htx_sl *sl;
2622 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2623 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2624
2625 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2626 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2627 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002628 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002629 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002630 }
2631
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002632 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2633 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 goto fail;
2635
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002638
2639 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002640 /* If an error occurred during an Early-hint rule, remove the incomplete
2641 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002642 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 free_trash_chunk(value);
2644 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002645}
2646
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002647/* This function executes one of the set-{method,path,query,uri} actions. It
2648 * takes the string from the variable 'replace' with length 'len', then modifies
2649 * the relevant part of the request line accordingly. Then it updates various
2650 * pointers to the next elements which were moved, and the total buffer length.
2651 * It finds the action to be performed in p[2], previously filled by function
2652 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2653 * error, though this can be revisited when this code is finally exploited.
2654 *
2655 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2656 * query string and 3 to replace uri.
2657 *
2658 * In query string case, the mark question '?' must be set at the start of the
2659 * string by the caller, event if the replacement query string is empty.
2660 */
2661int htx_req_replace_stline(int action, const char *replace, int len,
2662 struct proxy *px, struct stream *s)
2663{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002664 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002665
2666 switch (action) {
2667 case 0: // method
2668 if (!http_replace_req_meth(htx, ist2(replace, len)))
2669 return -1;
2670 break;
2671
2672 case 1: // path
2673 if (!http_replace_req_path(htx, ist2(replace, len)))
2674 return -1;
2675 break;
2676
2677 case 2: // query
2678 if (!http_replace_req_query(htx, ist2(replace, len)))
2679 return -1;
2680 break;
2681
2682 case 3: // uri
2683 if (!http_replace_req_uri(htx, ist2(replace, len)))
2684 return -1;
2685 break;
2686
2687 default:
2688 return -1;
2689 }
2690 return 0;
2691}
2692
2693/* This function replace the HTTP status code and the associated message. The
2694 * variable <status> contains the new status code. This function never fails.
2695 */
2696void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2697{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002698 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002699 char *res;
2700
2701 chunk_reset(&trash);
2702 res = ultoa_o(status, trash.area, trash.size);
2703 trash.data = res - trash.area;
2704
2705 /* Do we have a custom reason format string? */
2706 if (reason == NULL)
2707 reason = http_get_reason(status);
2708
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002709 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002710 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2711}
2712
Christopher Faulet3e964192018-10-24 11:39:23 +02002713/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2714 * transaction <txn>. Returns the verdict of the first rule that prevents
2715 * further processing of the request (auth, deny, ...), and defaults to
2716 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2717 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2718 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2719 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2720 * status.
2721 */
2722static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2723 struct stream *s, int *deny_status)
2724{
2725 struct session *sess = strm_sess(s);
2726 struct http_txn *txn = s->txn;
2727 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002728 struct act_rule *rule;
2729 struct http_hdr_ctx ctx;
2730 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002731 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2732 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002733 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002734
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002735 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002736
2737 /* If "the current_rule_list" match the executed rule list, we are in
2738 * resume condition. If a resume is needed it is always in the action
2739 * and never in the ACL or converters. In this case, we initialise the
2740 * current rule, and go to the action execution point.
2741 */
2742 if (s->current_rule) {
2743 rule = s->current_rule;
2744 s->current_rule = NULL;
2745 if (s->current_rule_list == rules)
2746 goto resume_execution;
2747 }
2748 s->current_rule_list = rules;
2749
2750 list_for_each_entry(rule, rules, list) {
2751 /* check optional condition */
2752 if (rule->cond) {
2753 int ret;
2754
2755 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2756 ret = acl_pass(ret);
2757
2758 if (rule->cond->pol == ACL_COND_UNLESS)
2759 ret = !ret;
2760
2761 if (!ret) /* condition not matched */
2762 continue;
2763 }
2764
2765 act_flags |= ACT_FLAG_FIRST;
2766 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002767 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2768 early_hints = 0;
2769 if (htx_reply_103_early_hints(&s->res) == -1) {
2770 rule_ret = HTTP_RULE_RES_BADREQ;
2771 goto end;
2772 }
2773 }
2774
Christopher Faulet3e964192018-10-24 11:39:23 +02002775 switch (rule->action) {
2776 case ACT_ACTION_ALLOW:
2777 rule_ret = HTTP_RULE_RES_STOP;
2778 goto end;
2779
2780 case ACT_ACTION_DENY:
2781 if (deny_status)
2782 *deny_status = rule->deny_status;
2783 rule_ret = HTTP_RULE_RES_DENY;
2784 goto end;
2785
2786 case ACT_HTTP_REQ_TARPIT:
2787 txn->flags |= TX_CLTARPIT;
2788 if (deny_status)
2789 *deny_status = rule->deny_status;
2790 rule_ret = HTTP_RULE_RES_DENY;
2791 goto end;
2792
2793 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002794 /* Auth might be performed on regular http-req rules as well as on stats */
2795 auth_realm = rule->arg.auth.realm;
2796 if (!auth_realm) {
2797 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2798 auth_realm = STATS_DEFAULT_REALM;
2799 else
2800 auth_realm = px->id;
2801 }
2802 /* send 401/407 depending on whether we use a proxy or not. We still
2803 * count one error, because normal browsing won't significantly
2804 * increase the counter but brute force attempts will.
2805 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002806 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002807 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2808 rule_ret = HTTP_RULE_RES_BADREQ;
2809 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002810 goto end;
2811
2812 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002813 rule_ret = HTTP_RULE_RES_DONE;
2814 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2815 rule_ret = HTTP_RULE_RES_BADREQ;
2816 goto end;
2817
2818 case ACT_HTTP_SET_NICE:
2819 s->task->nice = rule->arg.nice;
2820 break;
2821
2822 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002823 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 break;
2825
2826 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002827 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 break;
2829
2830 case ACT_HTTP_SET_LOGL:
2831 s->logs.level = rule->arg.loglevel;
2832 break;
2833
2834 case ACT_HTTP_REPLACE_HDR:
2835 case ACT_HTTP_REPLACE_VAL:
2836 if (htx_transform_header(s, &s->req, htx,
2837 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2838 &rule->arg.hdr_add.fmt,
2839 &rule->arg.hdr_add.re, rule->action)) {
2840 rule_ret = HTTP_RULE_RES_BADREQ;
2841 goto end;
2842 }
2843 break;
2844
2845 case ACT_HTTP_DEL_HDR:
2846 /* remove all occurrences of the header */
2847 ctx.blk = NULL;
2848 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2849 http_remove_header(htx, &ctx);
2850 break;
2851
2852 case ACT_HTTP_SET_HDR:
2853 case ACT_HTTP_ADD_HDR: {
2854 /* The scope of the trash buffer must be limited to this function. The
2855 * build_logline() function can execute a lot of other function which
2856 * can use the trash buffer. So for limiting the scope of this global
2857 * buffer, we build first the header value using build_logline, and
2858 * after we store the header name.
2859 */
2860 struct buffer *replace;
2861 struct ist n, v;
2862
2863 replace = alloc_trash_chunk();
2864 if (!replace) {
2865 rule_ret = HTTP_RULE_RES_BADREQ;
2866 goto end;
2867 }
2868
2869 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2870 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2871 v = ist2(replace->area, replace->data);
2872
2873 if (rule->action == ACT_HTTP_SET_HDR) {
2874 /* remove all occurrences of the header */
2875 ctx.blk = NULL;
2876 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2877 http_remove_header(htx, &ctx);
2878 }
2879
2880 if (!http_add_header(htx, n, v)) {
2881 static unsigned char rate_limit = 0;
2882
2883 if ((rate_limit++ & 255) == 0) {
2884 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);
2885 }
2886
Olivier Houcharda798bf52019-03-08 18:52:00 +01002887 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002888 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002889 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002890 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002891 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 }
2893 free_trash_chunk(replace);
2894 break;
2895 }
2896
2897 case ACT_HTTP_DEL_ACL:
2898 case ACT_HTTP_DEL_MAP: {
2899 struct pat_ref *ref;
2900 struct buffer *key;
2901
2902 /* collect reference */
2903 ref = pat_ref_lookup(rule->arg.map.ref);
2904 if (!ref)
2905 continue;
2906
2907 /* allocate key */
2908 key = alloc_trash_chunk();
2909 if (!key) {
2910 rule_ret = HTTP_RULE_RES_BADREQ;
2911 goto end;
2912 }
2913
2914 /* collect key */
2915 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2916 key->area[key->data] = '\0';
2917
2918 /* perform update */
2919 /* returned code: 1=ok, 0=ko */
2920 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2921 pat_ref_delete(ref, key->area);
2922 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2923
2924 free_trash_chunk(key);
2925 break;
2926 }
2927
2928 case ACT_HTTP_ADD_ACL: {
2929 struct pat_ref *ref;
2930 struct buffer *key;
2931
2932 /* collect reference */
2933 ref = pat_ref_lookup(rule->arg.map.ref);
2934 if (!ref)
2935 continue;
2936
2937 /* allocate key */
2938 key = alloc_trash_chunk();
2939 if (!key) {
2940 rule_ret = HTTP_RULE_RES_BADREQ;
2941 goto end;
2942 }
2943
2944 /* collect key */
2945 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2946 key->area[key->data] = '\0';
2947
2948 /* perform update */
2949 /* add entry only if it does not already exist */
2950 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2951 if (pat_ref_find_elt(ref, key->area) == NULL)
2952 pat_ref_add(ref, key->area, NULL, NULL);
2953 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2954
2955 free_trash_chunk(key);
2956 break;
2957 }
2958
2959 case ACT_HTTP_SET_MAP: {
2960 struct pat_ref *ref;
2961 struct buffer *key, *value;
2962
2963 /* collect reference */
2964 ref = pat_ref_lookup(rule->arg.map.ref);
2965 if (!ref)
2966 continue;
2967
2968 /* allocate key */
2969 key = alloc_trash_chunk();
2970 if (!key) {
2971 rule_ret = HTTP_RULE_RES_BADREQ;
2972 goto end;
2973 }
2974
2975 /* allocate value */
2976 value = alloc_trash_chunk();
2977 if (!value) {
2978 free_trash_chunk(key);
2979 rule_ret = HTTP_RULE_RES_BADREQ;
2980 goto end;
2981 }
2982
2983 /* collect key */
2984 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2985 key->area[key->data] = '\0';
2986
2987 /* collect value */
2988 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2989 value->area[value->data] = '\0';
2990
2991 /* perform update */
2992 if (pat_ref_find_elt(ref, key->area) != NULL)
2993 /* update entry if it exists */
2994 pat_ref_set(ref, key->area, value->area, NULL);
2995 else
2996 /* insert a new entry */
2997 pat_ref_add(ref, key->area, value->area, NULL);
2998
2999 free_trash_chunk(key);
3000 free_trash_chunk(value);
3001 break;
3002 }
3003
3004 case ACT_HTTP_EARLY_HINT:
3005 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3006 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003007 early_hints = htx_add_early_hint_header(s, early_hints,
3008 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003009 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003010 if (early_hints == -1) {
3011 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003012 goto end;
3013 }
3014 break;
3015
3016 case ACT_CUSTOM:
3017 if ((s->req.flags & CF_READ_ERROR) ||
3018 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003019 (px->options & PR_O_ABRT_CLOSE)))
3020 act_flags |= ACT_FLAG_FINAL;
3021
3022 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3023 case ACT_RET_ERR:
3024 case ACT_RET_CONT:
3025 break;
3026 case ACT_RET_STOP:
3027 rule_ret = HTTP_RULE_RES_DONE;
3028 goto end;
3029 case ACT_RET_YIELD:
3030 s->current_rule = rule;
3031 rule_ret = HTTP_RULE_RES_YIELD;
3032 goto end;
3033 }
3034 break;
3035
3036 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3037 /* Note: only the first valid tracking parameter of each
3038 * applies.
3039 */
3040
3041 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3042 struct stktable *t;
3043 struct stksess *ts;
3044 struct stktable_key *key;
3045 void *ptr1, *ptr2;
3046
3047 t = rule->arg.trk_ctr.table.t;
3048 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3049 rule->arg.trk_ctr.expr, NULL);
3050
3051 if (key && (ts = stktable_get_entry(t, key))) {
3052 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3053
3054 /* let's count a new HTTP request as it's the first time we do it */
3055 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3056 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3057 if (ptr1 || ptr2) {
3058 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3059
3060 if (ptr1)
3061 stktable_data_cast(ptr1, http_req_cnt)++;
3062
3063 if (ptr2)
3064 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3065 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3066
3067 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3068
3069 /* If data was modified, we need to touch to re-schedule sync */
3070 stktable_touch_local(t, ts, 0);
3071 }
3072
3073 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3074 if (sess->fe != s->be)
3075 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3076 }
3077 }
3078 break;
3079
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003080 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003081 default:
3082 break;
3083 }
3084 }
3085
3086 end:
3087 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003088 if (htx_reply_103_early_hints(&s->res) == -1)
3089 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003090 }
3091
3092 /* we reached the end of the rules, nothing to report */
3093 return rule_ret;
3094}
3095
3096/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3097 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3098 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3099 * is returned, the process can continue the evaluation of next rule list. If
3100 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3101 * is returned, it means the operation could not be processed and a server error
3102 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3103 * deny rule. If *YIELD is returned, the caller must call again the function
3104 * with the same context.
3105 */
3106static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3107 struct stream *s)
3108{
3109 struct session *sess = strm_sess(s);
3110 struct http_txn *txn = s->txn;
3111 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003112 struct act_rule *rule;
3113 struct http_hdr_ctx ctx;
3114 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3115 int act_flags = 0;
3116
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003117 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003118
3119 /* If "the current_rule_list" match the executed rule list, we are in
3120 * resume condition. If a resume is needed it is always in the action
3121 * and never in the ACL or converters. In this case, we initialise the
3122 * current rule, and go to the action execution point.
3123 */
3124 if (s->current_rule) {
3125 rule = s->current_rule;
3126 s->current_rule = NULL;
3127 if (s->current_rule_list == rules)
3128 goto resume_execution;
3129 }
3130 s->current_rule_list = rules;
3131
3132 list_for_each_entry(rule, rules, list) {
3133 /* check optional condition */
3134 if (rule->cond) {
3135 int ret;
3136
3137 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3138 ret = acl_pass(ret);
3139
3140 if (rule->cond->pol == ACL_COND_UNLESS)
3141 ret = !ret;
3142
3143 if (!ret) /* condition not matched */
3144 continue;
3145 }
3146
3147 act_flags |= ACT_FLAG_FIRST;
3148resume_execution:
3149 switch (rule->action) {
3150 case ACT_ACTION_ALLOW:
3151 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3152 goto end;
3153
3154 case ACT_ACTION_DENY:
3155 txn->flags |= TX_SVDENY;
3156 rule_ret = HTTP_RULE_RES_STOP;
3157 goto end;
3158
3159 case ACT_HTTP_SET_NICE:
3160 s->task->nice = rule->arg.nice;
3161 break;
3162
3163 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003164 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003165 break;
3166
3167 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003168 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003169 break;
3170
3171 case ACT_HTTP_SET_LOGL:
3172 s->logs.level = rule->arg.loglevel;
3173 break;
3174
3175 case ACT_HTTP_REPLACE_HDR:
3176 case ACT_HTTP_REPLACE_VAL:
3177 if (htx_transform_header(s, &s->res, htx,
3178 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3179 &rule->arg.hdr_add.fmt,
3180 &rule->arg.hdr_add.re, rule->action)) {
3181 rule_ret = HTTP_RULE_RES_BADREQ;
3182 goto end;
3183 }
3184 break;
3185
3186 case ACT_HTTP_DEL_HDR:
3187 /* remove all occurrences of the header */
3188 ctx.blk = NULL;
3189 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3190 http_remove_header(htx, &ctx);
3191 break;
3192
3193 case ACT_HTTP_SET_HDR:
3194 case ACT_HTTP_ADD_HDR: {
3195 struct buffer *replace;
3196 struct ist n, v;
3197
3198 replace = alloc_trash_chunk();
3199 if (!replace) {
3200 rule_ret = HTTP_RULE_RES_BADREQ;
3201 goto end;
3202 }
3203
3204 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3205 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3206 v = ist2(replace->area, replace->data);
3207
3208 if (rule->action == ACT_HTTP_SET_HDR) {
3209 /* remove all occurrences of the header */
3210 ctx.blk = NULL;
3211 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3212 http_remove_header(htx, &ctx);
3213 }
3214
3215 if (!http_add_header(htx, n, v)) {
3216 static unsigned char rate_limit = 0;
3217
3218 if ((rate_limit++ & 255) == 0) {
3219 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);
3220 }
3221
Olivier Houcharda798bf52019-03-08 18:52:00 +01003222 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003223 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003224 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003225 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003226 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003227 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003228 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003229 }
3230 free_trash_chunk(replace);
3231 break;
3232 }
3233
3234 case ACT_HTTP_DEL_ACL:
3235 case ACT_HTTP_DEL_MAP: {
3236 struct pat_ref *ref;
3237 struct buffer *key;
3238
3239 /* collect reference */
3240 ref = pat_ref_lookup(rule->arg.map.ref);
3241 if (!ref)
3242 continue;
3243
3244 /* allocate key */
3245 key = alloc_trash_chunk();
3246 if (!key) {
3247 rule_ret = HTTP_RULE_RES_BADREQ;
3248 goto end;
3249 }
3250
3251 /* collect key */
3252 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3253 key->area[key->data] = '\0';
3254
3255 /* perform update */
3256 /* returned code: 1=ok, 0=ko */
3257 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3258 pat_ref_delete(ref, key->area);
3259 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3260
3261 free_trash_chunk(key);
3262 break;
3263 }
3264
3265 case ACT_HTTP_ADD_ACL: {
3266 struct pat_ref *ref;
3267 struct buffer *key;
3268
3269 /* collect reference */
3270 ref = pat_ref_lookup(rule->arg.map.ref);
3271 if (!ref)
3272 continue;
3273
3274 /* allocate key */
3275 key = alloc_trash_chunk();
3276 if (!key) {
3277 rule_ret = HTTP_RULE_RES_BADREQ;
3278 goto end;
3279 }
3280
3281 /* collect key */
3282 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3283 key->area[key->data] = '\0';
3284
3285 /* perform update */
3286 /* check if the entry already exists */
3287 if (pat_ref_find_elt(ref, key->area) == NULL)
3288 pat_ref_add(ref, key->area, NULL, NULL);
3289
3290 free_trash_chunk(key);
3291 break;
3292 }
3293
3294 case ACT_HTTP_SET_MAP: {
3295 struct pat_ref *ref;
3296 struct buffer *key, *value;
3297
3298 /* collect reference */
3299 ref = pat_ref_lookup(rule->arg.map.ref);
3300 if (!ref)
3301 continue;
3302
3303 /* allocate key */
3304 key = alloc_trash_chunk();
3305 if (!key) {
3306 rule_ret = HTTP_RULE_RES_BADREQ;
3307 goto end;
3308 }
3309
3310 /* allocate value */
3311 value = alloc_trash_chunk();
3312 if (!value) {
3313 free_trash_chunk(key);
3314 rule_ret = HTTP_RULE_RES_BADREQ;
3315 goto end;
3316 }
3317
3318 /* collect key */
3319 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3320 key->area[key->data] = '\0';
3321
3322 /* collect value */
3323 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3324 value->area[value->data] = '\0';
3325
3326 /* perform update */
3327 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3328 if (pat_ref_find_elt(ref, key->area) != NULL)
3329 /* update entry if it exists */
3330 pat_ref_set(ref, key->area, value->area, NULL);
3331 else
3332 /* insert a new entry */
3333 pat_ref_add(ref, key->area, value->area, NULL);
3334 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3335 free_trash_chunk(key);
3336 free_trash_chunk(value);
3337 break;
3338 }
3339
3340 case ACT_HTTP_REDIR:
3341 rule_ret = HTTP_RULE_RES_DONE;
3342 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3343 rule_ret = HTTP_RULE_RES_BADREQ;
3344 goto end;
3345
3346 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3347 /* Note: only the first valid tracking parameter of each
3348 * applies.
3349 */
3350 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3351 struct stktable *t;
3352 struct stksess *ts;
3353 struct stktable_key *key;
3354 void *ptr;
3355
3356 t = rule->arg.trk_ctr.table.t;
3357 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3358 rule->arg.trk_ctr.expr, NULL);
3359
3360 if (key && (ts = stktable_get_entry(t, key))) {
3361 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3362
3363 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3364
3365 /* let's count a new HTTP request as it's the first time we do it */
3366 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3367 if (ptr)
3368 stktable_data_cast(ptr, http_req_cnt)++;
3369
3370 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3371 if (ptr)
3372 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3373 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3374
3375 /* When the client triggers a 4xx from the server, it's most often due
3376 * to a missing object or permission. These events should be tracked
3377 * because if they happen often, it may indicate a brute force or a
3378 * vulnerability scan. Normally this is done when receiving the response
3379 * but here we're tracking after this ought to have been done so we have
3380 * to do it on purpose.
3381 */
3382 if ((unsigned)(txn->status - 400) < 100) {
3383 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3384 if (ptr)
3385 stktable_data_cast(ptr, http_err_cnt)++;
3386
3387 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3388 if (ptr)
3389 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3390 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3391 }
3392
3393 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3394
3395 /* If data was modified, we need to touch to re-schedule sync */
3396 stktable_touch_local(t, ts, 0);
3397
3398 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3399 if (sess->fe != s->be)
3400 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3401 }
3402 }
3403 break;
3404
3405 case ACT_CUSTOM:
3406 if ((s->req.flags & CF_READ_ERROR) ||
3407 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003408 (px->options & PR_O_ABRT_CLOSE)))
3409 act_flags |= ACT_FLAG_FINAL;
3410
3411 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3412 case ACT_RET_ERR:
3413 case ACT_RET_CONT:
3414 break;
3415 case ACT_RET_STOP:
3416 rule_ret = HTTP_RULE_RES_STOP;
3417 goto end;
3418 case ACT_RET_YIELD:
3419 s->current_rule = rule;
3420 rule_ret = HTTP_RULE_RES_YIELD;
3421 goto end;
3422 }
3423 break;
3424
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003425 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003426 default:
3427 break;
3428 }
3429 }
3430
3431 end:
3432 /* we reached the end of the rules, nothing to report */
3433 return rule_ret;
3434}
3435
Christopher Faulet33640082018-10-24 11:53:01 +02003436/* Iterate the same filter through all request headers.
3437 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3438 * Since it can manage the switch to another backend, it updates the per-proxy
3439 * DENY stats.
3440 */
3441static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3442{
3443 struct http_txn *txn = s->txn;
3444 struct htx *htx;
3445 struct buffer *hdr = get_trash_chunk();
3446 int32_t pos;
3447
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003448 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003449
3450 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3451 struct htx_blk *blk = htx_get_blk(htx, pos);
3452 enum htx_blk_type type;
3453 struct ist n, v;
3454
3455 next_hdr:
3456 type = htx_get_blk_type(blk);
3457 if (type == HTX_BLK_EOH)
3458 break;
3459 if (type != HTX_BLK_HDR)
3460 continue;
3461
3462 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3463 return 1;
3464 else if (unlikely(txn->flags & TX_CLALLOW) &&
3465 (exp->action == ACT_ALLOW ||
3466 exp->action == ACT_DENY ||
3467 exp->action == ACT_TARPIT))
3468 return 0;
3469
3470 n = htx_get_blk_name(htx, blk);
3471 v = htx_get_blk_value(htx, blk);
3472
Christopher Faulet02e771a2019-02-26 15:36:05 +01003473 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003474 hdr->area[hdr->data++] = ':';
3475 hdr->area[hdr->data++] = ' ';
3476 chunk_memcat(hdr, v.ptr, v.len);
3477
3478 /* Now we have one header in <hdr> */
3479
3480 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3481 struct http_hdr_ctx ctx;
3482 int len;
3483
3484 switch (exp->action) {
3485 case ACT_ALLOW:
3486 txn->flags |= TX_CLALLOW;
3487 goto end;
3488
3489 case ACT_DENY:
3490 txn->flags |= TX_CLDENY;
3491 goto end;
3492
3493 case ACT_TARPIT:
3494 txn->flags |= TX_CLTARPIT;
3495 goto end;
3496
3497 case ACT_REPLACE:
3498 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3499 if (len < 0)
3500 return -1;
3501
3502 http_parse_header(ist2(trash.area, len), &n, &v);
3503 ctx.blk = blk;
3504 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003505 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003506 if (!http_replace_header(htx, &ctx, n, v))
3507 return -1;
3508 if (!ctx.blk)
3509 goto end;
3510 pos = htx_get_blk_pos(htx, blk);
3511 break;
3512
3513 case ACT_REMOVE:
3514 ctx.blk = blk;
3515 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003516 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003517 if (!http_remove_header(htx, &ctx))
3518 return -1;
3519 if (!ctx.blk)
3520 goto end;
3521 pos = htx_get_blk_pos(htx, blk);
3522 goto next_hdr;
3523
3524 }
3525 }
3526 }
3527 end:
3528 return 0;
3529}
3530
3531/* Apply the filter to the request line.
3532 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3533 * or -1 if a replacement resulted in an invalid request line.
3534 * Since it can manage the switch to another backend, it updates the per-proxy
3535 * DENY stats.
3536 */
3537static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3538{
3539 struct http_txn *txn = s->txn;
3540 struct htx *htx;
3541 struct buffer *reqline = get_trash_chunk();
3542 int done;
3543
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003544 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003545
3546 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3547 return 1;
3548 else if (unlikely(txn->flags & TX_CLALLOW) &&
3549 (exp->action == ACT_ALLOW ||
3550 exp->action == ACT_DENY ||
3551 exp->action == ACT_TARPIT))
3552 return 0;
3553 else if (exp->action == ACT_REMOVE)
3554 return 0;
3555
3556 done = 0;
3557
3558 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3559
3560 /* Now we have the request line between cur_ptr and cur_end */
3561 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003562 struct htx_sl *sl = http_find_stline(htx);
3563 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003564 int len;
3565
3566 switch (exp->action) {
3567 case ACT_ALLOW:
3568 txn->flags |= TX_CLALLOW;
3569 done = 1;
3570 break;
3571
3572 case ACT_DENY:
3573 txn->flags |= TX_CLDENY;
3574 done = 1;
3575 break;
3576
3577 case ACT_TARPIT:
3578 txn->flags |= TX_CLTARPIT;
3579 done = 1;
3580 break;
3581
3582 case ACT_REPLACE:
3583 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3584 if (len < 0)
3585 return -1;
3586
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003587 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3588 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3589 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003590 return -1;
3591 done = 1;
3592 break;
3593 }
3594 }
3595 return done;
3596}
3597
3598/*
3599 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3600 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3601 * unparsable request. Since it can manage the switch to another backend, it
3602 * updates the per-proxy DENY stats.
3603 */
3604static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3605{
3606 struct session *sess = s->sess;
3607 struct http_txn *txn = s->txn;
3608 struct hdr_exp *exp;
3609
3610 for (exp = px->req_exp; exp; exp = exp->next) {
3611 int ret;
3612
3613 /*
3614 * The interleaving of transformations and verdicts
3615 * makes it difficult to decide to continue or stop
3616 * the evaluation.
3617 */
3618
3619 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3620 break;
3621
3622 if ((txn->flags & TX_CLALLOW) &&
3623 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3624 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3625 continue;
3626
3627 /* if this filter had a condition, evaluate it now and skip to
3628 * next filter if the condition does not match.
3629 */
3630 if (exp->cond) {
3631 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3632 ret = acl_pass(ret);
3633 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3634 ret = !ret;
3635
3636 if (!ret)
3637 continue;
3638 }
3639
3640 /* Apply the filter to the request line. */
3641 ret = htx_apply_filter_to_req_line(s, req, exp);
3642 if (unlikely(ret < 0))
3643 return -1;
3644
3645 if (likely(ret == 0)) {
3646 /* The filter did not match the request, it can be
3647 * iterated through all headers.
3648 */
3649 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3650 return -1;
3651 }
3652 }
3653 return 0;
3654}
3655
3656/* Iterate the same filter through all response headers contained in <res>.
3657 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3658 */
3659static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3660{
3661 struct http_txn *txn = s->txn;
3662 struct htx *htx;
3663 struct buffer *hdr = get_trash_chunk();
3664 int32_t pos;
3665
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003666 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003667
3668 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3669 struct htx_blk *blk = htx_get_blk(htx, pos);
3670 enum htx_blk_type type;
3671 struct ist n, v;
3672
3673 next_hdr:
3674 type = htx_get_blk_type(blk);
3675 if (type == HTX_BLK_EOH)
3676 break;
3677 if (type != HTX_BLK_HDR)
3678 continue;
3679
3680 if (unlikely(txn->flags & TX_SVDENY))
3681 return 1;
3682 else if (unlikely(txn->flags & TX_SVALLOW) &&
3683 (exp->action == ACT_ALLOW ||
3684 exp->action == ACT_DENY))
3685 return 0;
3686
3687 n = htx_get_blk_name(htx, blk);
3688 v = htx_get_blk_value(htx, blk);
3689
Christopher Faulet02e771a2019-02-26 15:36:05 +01003690 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003691 hdr->area[hdr->data++] = ':';
3692 hdr->area[hdr->data++] = ' ';
3693 chunk_memcat(hdr, v.ptr, v.len);
3694
3695 /* Now we have one header in <hdr> */
3696
3697 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3698 struct http_hdr_ctx ctx;
3699 int len;
3700
3701 switch (exp->action) {
3702 case ACT_ALLOW:
3703 txn->flags |= TX_SVALLOW;
3704 goto end;
3705 break;
3706
3707 case ACT_DENY:
3708 txn->flags |= TX_SVDENY;
3709 goto end;
3710 break;
3711
3712 case ACT_REPLACE:
3713 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3714 if (len < 0)
3715 return -1;
3716
3717 http_parse_header(ist2(trash.area, len), &n, &v);
3718 ctx.blk = blk;
3719 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003720 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003721 if (!http_replace_header(htx, &ctx, n, v))
3722 return -1;
3723 if (!ctx.blk)
3724 goto end;
3725 pos = htx_get_blk_pos(htx, blk);
3726 break;
3727
3728 case ACT_REMOVE:
3729 ctx.blk = blk;
3730 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003731 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003732 if (!http_remove_header(htx, &ctx))
3733 return -1;
3734 if (!ctx.blk)
3735 goto end;
3736 pos = htx_get_blk_pos(htx, blk);
3737 goto next_hdr;
3738 }
3739 }
3740
3741 }
3742 end:
3743 return 0;
3744}
3745
3746/* Apply the filter to the status line in the response buffer <res>.
3747 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3748 * or -1 if a replacement resulted in an invalid status line.
3749 */
3750static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3751{
3752 struct http_txn *txn = s->txn;
3753 struct htx *htx;
3754 struct buffer *resline = get_trash_chunk();
3755 int done;
3756
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003757 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003758
3759 if (unlikely(txn->flags & TX_SVDENY))
3760 return 1;
3761 else if (unlikely(txn->flags & TX_SVALLOW) &&
3762 (exp->action == ACT_ALLOW ||
3763 exp->action == ACT_DENY))
3764 return 0;
3765 else if (exp->action == ACT_REMOVE)
3766 return 0;
3767
3768 done = 0;
3769 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3770
3771 /* Now we have the status line between cur_ptr and cur_end */
3772 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003773 struct htx_sl *sl = http_find_stline(htx);
3774 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003775 int len;
3776
3777 switch (exp->action) {
3778 case ACT_ALLOW:
3779 txn->flags |= TX_SVALLOW;
3780 done = 1;
3781 break;
3782
3783 case ACT_DENY:
3784 txn->flags |= TX_SVDENY;
3785 done = 1;
3786 break;
3787
3788 case ACT_REPLACE:
3789 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3790 if (len < 0)
3791 return -1;
3792
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003793 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3794 sl->info.res.status = strl2ui(code.ptr, code.len);
3795 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003796 return -1;
3797
3798 done = 1;
3799 return 1;
3800 }
3801 }
3802 return done;
3803}
3804
3805/*
3806 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3807 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3808 * unparsable response.
3809 */
3810static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3811{
3812 struct session *sess = s->sess;
3813 struct http_txn *txn = s->txn;
3814 struct hdr_exp *exp;
3815
3816 for (exp = px->rsp_exp; exp; exp = exp->next) {
3817 int ret;
3818
3819 /*
3820 * The interleaving of transformations and verdicts
3821 * makes it difficult to decide to continue or stop
3822 * the evaluation.
3823 */
3824
3825 if (txn->flags & TX_SVDENY)
3826 break;
3827
3828 if ((txn->flags & TX_SVALLOW) &&
3829 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3830 exp->action == ACT_PASS)) {
3831 exp = exp->next;
3832 continue;
3833 }
3834
3835 /* if this filter had a condition, evaluate it now and skip to
3836 * next filter if the condition does not match.
3837 */
3838 if (exp->cond) {
3839 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3840 ret = acl_pass(ret);
3841 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3842 ret = !ret;
3843 if (!ret)
3844 continue;
3845 }
3846
3847 /* Apply the filter to the status line. */
3848 ret = htx_apply_filter_to_sts_line(s, res, exp);
3849 if (unlikely(ret < 0))
3850 return -1;
3851
3852 if (likely(ret == 0)) {
3853 /* The filter did not match the response, it can be
3854 * iterated through all headers.
3855 */
3856 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3857 return -1;
3858 }
3859 }
3860 return 0;
3861}
3862
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003863/*
3864 * Manage client-side cookie. It can impact performance by about 2% so it is
3865 * desirable to call it only when needed. This code is quite complex because
3866 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3867 * highly recommended not to touch this part without a good reason !
3868 */
3869static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3870{
3871 struct session *sess = s->sess;
3872 struct http_txn *txn = s->txn;
3873 struct htx *htx;
3874 struct http_hdr_ctx ctx;
3875 char *hdr_beg, *hdr_end, *del_from;
3876 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3877 int preserve_hdr;
3878
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003879 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003880 ctx.blk = NULL;
3881 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3882 del_from = NULL; /* nothing to be deleted */
3883 preserve_hdr = 0; /* assume we may kill the whole header */
3884
3885 /* Now look for cookies. Conforming to RFC2109, we have to support
3886 * attributes whose name begin with a '$', and associate them with
3887 * the right cookie, if we want to delete this cookie.
3888 * So there are 3 cases for each cookie read :
3889 * 1) it's a special attribute, beginning with a '$' : ignore it.
3890 * 2) it's a server id cookie that we *MAY* want to delete : save
3891 * some pointers on it (last semi-colon, beginning of cookie...)
3892 * 3) it's an application cookie : we *MAY* have to delete a previous
3893 * "special" cookie.
3894 * At the end of loop, if a "special" cookie remains, we may have to
3895 * remove it. If no application cookie persists in the header, we
3896 * *MUST* delete it.
3897 *
3898 * Note: RFC2965 is unclear about the processing of spaces around
3899 * the equal sign in the ATTR=VALUE form. A careful inspection of
3900 * the RFC explicitly allows spaces before it, and not within the
3901 * tokens (attrs or values). An inspection of RFC2109 allows that
3902 * too but section 10.1.3 lets one think that spaces may be allowed
3903 * after the equal sign too, resulting in some (rare) buggy
3904 * implementations trying to do that. So let's do what servers do.
3905 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3906 * allowed quoted strings in values, with any possible character
3907 * after a backslash, including control chars and delimitors, which
3908 * causes parsing to become ambiguous. Browsers also allow spaces
3909 * within values even without quotes.
3910 *
3911 * We have to keep multiple pointers in order to support cookie
3912 * removal at the beginning, middle or end of header without
3913 * corrupting the header. All of these headers are valid :
3914 *
3915 * hdr_beg hdr_end
3916 * | |
3917 * v |
3918 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3919 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3920 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3921 * | | | | | | |
3922 * | | | | | | |
3923 * | | | | | | +--> next
3924 * | | | | | +----> val_end
3925 * | | | | +-----------> val_beg
3926 * | | | +--------------> equal
3927 * | | +----------------> att_end
3928 * | +---------------------> att_beg
3929 * +--------------------------> prev
3930 *
3931 */
3932 hdr_beg = ctx.value.ptr;
3933 hdr_end = hdr_beg + ctx.value.len;
3934 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3935 /* Iterate through all cookies on this line */
3936
3937 /* find att_beg */
3938 att_beg = prev;
3939 if (prev > hdr_beg)
3940 att_beg++;
3941
3942 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3943 att_beg++;
3944
3945 /* find att_end : this is the first character after the last non
3946 * space before the equal. It may be equal to hdr_end.
3947 */
3948 equal = att_end = att_beg;
3949 while (equal < hdr_end) {
3950 if (*equal == '=' || *equal == ',' || *equal == ';')
3951 break;
3952 if (HTTP_IS_SPHT(*equal++))
3953 continue;
3954 att_end = equal;
3955 }
3956
3957 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3958 * is between <att_beg> and <equal>, both may be identical.
3959 */
3960 /* look for end of cookie if there is an equal sign */
3961 if (equal < hdr_end && *equal == '=') {
3962 /* look for the beginning of the value */
3963 val_beg = equal + 1;
3964 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3965 val_beg++;
3966
3967 /* find the end of the value, respecting quotes */
3968 next = http_find_cookie_value_end(val_beg, hdr_end);
3969
3970 /* make val_end point to the first white space or delimitor after the value */
3971 val_end = next;
3972 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3973 val_end--;
3974 }
3975 else
3976 val_beg = val_end = next = equal;
3977
3978 /* We have nothing to do with attributes beginning with
3979 * '$'. However, they will automatically be removed if a
3980 * header before them is removed, since they're supposed
3981 * to be linked together.
3982 */
3983 if (*att_beg == '$')
3984 continue;
3985
3986 /* Ignore cookies with no equal sign */
3987 if (equal == next) {
3988 /* This is not our cookie, so we must preserve it. But if we already
3989 * scheduled another cookie for removal, we cannot remove the
3990 * complete header, but we can remove the previous block itself.
3991 */
3992 preserve_hdr = 1;
3993 if (del_from != NULL) {
3994 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3995 val_end += delta;
3996 next += delta;
3997 hdr_end += delta;
3998 prev = del_from;
3999 del_from = NULL;
4000 }
4001 continue;
4002 }
4003
4004 /* if there are spaces around the equal sign, we need to
4005 * strip them otherwise we'll get trouble for cookie captures,
4006 * or even for rewrites. Since this happens extremely rarely,
4007 * it does not hurt performance.
4008 */
4009 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4010 int stripped_before = 0;
4011 int stripped_after = 0;
4012
4013 if (att_end != equal) {
4014 memmove(att_end, equal, hdr_end - equal);
4015 stripped_before = (att_end - equal);
4016 equal += stripped_before;
4017 val_beg += stripped_before;
4018 }
4019
4020 if (val_beg > equal + 1) {
4021 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4022 stripped_after = (equal + 1) - val_beg;
4023 val_beg += stripped_after;
4024 stripped_before += stripped_after;
4025 }
4026
4027 val_end += stripped_before;
4028 next += stripped_before;
4029 hdr_end += stripped_before;
4030 }
4031 /* now everything is as on the diagram above */
4032
4033 /* First, let's see if we want to capture this cookie. We check
4034 * that we don't already have a client side cookie, because we
4035 * can only capture one. Also as an optimisation, we ignore
4036 * cookies shorter than the declared name.
4037 */
4038 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4039 (val_end - att_beg >= sess->fe->capture_namelen) &&
4040 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4041 int log_len = val_end - att_beg;
4042
4043 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4044 ha_alert("HTTP logging : out of memory.\n");
4045 } else {
4046 if (log_len > sess->fe->capture_len)
4047 log_len = sess->fe->capture_len;
4048 memcpy(txn->cli_cookie, att_beg, log_len);
4049 txn->cli_cookie[log_len] = 0;
4050 }
4051 }
4052
4053 /* Persistence cookies in passive, rewrite or insert mode have the
4054 * following form :
4055 *
4056 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4057 *
4058 * For cookies in prefix mode, the form is :
4059 *
4060 * Cookie: NAME=SRV~VALUE
4061 */
4062 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4063 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4064 struct server *srv = s->be->srv;
4065 char *delim;
4066
4067 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4068 * have the server ID between val_beg and delim, and the original cookie between
4069 * delim+1 and val_end. Otherwise, delim==val_end :
4070 *
4071 * hdr_beg
4072 * |
4073 * v
4074 * NAME=SRV; # in all but prefix modes
4075 * NAME=SRV~OPAQUE ; # in prefix mode
4076 * || || | |+-> next
4077 * || || | +--> val_end
4078 * || || +---------> delim
4079 * || |+------------> val_beg
4080 * || +-------------> att_end = equal
4081 * |+-----------------> att_beg
4082 * +------------------> prev
4083 *
4084 */
4085 if (s->be->ck_opts & PR_CK_PFX) {
4086 for (delim = val_beg; delim < val_end; delim++)
4087 if (*delim == COOKIE_DELIM)
4088 break;
4089 }
4090 else {
4091 char *vbar1;
4092 delim = val_end;
4093 /* Now check if the cookie contains a date field, which would
4094 * appear after a vertical bar ('|') just after the server name
4095 * and before the delimiter.
4096 */
4097 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4098 if (vbar1) {
4099 /* OK, so left of the bar is the server's cookie and
4100 * right is the last seen date. It is a base64 encoded
4101 * 30-bit value representing the UNIX date since the
4102 * epoch in 4-second quantities.
4103 */
4104 int val;
4105 delim = vbar1++;
4106 if (val_end - vbar1 >= 5) {
4107 val = b64tos30(vbar1);
4108 if (val > 0)
4109 txn->cookie_last_date = val << 2;
4110 }
4111 /* look for a second vertical bar */
4112 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4113 if (vbar1 && (val_end - vbar1 > 5)) {
4114 val = b64tos30(vbar1 + 1);
4115 if (val > 0)
4116 txn->cookie_first_date = val << 2;
4117 }
4118 }
4119 }
4120
4121 /* if the cookie has an expiration date and the proxy wants to check
4122 * it, then we do that now. We first check if the cookie is too old,
4123 * then only if it has expired. We detect strict overflow because the
4124 * time resolution here is not great (4 seconds). Cookies with dates
4125 * in the future are ignored if their offset is beyond one day. This
4126 * allows an admin to fix timezone issues without expiring everyone
4127 * and at the same time avoids keeping unwanted side effects for too
4128 * long.
4129 */
4130 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4131 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4132 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4133 txn->flags &= ~TX_CK_MASK;
4134 txn->flags |= TX_CK_OLD;
4135 delim = val_beg; // let's pretend we have not found the cookie
4136 txn->cookie_first_date = 0;
4137 txn->cookie_last_date = 0;
4138 }
4139 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4140 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4141 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4142 txn->flags &= ~TX_CK_MASK;
4143 txn->flags |= TX_CK_EXPIRED;
4144 delim = val_beg; // let's pretend we have not found the cookie
4145 txn->cookie_first_date = 0;
4146 txn->cookie_last_date = 0;
4147 }
4148
4149 /* Here, we'll look for the first running server which supports the cookie.
4150 * This allows to share a same cookie between several servers, for example
4151 * to dedicate backup servers to specific servers only.
4152 * However, to prevent clients from sticking to cookie-less backup server
4153 * when they have incidentely learned an empty cookie, we simply ignore
4154 * empty cookies and mark them as invalid.
4155 * The same behaviour is applied when persistence must be ignored.
4156 */
4157 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4158 srv = NULL;
4159
4160 while (srv) {
4161 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4162 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4163 if ((srv->cur_state != SRV_ST_STOPPED) ||
4164 (s->be->options & PR_O_PERSIST) ||
4165 (s->flags & SF_FORCE_PRST)) {
4166 /* we found the server and we can use it */
4167 txn->flags &= ~TX_CK_MASK;
4168 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4169 s->flags |= SF_DIRECT | SF_ASSIGNED;
4170 s->target = &srv->obj_type;
4171 break;
4172 } else {
4173 /* we found a server, but it's down,
4174 * mark it as such and go on in case
4175 * another one is available.
4176 */
4177 txn->flags &= ~TX_CK_MASK;
4178 txn->flags |= TX_CK_DOWN;
4179 }
4180 }
4181 srv = srv->next;
4182 }
4183
4184 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4185 /* no server matched this cookie or we deliberately skipped it */
4186 txn->flags &= ~TX_CK_MASK;
4187 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4188 txn->flags |= TX_CK_UNUSED;
4189 else
4190 txn->flags |= TX_CK_INVALID;
4191 }
4192
4193 /* depending on the cookie mode, we may have to either :
4194 * - delete the complete cookie if we're in insert+indirect mode, so that
4195 * the server never sees it ;
4196 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004197 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004198 * if we're in cookie prefix mode
4199 */
4200 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4201 int delta; /* negative */
4202
4203 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4204 delta = val_beg - (delim + 1);
4205 val_end += delta;
4206 next += delta;
4207 hdr_end += delta;
4208 del_from = NULL;
4209 preserve_hdr = 1; /* we want to keep this cookie */
4210 }
4211 else if (del_from == NULL &&
4212 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4213 del_from = prev;
4214 }
4215 }
4216 else {
4217 /* This is not our cookie, so we must preserve it. But if we already
4218 * scheduled another cookie for removal, we cannot remove the
4219 * complete header, but we can remove the previous block itself.
4220 */
4221 preserve_hdr = 1;
4222
4223 if (del_from != NULL) {
4224 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4225 if (att_beg >= del_from)
4226 att_beg += delta;
4227 if (att_end >= del_from)
4228 att_end += delta;
4229 val_beg += delta;
4230 val_end += delta;
4231 next += delta;
4232 hdr_end += delta;
4233 prev = del_from;
4234 del_from = NULL;
4235 }
4236 }
4237
4238 /* continue with next cookie on this header line */
4239 att_beg = next;
4240 } /* for each cookie */
4241
4242
4243 /* There are no more cookies on this line.
4244 * We may still have one (or several) marked for deletion at the
4245 * end of the line. We must do this now in two ways :
4246 * - if some cookies must be preserved, we only delete from the
4247 * mark to the end of line ;
4248 * - if nothing needs to be preserved, simply delete the whole header
4249 */
4250 if (del_from) {
4251 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4252 }
4253 if ((hdr_end - hdr_beg) != ctx.value.len) {
4254 if (hdr_beg != hdr_end) {
4255 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004256 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004257 }
4258 else
4259 http_remove_header(htx, &ctx);
4260 }
4261 } /* for each "Cookie header */
4262}
4263
4264/*
4265 * Manage server-side cookies. It can impact performance by about 2% so it is
4266 * desirable to call it only when needed. This function is also used when we
4267 * just need to know if there is a cookie (eg: for check-cache).
4268 */
4269static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4270{
4271 struct session *sess = s->sess;
4272 struct http_txn *txn = s->txn;
4273 struct htx *htx;
4274 struct http_hdr_ctx ctx;
4275 struct server *srv;
4276 char *hdr_beg, *hdr_end;
4277 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4278 int is_cookie2;
4279
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004280 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004281
4282 ctx.blk = NULL;
4283 while (1) {
4284 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4285 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4286 break;
4287 is_cookie2 = 1;
4288 }
4289
4290 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4291 * <prev> points to the colon.
4292 */
4293 txn->flags |= TX_SCK_PRESENT;
4294
4295 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4296 * check-cache is enabled) and we are not interested in checking
4297 * them. Warning, the cookie capture is declared in the frontend.
4298 */
4299 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4300 break;
4301
4302 /* OK so now we know we have to process this response cookie.
4303 * The format of the Set-Cookie header is slightly different
4304 * from the format of the Cookie header in that it does not
4305 * support the comma as a cookie delimiter (thus the header
4306 * cannot be folded) because the Expires attribute described in
4307 * the original Netscape's spec may contain an unquoted date
4308 * with a comma inside. We have to live with this because
4309 * many browsers don't support Max-Age and some browsers don't
4310 * support quoted strings. However the Set-Cookie2 header is
4311 * clean.
4312 *
4313 * We have to keep multiple pointers in order to support cookie
4314 * removal at the beginning, middle or end of header without
4315 * corrupting the header (in case of set-cookie2). A special
4316 * pointer, <scav> points to the beginning of the set-cookie-av
4317 * fields after the first semi-colon. The <next> pointer points
4318 * either to the end of line (set-cookie) or next unquoted comma
4319 * (set-cookie2). All of these headers are valid :
4320 *
4321 * hdr_beg hdr_end
4322 * | |
4323 * v |
4324 * NAME1 = VALUE 1 ; Secure; Path="/" |
4325 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4326 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4327 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4328 * | | | | | | | |
4329 * | | | | | | | +-> next
4330 * | | | | | | +------------> scav
4331 * | | | | | +--------------> val_end
4332 * | | | | +--------------------> val_beg
4333 * | | | +----------------------> equal
4334 * | | +------------------------> att_end
4335 * | +----------------------------> att_beg
4336 * +------------------------------> prev
4337 * -------------------------------> hdr_beg
4338 */
4339 hdr_beg = ctx.value.ptr;
4340 hdr_end = hdr_beg + ctx.value.len;
4341 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4342
4343 /* Iterate through all cookies on this line */
4344
4345 /* find att_beg */
4346 att_beg = prev;
4347 if (prev > hdr_beg)
4348 att_beg++;
4349
4350 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4351 att_beg++;
4352
4353 /* find att_end : this is the first character after the last non
4354 * space before the equal. It may be equal to hdr_end.
4355 */
4356 equal = att_end = att_beg;
4357
4358 while (equal < hdr_end) {
4359 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4360 break;
4361 if (HTTP_IS_SPHT(*equal++))
4362 continue;
4363 att_end = equal;
4364 }
4365
4366 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4367 * is between <att_beg> and <equal>, both may be identical.
4368 */
4369
4370 /* look for end of cookie if there is an equal sign */
4371 if (equal < hdr_end && *equal == '=') {
4372 /* look for the beginning of the value */
4373 val_beg = equal + 1;
4374 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4375 val_beg++;
4376
4377 /* find the end of the value, respecting quotes */
4378 next = http_find_cookie_value_end(val_beg, hdr_end);
4379
4380 /* make val_end point to the first white space or delimitor after the value */
4381 val_end = next;
4382 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4383 val_end--;
4384 }
4385 else {
4386 /* <equal> points to next comma, semi-colon or EOL */
4387 val_beg = val_end = next = equal;
4388 }
4389
4390 if (next < hdr_end) {
4391 /* Set-Cookie2 supports multiple cookies, and <next> points to
4392 * a colon or semi-colon before the end. So skip all attr-value
4393 * pairs and look for the next comma. For Set-Cookie, since
4394 * commas are permitted in values, skip to the end.
4395 */
4396 if (is_cookie2)
4397 next = http_find_hdr_value_end(next, hdr_end);
4398 else
4399 next = hdr_end;
4400 }
4401
4402 /* Now everything is as on the diagram above */
4403
4404 /* Ignore cookies with no equal sign */
4405 if (equal == val_end)
4406 continue;
4407
4408 /* If there are spaces around the equal sign, we need to
4409 * strip them otherwise we'll get trouble for cookie captures,
4410 * or even for rewrites. Since this happens extremely rarely,
4411 * it does not hurt performance.
4412 */
4413 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4414 int stripped_before = 0;
4415 int stripped_after = 0;
4416
4417 if (att_end != equal) {
4418 memmove(att_end, equal, hdr_end - equal);
4419 stripped_before = (att_end - equal);
4420 equal += stripped_before;
4421 val_beg += stripped_before;
4422 }
4423
4424 if (val_beg > equal + 1) {
4425 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4426 stripped_after = (equal + 1) - val_beg;
4427 val_beg += stripped_after;
4428 stripped_before += stripped_after;
4429 }
4430
4431 val_end += stripped_before;
4432 next += stripped_before;
4433 hdr_end += stripped_before;
4434
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004435 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4436 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004437 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004438 }
4439
4440 /* First, let's see if we want to capture this cookie. We check
4441 * that we don't already have a server side cookie, because we
4442 * can only capture one. Also as an optimisation, we ignore
4443 * cookies shorter than the declared name.
4444 */
4445 if (sess->fe->capture_name != NULL &&
4446 txn->srv_cookie == NULL &&
4447 (val_end - att_beg >= sess->fe->capture_namelen) &&
4448 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4449 int log_len = val_end - att_beg;
4450 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4451 ha_alert("HTTP logging : out of memory.\n");
4452 }
4453 else {
4454 if (log_len > sess->fe->capture_len)
4455 log_len = sess->fe->capture_len;
4456 memcpy(txn->srv_cookie, att_beg, log_len);
4457 txn->srv_cookie[log_len] = 0;
4458 }
4459 }
4460
4461 srv = objt_server(s->target);
4462 /* now check if we need to process it for persistence */
4463 if (!(s->flags & SF_IGNORE_PRST) &&
4464 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4465 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4466 /* assume passive cookie by default */
4467 txn->flags &= ~TX_SCK_MASK;
4468 txn->flags |= TX_SCK_FOUND;
4469
4470 /* If the cookie is in insert mode on a known server, we'll delete
4471 * this occurrence because we'll insert another one later.
4472 * We'll delete it too if the "indirect" option is set and we're in
4473 * a direct access.
4474 */
4475 if (s->be->ck_opts & PR_CK_PSV) {
4476 /* The "preserve" flag was set, we don't want to touch the
4477 * server's cookie.
4478 */
4479 }
4480 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4481 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4482 /* this cookie must be deleted */
4483 if (prev == hdr_beg && next == hdr_end) {
4484 /* whole header */
4485 http_remove_header(htx, &ctx);
4486 /* note: while both invalid now, <next> and <hdr_end>
4487 * are still equal, so the for() will stop as expected.
4488 */
4489 } else {
4490 /* just remove the value */
4491 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4492 next = prev;
4493 hdr_end += delta;
4494 }
4495 txn->flags &= ~TX_SCK_MASK;
4496 txn->flags |= TX_SCK_DELETED;
4497 /* and go on with next cookie */
4498 }
4499 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4500 /* replace bytes val_beg->val_end with the cookie name associated
4501 * with this server since we know it.
4502 */
4503 int sliding, delta;
4504
4505 ctx.value = ist2(val_beg, val_end - val_beg);
4506 ctx.lws_before = ctx.lws_after = 0;
4507 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4508 delta = srv->cklen - (val_end - val_beg);
4509 sliding = (ctx.value.ptr - val_beg);
4510 hdr_beg += sliding;
4511 val_beg += sliding;
4512 next += sliding + delta;
4513 hdr_end += sliding + delta;
4514
4515 txn->flags &= ~TX_SCK_MASK;
4516 txn->flags |= TX_SCK_REPLACED;
4517 }
4518 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4519 /* insert the cookie name associated with this server
4520 * before existing cookie, and insert a delimiter between them..
4521 */
4522 int sliding, delta;
4523 ctx.value = ist2(val_beg, 0);
4524 ctx.lws_before = ctx.lws_after = 0;
4525 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4526 delta = srv->cklen + 1;
4527 sliding = (ctx.value.ptr - val_beg);
4528 hdr_beg += sliding;
4529 val_beg += sliding;
4530 next += sliding + delta;
4531 hdr_end += sliding + delta;
4532
4533 val_beg[srv->cklen] = COOKIE_DELIM;
4534 txn->flags &= ~TX_SCK_MASK;
4535 txn->flags |= TX_SCK_REPLACED;
4536 }
4537 }
4538 /* that's done for this cookie, check the next one on the same
4539 * line when next != hdr_end (only if is_cookie2).
4540 */
4541 }
4542 }
4543}
4544
Christopher Faulet25a02f62018-10-24 12:00:25 +02004545/*
4546 * Parses the Cache-Control and Pragma request header fields to determine if
4547 * the request may be served from the cache and/or if it is cacheable. Updates
4548 * s->txn->flags.
4549 */
4550void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4551{
4552 struct http_txn *txn = s->txn;
4553 struct htx *htx;
4554 int32_t pos;
4555 int pragma_found, cc_found, i;
4556
4557 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4558 return; /* nothing more to do here */
4559
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004560 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004561 pragma_found = cc_found = 0;
4562 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4563 struct htx_blk *blk = htx_get_blk(htx, pos);
4564 enum htx_blk_type type = htx_get_blk_type(blk);
4565 struct ist n, v;
4566
4567 if (type == HTX_BLK_EOH)
4568 break;
4569 if (type != HTX_BLK_HDR)
4570 continue;
4571
4572 n = htx_get_blk_name(htx, blk);
4573 v = htx_get_blk_value(htx, blk);
4574
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004575 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004576 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4577 pragma_found = 1;
4578 continue;
4579 }
4580 }
4581
4582 /* Don't use the cache and don't try to store if we found the
4583 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004584 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004585 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4586 txn->flags |= TX_CACHE_IGNORE;
4587 continue;
4588 }
4589
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004590 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004591 continue;
4592
4593 /* OK, right now we know we have a cache-control header */
4594 cc_found = 1;
4595 if (!v.len) /* no info */
4596 continue;
4597
4598 i = 0;
4599 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4600 !isspace((unsigned char)*(v.ptr+i)))
4601 i++;
4602
4603 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4604 * values after max-age, max-stale nor min-fresh, we simply don't
4605 * use the cache when they're specified.
4606 */
4607 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4608 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4609 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4610 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4611 txn->flags |= TX_CACHE_IGNORE;
4612 continue;
4613 }
4614
4615 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4616 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4617 continue;
4618 }
4619 }
4620
4621 /* RFC7234#5.4:
4622 * When the Cache-Control header field is also present and
4623 * understood in a request, Pragma is ignored.
4624 * When the Cache-Control header field is not present in a
4625 * request, caches MUST consider the no-cache request
4626 * pragma-directive as having the same effect as if
4627 * "Cache-Control: no-cache" were present.
4628 */
4629 if (!cc_found && pragma_found)
4630 txn->flags |= TX_CACHE_IGNORE;
4631}
4632
4633/*
4634 * Check if response is cacheable or not. Updates s->txn->flags.
4635 */
4636void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4637{
4638 struct http_txn *txn = s->txn;
4639 struct htx *htx;
4640 int32_t pos;
4641 int i;
4642
4643 if (txn->status < 200) {
4644 /* do not try to cache interim responses! */
4645 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4646 return;
4647 }
4648
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004649 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004650 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4651 struct htx_blk *blk = htx_get_blk(htx, pos);
4652 enum htx_blk_type type = htx_get_blk_type(blk);
4653 struct ist n, v;
4654
4655 if (type == HTX_BLK_EOH)
4656 break;
4657 if (type != HTX_BLK_HDR)
4658 continue;
4659
4660 n = htx_get_blk_name(htx, blk);
4661 v = htx_get_blk_value(htx, blk);
4662
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004663 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004664 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4665 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4666 return;
4667 }
4668 }
4669
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004670 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004671 continue;
4672
4673 /* OK, right now we know we have a cache-control header */
4674 if (!v.len) /* no info */
4675 continue;
4676
4677 i = 0;
4678 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4679 !isspace((unsigned char)*(v.ptr+i)))
4680 i++;
4681
4682 /* we have a complete value between v.ptr and (v.ptr+i) */
4683 if (i < v.len && *(v.ptr + i) == '=') {
4684 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4685 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4686 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4687 continue;
4688 }
4689
4690 /* we have something of the form no-cache="set-cookie" */
4691 if ((v.len >= 21) &&
4692 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4693 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4694 txn->flags &= ~TX_CACHE_COOK;
4695 continue;
4696 }
4697
4698 /* OK, so we know that either p2 points to the end of string or to a comma */
4699 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4700 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4701 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4702 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4703 return;
4704 }
4705
4706 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4707 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4708 continue;
4709 }
4710 }
4711}
4712
Christopher Faulet64159df2018-10-24 21:15:35 +02004713/* send a server's name with an outgoing request over an established connection.
4714 * Note: this function is designed to be called once the request has been
4715 * scheduled for being forwarded. This is the reason why the number of forwarded
4716 * bytes have to be adjusted.
4717 */
4718int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4719{
4720 struct htx *htx;
4721 struct http_hdr_ctx ctx;
4722 struct ist hdr;
4723 uint32_t data;
4724
4725 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004726 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004727 data = htx->data;
4728
4729 ctx.blk = NULL;
4730 while (http_find_header(htx, hdr, &ctx, 1))
4731 http_remove_header(htx, &ctx);
4732 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4733
4734 if (co_data(&s->req)) {
4735 if (data >= htx->data)
4736 c_rew(&s->req, data - htx->data);
4737 else
4738 c_adv(&s->req, htx->data - data);
4739 }
4740 return 0;
4741}
4742
Christopher Faulet377c5a52018-10-24 21:21:30 +02004743/*
4744 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4745 * for the current backend.
4746 *
4747 * It is assumed that the request is either a HEAD, GET, or POST and that the
4748 * uri_auth field is valid.
4749 *
4750 * Returns 1 if stats should be provided, otherwise 0.
4751 */
4752static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4753{
4754 struct uri_auth *uri_auth = backend->uri_auth;
4755 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004756 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004757 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004758
4759 if (!uri_auth)
4760 return 0;
4761
4762 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4763 return 0;
4764
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004765 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004766 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004767 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004768
4769 /* check URI size */
4770 if (uri_auth->uri_len > uri.len)
4771 return 0;
4772
4773 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4774 return 0;
4775
4776 return 1;
4777}
4778
4779/* This function prepares an applet to handle the stats. It can deal with the
4780 * "100-continue" expectation, check that admin rules are met for POST requests,
4781 * and program a response message if something was unexpected. It cannot fail
4782 * and always relies on the stats applet to complete the job. It does not touch
4783 * analysers nor counters, which are left to the caller. It does not touch
4784 * s->target which is supposed to already point to the stats applet. The caller
4785 * is expected to have already assigned an appctx to the stream.
4786 */
4787static int htx_handle_stats(struct stream *s, struct channel *req)
4788{
4789 struct stats_admin_rule *stats_admin_rule;
4790 struct stream_interface *si = &s->si[1];
4791 struct session *sess = s->sess;
4792 struct http_txn *txn = s->txn;
4793 struct http_msg *msg = &txn->req;
4794 struct uri_auth *uri_auth = s->be->uri_auth;
4795 const char *h, *lookup, *end;
4796 struct appctx *appctx;
4797 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004798 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004799
4800 appctx = si_appctx(si);
4801 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4802 appctx->st1 = appctx->st2 = 0;
4803 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4804 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4805 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4806 appctx->ctx.stats.flags |= STAT_CHUNKED;
4807
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004808 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004809 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004810 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4811 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812
4813 for (h = lookup; h <= end - 3; h++) {
4814 if (memcmp(h, ";up", 3) == 0) {
4815 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4816 break;
4817 }
4818 }
4819
4820 if (uri_auth->refresh) {
4821 for (h = lookup; h <= end - 10; h++) {
4822 if (memcmp(h, ";norefresh", 10) == 0) {
4823 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4824 break;
4825 }
4826 }
4827 }
4828
4829 for (h = lookup; h <= end - 4; h++) {
4830 if (memcmp(h, ";csv", 4) == 0) {
4831 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4832 break;
4833 }
4834 }
4835
4836 for (h = lookup; h <= end - 6; h++) {
4837 if (memcmp(h, ";typed", 6) == 0) {
4838 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4839 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4840 break;
4841 }
4842 }
4843
4844 for (h = lookup; h <= end - 8; h++) {
4845 if (memcmp(h, ";st=", 4) == 0) {
4846 int i;
4847 h += 4;
4848 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4849 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4850 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4851 appctx->ctx.stats.st_code = i;
4852 break;
4853 }
4854 }
4855 break;
4856 }
4857 }
4858
4859 appctx->ctx.stats.scope_str = 0;
4860 appctx->ctx.stats.scope_len = 0;
4861 for (h = lookup; h <= end - 8; h++) {
4862 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4863 int itx = 0;
4864 const char *h2;
4865 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4866 const char *err;
4867
4868 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4869 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004870 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4871 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004872 if (*h == ';' || *h == '&' || *h == ' ')
4873 break;
4874 itx++;
4875 h++;
4876 }
4877
4878 if (itx > STAT_SCOPE_TXT_MAXLEN)
4879 itx = STAT_SCOPE_TXT_MAXLEN;
4880 appctx->ctx.stats.scope_len = itx;
4881
4882 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4883 memcpy(scope_txt, h2, itx);
4884 scope_txt[itx] = '\0';
4885 err = invalid_char(scope_txt);
4886 if (err) {
4887 /* bad char in search text => clear scope */
4888 appctx->ctx.stats.scope_str = 0;
4889 appctx->ctx.stats.scope_len = 0;
4890 }
4891 break;
4892 }
4893 }
4894
4895 /* now check whether we have some admin rules for this request */
4896 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4897 int ret = 1;
4898
4899 if (stats_admin_rule->cond) {
4900 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4901 ret = acl_pass(ret);
4902 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4903 ret = !ret;
4904 }
4905
4906 if (ret) {
4907 /* no rule, or the rule matches */
4908 appctx->ctx.stats.flags |= STAT_ADMIN;
4909 break;
4910 }
4911 }
4912
Christopher Faulet5d45e382019-02-27 15:15:23 +01004913 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4914 appctx->st0 = STAT_HTTP_HEAD;
4915 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004916 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004917 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004918 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004919 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004920 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4921 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4922 appctx->st0 = STAT_HTTP_LAST;
4923 }
4924 }
4925 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004926 /* Unsupported method */
4927 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4928 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4929 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004930 }
4931
4932 s->task->nice = -32; /* small boost for HTTP statistics */
4933 return 1;
4934}
4935
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004936void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4937{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004938 struct channel *req = &s->req;
4939 struct channel *res = &s->res;
4940 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004941 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004942 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004943 struct ist path, location;
4944 unsigned int flags;
4945 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004946
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004947 /*
4948 * Create the location
4949 */
4950 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004951
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004952 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004953 /* special prefix "/" means don't change URL */
4954 srv = __objt_server(s->target);
4955 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4956 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4957 return;
4958 }
4959
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004960 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004961 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004962 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004963 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004964 if (!path.ptr)
4965 return;
4966
4967 if (!chunk_memcat(&trash, path.ptr, path.len))
4968 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004969 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004970
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004971 /*
4972 * Create the 302 respone
4973 */
4974 htx = htx_from_buf(&res->buf);
4975 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4976 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4977 ist("HTTP/1.1"), ist("302"), ist("Found"));
4978 if (!sl)
4979 goto fail;
4980 sl->info.res.status = 302;
4981 s->txn->status = 302;
4982
4983 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4984 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4985 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4986 !htx_add_header(htx, ist("Location"), location))
4987 goto fail;
4988
4989 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4990 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004991
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004992 /*
4993 * Send the message
4994 */
4995 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004996 c_adv(res, data);
4997 res->total += data;
4998
4999 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005000 si_shutr(si);
5001 si_shutw(si);
5002 si->err_type = SI_ET_NONE;
5003 si->state = SI_ST_CLO;
5004
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005005 channel_auto_read(req);
5006 channel_abort(req);
5007 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005008 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005009 channel_auto_read(res);
5010 channel_auto_close(res);
5011
5012 if (!(s->flags & SF_ERR_MASK))
5013 s->flags |= SF_ERR_LOCAL;
5014 if (!(s->flags & SF_FINST_MASK))
5015 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005016
5017 /* FIXME: we should increase a counter of redirects per server and per backend. */
5018 srv_inc_sess_ctr(srv);
5019 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005020 return;
5021
5022 fail:
5023 /* If an error occurred, remove the incomplete HTTP response from the
5024 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005025 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005026}
5027
Christopher Fauletf2824e62018-10-01 12:12:37 +02005028/* This function terminates the request because it was completly analyzed or
5029 * because an error was triggered during the body forwarding.
5030 */
5031static void htx_end_request(struct stream *s)
5032{
5033 struct channel *chn = &s->req;
5034 struct http_txn *txn = s->txn;
5035
5036 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5037 now_ms, __FUNCTION__, s,
5038 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5039 s->req.analysers, s->res.analysers);
5040
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005041 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5042 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005043 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005044 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005045 goto end;
5046 }
5047
5048 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5049 return;
5050
5051 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005052 /* No need to read anymore, the request was completely parsed.
5053 * We can shut the read side unless we want to abort_on_close,
5054 * or we have a POST request. The issue with POST requests is
5055 * that some browsers still send a CRLF after the request, and
5056 * this CRLF must be read so that it does not remain in the kernel
5057 * buffers, otherwise a close could cause an RST on some systems
5058 * (eg: Linux).
5059 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005060 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005061 channel_dont_read(chn);
5062
5063 /* if the server closes the connection, we want to immediately react
5064 * and close the socket to save packets and syscalls.
5065 */
5066 s->si[1].flags |= SI_FL_NOHALF;
5067
5068 /* In any case we've finished parsing the request so we must
5069 * disable Nagle when sending data because 1) we're not going
5070 * to shut this side, and 2) the server is waiting for us to
5071 * send pending data.
5072 */
5073 chn->flags |= CF_NEVER_WAIT;
5074
Christopher Fauletd01ce402019-01-02 17:44:13 +01005075 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5076 /* The server has not finished to respond, so we
5077 * don't want to move in order not to upset it.
5078 */
5079 return;
5080 }
5081
Christopher Fauletf2824e62018-10-01 12:12:37 +02005082 /* When we get here, it means that both the request and the
5083 * response have finished receiving. Depending on the connection
5084 * mode, we'll have to wait for the last bytes to leave in either
5085 * direction, and sometimes for a close to be effective.
5086 */
5087 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5088 /* Tunnel mode will not have any analyser so it needs to
5089 * poll for reads.
5090 */
5091 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005092 if (b_data(&chn->buf))
5093 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005094 txn->req.msg_state = HTTP_MSG_TUNNEL;
5095 }
5096 else {
5097 /* we're not expecting any new data to come for this
5098 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005099 *
5100 * However, there is an exception if the response
5101 * length is undefined. In this case, we need to wait
5102 * the close from the server. The response will be
5103 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005104 */
5105 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5106 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005107 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005108
5109 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5110 channel_shutr_now(chn);
5111 channel_shutw_now(chn);
5112 }
5113 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005114 goto check_channel_flags;
5115 }
5116
5117 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5118 http_msg_closing:
5119 /* nothing else to forward, just waiting for the output buffer
5120 * to be empty and for the shutw_now to take effect.
5121 */
5122 if (channel_is_empty(chn)) {
5123 txn->req.msg_state = HTTP_MSG_CLOSED;
5124 goto http_msg_closed;
5125 }
5126 else if (chn->flags & CF_SHUTW) {
5127 txn->req.err_state = txn->req.msg_state;
5128 txn->req.msg_state = HTTP_MSG_ERROR;
5129 goto end;
5130 }
5131 return;
5132 }
5133
5134 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5135 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136 /* if we don't know whether the server will close, we need to hard close */
5137 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5138 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005139 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005140 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005141 channel_dont_read(chn);
5142 goto end;
5143 }
5144
5145 check_channel_flags:
5146 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5147 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5148 /* if we've just closed an output, let's switch */
5149 txn->req.msg_state = HTTP_MSG_CLOSING;
5150 goto http_msg_closing;
5151 }
5152
5153 end:
5154 chn->analysers &= AN_REQ_FLT_END;
5155 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5156 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5157 channel_auto_close(chn);
5158 channel_auto_read(chn);
5159}
5160
5161
5162/* This function terminates the response because it was completly analyzed or
5163 * because an error was triggered during the body forwarding.
5164 */
5165static void htx_end_response(struct stream *s)
5166{
5167 struct channel *chn = &s->res;
5168 struct http_txn *txn = s->txn;
5169
5170 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5171 now_ms, __FUNCTION__, s,
5172 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5173 s->req.analysers, s->res.analysers);
5174
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005175 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5176 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005177 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005178 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005179 goto end;
5180 }
5181
5182 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5183 return;
5184
5185 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5186 /* In theory, we don't need to read anymore, but we must
5187 * still monitor the server connection for a possible close
5188 * while the request is being uploaded, so we don't disable
5189 * reading.
5190 */
5191 /* channel_dont_read(chn); */
5192
5193 if (txn->req.msg_state < HTTP_MSG_DONE) {
5194 /* The client seems to still be sending data, probably
5195 * because we got an error response during an upload.
5196 * We have the choice of either breaking the connection
5197 * or letting it pass through. Let's do the later.
5198 */
5199 return;
5200 }
5201
5202 /* When we get here, it means that both the request and the
5203 * response have finished receiving. Depending on the connection
5204 * mode, we'll have to wait for the last bytes to leave in either
5205 * direction, and sometimes for a close to be effective.
5206 */
5207 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5208 channel_auto_read(chn);
5209 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005210 if (b_data(&chn->buf))
5211 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005212 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5213 }
5214 else {
5215 /* we're not expecting any new data to come for this
5216 * transaction, so we can close it.
5217 */
5218 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5219 channel_shutr_now(chn);
5220 channel_shutw_now(chn);
5221 }
5222 }
5223 goto check_channel_flags;
5224 }
5225
5226 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5227 http_msg_closing:
5228 /* nothing else to forward, just waiting for the output buffer
5229 * to be empty and for the shutw_now to take effect.
5230 */
5231 if (channel_is_empty(chn)) {
5232 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5233 goto http_msg_closed;
5234 }
5235 else if (chn->flags & CF_SHUTW) {
5236 txn->rsp.err_state = txn->rsp.msg_state;
5237 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005238 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005239 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005240 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005241 goto end;
5242 }
5243 return;
5244 }
5245
5246 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5247 http_msg_closed:
5248 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005249 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005250 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005251 goto end;
5252 }
5253
5254 check_channel_flags:
5255 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5256 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5257 /* if we've just closed an output, let's switch */
5258 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5259 goto http_msg_closing;
5260 }
5261
5262 end:
5263 chn->analysers &= AN_RES_FLT_END;
5264 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5265 chn->analysers |= AN_RES_FLT_XFER_DATA;
5266 channel_auto_close(chn);
5267 channel_auto_read(chn);
5268}
5269
Christopher Faulet0f226952018-10-22 09:29:56 +02005270void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5271 int finst, const struct buffer *msg)
5272{
5273 channel_auto_read(si_oc(si));
5274 channel_abort(si_oc(si));
5275 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005276 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005277 channel_auto_close(si_ic(si));
5278 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005279
5280 /* <msg> is an HTX structure. So we copy it in the response's
5281 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005282 if (msg) {
5283 struct channel *chn = si_ic(si);
5284 struct htx *htx;
5285
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005286 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005287 chn->buf.data = msg->data;
5288 memcpy(chn->buf.area, msg->area, msg->data);
5289 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005290 c_adv(chn, htx->data);
5291 chn->total += htx->data;
5292 }
5293 if (!(s->flags & SF_ERR_MASK))
5294 s->flags |= err;
5295 if (!(s->flags & SF_FINST_MASK))
5296 s->flags |= finst;
5297}
5298
5299void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5300{
5301 channel_auto_read(&s->req);
5302 channel_abort(&s->req);
5303 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005304 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5305 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005306
5307 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005308
5309 /* <msg> is an HTX structure. So we copy it in the response's
5310 * channel */
5311 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005312 if (msg) {
5313 struct channel *chn = &s->res;
5314 struct htx *htx;
5315
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005316 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005317 chn->buf.data = msg->data;
5318 memcpy(chn->buf.area, msg->area, msg->data);
5319 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005320 c_adv(chn, htx->data);
5321 chn->total += htx->data;
5322 }
5323
5324 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5325 channel_auto_read(&s->res);
5326 channel_auto_close(&s->res);
5327 channel_shutr_now(&s->res);
5328}
5329
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005330struct buffer *htx_error_message(struct stream *s)
5331{
5332 const int msgnum = http_get_status_idx(s->txn->status);
5333
5334 if (s->be->errmsg[msgnum].area)
5335 return &s->be->errmsg[msgnum];
5336 else if (strm_fe(s)->errmsg[msgnum].area)
5337 return &strm_fe(s)->errmsg[msgnum];
5338 else
5339 return &htx_err_chunks[msgnum];
5340}
5341
5342
Christopher Faulet4a28a532019-03-01 11:19:40 +01005343/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5344 * on success and -1 on error.
5345 */
5346static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5347{
5348 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5349 * then we must send an HTTP/1.1 100 Continue intermediate response.
5350 */
5351 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5352 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5353 struct ist hdr = { .ptr = "Expect", .len = 6 };
5354 struct http_hdr_ctx ctx;
5355
5356 ctx.blk = NULL;
5357 /* Expect is allowed in 1.1, look for it */
5358 if (http_find_header(htx, hdr, &ctx, 0) &&
5359 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5360 if (htx_reply_100_continue(s) == -1)
5361 return -1;
5362 http_remove_header(htx, &ctx);
5363 }
5364 }
5365 return 0;
5366}
5367
Christopher Faulet23a3c792018-11-28 10:01:23 +01005368/* Send a 100-Continue response to the client. It returns 0 on success and -1
5369 * on error. The response channel is updated accordingly.
5370 */
5371static int htx_reply_100_continue(struct stream *s)
5372{
5373 struct channel *res = &s->res;
5374 struct htx *htx = htx_from_buf(&res->buf);
5375 struct htx_sl *sl;
5376 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5377 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5378 size_t data;
5379
5380 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5381 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5382 if (!sl)
5383 goto fail;
5384 sl->info.res.status = 100;
5385
5386 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5387 goto fail;
5388
5389 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005390 c_adv(res, data);
5391 res->total += data;
5392 return 0;
5393
5394 fail:
5395 /* If an error occurred, remove the incomplete HTTP response from the
5396 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005397 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005398 return -1;
5399}
5400
Christopher Faulet12c51e22018-11-28 15:59:42 +01005401
5402/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5403 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5404 * error. The response channel is updated accordingly.
5405 */
5406static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5407{
5408 struct channel *res = &s->res;
5409 struct htx *htx = htx_from_buf(&res->buf);
5410 struct htx_sl *sl;
5411 struct ist code, body;
5412 int status;
5413 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5414 size_t data;
5415
5416 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5417 status = 401;
5418 code = ist("401");
5419 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5420 "You need a valid user and password to access this content.\n"
5421 "</body></html>\n");
5422 }
5423 else {
5424 status = 407;
5425 code = ist("407");
5426 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5427 "You need a valid user and password to access this content.\n"
5428 "</body></html>\n");
5429 }
5430
5431 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5432 ist("HTTP/1.1"), code, ist("Unauthorized"));
5433 if (!sl)
5434 goto fail;
5435 sl->info.res.status = status;
5436 s->txn->status = status;
5437
5438 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5439 goto fail;
5440
5441 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5442 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005443 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5444 goto fail;
5445 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5446 goto fail;
5447 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005448 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005449 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5450 goto fail;
5451
5452 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005453 c_adv(res, data);
5454 res->total += data;
5455
5456 channel_auto_read(&s->req);
5457 channel_abort(&s->req);
5458 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005459 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005460
5461 res->wex = tick_add_ifset(now_ms, res->wto);
5462 channel_auto_read(res);
5463 channel_auto_close(res);
5464 channel_shutr_now(res);
5465 return 0;
5466
5467 fail:
5468 /* If an error occurred, remove the incomplete HTTP response from the
5469 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005470 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005471 return -1;
5472}
5473
Christopher Faulet0f226952018-10-22 09:29:56 +02005474/*
5475 * Capture headers from message <htx> according to header list <cap_hdr>, and
5476 * fill the <cap> pointers appropriately.
5477 */
5478static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5479{
5480 struct cap_hdr *h;
5481 int32_t pos;
5482
5483 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5484 struct htx_blk *blk = htx_get_blk(htx, pos);
5485 enum htx_blk_type type = htx_get_blk_type(blk);
5486 struct ist n, v;
5487
5488 if (type == HTX_BLK_EOH)
5489 break;
5490 if (type != HTX_BLK_HDR)
5491 continue;
5492
5493 n = htx_get_blk_name(htx, blk);
5494
5495 for (h = cap_hdr; h; h = h->next) {
5496 if (h->namelen && (h->namelen == n.len) &&
5497 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5498 if (cap[h->index] == NULL)
5499 cap[h->index] =
5500 pool_alloc(h->pool);
5501
5502 if (cap[h->index] == NULL) {
5503 ha_alert("HTTP capture : out of memory.\n");
5504 break;
5505 }
5506
5507 v = htx_get_blk_value(htx, blk);
5508 if (v.len > h->len)
5509 v.len = h->len;
5510
5511 memcpy(cap[h->index], v.ptr, v.len);
5512 cap[h->index][v.len]=0;
5513 }
5514 }
5515 }
5516}
5517
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005518/* Delete a value in a header between delimiters <from> and <next>. The header
5519 * itself is delimited by <start> and <end> pointers. The number of characters
5520 * displaced is returned, and the pointer to the first delimiter is updated if
5521 * required. The function tries as much as possible to respect the following
5522 * principles :
5523 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5524 * in which case <next> is simply removed
5525 * - set exactly one space character after the new first delimiter, unless there
5526 * are not enough characters in the block being moved to do so.
5527 * - remove unneeded spaces before the previous delimiter and after the new
5528 * one.
5529 *
5530 * It is the caller's responsibility to ensure that :
5531 * - <from> points to a valid delimiter or <start> ;
5532 * - <next> points to a valid delimiter or <end> ;
5533 * - there are non-space chars before <from>.
5534 */
5535static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5536{
5537 char *prev = *from;
5538
5539 if (prev == start) {
5540 /* We're removing the first value. eat the semicolon, if <next>
5541 * is lower than <end> */
5542 if (next < end)
5543 next++;
5544
5545 while (next < end && HTTP_IS_SPHT(*next))
5546 next++;
5547 }
5548 else {
5549 /* Remove useless spaces before the old delimiter. */
5550 while (HTTP_IS_SPHT(*(prev-1)))
5551 prev--;
5552 *from = prev;
5553
5554 /* copy the delimiter and if possible a space if we're
5555 * not at the end of the line.
5556 */
5557 if (next < end) {
5558 *prev++ = *next++;
5559 if (prev + 1 < next)
5560 *prev++ = ' ';
5561 while (next < end && HTTP_IS_SPHT(*next))
5562 next++;
5563 }
5564 }
5565 memmove(prev, next, end - next);
5566 return (prev - next);
5567}
5568
Christopher Faulet0f226952018-10-22 09:29:56 +02005569
5570/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005571 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005572 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005573static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005574{
5575 struct ist dst = ist2(str, 0);
5576
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005577 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005578 goto end;
5579 if (dst.len + 1 > len)
5580 goto end;
5581 dst.ptr[dst.len++] = ' ';
5582
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005583 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005584 goto end;
5585 if (dst.len + 1 > len)
5586 goto end;
5587 dst.ptr[dst.len++] = ' ';
5588
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005589 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005590 end:
5591 return dst.len;
5592}
5593
Christopher Fauletf0523542018-10-24 11:06:58 +02005594/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005595 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005596 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005597static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005598{
5599 struct ist dst = ist2(str, 0);
5600
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005601 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005602 goto end;
5603 if (dst.len + 1 > len)
5604 goto end;
5605 dst.ptr[dst.len++] = ' ';
5606
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005607 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005608 goto end;
5609 if (dst.len + 1 > len)
5610 goto end;
5611 dst.ptr[dst.len++] = ' ';
5612
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005613 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005614 end:
5615 return dst.len;
5616}
5617
5618
Christopher Faulet0f226952018-10-22 09:29:56 +02005619/*
5620 * Print a debug line with a start line.
5621 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005622static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005623{
5624 struct session *sess = strm_sess(s);
5625 int max;
5626
5627 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5628 dir,
5629 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5630 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5631
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005632 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005633 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005634 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005635 trash.area[trash.data++] = ' ';
5636
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005638 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005639 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005640 trash.area[trash.data++] = ' ';
5641
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005643 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005644 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005645 trash.area[trash.data++] = '\n';
5646
5647 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5648}
5649
5650/*
5651 * Print a debug line with a header.
5652 */
5653static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5654{
5655 struct session *sess = strm_sess(s);
5656 int max;
5657
5658 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5659 dir,
5660 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5661 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5662
5663 max = n.len;
5664 UBOUND(max, trash.size - trash.data - 3);
5665 chunk_memcat(&trash, n.ptr, max);
5666 trash.area[trash.data++] = ':';
5667 trash.area[trash.data++] = ' ';
5668
5669 max = v.len;
5670 UBOUND(max, trash.size - trash.data - 1);
5671 chunk_memcat(&trash, v.ptr, max);
5672 trash.area[trash.data++] = '\n';
5673
5674 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5675}
5676
5677
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005678__attribute__((constructor))
5679static void __htx_protocol_init(void)
5680{
5681}
5682
5683
5684/*
5685 * Local variables:
5686 * c-indent-level: 8
5687 * c-basic-offset: 8
5688 * End:
5689 */