blob: 33879438a819100d54b7168f5303f5a2907f651c [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
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100412 /* by default, close the stream at the end of the transaction. */
413 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
415 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200416 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417 req->analysers |= AN_REQ_HTTP_BODY;
418
419 /*
420 * RFC7234#4:
421 * A cache MUST write through requests with methods
422 * that are unsafe (Section 4.2.1 of [RFC7231]) to
423 * the origin server; i.e., a cache is not allowed
424 * to generate a reply to such a request before
425 * having forwarded the request and having received
426 * a corresponding response.
427 *
428 * RFC7231#4.2.1:
429 * Of the request methods defined by this
430 * specification, the GET, HEAD, OPTIONS, and TRACE
431 * methods are defined to be safe.
432 */
433 if (likely(txn->meth == HTTP_METH_GET ||
434 txn->meth == HTTP_METH_HEAD ||
435 txn->meth == HTTP_METH_OPTIONS ||
436 txn->meth == HTTP_METH_TRACE))
437 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
438
439 /* end of job, return OK */
440 req->analysers &= ~an_bit;
441 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200442
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 return 1;
444
445 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200446 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200447 txn->req.err_state = txn->req.msg_state;
448 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100449 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100450 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200451 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100452 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453
454 return_prx_cond:
455 if (!(s->flags & SF_ERR_MASK))
456 s->flags |= SF_ERR_PRXCOND;
457 if (!(s->flags & SF_FINST_MASK))
458 s->flags |= SF_FINST_R;
459
460 req->analysers &= AN_REQ_FLT_END;
461 req->analyse_exp = TICK_ETERNITY;
462 return 0;
463}
464
465
466/* This stream analyser runs all HTTP request processing which is common to
467 * frontends and backends, which means blocking ACLs, filters, connection-close,
468 * reqadd, stats and redirects. This is performed for the designated proxy.
469 * It returns 1 if the processing can continue on next analysers, or zero if it
470 * either needs more data or wants to immediately abort the request (eg: deny,
471 * error, ...).
472 */
473int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
474{
475 struct session *sess = s->sess;
476 struct http_txn *txn = s->txn;
477 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200478 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200479 struct redirect_rule *rule;
480 struct cond_wordlist *wl;
481 enum rule_result verdict;
482 int deny_status = HTTP_ERR_403;
483 struct connection *conn = objt_conn(sess->origin);
484
485 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
486 /* we need more data */
487 goto return_prx_yield;
488 }
489
490 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
491 now_ms, __FUNCTION__,
492 s,
493 req,
494 req->rex, req->wex,
495 req->flags,
496 ci_data(req),
497 req->analysers);
498
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100499 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501 /* just in case we have some per-backend tracking */
502 stream_inc_be_http_req_ctr(s);
503
504 /* evaluate http-request rules */
505 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200506 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200507
508 switch (verdict) {
509 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
510 goto return_prx_yield;
511
512 case HTTP_RULE_RES_CONT:
513 case HTTP_RULE_RES_STOP: /* nothing to do */
514 break;
515
516 case HTTP_RULE_RES_DENY: /* deny or tarpit */
517 if (txn->flags & TX_CLTARPIT)
518 goto tarpit;
519 goto deny;
520
521 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
522 goto return_prx_cond;
523
524 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
525 goto done;
526
527 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
528 goto return_bad_req;
529 }
530 }
531
532 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
533 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200534 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535
Christopher Fauletff2759f2018-10-24 11:13:16 +0200536 ctx.blk = NULL;
537 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
538 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200539 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200541 }
542
543 /* OK at this stage, we know that the request was accepted according to
544 * the http-request rules, we can check for the stats. Note that the
545 * URI is detected *before* the req* rules in order not to be affected
546 * by a possible reqrep, while they are processed *after* so that a
547 * reqdeny can still block them. This clearly needs to change in 1.6!
548 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200549 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100551 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200552 txn->status = 500;
553 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100554 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555
556 if (!(s->flags & SF_ERR_MASK))
557 s->flags |= SF_ERR_RESOURCE;
558 goto return_prx_cond;
559 }
560
561 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200562 htx_handle_stats(s, req);
563 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200564 /* not all actions implemented: deny, allow, auth */
565
566 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
567 goto deny;
568
569 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
570 goto return_prx_cond;
571 }
572
573 /* evaluate the req* rules except reqadd */
574 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200575 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200576 goto return_bad_req;
577
578 if (txn->flags & TX_CLDENY)
579 goto deny;
580
581 if (txn->flags & TX_CLTARPIT) {
582 deny_status = HTTP_ERR_500;
583 goto tarpit;
584 }
585 }
586
587 /* add request headers from the rule sets in the same order */
588 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200589 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200590 if (wl->cond) {
591 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
592 ret = acl_pass(ret);
593 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
594 ret = !ret;
595 if (!ret)
596 continue;
597 }
598
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
600 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601 goto return_bad_req;
602 }
603
Christopher Faulet2571bc62019-03-01 11:44:26 +0100604 /* Proceed with the applets now. */
605 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100607 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200608
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100609 if (htx_handle_expect_hdr(s, htx, msg) == -1)
610 goto return_bad_req;
611
Christopher Faulete0768eb2018-10-03 16:38:02 +0200612 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
613 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
614 if (!(s->flags & SF_FINST_MASK))
615 s->flags |= SF_FINST_R;
616
617 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
618 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
619 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
620 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100621
622 req->flags |= CF_SEND_DONTWAIT;
623 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200624 goto done;
625 }
626
627 /* check whether we have some ACLs set to redirect this request */
628 list_for_each_entry(rule, &px->redirect_rules, list) {
629 if (rule->cond) {
630 int ret;
631
632 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
633 ret = acl_pass(ret);
634 if (rule->cond->pol == ACL_COND_UNLESS)
635 ret = !ret;
636 if (!ret)
637 continue;
638 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200639 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200640 goto return_bad_req;
641 goto done;
642 }
643
644 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
645 * If this happens, then the data will not come immediately, so we must
646 * send all what we have without waiting. Note that due to the small gain
647 * in waiting for the body of the request, it's easier to simply put the
648 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
649 * itself once used.
650 */
651 req->flags |= CF_SEND_DONTWAIT;
652
653 done: /* done with this analyser, continue with next ones that the calling
654 * points will have set, if any.
655 */
656 req->analyse_exp = TICK_ETERNITY;
657 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
658 req->analysers &= ~an_bit;
659 return 1;
660
661 tarpit:
662 /* Allow cookie logging
663 */
664 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200665 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200666
667 /* When a connection is tarpitted, we use the tarpit timeout,
668 * which may be the same as the connect timeout if unspecified.
669 * If unset, then set it to zero because we really want it to
670 * eventually expire. We build the tarpit as an analyser.
671 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100672 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200673
674 /* wipe the request out so that we can drop the connection early
675 * if the client closes first.
676 */
677 channel_dont_connect(req);
678
679 txn->status = http_err_codes[deny_status];
680
681 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
682 req->analysers |= AN_REQ_HTTP_TARPIT;
683 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
684 if (!req->analyse_exp)
685 req->analyse_exp = tick_add(now_ms, 0);
686 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100687 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200688 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100689 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200690 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100691 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200692 goto done_without_exp;
693
694 deny: /* this request was blocked (denied) */
695
696 /* Allow cookie logging
697 */
698 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200699 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700
701 txn->flags |= TX_CLDENY;
702 txn->status = http_err_codes[deny_status];
703 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100704 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100706 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100708 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200709 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100710 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711 goto return_prx_cond;
712
713 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 txn->req.err_state = txn->req.msg_state;
715 txn->req.msg_state = HTTP_MSG_ERROR;
716 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100717 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200718
Olivier Houcharda798bf52019-03-08 18:52:00 +0100719 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100721 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200722
723 return_prx_cond:
724 if (!(s->flags & SF_ERR_MASK))
725 s->flags |= SF_ERR_PRXCOND;
726 if (!(s->flags & SF_FINST_MASK))
727 s->flags |= SF_FINST_R;
728
729 req->analysers &= AN_REQ_FLT_END;
730 req->analyse_exp = TICK_ETERNITY;
731 return 0;
732
733 return_prx_yield:
734 channel_dont_connect(req);
735 return 0;
736}
737
738/* This function performs all the processing enabled for the current request.
739 * It returns 1 if the processing can continue on next analysers, or zero if it
740 * needs more data, encounters an error, or wants to immediately abort the
741 * request. It relies on buffers flags, and updates s->req.analysers.
742 */
743int htx_process_request(struct stream *s, struct channel *req, int an_bit)
744{
745 struct session *sess = s->sess;
746 struct http_txn *txn = s->txn;
747 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200748 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200749 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
750
751 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
752 /* we need more data */
753 channel_dont_connect(req);
754 return 0;
755 }
756
757 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
758 now_ms, __FUNCTION__,
759 s,
760 req,
761 req->rex, req->wex,
762 req->flags,
763 ci_data(req),
764 req->analysers);
765
766 /*
767 * Right now, we know that we have processed the entire headers
768 * and that unwanted requests have been filtered out. We can do
769 * whatever we want with the remaining request. Also, now we
770 * may have separate values for ->fe, ->be.
771 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100772 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200773
774 /*
775 * If HTTP PROXY is set we simply get remote server address parsing
776 * incoming request. Note that this requires that a connection is
777 * allocated on the server side.
778 */
779 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
780 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100781 struct htx_sl *sl;
782 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 /* Note that for now we don't reuse existing proxy connections */
785 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
786 txn->req.err_state = txn->req.msg_state;
787 txn->req.msg_state = HTTP_MSG_ERROR;
788 txn->status = 500;
789 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100790 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200791
792 if (!(s->flags & SF_ERR_MASK))
793 s->flags |= SF_ERR_RESOURCE;
794 if (!(s->flags & SF_FINST_MASK))
795 s->flags |= SF_FINST_R;
796
797 return 0;
798 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100800 uri = htx_sl_req_uri(sl);
801 path = http_get_path(uri);
802 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200803 goto return_bad_req;
804
805 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200806 * uri.ptr and path.ptr (excluded). If it was not found, we need
807 * to replace from all the uri by a single "/".
808 *
809 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100810 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200811 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200812 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100813 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200814 }
815
816 /*
817 * 7: Now we can work with the cookies.
818 * Note that doing so might move headers in the request, but
819 * the fields will stay coherent and the URI will not move.
820 * This should only be performed in the backend.
821 */
822 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100823 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200824
825 /* add unique-id if "header-unique-id" is specified */
826
827 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
828 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
829 goto return_bad_req;
830 s->unique_id[0] = '\0';
831 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
832 }
833
834 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200835 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
836 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
837
838 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200839 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200840 }
841
842 /*
843 * 9: add X-Forwarded-For if either the frontend or the backend
844 * asks for it.
845 */
846 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 struct http_hdr_ctx ctx = { .blk = NULL };
848 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
849 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
850
Christopher Faulete0768eb2018-10-03 16:38:02 +0200851 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200852 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200853 /* The header is set to be added only if none is present
854 * and we found it, so don't do anything.
855 */
856 }
857 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
858 /* Add an X-Forwarded-For header unless the source IP is
859 * in the 'except' network range.
860 */
861 if ((!sess->fe->except_mask.s_addr ||
862 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
863 != sess->fe->except_net.s_addr) &&
864 (!s->be->except_mask.s_addr ||
865 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
866 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200867 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200868
869 /* Note: we rely on the backend to get the header name to be used for
870 * x-forwarded-for, because the header is really meant for the backends.
871 * However, if the backend did not specify any option, we have to rely
872 * on the frontend's header name.
873 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200874 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
875 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200876 goto return_bad_req;
877 }
878 }
879 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
880 /* FIXME: for the sake of completeness, we should also support
881 * 'except' here, although it is mostly useless in this case.
882 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200883 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200884
Christopher Faulete0768eb2018-10-03 16:38:02 +0200885 inet_ntop(AF_INET6,
886 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
887 pn, sizeof(pn));
888
889 /* Note: we rely on the backend to get the header name to be used for
890 * x-forwarded-for, because the header is really meant for the backends.
891 * However, if the backend did not specify any option, we have to rely
892 * on the frontend's header name.
893 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200894 chunk_printf(&trash, "%s", pn);
895 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200896 goto return_bad_req;
897 }
898 }
899
900 /*
901 * 10: add X-Original-To if either the frontend or the backend
902 * asks for it.
903 */
904 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
905
906 /* FIXME: don't know if IPv6 can handle that case too. */
907 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
908 /* Add an X-Original-To header unless the destination IP is
909 * in the 'except' network range.
910 */
911 conn_get_to_addr(cli_conn);
912
913 if (cli_conn->addr.to.ss_family == AF_INET &&
914 ((!sess->fe->except_mask_to.s_addr ||
915 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
916 != sess->fe->except_to.s_addr) &&
917 (!s->be->except_mask_to.s_addr ||
918 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
919 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200920 struct ist hdr;
921 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200922
923 /* Note: we rely on the backend to get the header name to be used for
924 * x-original-to, because the header is really meant for the backends.
925 * However, if the backend did not specify any option, we have to rely
926 * on the frontend's header name.
927 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 if (s->be->orgto_hdr_len)
929 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
930 else
931 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200933 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
934 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 goto return_bad_req;
936 }
937 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938 }
939
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 /* If we have no server assigned yet and we're balancing on url_param
941 * with a POST request, we may be interested in checking the body for
942 * that parameter. This will be done in another analyser.
943 */
944 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100945 s->txn->meth == HTTP_METH_POST &&
946 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200947 channel_dont_connect(req);
948 req->analysers |= AN_REQ_HTTP_BODY;
949 }
950
951 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
952 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100953
Christopher Faulete0768eb2018-10-03 16:38:02 +0200954 /* We expect some data from the client. Unless we know for sure
955 * we already have a full request, we have to re-enable quick-ack
956 * in case we previously disabled it, otherwise we might cause
957 * the client to delay further data.
958 */
959 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200960 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100961 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200962
963 /*************************************************************
964 * OK, that's finished for the headers. We have done what we *
965 * could. Let's switch to the DATA state. *
966 ************************************************************/
967 req->analyse_exp = TICK_ETERNITY;
968 req->analysers &= ~an_bit;
969
970 s->logs.tv_request = now;
971 /* OK let's go on with the BODY now */
972 return 1;
973
974 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975 txn->req.err_state = txn->req.msg_state;
976 txn->req.msg_state = HTTP_MSG_ERROR;
977 txn->status = 400;
978 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100979 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200980
Olivier Houcharda798bf52019-03-08 18:52:00 +0100981 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200982 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100983 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200984
985 if (!(s->flags & SF_ERR_MASK))
986 s->flags |= SF_ERR_PRXCOND;
987 if (!(s->flags & SF_FINST_MASK))
988 s->flags |= SF_FINST_R;
989 return 0;
990}
991
992/* This function is an analyser which processes the HTTP tarpit. It always
993 * returns zero, at the beginning because it prevents any other processing
994 * from occurring, and at the end because it terminates the request.
995 */
996int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
997{
998 struct http_txn *txn = s->txn;
999
1000 /* This connection is being tarpitted. The CLIENT side has
1001 * already set the connect expiration date to the right
1002 * timeout. We just have to check that the client is still
1003 * there and that the timeout has not expired.
1004 */
1005 channel_dont_connect(req);
1006 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1007 !tick_is_expired(req->analyse_exp, now_ms))
1008 return 0;
1009
1010 /* We will set the queue timer to the time spent, just for
1011 * logging purposes. We fake a 500 server error, so that the
1012 * attacker will not suspect his connection has been tarpitted.
1013 * It will not cause trouble to the logs because we can exclude
1014 * the tarpitted connections by filtering on the 'PT' status flags.
1015 */
1016 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1017
1018 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001019 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001020
1021 req->analysers &= AN_REQ_FLT_END;
1022 req->analyse_exp = TICK_ETERNITY;
1023
1024 if (!(s->flags & SF_ERR_MASK))
1025 s->flags |= SF_ERR_PRXCOND;
1026 if (!(s->flags & SF_FINST_MASK))
1027 s->flags |= SF_FINST_T;
1028 return 0;
1029}
1030
1031/* This function is an analyser which waits for the HTTP request body. It waits
1032 * for either the buffer to be full, or the full advertised contents to have
1033 * reached the buffer. It must only be called after the standard HTTP request
1034 * processing has occurred, because it expects the request to be parsed and will
1035 * look for the Expect header. It may send a 100-Continue interim response. It
1036 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1037 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1038 * needs to read more data, or 1 once it has completed its analysis.
1039 */
1040int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1041{
1042 struct session *sess = s->sess;
1043 struct http_txn *txn = s->txn;
1044 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001045 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001046
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001047
1048 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1049 now_ms, __FUNCTION__,
1050 s,
1051 req,
1052 req->rex, req->wex,
1053 req->flags,
1054 ci_data(req),
1055 req->analysers);
1056
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001057 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001058
Willy Tarreau4236f032019-03-05 10:43:32 +01001059 if (htx->flags & HTX_FL_PARSING_ERROR)
1060 goto return_bad_req;
1061
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001062 if (msg->msg_state < HTTP_MSG_BODY)
1063 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001064
Christopher Faulete0768eb2018-10-03 16:38:02 +02001065 /* We have to parse the HTTP request body to find any required data.
1066 * "balance url_param check_post" should have been the only way to get
1067 * into this. We were brought here after HTTP header analysis, so all
1068 * related structures are ready.
1069 */
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001072 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1073 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 }
1075
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001076 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001078 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1079 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001082 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083 goto http_end;
1084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1087 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001088 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089
1090 if (!(s->flags & SF_ERR_MASK))
1091 s->flags |= SF_ERR_CLITO;
1092 if (!(s->flags & SF_FINST_MASK))
1093 s->flags |= SF_FINST_D;
1094 goto return_err_msg;
1095 }
1096
1097 /* we get here if we need to wait for more data */
1098 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1099 /* Not enough data. We'll re-use the http-request
1100 * timeout here. Ideally, we should set the timeout
1101 * relative to the accept() date. We just set the
1102 * request timeout once at the beginning of the
1103 * request.
1104 */
1105 channel_dont_connect(req);
1106 if (!tick_isset(req->analyse_exp))
1107 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1108 return 0;
1109 }
1110
1111 http_end:
1112 /* The situation will not evolve, so let's give up on the analysis. */
1113 s->logs.tv_request = now; /* update the request timer to reflect full request */
1114 req->analysers &= ~an_bit;
1115 req->analyse_exp = TICK_ETERNITY;
1116 return 1;
1117
1118 return_bad_req: /* let's centralize all bad requests */
1119 txn->req.err_state = txn->req.msg_state;
1120 txn->req.msg_state = HTTP_MSG_ERROR;
1121 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001122 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001123
1124 if (!(s->flags & SF_ERR_MASK))
1125 s->flags |= SF_ERR_PRXCOND;
1126 if (!(s->flags & SF_FINST_MASK))
1127 s->flags |= SF_FINST_R;
1128
1129 return_err_msg:
1130 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001131 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001132 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001133 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001134 return 0;
1135}
1136
1137/* This function is an analyser which forwards request body (including chunk
1138 * sizes if any). It is called as soon as we must forward, even if we forward
1139 * zero byte. The only situation where it must not be called is when we're in
1140 * tunnel mode and we want to forward till the close. It's used both to forward
1141 * remaining data and to resync after end of body. It expects the msg_state to
1142 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1143 * read more data, or 1 once we can go on with next request or end the stream.
1144 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1145 * bytes of pending data + the headers if not already done.
1146 */
1147int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1148{
1149 struct session *sess = s->sess;
1150 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001151 struct http_msg *msg = &txn->req;
1152 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001153 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001154 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001155
1156 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1157 now_ms, __FUNCTION__,
1158 s,
1159 req,
1160 req->rex, req->wex,
1161 req->flags,
1162 ci_data(req),
1163 req->analysers);
1164
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001165 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001166
1167 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1168 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1169 /* Output closed while we were sending data. We must abort and
1170 * wake the other side up.
1171 */
1172 msg->err_state = msg->msg_state;
1173 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001174 htx_end_request(s);
1175 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 return 1;
1177 }
1178
1179 /* Note that we don't have to send 100-continue back because we don't
1180 * need the data to complete our job, and it's up to the server to
1181 * decide whether to return 100, 417 or anything else in return of
1182 * an "Expect: 100-continue" header.
1183 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001184 if (msg->msg_state == HTTP_MSG_BODY)
1185 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 /* Some post-connect processing might want us to refrain from starting to
1188 * forward data. Currently, the only reason for this is "balance url_param"
1189 * whichs need to parse/process the request after we've enabled forwarding.
1190 */
1191 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1192 if (!(s->res.flags & CF_READ_ATTACHED)) {
1193 channel_auto_connect(req);
1194 req->flags |= CF_WAKE_CONNECT;
1195 channel_dont_close(req); /* don't fail on early shutr */
1196 goto waiting;
1197 }
1198 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1199 }
1200
1201 /* in most states, we should abort in case of early close */
1202 channel_auto_close(req);
1203
1204 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001205 if (req->to_forward == CHN_INFINITE_FORWARD) {
1206 if (req->flags & (CF_SHUTR|CF_EOI)) {
1207 msg->msg_state = HTTP_MSG_DONE;
1208 req->to_forward = 0;
1209 goto done;
1210 }
1211 }
1212 else {
1213 /* We can't process the buffer's contents yet */
1214 req->flags |= CF_WAKE_WRITE;
1215 goto missing_data_or_waiting;
1216 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001217 }
1218
Christopher Faulet9768c262018-10-22 09:34:31 +02001219 if (msg->msg_state >= HTTP_MSG_DONE)
1220 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001221 /* Forward input data. We get it by removing all outgoing data not
1222 * forwarded yet from HTX data size. If there are some data filters, we
1223 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001224 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001225 if (HAS_REQ_DATA_FILTERS(s)) {
1226 ret = flt_http_payload(s, msg, htx->data);
1227 if (ret < 0)
1228 goto return_bad_req;
1229 c_adv(req, ret);
1230 if (htx->data != co_data(req) || htx->extra)
1231 goto missing_data_or_waiting;
1232 }
1233 else {
1234 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001235 if (msg->flags & HTTP_MSGF_XFER_LEN)
1236 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001237 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001238
Christopher Faulet9768c262018-10-22 09:34:31 +02001239 /* Check if the end-of-message is reached and if so, switch the message
1240 * in HTTP_MSG_DONE state.
1241 */
1242 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1243 goto missing_data_or_waiting;
1244
1245 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001246 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001247
1248 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001249 /* other states, DONE...TUNNEL */
1250 /* we don't want to forward closes on DONE except in tunnel mode. */
1251 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1252 channel_dont_close(req);
1253
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001254 if (HAS_REQ_DATA_FILTERS(s)) {
1255 ret = flt_http_end(s, msg);
1256 if (ret <= 0) {
1257 if (!ret)
1258 goto missing_data_or_waiting;
1259 goto return_bad_req;
1260 }
1261 }
1262
Christopher Fauletf2824e62018-10-01 12:12:37 +02001263 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001264 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001265 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001266 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1267 if (req->flags & CF_SHUTW) {
1268 /* request errors are most likely due to the
1269 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001270 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001272 goto return_bad_req;
1273 }
1274 return 1;
1275 }
1276
1277 /* If "option abortonclose" is set on the backend, we want to monitor
1278 * the client's connection and forward any shutdown notification to the
1279 * server, which will decide whether to close or to go on processing the
1280 * request. We only do that in tunnel mode, and not in other modes since
1281 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001282 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001283 channel_auto_read(req);
1284 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1285 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1286 s->si[1].flags |= SI_FL_NOLINGER;
1287 channel_auto_close(req);
1288 }
1289 else if (s->txn->meth == HTTP_METH_POST) {
1290 /* POST requests may require to read extra CRLF sent by broken
1291 * browsers and which could cause an RST to be sent upon close
1292 * on some systems (eg: Linux). */
1293 channel_auto_read(req);
1294 }
1295 return 0;
1296
1297 missing_data_or_waiting:
1298 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001299 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1300 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001301
1302 waiting:
1303 /* waiting for the last bits to leave the buffer */
1304 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001305 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001306
Christopher Faulet47365272018-10-31 17:40:50 +01001307 if (htx->flags & HTX_FL_PARSING_ERROR)
1308 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001309
Christopher Faulete0768eb2018-10-03 16:38:02 +02001310 /* When TE: chunked is used, we need to get there again to parse remaining
1311 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1312 * And when content-length is used, we never want to let the possible
1313 * shutdown be forwarded to the other side, as the state machine will
1314 * take care of it once the client responds. It's also important to
1315 * prevent TIME_WAITs from accumulating on the backend side, and for
1316 * HTTP/2 where the last frame comes with a shutdown.
1317 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001318 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001319 channel_dont_close(req);
1320
1321 /* We know that more data are expected, but we couldn't send more that
1322 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1323 * system knows it must not set a PUSH on this first part. Interactive
1324 * modes are already handled by the stream sock layer. We must not do
1325 * this in content-length mode because it could present the MSG_MORE
1326 * flag with the last block of forwarded data, which would cause an
1327 * additional delay to be observed by the receiver.
1328 */
1329 if (msg->flags & HTTP_MSGF_TE_CHNK)
1330 req->flags |= CF_EXPECT_MORE;
1331
1332 return 0;
1333
Christopher Faulet93e02d82019-03-08 14:18:50 +01001334 return_cli_abort:
1335 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1336 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1337 if (objt_server(s->target))
1338 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1339 if (!(s->flags & SF_ERR_MASK))
1340 s->flags |= SF_ERR_CLICL;
1341 status = 400;
1342 goto return_error;
1343
1344 return_srv_abort:
1345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1346 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1347 if (objt_server(s->target))
1348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1349 if (!(s->flags & SF_ERR_MASK))
1350 s->flags |= SF_ERR_SRVCL;
1351 status = 502;
1352 goto return_error;
1353
1354 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001355 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001356 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001357 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001359 s->flags |= SF_ERR_CLICL;
1360 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361
Christopher Faulet93e02d82019-03-08 14:18:50 +01001362 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 txn->req.err_state = txn->req.msg_state;
1364 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001365 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001367 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001369 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001370 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 }
1372 req->analysers &= AN_REQ_FLT_END;
1373 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 +01001374 if (!(s->flags & SF_FINST_MASK))
1375 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 return 0;
1377}
1378
1379/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1380 * processing can continue on next analysers, or zero if it either needs more
1381 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1382 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1383 * when it has nothing left to do, and may remove any analyser when it wants to
1384 * abort.
1385 */
1386int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1387{
Christopher Faulet9768c262018-10-22 09:34:31 +02001388 /*
1389 * We will analyze a complete HTTP response to check the its syntax.
1390 *
1391 * Once the start line and all headers are received, we may perform a
1392 * capture of the error (if any), and we will set a few fields. We also
1393 * logging and finally headers capture.
1394 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 struct session *sess = s->sess;
1396 struct http_txn *txn = s->txn;
1397 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001398 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001399 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001400 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001401 int n;
1402
1403 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1404 now_ms, __FUNCTION__,
1405 s,
1406 rep,
1407 rep->rex, rep->wex,
1408 rep->flags,
1409 ci_data(rep),
1410 rep->analysers);
1411
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001412 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001413
Willy Tarreau4236f032019-03-05 10:43:32 +01001414 /* Parsing errors are caught here */
1415 if (htx->flags & HTX_FL_PARSING_ERROR)
1416 goto return_bad_res;
1417
Christopher Faulete0768eb2018-10-03 16:38:02 +02001418 /*
1419 * Now we quickly check if we have found a full valid response.
1420 * If not so, we check the FD and buffer states before leaving.
1421 * A full response is indicated by the fact that we have seen
1422 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1423 * responses are checked first.
1424 *
1425 * Depending on whether the client is still there or not, we
1426 * may send an error response back or not. Note that normally
1427 * we should only check for HTTP status there, and check I/O
1428 * errors somewhere else.
1429 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001430 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001431 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001432 * First catch invalid response because of a parsing error or
1433 * because only part of headers have been transfered.
1434 * Multiplexers have the responsibility to emit all headers at
1435 * once. We must be sure to have forwarded all outgoing data
1436 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001437 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001438 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001439 goto return_bad_res;
1440
Christopher Faulet9768c262018-10-22 09:34:31 +02001441 /* 1: have we encountered a read error ? */
1442 if (rep->flags & CF_READ_ERROR) {
1443 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001444 goto abort_keep_alive;
1445
Olivier Houcharda798bf52019-03-08 18:52:00 +01001446 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001447 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001448 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001449 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001450 }
1451
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452 rep->analysers &= AN_RES_FLT_END;
1453 txn->status = 502;
1454
1455 /* Check to see if the server refused the early data.
1456 * If so, just send a 425
1457 */
1458 if (objt_cs(s->si[1].end)) {
1459 struct connection *conn = objt_cs(s->si[1].end)->conn;
1460
1461 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1462 txn->status = 425;
1463 }
1464
1465 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001466 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001467
1468 if (!(s->flags & SF_ERR_MASK))
1469 s->flags |= SF_ERR_SRVCL;
1470 if (!(s->flags & SF_FINST_MASK))
1471 s->flags |= SF_FINST_H;
1472 return 0;
1473 }
1474
Christopher Faulet9768c262018-10-22 09:34:31 +02001475 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001476 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001477 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001478 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001479 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001480 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001481 }
1482
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 rep->analysers &= AN_RES_FLT_END;
1484 txn->status = 504;
1485 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001486 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001487
1488 if (!(s->flags & SF_ERR_MASK))
1489 s->flags |= SF_ERR_SRVTO;
1490 if (!(s->flags & SF_FINST_MASK))
1491 s->flags |= SF_FINST_H;
1492 return 0;
1493 }
1494
Christopher Faulet9768c262018-10-22 09:34:31 +02001495 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001497 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1498 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001499 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001500 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501
1502 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001504 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505
1506 if (!(s->flags & SF_ERR_MASK))
1507 s->flags |= SF_ERR_CLICL;
1508 if (!(s->flags & SF_FINST_MASK))
1509 s->flags |= SF_FINST_H;
1510
1511 /* process_stream() will take care of the error */
1512 return 0;
1513 }
1514
Christopher Faulet9768c262018-10-22 09:34:31 +02001515 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001517 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 goto abort_keep_alive;
1519
Olivier Houcharda798bf52019-03-08 18:52:00 +01001520 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001522 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001523 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 }
1525
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 rep->analysers &= AN_RES_FLT_END;
1527 txn->status = 502;
1528 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001529 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530
1531 if (!(s->flags & SF_ERR_MASK))
1532 s->flags |= SF_ERR_SRVCL;
1533 if (!(s->flags & SF_FINST_MASK))
1534 s->flags |= SF_FINST_H;
1535 return 0;
1536 }
1537
Christopher Faulet9768c262018-10-22 09:34:31 +02001538 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001540 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 goto abort_keep_alive;
1542
Olivier Houcharda798bf52019-03-08 18:52:00 +01001543 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545
1546 if (!(s->flags & SF_ERR_MASK))
1547 s->flags |= SF_ERR_CLICL;
1548 if (!(s->flags & SF_FINST_MASK))
1549 s->flags |= SF_FINST_H;
1550
1551 /* process_stream() will take care of the error */
1552 return 0;
1553 }
1554
1555 channel_dont_close(rep);
1556 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1557 return 0;
1558 }
1559
1560 /* More interesting part now : we know that we have a complete
1561 * response which at least looks like HTTP. We have an indicator
1562 * of each header's length, so we can parse them quickly.
1563 */
1564
Christopher Faulet9768c262018-10-22 09:34:31 +02001565 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001566 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001567
Christopher Faulet9768c262018-10-22 09:34:31 +02001568 /* 0: we might have to print this header in debug mode */
1569 if (unlikely((global.mode & MODE_DEBUG) &&
1570 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1571 int32_t pos;
1572
Christopher Faulet03599112018-11-27 11:21:21 +01001573 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001574
1575 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1576 struct htx_blk *blk = htx_get_blk(htx, pos);
1577 enum htx_blk_type type = htx_get_blk_type(blk);
1578
1579 if (type == HTX_BLK_EOH)
1580 break;
1581 if (type != HTX_BLK_HDR)
1582 continue;
1583
1584 htx_debug_hdr("srvhdr", s,
1585 htx_get_blk_name(htx, blk),
1586 htx_get_blk_value(htx, blk));
1587 }
1588 }
1589
Christopher Faulet03599112018-11-27 11:21:21 +01001590 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001591 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001592 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001593 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001594 if (sl->flags & HTX_SL_F_XFER_LEN) {
1595 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001596 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001597 if (sl->flags & HTX_SL_F_BODYLESS)
1598 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001599 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001600
1601 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602 if (n < 1 || n > 5)
1603 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001604
Christopher Faulete0768eb2018-10-03 16:38:02 +02001605 /* when the client triggers a 4xx from the server, it's most often due
1606 * to a missing object or permission. These events should be tracked
1607 * because if they happen often, it may indicate a brute force or a
1608 * vulnerability scan.
1609 */
1610 if (n == 4)
1611 stream_inc_http_err_ctr(s);
1612
1613 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001614 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615
Christopher Faulete0768eb2018-10-03 16:38:02 +02001616 /* Adjust server's health based on status code. Note: status codes 501
1617 * and 505 are triggered on demand by client request, so we must not
1618 * count them as server failures.
1619 */
1620 if (objt_server(s->target)) {
1621 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001622 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001624 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625 }
1626
1627 /*
1628 * We may be facing a 100-continue response, or any other informational
1629 * 1xx response which is non-final, in which case this is not the right
1630 * response, and we're waiting for the next one. Let's allow this response
1631 * to go to the client and wait for the next one. There's an exception for
1632 * 101 which is used later in the code to switch protocols.
1633 */
1634 if (txn->status < 200 &&
1635 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001636 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001637 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001638 msg->msg_state = HTTP_MSG_RPBEFORE;
1639 txn->status = 0;
1640 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001641 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001642 }
1643
1644 /*
1645 * 2: check for cacheability.
1646 */
1647
1648 switch (txn->status) {
1649 case 200:
1650 case 203:
1651 case 204:
1652 case 206:
1653 case 300:
1654 case 301:
1655 case 404:
1656 case 405:
1657 case 410:
1658 case 414:
1659 case 501:
1660 break;
1661 default:
1662 /* RFC7231#6.1:
1663 * Responses with status codes that are defined as
1664 * cacheable by default (e.g., 200, 203, 204, 206,
1665 * 300, 301, 404, 405, 410, 414, and 501 in this
1666 * specification) can be reused by a cache with
1667 * heuristic expiration unless otherwise indicated
1668 * by the method definition or explicit cache
1669 * controls [RFC7234]; all other status codes are
1670 * not cacheable by default.
1671 */
1672 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1673 break;
1674 }
1675
1676 /*
1677 * 3: we may need to capture headers
1678 */
1679 s->logs.logwait &= ~LW_RESP;
1680 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001681 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001682
Christopher Faulet9768c262018-10-22 09:34:31 +02001683 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001684 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1685 txn->status == 101)) {
1686 /* Either we've established an explicit tunnel, or we're
1687 * switching the protocol. In both cases, we're very unlikely
1688 * to understand the next protocols. We have to switch to tunnel
1689 * mode, so that we transfer the request and responses then let
1690 * this protocol pass unmodified. When we later implement specific
1691 * parsers for such protocols, we'll want to check the Upgrade
1692 * header which contains information about that protocol for
1693 * responses with status 101 (eg: see RFC2817 about TLS).
1694 */
1695 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001696 }
1697
Christopher Faulet61608322018-11-23 16:23:45 +01001698 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1699 * 407 (Proxy-Authenticate) responses and set the connection to private
1700 */
1701 srv_conn = cs_conn(objt_cs(s->si[1].end));
1702 if (srv_conn) {
1703 struct ist hdr;
1704 struct http_hdr_ctx ctx;
1705
1706 if (txn->status == 401)
1707 hdr = ist("WWW-Authenticate");
1708 else if (txn->status == 407)
1709 hdr = ist("Proxy-Authenticate");
1710 else
1711 goto end;
1712
1713 ctx.blk = NULL;
1714 while (http_find_header(htx, hdr, &ctx, 0)) {
1715 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1716 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1717 srv_conn->flags |= CO_FL_PRIVATE;
1718 }
1719 }
1720
1721 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001722 /* we want to have the response time before we start processing it */
1723 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1724
1725 /* end of job, return OK */
1726 rep->analysers &= ~an_bit;
1727 rep->analyse_exp = TICK_ETERNITY;
1728 channel_auto_close(rep);
1729 return 1;
1730
Christopher Faulet47365272018-10-31 17:40:50 +01001731 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001732 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001733 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001734 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001735 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001736 }
1737 txn->status = 502;
1738 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001739 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001740 rep->analysers &= AN_RES_FLT_END;
1741
1742 if (!(s->flags & SF_ERR_MASK))
1743 s->flags |= SF_ERR_PRXCOND;
1744 if (!(s->flags & SF_FINST_MASK))
1745 s->flags |= SF_FINST_H;
1746 return 0;
1747
Christopher Faulete0768eb2018-10-03 16:38:02 +02001748 abort_keep_alive:
1749 /* A keep-alive request to the server failed on a network error.
1750 * The client is required to retry. We need to close without returning
1751 * any other information so that the client retries.
1752 */
1753 txn->status = 0;
1754 rep->analysers &= AN_RES_FLT_END;
1755 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001756 s->logs.logwait = 0;
1757 s->logs.level = 0;
1758 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001759 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001760 return 0;
1761}
1762
1763/* This function performs all the processing enabled for the current response.
1764 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1765 * and updates s->res.analysers. It might make sense to explode it into several
1766 * other functions. It works like process_request (see indications above).
1767 */
1768int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1769{
1770 struct session *sess = s->sess;
1771 struct http_txn *txn = s->txn;
1772 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001773 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001774 struct proxy *cur_proxy;
1775 struct cond_wordlist *wl;
1776 enum rule_result ret = HTTP_RULE_RES_CONT;
1777
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001778 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1779 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001780
Christopher Faulete0768eb2018-10-03 16:38:02 +02001781 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1782 now_ms, __FUNCTION__,
1783 s,
1784 rep,
1785 rep->rex, rep->wex,
1786 rep->flags,
1787 ci_data(rep),
1788 rep->analysers);
1789
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001790 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791
1792 /* The stats applet needs to adjust the Connection header but we don't
1793 * apply any filter there.
1794 */
1795 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1796 rep->analysers &= ~an_bit;
1797 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001798 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001799 }
1800
1801 /*
1802 * We will have to evaluate the filters.
1803 * As opposed to version 1.2, now they will be evaluated in the
1804 * filters order and not in the header order. This means that
1805 * each filter has to be validated among all headers.
1806 *
1807 * Filters are tried with ->be first, then with ->fe if it is
1808 * different from ->be.
1809 *
1810 * Maybe we are in resume condiion. In this case I choose the
1811 * "struct proxy" which contains the rule list matching the resume
1812 * pointer. If none of theses "struct proxy" match, I initialise
1813 * the process with the first one.
1814 *
1815 * In fact, I check only correspondance betwwen the current list
1816 * pointer and the ->fe rule list. If it doesn't match, I initialize
1817 * the loop with the ->be.
1818 */
1819 if (s->current_rule_list == &sess->fe->http_res_rules)
1820 cur_proxy = sess->fe;
1821 else
1822 cur_proxy = s->be;
1823 while (1) {
1824 struct proxy *rule_set = cur_proxy;
1825
1826 /* evaluate http-response rules */
1827 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001828 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001829
1830 if (ret == HTTP_RULE_RES_BADREQ)
1831 goto return_srv_prx_502;
1832
1833 if (ret == HTTP_RULE_RES_DONE) {
1834 rep->analysers &= ~an_bit;
1835 rep->analyse_exp = TICK_ETERNITY;
1836 return 1;
1837 }
1838 }
1839
1840 /* we need to be called again. */
1841 if (ret == HTTP_RULE_RES_YIELD) {
1842 channel_dont_close(rep);
1843 return 0;
1844 }
1845
1846 /* try headers filters */
1847 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001848 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1849 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001850 }
1851
1852 /* has the response been denied ? */
1853 if (txn->flags & TX_SVDENY) {
1854 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001855 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001856
Olivier Houcharda798bf52019-03-08 18:52:00 +01001857 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1858 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001860 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861 goto return_srv_prx_502;
1862 }
1863
1864 /* add response headers from the rule sets in the same order */
1865 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001866 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 if (txn->status < 200 && txn->status != 101)
1868 break;
1869 if (wl->cond) {
1870 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1871 ret = acl_pass(ret);
1872 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1873 ret = !ret;
1874 if (!ret)
1875 continue;
1876 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001877
1878 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1879 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001880 goto return_bad_resp;
1881 }
1882
1883 /* check whether we're already working on the frontend */
1884 if (cur_proxy == sess->fe)
1885 break;
1886 cur_proxy = sess->fe;
1887 }
1888
1889 /* After this point, this anayzer can't return yield, so we can
1890 * remove the bit corresponding to this analyzer from the list.
1891 *
1892 * Note that the intermediate returns and goto found previously
1893 * reset the analyzers.
1894 */
1895 rep->analysers &= ~an_bit;
1896 rep->analyse_exp = TICK_ETERNITY;
1897
1898 /* OK that's all we can do for 1xx responses */
1899 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001900 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001901
1902 /*
1903 * Now check for a server cookie.
1904 */
1905 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001906 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001907
1908 /*
1909 * Check for cache-control or pragma headers if required.
1910 */
1911 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1912 check_response_for_cacheability(s, rep);
1913
1914 /*
1915 * Add server cookie in the response if needed
1916 */
1917 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1918 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1919 (!(s->flags & SF_DIRECT) ||
1920 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1921 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1922 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1923 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1924 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1925 !(s->flags & SF_IGNORE_PRST)) {
1926 /* the server is known, it's not the one the client requested, or the
1927 * cookie's last seen date needs to be refreshed. We have to
1928 * insert a set-cookie here, except if we want to insert only on POST
1929 * requests and this one isn't. Note that servers which don't have cookies
1930 * (eg: some backup servers) will return a full cookie removal request.
1931 */
1932 if (!objt_server(s->target)->cookie) {
1933 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001934 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001935 s->be->cookie_name);
1936 }
1937 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001938 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001939
1940 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1941 /* emit last_date, which is mandatory */
1942 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1943 s30tob64((date.tv_sec+3) >> 2,
1944 trash.area + trash.data);
1945 trash.data += 5;
1946
1947 if (s->be->cookie_maxlife) {
1948 /* emit first_date, which is either the original one or
1949 * the current date.
1950 */
1951 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1952 s30tob64(txn->cookie_first_date ?
1953 txn->cookie_first_date >> 2 :
1954 (date.tv_sec+3) >> 2,
1955 trash.area + trash.data);
1956 trash.data += 5;
1957 }
1958 }
1959 chunk_appendf(&trash, "; path=/");
1960 }
1961
1962 if (s->be->cookie_domain)
1963 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1964
1965 if (s->be->ck_opts & PR_CK_HTTPONLY)
1966 chunk_appendf(&trash, "; HttpOnly");
1967
1968 if (s->be->ck_opts & PR_CK_SECURE)
1969 chunk_appendf(&trash, "; Secure");
1970
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001971 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001972 goto return_bad_resp;
1973
1974 txn->flags &= ~TX_SCK_MASK;
1975 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1976 /* the server did not change, only the date was updated */
1977 txn->flags |= TX_SCK_UPDATED;
1978 else
1979 txn->flags |= TX_SCK_INSERTED;
1980
1981 /* Here, we will tell an eventual cache on the client side that we don't
1982 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1983 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1984 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1985 */
1986 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1987
1988 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1989
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001990 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001991 goto return_bad_resp;
1992 }
1993 }
1994
1995 /*
1996 * Check if result will be cacheable with a cookie.
1997 * We'll block the response if security checks have caught
1998 * nasty things such as a cacheable cookie.
1999 */
2000 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2001 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2002 (s->be->options & PR_O_CHK_CACHE)) {
2003 /* we're in presence of a cacheable response containing
2004 * a set-cookie header. We'll block it as requested by
2005 * the 'checkcache' option, and send an alert.
2006 */
2007 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002008 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002009
Olivier Houcharda798bf52019-03-08 18:52:00 +01002010 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2011 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002012 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002013 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002014
2015 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2016 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2017 send_log(s->be, LOG_ALERT,
2018 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2019 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2020 goto return_srv_prx_502;
2021 }
2022
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002023 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024 /* Always enter in the body analyzer */
2025 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2026 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2027
2028 /* if the user wants to log as soon as possible, without counting
2029 * bytes from the server, then this is the right moment. We have
2030 * to temporarily assign bytes_out to log what we currently have.
2031 */
2032 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2033 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002034 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002035 s->do_log(s);
2036 s->logs.bytes_out = 0;
2037 }
2038 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002039
2040 return_bad_resp:
2041 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002042 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002043 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002044 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002045 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002046
2047 return_srv_prx_502:
2048 rep->analysers &= AN_RES_FLT_END;
2049 txn->status = 502;
2050 s->logs.t_data = -1; /* was not a valid response */
2051 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002052 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002053 if (!(s->flags & SF_ERR_MASK))
2054 s->flags |= SF_ERR_PRXCOND;
2055 if (!(s->flags & SF_FINST_MASK))
2056 s->flags |= SF_FINST_H;
2057 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002058}
2059
2060/* This function is an analyser which forwards response body (including chunk
2061 * sizes if any). It is called as soon as we must forward, even if we forward
2062 * zero byte. The only situation where it must not be called is when we're in
2063 * tunnel mode and we want to forward till the close. It's used both to forward
2064 * remaining data and to resync after end of body. It expects the msg_state to
2065 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2066 * read more data, or 1 once we can go on with next request or end the stream.
2067 *
2068 * It is capable of compressing response data both in content-length mode and
2069 * in chunked mode. The state machines follows different flows depending on
2070 * whether content-length and chunked modes are used, since there are no
2071 * trailers in content-length :
2072 *
2073 * chk-mode cl-mode
2074 * ,----- BODY -----.
2075 * / \
2076 * V size > 0 V chk-mode
2077 * .--> SIZE -------------> DATA -------------> CRLF
2078 * | | size == 0 | last byte |
2079 * | v final crlf v inspected |
2080 * | TRAILERS -----------> DONE |
2081 * | |
2082 * `----------------------------------------------'
2083 *
2084 * Compression only happens in the DATA state, and must be flushed in final
2085 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2086 * is performed at once on final states for all bytes parsed, or when leaving
2087 * on missing data.
2088 */
2089int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2090{
2091 struct session *sess = s->sess;
2092 struct http_txn *txn = s->txn;
2093 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002094 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002095 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002096
2097 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2098 now_ms, __FUNCTION__,
2099 s,
2100 res,
2101 res->rex, res->wex,
2102 res->flags,
2103 ci_data(res),
2104 res->analysers);
2105
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002106 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002107
2108 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002109 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002110 /* Output closed while we were sending data. We must abort and
2111 * wake the other side up.
2112 */
2113 msg->err_state = msg->msg_state;
2114 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002115 htx_end_response(s);
2116 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002117 return 1;
2118 }
2119
Christopher Faulet9768c262018-10-22 09:34:31 +02002120 if (msg->msg_state == HTTP_MSG_BODY)
2121 msg->msg_state = HTTP_MSG_DATA;
2122
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123 /* in most states, we should abort in case of early close */
2124 channel_auto_close(res);
2125
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002127 if (res->to_forward == CHN_INFINITE_FORWARD) {
2128 if (res->flags & (CF_SHUTR|CF_EOI)) {
2129 msg->msg_state = HTTP_MSG_DONE;
2130 res->to_forward = 0;
2131 goto done;
2132 }
2133 }
2134 else {
2135 /* We can't process the buffer's contents yet */
2136 res->flags |= CF_WAKE_WRITE;
2137 goto missing_data_or_waiting;
2138 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002139 }
2140
Christopher Faulet9768c262018-10-22 09:34:31 +02002141 if (msg->msg_state >= HTTP_MSG_DONE)
2142 goto done;
2143
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002144 /* Forward input data. We get it by removing all outgoing data not
2145 * forwarded yet from HTX data size. If there are some data filters, we
2146 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002147 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002148 if (HAS_RSP_DATA_FILTERS(s)) {
2149 ret = flt_http_payload(s, msg, htx->data);
2150 if (ret < 0)
2151 goto return_bad_res;
2152 c_adv(res, ret);
2153 if (htx->data != co_data(res) || htx->extra)
2154 goto missing_data_or_waiting;
2155 }
2156 else {
2157 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002158 if (msg->flags & HTTP_MSGF_XFER_LEN)
2159 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002160 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002161
2162 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2163 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002164 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002165 msg->msg_state = HTTP_MSG_TUNNEL;
2166 goto done;
2167 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002168 }
2169
Christopher Faulet9768c262018-10-22 09:34:31 +02002170 /* Check if the end-of-message is reached and if so, switch the message
2171 * in HTTP_MSG_DONE state.
2172 */
2173 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2174 goto missing_data_or_waiting;
2175
2176 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002177 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002178
2179 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002180 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002181 channel_dont_close(res);
2182
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002183 if (HAS_RSP_DATA_FILTERS(s)) {
2184 ret = flt_http_end(s, msg);
2185 if (ret <= 0) {
2186 if (!ret)
2187 goto missing_data_or_waiting;
2188 goto return_bad_res;
2189 }
2190 }
2191
Christopher Fauletf2824e62018-10-01 12:12:37 +02002192 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002193 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002194 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002195 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2196 if (res->flags & CF_SHUTW) {
2197 /* response errors are most likely due to the
2198 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002199 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201 goto return_bad_res;
2202 }
2203 return 1;
2204 }
2205 return 0;
2206
2207 missing_data_or_waiting:
2208 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002209 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210
Christopher Faulet47365272018-10-31 17:40:50 +01002211 if (htx->flags & HTX_FL_PARSING_ERROR)
2212 goto return_bad_res;
2213
Christopher Faulete0768eb2018-10-03 16:38:02 +02002214 /* stop waiting for data if the input is closed before the end. If the
2215 * client side was already closed, it means that the client has aborted,
2216 * so we don't want to count this as a server abort. Otherwise it's a
2217 * server abort.
2218 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002219 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002221 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002223 if (htx_is_empty(htx))
2224 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 }
2226
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227 /* When TE: chunked is used, we need to get there again to parse
2228 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002229 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2230 * are filters registered on the stream, we don't want to forward a
2231 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002233 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 channel_dont_close(res);
2235
2236 /* We know that more data are expected, but we couldn't send more that
2237 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2238 * system knows it must not set a PUSH on this first part. Interactive
2239 * modes are already handled by the stream sock layer. We must not do
2240 * this in content-length mode because it could present the MSG_MORE
2241 * flag with the last block of forwarded data, which would cause an
2242 * additional delay to be observed by the receiver.
2243 */
2244 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2245 res->flags |= CF_EXPECT_MORE;
2246
2247 /* the stream handler will take care of timeouts and errors */
2248 return 0;
2249
Christopher Faulet93e02d82019-03-08 14:18:50 +01002250 return_srv_abort:
2251 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2252 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002254 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2255 if (!(s->flags & SF_ERR_MASK))
2256 s->flags |= SF_ERR_SRVCL;
2257 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258
Christopher Faulet93e02d82019-03-08 14:18:50 +01002259 return_cli_abort:
2260 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2261 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002262 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002263 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2264 if (!(s->flags & SF_ERR_MASK))
2265 s->flags |= SF_ERR_CLICL;
2266 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002267
Christopher Faulet93e02d82019-03-08 14:18:50 +01002268 return_bad_res:
2269 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2270 if (objt_server(s->target)) {
2271 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2272 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2273 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276
Christopher Faulet93e02d82019-03-08 14:18:50 +01002277 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278 txn->rsp.err_state = txn->rsp.msg_state;
2279 txn->rsp.msg_state = HTTP_MSG_ERROR;
2280 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002281 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 res->analysers &= AN_RES_FLT_END;
2283 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 +02002284 if (!(s->flags & SF_FINST_MASK))
2285 s->flags |= SF_FINST_D;
2286 return 0;
2287}
2288
Christopher Fauletf2824e62018-10-01 12:12:37 +02002289/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002290 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002291 * as too large a request to build a valid response.
2292 */
2293int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2294{
Christopher Faulet99daf282018-11-28 22:58:13 +01002295 struct channel *req = &s->req;
2296 struct channel *res = &s->res;
2297 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002298 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002299 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002300 struct ist status, reason, location;
2301 unsigned int flags;
2302 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002303
2304 chunk = alloc_trash_chunk();
2305 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002306 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002307
Christopher Faulet99daf282018-11-28 22:58:13 +01002308 /*
2309 * Create the location
2310 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002311 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002312 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002313 case REDIRECT_TYPE_SCHEME: {
2314 struct http_hdr_ctx ctx;
2315 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002316
Christopher Faulet99daf282018-11-28 22:58:13 +01002317 host = ist("");
2318 ctx.blk = NULL;
2319 if (http_find_header(htx, ist("Host"), &ctx, 0))
2320 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002321
Christopher Faulet99daf282018-11-28 22:58:13 +01002322 sl = http_find_stline(htx);
2323 path = http_get_path(htx_sl_req_uri(sl));
2324 /* build message using path */
2325 if (path.ptr) {
2326 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2327 int qs = 0;
2328 while (qs < path.len) {
2329 if (*(path.ptr + qs) == '?') {
2330 path.len = qs;
2331 break;
2332 }
2333 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002334 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002335 }
2336 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002337 else
2338 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002339
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 if (rule->rdr_str) { /* this is an old "redirect" rule */
2341 /* add scheme */
2342 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2343 goto fail;
2344 }
2345 else {
2346 /* add scheme with executing log format */
2347 chunk->data += build_logline(s, chunk->area + chunk->data,
2348 chunk->size - chunk->data,
2349 &rule->rdr_fmt);
2350 }
2351 /* add "://" + host + path */
2352 if (!chunk_memcat(chunk, "://", 3) ||
2353 !chunk_memcat(chunk, host.ptr, host.len) ||
2354 !chunk_memcat(chunk, path.ptr, path.len))
2355 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 /* append a slash at the end of the location if needed and missing */
2358 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2359 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2360 if (chunk->data + 1 >= chunk->size)
2361 goto fail;
2362 chunk->area[chunk->data++] = '/';
2363 }
2364 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002365 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366
Christopher Faulet99daf282018-11-28 22:58:13 +01002367 case REDIRECT_TYPE_PREFIX: {
2368 struct ist path;
2369
2370 sl = http_find_stline(htx);
2371 path = http_get_path(htx_sl_req_uri(sl));
2372 /* build message using path */
2373 if (path.ptr) {
2374 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2375 int qs = 0;
2376 while (qs < path.len) {
2377 if (*(path.ptr + qs) == '?') {
2378 path.len = qs;
2379 break;
2380 }
2381 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383 }
2384 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 else
2386 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002387
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 if (rule->rdr_str) { /* this is an old "redirect" rule */
2389 /* add prefix. Note that if prefix == "/", we don't want to
2390 * add anything, otherwise it makes it hard for the user to
2391 * configure a self-redirection.
2392 */
2393 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2394 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2395 goto fail;
2396 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002398 else {
2399 /* add prefix with executing log format */
2400 chunk->data += build_logline(s, chunk->area + chunk->data,
2401 chunk->size - chunk->data,
2402 &rule->rdr_fmt);
2403 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 /* add path */
2406 if (!chunk_memcat(chunk, path.ptr, path.len))
2407 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002408
Christopher Faulet99daf282018-11-28 22:58:13 +01002409 /* append a slash at the end of the location if needed and missing */
2410 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2411 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2412 if (chunk->data + 1 >= chunk->size)
2413 goto fail;
2414 chunk->area[chunk->data++] = '/';
2415 }
2416 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002418 case REDIRECT_TYPE_LOCATION:
2419 default:
2420 if (rule->rdr_str) { /* this is an old "redirect" rule */
2421 /* add location */
2422 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2423 goto fail;
2424 }
2425 else {
2426 /* add location with executing log format */
2427 chunk->data += build_logline(s, chunk->area + chunk->data,
2428 chunk->size - chunk->data,
2429 &rule->rdr_fmt);
2430 }
2431 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 location = ist2(chunk->area, chunk->data);
2434
2435 /*
2436 * Create the 30x response
2437 */
2438 switch (rule->code) {
2439 case 308:
2440 status = ist("308");
2441 reason = ist("Permanent Redirect");
2442 break;
2443 case 307:
2444 status = ist("307");
2445 reason = ist("Temporary Redirect");
2446 break;
2447 case 303:
2448 status = ist("303");
2449 reason = ist("See Other");
2450 break;
2451 case 301:
2452 status = ist("301");
2453 reason = ist("Moved Permanently");
2454 break;
2455 case 302:
2456 default:
2457 status = ist("302");
2458 reason = ist("Found");
2459 break;
2460 }
2461
2462 htx = htx_from_buf(&res->buf);
2463 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2464 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2465 if (!sl)
2466 goto fail;
2467 sl->info.res.status = rule->code;
2468 s->txn->status = rule->code;
2469
2470 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2471 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2472 !htx_add_header(htx, ist("Location"), location))
2473 goto fail;
2474
2475 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2476 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2477 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002478 }
2479
2480 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002481 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2482 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002483 }
2484
Christopher Faulet99daf282018-11-28 22:58:13 +01002485 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2486 goto fail;
2487
Christopher Fauletf2824e62018-10-01 12:12:37 +02002488 /* let's log the request time */
2489 s->logs.tv_request = now;
2490
Christopher Faulet99daf282018-11-28 22:58:13 +01002491 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002492 c_adv(res, data);
2493 res->total += data;
2494
2495 channel_auto_read(req);
2496 channel_abort(req);
2497 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002498 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002499
2500 res->wex = tick_add_ifset(now_ms, res->wto);
2501 channel_auto_read(res);
2502 channel_auto_close(res);
2503 channel_shutr_now(res);
2504
2505 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002506
2507 if (!(s->flags & SF_ERR_MASK))
2508 s->flags |= SF_ERR_LOCAL;
2509 if (!(s->flags & SF_FINST_MASK))
2510 s->flags |= SF_FINST_R;
2511
Christopher Faulet99daf282018-11-28 22:58:13 +01002512 free_trash_chunk(chunk);
2513 return 1;
2514
2515 fail:
2516 /* If an error occurred, remove the incomplete HTTP response from the
2517 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002518 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002519 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002521}
2522
Christopher Faulet72333522018-10-24 11:25:02 +02002523int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2524 struct ist name, const char *str, struct my_regex *re, int action)
2525{
2526 struct http_hdr_ctx ctx;
2527 struct buffer *output = get_trash_chunk();
2528
2529 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2530 ctx.blk = NULL;
2531 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2532 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2533 continue;
2534
2535 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2536 if (output->data == -1)
2537 return -1;
2538 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2539 return -1;
2540 }
2541 return 0;
2542}
2543
2544static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2545 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2546{
2547 struct buffer *replace;
2548 int ret = -1;
2549
2550 replace = alloc_trash_chunk();
2551 if (!replace)
2552 goto leave;
2553
2554 replace->data = build_logline(s, replace->area, replace->size, fmt);
2555 if (replace->data >= replace->size - 1)
2556 goto leave;
2557
2558 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2559
2560 leave:
2561 free_trash_chunk(replace);
2562 return ret;
2563}
2564
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002565
2566/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2567 * on success and -1 on error. The response channel is updated accordingly.
2568 */
2569static int htx_reply_103_early_hints(struct channel *res)
2570{
2571 struct htx *htx = htx_from_buf(&res->buf);
2572 size_t data;
2573
2574 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2575 /* If an error occurred during an Early-hint rule,
2576 * remove the incomplete HTTP 103 response from the
2577 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002578 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002579 return -1;
2580 }
2581
2582 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002583 c_adv(res, data);
2584 res->total += data;
2585 return 0;
2586}
2587
Christopher Faulet6eb92892018-11-15 16:39:29 +01002588/*
2589 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2590 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002591 * If <early_hints> is 0, it is starts a new response by adding the start
2592 * line. If an error occurred -1 is returned. On success 0 is returned. The
2593 * channel is not updated here. It must be done calling the function
2594 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002595 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002596static 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 +01002597{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002598 struct channel *res = &s->res;
2599 struct htx *htx = htx_from_buf(&res->buf);
2600 struct buffer *value = alloc_trash_chunk();
2601
Christopher Faulet6eb92892018-11-15 16:39:29 +01002602 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002603 struct htx_sl *sl;
2604 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2605 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2606
2607 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2608 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2609 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002610 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002611 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002612 }
2613
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002614 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2615 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002616 goto fail;
2617
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002618 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002619 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002620
2621 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 /* If an error occurred during an Early-hint rule, remove the incomplete
2623 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002624 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002625 free_trash_chunk(value);
2626 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002627}
2628
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002629/* This function executes one of the set-{method,path,query,uri} actions. It
2630 * takes the string from the variable 'replace' with length 'len', then modifies
2631 * the relevant part of the request line accordingly. Then it updates various
2632 * pointers to the next elements which were moved, and the total buffer length.
2633 * It finds the action to be performed in p[2], previously filled by function
2634 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2635 * error, though this can be revisited when this code is finally exploited.
2636 *
2637 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2638 * query string and 3 to replace uri.
2639 *
2640 * In query string case, the mark question '?' must be set at the start of the
2641 * string by the caller, event if the replacement query string is empty.
2642 */
2643int htx_req_replace_stline(int action, const char *replace, int len,
2644 struct proxy *px, struct stream *s)
2645{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002646 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002647
2648 switch (action) {
2649 case 0: // method
2650 if (!http_replace_req_meth(htx, ist2(replace, len)))
2651 return -1;
2652 break;
2653
2654 case 1: // path
2655 if (!http_replace_req_path(htx, ist2(replace, len)))
2656 return -1;
2657 break;
2658
2659 case 2: // query
2660 if (!http_replace_req_query(htx, ist2(replace, len)))
2661 return -1;
2662 break;
2663
2664 case 3: // uri
2665 if (!http_replace_req_uri(htx, ist2(replace, len)))
2666 return -1;
2667 break;
2668
2669 default:
2670 return -1;
2671 }
2672 return 0;
2673}
2674
2675/* This function replace the HTTP status code and the associated message. The
2676 * variable <status> contains the new status code. This function never fails.
2677 */
2678void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2679{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002680 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002681 char *res;
2682
2683 chunk_reset(&trash);
2684 res = ultoa_o(status, trash.area, trash.size);
2685 trash.data = res - trash.area;
2686
2687 /* Do we have a custom reason format string? */
2688 if (reason == NULL)
2689 reason = http_get_reason(status);
2690
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002691 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002692 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2693}
2694
Christopher Faulet3e964192018-10-24 11:39:23 +02002695/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2696 * transaction <txn>. Returns the verdict of the first rule that prevents
2697 * further processing of the request (auth, deny, ...), and defaults to
2698 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2699 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2700 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2701 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2702 * status.
2703 */
2704static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2705 struct stream *s, int *deny_status)
2706{
2707 struct session *sess = strm_sess(s);
2708 struct http_txn *txn = s->txn;
2709 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002710 struct act_rule *rule;
2711 struct http_hdr_ctx ctx;
2712 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002713 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2714 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002715 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002716
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002717 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002718
2719 /* If "the current_rule_list" match the executed rule list, we are in
2720 * resume condition. If a resume is needed it is always in the action
2721 * and never in the ACL or converters. In this case, we initialise the
2722 * current rule, and go to the action execution point.
2723 */
2724 if (s->current_rule) {
2725 rule = s->current_rule;
2726 s->current_rule = NULL;
2727 if (s->current_rule_list == rules)
2728 goto resume_execution;
2729 }
2730 s->current_rule_list = rules;
2731
2732 list_for_each_entry(rule, rules, list) {
2733 /* check optional condition */
2734 if (rule->cond) {
2735 int ret;
2736
2737 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2738 ret = acl_pass(ret);
2739
2740 if (rule->cond->pol == ACL_COND_UNLESS)
2741 ret = !ret;
2742
2743 if (!ret) /* condition not matched */
2744 continue;
2745 }
2746
2747 act_flags |= ACT_FLAG_FIRST;
2748 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002749 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2750 early_hints = 0;
2751 if (htx_reply_103_early_hints(&s->res) == -1) {
2752 rule_ret = HTTP_RULE_RES_BADREQ;
2753 goto end;
2754 }
2755 }
2756
Christopher Faulet3e964192018-10-24 11:39:23 +02002757 switch (rule->action) {
2758 case ACT_ACTION_ALLOW:
2759 rule_ret = HTTP_RULE_RES_STOP;
2760 goto end;
2761
2762 case ACT_ACTION_DENY:
2763 if (deny_status)
2764 *deny_status = rule->deny_status;
2765 rule_ret = HTTP_RULE_RES_DENY;
2766 goto end;
2767
2768 case ACT_HTTP_REQ_TARPIT:
2769 txn->flags |= TX_CLTARPIT;
2770 if (deny_status)
2771 *deny_status = rule->deny_status;
2772 rule_ret = HTTP_RULE_RES_DENY;
2773 goto end;
2774
2775 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002776 /* Auth might be performed on regular http-req rules as well as on stats */
2777 auth_realm = rule->arg.auth.realm;
2778 if (!auth_realm) {
2779 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2780 auth_realm = STATS_DEFAULT_REALM;
2781 else
2782 auth_realm = px->id;
2783 }
2784 /* send 401/407 depending on whether we use a proxy or not. We still
2785 * count one error, because normal browsing won't significantly
2786 * increase the counter but brute force attempts will.
2787 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002788 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002789 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2790 rule_ret = HTTP_RULE_RES_BADREQ;
2791 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002792 goto end;
2793
2794 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002795 rule_ret = HTTP_RULE_RES_DONE;
2796 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2797 rule_ret = HTTP_RULE_RES_BADREQ;
2798 goto end;
2799
2800 case ACT_HTTP_SET_NICE:
2801 s->task->nice = rule->arg.nice;
2802 break;
2803
2804 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002805 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002806 break;
2807
2808 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002809 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002810 break;
2811
2812 case ACT_HTTP_SET_LOGL:
2813 s->logs.level = rule->arg.loglevel;
2814 break;
2815
2816 case ACT_HTTP_REPLACE_HDR:
2817 case ACT_HTTP_REPLACE_VAL:
2818 if (htx_transform_header(s, &s->req, htx,
2819 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2820 &rule->arg.hdr_add.fmt,
2821 &rule->arg.hdr_add.re, rule->action)) {
2822 rule_ret = HTTP_RULE_RES_BADREQ;
2823 goto end;
2824 }
2825 break;
2826
2827 case ACT_HTTP_DEL_HDR:
2828 /* remove all occurrences of the header */
2829 ctx.blk = NULL;
2830 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2831 http_remove_header(htx, &ctx);
2832 break;
2833
2834 case ACT_HTTP_SET_HDR:
2835 case ACT_HTTP_ADD_HDR: {
2836 /* The scope of the trash buffer must be limited to this function. The
2837 * build_logline() function can execute a lot of other function which
2838 * can use the trash buffer. So for limiting the scope of this global
2839 * buffer, we build first the header value using build_logline, and
2840 * after we store the header name.
2841 */
2842 struct buffer *replace;
2843 struct ist n, v;
2844
2845 replace = alloc_trash_chunk();
2846 if (!replace) {
2847 rule_ret = HTTP_RULE_RES_BADREQ;
2848 goto end;
2849 }
2850
2851 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2852 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2853 v = ist2(replace->area, replace->data);
2854
2855 if (rule->action == ACT_HTTP_SET_HDR) {
2856 /* remove all occurrences of the header */
2857 ctx.blk = NULL;
2858 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2859 http_remove_header(htx, &ctx);
2860 }
2861
2862 if (!http_add_header(htx, n, v)) {
2863 static unsigned char rate_limit = 0;
2864
2865 if ((rate_limit++ & 255) == 0) {
2866 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);
2867 }
2868
Olivier Houcharda798bf52019-03-08 18:52:00 +01002869 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002870 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002871 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002872 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002873 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002874 }
2875 free_trash_chunk(replace);
2876 break;
2877 }
2878
2879 case ACT_HTTP_DEL_ACL:
2880 case ACT_HTTP_DEL_MAP: {
2881 struct pat_ref *ref;
2882 struct buffer *key;
2883
2884 /* collect reference */
2885 ref = pat_ref_lookup(rule->arg.map.ref);
2886 if (!ref)
2887 continue;
2888
2889 /* allocate key */
2890 key = alloc_trash_chunk();
2891 if (!key) {
2892 rule_ret = HTTP_RULE_RES_BADREQ;
2893 goto end;
2894 }
2895
2896 /* collect key */
2897 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2898 key->area[key->data] = '\0';
2899
2900 /* perform update */
2901 /* returned code: 1=ok, 0=ko */
2902 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2903 pat_ref_delete(ref, key->area);
2904 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2905
2906 free_trash_chunk(key);
2907 break;
2908 }
2909
2910 case ACT_HTTP_ADD_ACL: {
2911 struct pat_ref *ref;
2912 struct buffer *key;
2913
2914 /* collect reference */
2915 ref = pat_ref_lookup(rule->arg.map.ref);
2916 if (!ref)
2917 continue;
2918
2919 /* allocate key */
2920 key = alloc_trash_chunk();
2921 if (!key) {
2922 rule_ret = HTTP_RULE_RES_BADREQ;
2923 goto end;
2924 }
2925
2926 /* collect key */
2927 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2928 key->area[key->data] = '\0';
2929
2930 /* perform update */
2931 /* add entry only if it does not already exist */
2932 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2933 if (pat_ref_find_elt(ref, key->area) == NULL)
2934 pat_ref_add(ref, key->area, NULL, NULL);
2935 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2936
2937 free_trash_chunk(key);
2938 break;
2939 }
2940
2941 case ACT_HTTP_SET_MAP: {
2942 struct pat_ref *ref;
2943 struct buffer *key, *value;
2944
2945 /* collect reference */
2946 ref = pat_ref_lookup(rule->arg.map.ref);
2947 if (!ref)
2948 continue;
2949
2950 /* allocate key */
2951 key = alloc_trash_chunk();
2952 if (!key) {
2953 rule_ret = HTTP_RULE_RES_BADREQ;
2954 goto end;
2955 }
2956
2957 /* allocate value */
2958 value = alloc_trash_chunk();
2959 if (!value) {
2960 free_trash_chunk(key);
2961 rule_ret = HTTP_RULE_RES_BADREQ;
2962 goto end;
2963 }
2964
2965 /* collect key */
2966 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2967 key->area[key->data] = '\0';
2968
2969 /* collect value */
2970 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2971 value->area[value->data] = '\0';
2972
2973 /* perform update */
2974 if (pat_ref_find_elt(ref, key->area) != NULL)
2975 /* update entry if it exists */
2976 pat_ref_set(ref, key->area, value->area, NULL);
2977 else
2978 /* insert a new entry */
2979 pat_ref_add(ref, key->area, value->area, NULL);
2980
2981 free_trash_chunk(key);
2982 free_trash_chunk(value);
2983 break;
2984 }
2985
2986 case ACT_HTTP_EARLY_HINT:
2987 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2988 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002989 early_hints = htx_add_early_hint_header(s, early_hints,
2990 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02002991 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002992 if (early_hints == -1) {
2993 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02002994 goto end;
2995 }
2996 break;
2997
2998 case ACT_CUSTOM:
2999 if ((s->req.flags & CF_READ_ERROR) ||
3000 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003001 (px->options & PR_O_ABRT_CLOSE)))
3002 act_flags |= ACT_FLAG_FINAL;
3003
3004 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3005 case ACT_RET_ERR:
3006 case ACT_RET_CONT:
3007 break;
3008 case ACT_RET_STOP:
3009 rule_ret = HTTP_RULE_RES_DONE;
3010 goto end;
3011 case ACT_RET_YIELD:
3012 s->current_rule = rule;
3013 rule_ret = HTTP_RULE_RES_YIELD;
3014 goto end;
3015 }
3016 break;
3017
3018 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3019 /* Note: only the first valid tracking parameter of each
3020 * applies.
3021 */
3022
3023 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3024 struct stktable *t;
3025 struct stksess *ts;
3026 struct stktable_key *key;
3027 void *ptr1, *ptr2;
3028
3029 t = rule->arg.trk_ctr.table.t;
3030 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3031 rule->arg.trk_ctr.expr, NULL);
3032
3033 if (key && (ts = stktable_get_entry(t, key))) {
3034 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3035
3036 /* let's count a new HTTP request as it's the first time we do it */
3037 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3038 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3039 if (ptr1 || ptr2) {
3040 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3041
3042 if (ptr1)
3043 stktable_data_cast(ptr1, http_req_cnt)++;
3044
3045 if (ptr2)
3046 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3047 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3048
3049 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3050
3051 /* If data was modified, we need to touch to re-schedule sync */
3052 stktable_touch_local(t, ts, 0);
3053 }
3054
3055 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3056 if (sess->fe != s->be)
3057 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3058 }
3059 }
3060 break;
3061
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003062 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003063 default:
3064 break;
3065 }
3066 }
3067
3068 end:
3069 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003070 if (htx_reply_103_early_hints(&s->res) == -1)
3071 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003072 }
3073
3074 /* we reached the end of the rules, nothing to report */
3075 return rule_ret;
3076}
3077
3078/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3079 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3080 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3081 * is returned, the process can continue the evaluation of next rule list. If
3082 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3083 * is returned, it means the operation could not be processed and a server error
3084 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3085 * deny rule. If *YIELD is returned, the caller must call again the function
3086 * with the same context.
3087 */
3088static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3089 struct stream *s)
3090{
3091 struct session *sess = strm_sess(s);
3092 struct http_txn *txn = s->txn;
3093 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003094 struct act_rule *rule;
3095 struct http_hdr_ctx ctx;
3096 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3097 int act_flags = 0;
3098
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003099 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003100
3101 /* If "the current_rule_list" match the executed rule list, we are in
3102 * resume condition. If a resume is needed it is always in the action
3103 * and never in the ACL or converters. In this case, we initialise the
3104 * current rule, and go to the action execution point.
3105 */
3106 if (s->current_rule) {
3107 rule = s->current_rule;
3108 s->current_rule = NULL;
3109 if (s->current_rule_list == rules)
3110 goto resume_execution;
3111 }
3112 s->current_rule_list = rules;
3113
3114 list_for_each_entry(rule, rules, list) {
3115 /* check optional condition */
3116 if (rule->cond) {
3117 int ret;
3118
3119 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3120 ret = acl_pass(ret);
3121
3122 if (rule->cond->pol == ACL_COND_UNLESS)
3123 ret = !ret;
3124
3125 if (!ret) /* condition not matched */
3126 continue;
3127 }
3128
3129 act_flags |= ACT_FLAG_FIRST;
3130resume_execution:
3131 switch (rule->action) {
3132 case ACT_ACTION_ALLOW:
3133 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3134 goto end;
3135
3136 case ACT_ACTION_DENY:
3137 txn->flags |= TX_SVDENY;
3138 rule_ret = HTTP_RULE_RES_STOP;
3139 goto end;
3140
3141 case ACT_HTTP_SET_NICE:
3142 s->task->nice = rule->arg.nice;
3143 break;
3144
3145 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003146 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003147 break;
3148
3149 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003150 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003151 break;
3152
3153 case ACT_HTTP_SET_LOGL:
3154 s->logs.level = rule->arg.loglevel;
3155 break;
3156
3157 case ACT_HTTP_REPLACE_HDR:
3158 case ACT_HTTP_REPLACE_VAL:
3159 if (htx_transform_header(s, &s->res, htx,
3160 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3161 &rule->arg.hdr_add.fmt,
3162 &rule->arg.hdr_add.re, rule->action)) {
3163 rule_ret = HTTP_RULE_RES_BADREQ;
3164 goto end;
3165 }
3166 break;
3167
3168 case ACT_HTTP_DEL_HDR:
3169 /* remove all occurrences of the header */
3170 ctx.blk = NULL;
3171 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3172 http_remove_header(htx, &ctx);
3173 break;
3174
3175 case ACT_HTTP_SET_HDR:
3176 case ACT_HTTP_ADD_HDR: {
3177 struct buffer *replace;
3178 struct ist n, v;
3179
3180 replace = alloc_trash_chunk();
3181 if (!replace) {
3182 rule_ret = HTTP_RULE_RES_BADREQ;
3183 goto end;
3184 }
3185
3186 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3187 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3188 v = ist2(replace->area, replace->data);
3189
3190 if (rule->action == ACT_HTTP_SET_HDR) {
3191 /* remove all occurrences of the header */
3192 ctx.blk = NULL;
3193 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3194 http_remove_header(htx, &ctx);
3195 }
3196
3197 if (!http_add_header(htx, n, v)) {
3198 static unsigned char rate_limit = 0;
3199
3200 if ((rate_limit++ & 255) == 0) {
3201 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);
3202 }
3203
Olivier Houcharda798bf52019-03-08 18:52:00 +01003204 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003205 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003206 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003207 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003208 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003209 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003210 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003211 }
3212 free_trash_chunk(replace);
3213 break;
3214 }
3215
3216 case ACT_HTTP_DEL_ACL:
3217 case ACT_HTTP_DEL_MAP: {
3218 struct pat_ref *ref;
3219 struct buffer *key;
3220
3221 /* collect reference */
3222 ref = pat_ref_lookup(rule->arg.map.ref);
3223 if (!ref)
3224 continue;
3225
3226 /* allocate key */
3227 key = alloc_trash_chunk();
3228 if (!key) {
3229 rule_ret = HTTP_RULE_RES_BADREQ;
3230 goto end;
3231 }
3232
3233 /* collect key */
3234 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3235 key->area[key->data] = '\0';
3236
3237 /* perform update */
3238 /* returned code: 1=ok, 0=ko */
3239 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3240 pat_ref_delete(ref, key->area);
3241 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3242
3243 free_trash_chunk(key);
3244 break;
3245 }
3246
3247 case ACT_HTTP_ADD_ACL: {
3248 struct pat_ref *ref;
3249 struct buffer *key;
3250
3251 /* collect reference */
3252 ref = pat_ref_lookup(rule->arg.map.ref);
3253 if (!ref)
3254 continue;
3255
3256 /* allocate key */
3257 key = alloc_trash_chunk();
3258 if (!key) {
3259 rule_ret = HTTP_RULE_RES_BADREQ;
3260 goto end;
3261 }
3262
3263 /* collect key */
3264 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3265 key->area[key->data] = '\0';
3266
3267 /* perform update */
3268 /* check if the entry already exists */
3269 if (pat_ref_find_elt(ref, key->area) == NULL)
3270 pat_ref_add(ref, key->area, NULL, NULL);
3271
3272 free_trash_chunk(key);
3273 break;
3274 }
3275
3276 case ACT_HTTP_SET_MAP: {
3277 struct pat_ref *ref;
3278 struct buffer *key, *value;
3279
3280 /* collect reference */
3281 ref = pat_ref_lookup(rule->arg.map.ref);
3282 if (!ref)
3283 continue;
3284
3285 /* allocate key */
3286 key = alloc_trash_chunk();
3287 if (!key) {
3288 rule_ret = HTTP_RULE_RES_BADREQ;
3289 goto end;
3290 }
3291
3292 /* allocate value */
3293 value = alloc_trash_chunk();
3294 if (!value) {
3295 free_trash_chunk(key);
3296 rule_ret = HTTP_RULE_RES_BADREQ;
3297 goto end;
3298 }
3299
3300 /* collect key */
3301 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3302 key->area[key->data] = '\0';
3303
3304 /* collect value */
3305 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3306 value->area[value->data] = '\0';
3307
3308 /* perform update */
3309 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3310 if (pat_ref_find_elt(ref, key->area) != NULL)
3311 /* update entry if it exists */
3312 pat_ref_set(ref, key->area, value->area, NULL);
3313 else
3314 /* insert a new entry */
3315 pat_ref_add(ref, key->area, value->area, NULL);
3316 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3317 free_trash_chunk(key);
3318 free_trash_chunk(value);
3319 break;
3320 }
3321
3322 case ACT_HTTP_REDIR:
3323 rule_ret = HTTP_RULE_RES_DONE;
3324 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3325 rule_ret = HTTP_RULE_RES_BADREQ;
3326 goto end;
3327
3328 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3329 /* Note: only the first valid tracking parameter of each
3330 * applies.
3331 */
3332 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3333 struct stktable *t;
3334 struct stksess *ts;
3335 struct stktable_key *key;
3336 void *ptr;
3337
3338 t = rule->arg.trk_ctr.table.t;
3339 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3340 rule->arg.trk_ctr.expr, NULL);
3341
3342 if (key && (ts = stktable_get_entry(t, key))) {
3343 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3344
3345 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3346
3347 /* let's count a new HTTP request as it's the first time we do it */
3348 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3349 if (ptr)
3350 stktable_data_cast(ptr, http_req_cnt)++;
3351
3352 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3353 if (ptr)
3354 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3355 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3356
3357 /* When the client triggers a 4xx from the server, it's most often due
3358 * to a missing object or permission. These events should be tracked
3359 * because if they happen often, it may indicate a brute force or a
3360 * vulnerability scan. Normally this is done when receiving the response
3361 * but here we're tracking after this ought to have been done so we have
3362 * to do it on purpose.
3363 */
3364 if ((unsigned)(txn->status - 400) < 100) {
3365 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3366 if (ptr)
3367 stktable_data_cast(ptr, http_err_cnt)++;
3368
3369 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3370 if (ptr)
3371 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3372 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3373 }
3374
3375 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3376
3377 /* If data was modified, we need to touch to re-schedule sync */
3378 stktable_touch_local(t, ts, 0);
3379
3380 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3381 if (sess->fe != s->be)
3382 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3383 }
3384 }
3385 break;
3386
3387 case ACT_CUSTOM:
3388 if ((s->req.flags & CF_READ_ERROR) ||
3389 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003390 (px->options & PR_O_ABRT_CLOSE)))
3391 act_flags |= ACT_FLAG_FINAL;
3392
3393 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3394 case ACT_RET_ERR:
3395 case ACT_RET_CONT:
3396 break;
3397 case ACT_RET_STOP:
3398 rule_ret = HTTP_RULE_RES_STOP;
3399 goto end;
3400 case ACT_RET_YIELD:
3401 s->current_rule = rule;
3402 rule_ret = HTTP_RULE_RES_YIELD;
3403 goto end;
3404 }
3405 break;
3406
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003407 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003408 default:
3409 break;
3410 }
3411 }
3412
3413 end:
3414 /* we reached the end of the rules, nothing to report */
3415 return rule_ret;
3416}
3417
Christopher Faulet33640082018-10-24 11:53:01 +02003418/* Iterate the same filter through all request headers.
3419 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3420 * Since it can manage the switch to another backend, it updates the per-proxy
3421 * DENY stats.
3422 */
3423static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3424{
3425 struct http_txn *txn = s->txn;
3426 struct htx *htx;
3427 struct buffer *hdr = get_trash_chunk();
3428 int32_t pos;
3429
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003430 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003431
3432 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3433 struct htx_blk *blk = htx_get_blk(htx, pos);
3434 enum htx_blk_type type;
3435 struct ist n, v;
3436
3437 next_hdr:
3438 type = htx_get_blk_type(blk);
3439 if (type == HTX_BLK_EOH)
3440 break;
3441 if (type != HTX_BLK_HDR)
3442 continue;
3443
3444 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3445 return 1;
3446 else if (unlikely(txn->flags & TX_CLALLOW) &&
3447 (exp->action == ACT_ALLOW ||
3448 exp->action == ACT_DENY ||
3449 exp->action == ACT_TARPIT))
3450 return 0;
3451
3452 n = htx_get_blk_name(htx, blk);
3453 v = htx_get_blk_value(htx, blk);
3454
Christopher Faulet02e771a2019-02-26 15:36:05 +01003455 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003456 hdr->area[hdr->data++] = ':';
3457 hdr->area[hdr->data++] = ' ';
3458 chunk_memcat(hdr, v.ptr, v.len);
3459
3460 /* Now we have one header in <hdr> */
3461
3462 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3463 struct http_hdr_ctx ctx;
3464 int len;
3465
3466 switch (exp->action) {
3467 case ACT_ALLOW:
3468 txn->flags |= TX_CLALLOW;
3469 goto end;
3470
3471 case ACT_DENY:
3472 txn->flags |= TX_CLDENY;
3473 goto end;
3474
3475 case ACT_TARPIT:
3476 txn->flags |= TX_CLTARPIT;
3477 goto end;
3478
3479 case ACT_REPLACE:
3480 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3481 if (len < 0)
3482 return -1;
3483
3484 http_parse_header(ist2(trash.area, len), &n, &v);
3485 ctx.blk = blk;
3486 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003487 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003488 if (!http_replace_header(htx, &ctx, n, v))
3489 return -1;
3490 if (!ctx.blk)
3491 goto end;
3492 pos = htx_get_blk_pos(htx, blk);
3493 break;
3494
3495 case ACT_REMOVE:
3496 ctx.blk = blk;
3497 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003498 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003499 if (!http_remove_header(htx, &ctx))
3500 return -1;
3501 if (!ctx.blk)
3502 goto end;
3503 pos = htx_get_blk_pos(htx, blk);
3504 goto next_hdr;
3505
3506 }
3507 }
3508 }
3509 end:
3510 return 0;
3511}
3512
3513/* Apply the filter to the request line.
3514 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3515 * or -1 if a replacement resulted in an invalid request line.
3516 * Since it can manage the switch to another backend, it updates the per-proxy
3517 * DENY stats.
3518 */
3519static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3520{
3521 struct http_txn *txn = s->txn;
3522 struct htx *htx;
3523 struct buffer *reqline = get_trash_chunk();
3524 int done;
3525
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003526 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003527
3528 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3529 return 1;
3530 else if (unlikely(txn->flags & TX_CLALLOW) &&
3531 (exp->action == ACT_ALLOW ||
3532 exp->action == ACT_DENY ||
3533 exp->action == ACT_TARPIT))
3534 return 0;
3535 else if (exp->action == ACT_REMOVE)
3536 return 0;
3537
3538 done = 0;
3539
3540 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3541
3542 /* Now we have the request line between cur_ptr and cur_end */
3543 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003544 struct htx_sl *sl = http_find_stline(htx);
3545 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003546 int len;
3547
3548 switch (exp->action) {
3549 case ACT_ALLOW:
3550 txn->flags |= TX_CLALLOW;
3551 done = 1;
3552 break;
3553
3554 case ACT_DENY:
3555 txn->flags |= TX_CLDENY;
3556 done = 1;
3557 break;
3558
3559 case ACT_TARPIT:
3560 txn->flags |= TX_CLTARPIT;
3561 done = 1;
3562 break;
3563
3564 case ACT_REPLACE:
3565 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3566 if (len < 0)
3567 return -1;
3568
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003569 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3570 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3571 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003572 return -1;
3573 done = 1;
3574 break;
3575 }
3576 }
3577 return done;
3578}
3579
3580/*
3581 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3582 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3583 * unparsable request. Since it can manage the switch to another backend, it
3584 * updates the per-proxy DENY stats.
3585 */
3586static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3587{
3588 struct session *sess = s->sess;
3589 struct http_txn *txn = s->txn;
3590 struct hdr_exp *exp;
3591
3592 for (exp = px->req_exp; exp; exp = exp->next) {
3593 int ret;
3594
3595 /*
3596 * The interleaving of transformations and verdicts
3597 * makes it difficult to decide to continue or stop
3598 * the evaluation.
3599 */
3600
3601 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3602 break;
3603
3604 if ((txn->flags & TX_CLALLOW) &&
3605 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3606 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3607 continue;
3608
3609 /* if this filter had a condition, evaluate it now and skip to
3610 * next filter if the condition does not match.
3611 */
3612 if (exp->cond) {
3613 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3614 ret = acl_pass(ret);
3615 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3616 ret = !ret;
3617
3618 if (!ret)
3619 continue;
3620 }
3621
3622 /* Apply the filter to the request line. */
3623 ret = htx_apply_filter_to_req_line(s, req, exp);
3624 if (unlikely(ret < 0))
3625 return -1;
3626
3627 if (likely(ret == 0)) {
3628 /* The filter did not match the request, it can be
3629 * iterated through all headers.
3630 */
3631 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3632 return -1;
3633 }
3634 }
3635 return 0;
3636}
3637
3638/* Iterate the same filter through all response headers contained in <res>.
3639 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3640 */
3641static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3642{
3643 struct http_txn *txn = s->txn;
3644 struct htx *htx;
3645 struct buffer *hdr = get_trash_chunk();
3646 int32_t pos;
3647
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003648 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003649
3650 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3651 struct htx_blk *blk = htx_get_blk(htx, pos);
3652 enum htx_blk_type type;
3653 struct ist n, v;
3654
3655 next_hdr:
3656 type = htx_get_blk_type(blk);
3657 if (type == HTX_BLK_EOH)
3658 break;
3659 if (type != HTX_BLK_HDR)
3660 continue;
3661
3662 if (unlikely(txn->flags & TX_SVDENY))
3663 return 1;
3664 else if (unlikely(txn->flags & TX_SVALLOW) &&
3665 (exp->action == ACT_ALLOW ||
3666 exp->action == ACT_DENY))
3667 return 0;
3668
3669 n = htx_get_blk_name(htx, blk);
3670 v = htx_get_blk_value(htx, blk);
3671
Christopher Faulet02e771a2019-02-26 15:36:05 +01003672 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003673 hdr->area[hdr->data++] = ':';
3674 hdr->area[hdr->data++] = ' ';
3675 chunk_memcat(hdr, v.ptr, v.len);
3676
3677 /* Now we have one header in <hdr> */
3678
3679 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3680 struct http_hdr_ctx ctx;
3681 int len;
3682
3683 switch (exp->action) {
3684 case ACT_ALLOW:
3685 txn->flags |= TX_SVALLOW;
3686 goto end;
3687 break;
3688
3689 case ACT_DENY:
3690 txn->flags |= TX_SVDENY;
3691 goto end;
3692 break;
3693
3694 case ACT_REPLACE:
3695 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3696 if (len < 0)
3697 return -1;
3698
3699 http_parse_header(ist2(trash.area, len), &n, &v);
3700 ctx.blk = blk;
3701 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003702 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003703 if (!http_replace_header(htx, &ctx, n, v))
3704 return -1;
3705 if (!ctx.blk)
3706 goto end;
3707 pos = htx_get_blk_pos(htx, blk);
3708 break;
3709
3710 case ACT_REMOVE:
3711 ctx.blk = blk;
3712 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003713 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003714 if (!http_remove_header(htx, &ctx))
3715 return -1;
3716 if (!ctx.blk)
3717 goto end;
3718 pos = htx_get_blk_pos(htx, blk);
3719 goto next_hdr;
3720 }
3721 }
3722
3723 }
3724 end:
3725 return 0;
3726}
3727
3728/* Apply the filter to the status line in the response buffer <res>.
3729 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3730 * or -1 if a replacement resulted in an invalid status line.
3731 */
3732static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3733{
3734 struct http_txn *txn = s->txn;
3735 struct htx *htx;
3736 struct buffer *resline = get_trash_chunk();
3737 int done;
3738
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003739 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003740
3741 if (unlikely(txn->flags & TX_SVDENY))
3742 return 1;
3743 else if (unlikely(txn->flags & TX_SVALLOW) &&
3744 (exp->action == ACT_ALLOW ||
3745 exp->action == ACT_DENY))
3746 return 0;
3747 else if (exp->action == ACT_REMOVE)
3748 return 0;
3749
3750 done = 0;
3751 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3752
3753 /* Now we have the status line between cur_ptr and cur_end */
3754 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003755 struct htx_sl *sl = http_find_stline(htx);
3756 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003757 int len;
3758
3759 switch (exp->action) {
3760 case ACT_ALLOW:
3761 txn->flags |= TX_SVALLOW;
3762 done = 1;
3763 break;
3764
3765 case ACT_DENY:
3766 txn->flags |= TX_SVDENY;
3767 done = 1;
3768 break;
3769
3770 case ACT_REPLACE:
3771 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3772 if (len < 0)
3773 return -1;
3774
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003775 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3776 sl->info.res.status = strl2ui(code.ptr, code.len);
3777 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003778 return -1;
3779
3780 done = 1;
3781 return 1;
3782 }
3783 }
3784 return done;
3785}
3786
3787/*
3788 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3789 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3790 * unparsable response.
3791 */
3792static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3793{
3794 struct session *sess = s->sess;
3795 struct http_txn *txn = s->txn;
3796 struct hdr_exp *exp;
3797
3798 for (exp = px->rsp_exp; exp; exp = exp->next) {
3799 int ret;
3800
3801 /*
3802 * The interleaving of transformations and verdicts
3803 * makes it difficult to decide to continue or stop
3804 * the evaluation.
3805 */
3806
3807 if (txn->flags & TX_SVDENY)
3808 break;
3809
3810 if ((txn->flags & TX_SVALLOW) &&
3811 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3812 exp->action == ACT_PASS)) {
3813 exp = exp->next;
3814 continue;
3815 }
3816
3817 /* if this filter had a condition, evaluate it now and skip to
3818 * next filter if the condition does not match.
3819 */
3820 if (exp->cond) {
3821 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3822 ret = acl_pass(ret);
3823 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3824 ret = !ret;
3825 if (!ret)
3826 continue;
3827 }
3828
3829 /* Apply the filter to the status line. */
3830 ret = htx_apply_filter_to_sts_line(s, res, exp);
3831 if (unlikely(ret < 0))
3832 return -1;
3833
3834 if (likely(ret == 0)) {
3835 /* The filter did not match the response, it can be
3836 * iterated through all headers.
3837 */
3838 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3839 return -1;
3840 }
3841 }
3842 return 0;
3843}
3844
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003845/*
3846 * Manage client-side cookie. It can impact performance by about 2% so it is
3847 * desirable to call it only when needed. This code is quite complex because
3848 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3849 * highly recommended not to touch this part without a good reason !
3850 */
3851static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3852{
3853 struct session *sess = s->sess;
3854 struct http_txn *txn = s->txn;
3855 struct htx *htx;
3856 struct http_hdr_ctx ctx;
3857 char *hdr_beg, *hdr_end, *del_from;
3858 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3859 int preserve_hdr;
3860
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003861 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003862 ctx.blk = NULL;
3863 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3864 del_from = NULL; /* nothing to be deleted */
3865 preserve_hdr = 0; /* assume we may kill the whole header */
3866
3867 /* Now look for cookies. Conforming to RFC2109, we have to support
3868 * attributes whose name begin with a '$', and associate them with
3869 * the right cookie, if we want to delete this cookie.
3870 * So there are 3 cases for each cookie read :
3871 * 1) it's a special attribute, beginning with a '$' : ignore it.
3872 * 2) it's a server id cookie that we *MAY* want to delete : save
3873 * some pointers on it (last semi-colon, beginning of cookie...)
3874 * 3) it's an application cookie : we *MAY* have to delete a previous
3875 * "special" cookie.
3876 * At the end of loop, if a "special" cookie remains, we may have to
3877 * remove it. If no application cookie persists in the header, we
3878 * *MUST* delete it.
3879 *
3880 * Note: RFC2965 is unclear about the processing of spaces around
3881 * the equal sign in the ATTR=VALUE form. A careful inspection of
3882 * the RFC explicitly allows spaces before it, and not within the
3883 * tokens (attrs or values). An inspection of RFC2109 allows that
3884 * too but section 10.1.3 lets one think that spaces may be allowed
3885 * after the equal sign too, resulting in some (rare) buggy
3886 * implementations trying to do that. So let's do what servers do.
3887 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3888 * allowed quoted strings in values, with any possible character
3889 * after a backslash, including control chars and delimitors, which
3890 * causes parsing to become ambiguous. Browsers also allow spaces
3891 * within values even without quotes.
3892 *
3893 * We have to keep multiple pointers in order to support cookie
3894 * removal at the beginning, middle or end of header without
3895 * corrupting the header. All of these headers are valid :
3896 *
3897 * hdr_beg hdr_end
3898 * | |
3899 * v |
3900 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3901 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3902 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3903 * | | | | | | |
3904 * | | | | | | |
3905 * | | | | | | +--> next
3906 * | | | | | +----> val_end
3907 * | | | | +-----------> val_beg
3908 * | | | +--------------> equal
3909 * | | +----------------> att_end
3910 * | +---------------------> att_beg
3911 * +--------------------------> prev
3912 *
3913 */
3914 hdr_beg = ctx.value.ptr;
3915 hdr_end = hdr_beg + ctx.value.len;
3916 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3917 /* Iterate through all cookies on this line */
3918
3919 /* find att_beg */
3920 att_beg = prev;
3921 if (prev > hdr_beg)
3922 att_beg++;
3923
3924 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3925 att_beg++;
3926
3927 /* find att_end : this is the first character after the last non
3928 * space before the equal. It may be equal to hdr_end.
3929 */
3930 equal = att_end = att_beg;
3931 while (equal < hdr_end) {
3932 if (*equal == '=' || *equal == ',' || *equal == ';')
3933 break;
3934 if (HTTP_IS_SPHT(*equal++))
3935 continue;
3936 att_end = equal;
3937 }
3938
3939 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3940 * is between <att_beg> and <equal>, both may be identical.
3941 */
3942 /* look for end of cookie if there is an equal sign */
3943 if (equal < hdr_end && *equal == '=') {
3944 /* look for the beginning of the value */
3945 val_beg = equal + 1;
3946 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3947 val_beg++;
3948
3949 /* find the end of the value, respecting quotes */
3950 next = http_find_cookie_value_end(val_beg, hdr_end);
3951
3952 /* make val_end point to the first white space or delimitor after the value */
3953 val_end = next;
3954 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3955 val_end--;
3956 }
3957 else
3958 val_beg = val_end = next = equal;
3959
3960 /* We have nothing to do with attributes beginning with
3961 * '$'. However, they will automatically be removed if a
3962 * header before them is removed, since they're supposed
3963 * to be linked together.
3964 */
3965 if (*att_beg == '$')
3966 continue;
3967
3968 /* Ignore cookies with no equal sign */
3969 if (equal == next) {
3970 /* This is not our cookie, so we must preserve it. But if we already
3971 * scheduled another cookie for removal, we cannot remove the
3972 * complete header, but we can remove the previous block itself.
3973 */
3974 preserve_hdr = 1;
3975 if (del_from != NULL) {
3976 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3977 val_end += delta;
3978 next += delta;
3979 hdr_end += delta;
3980 prev = del_from;
3981 del_from = NULL;
3982 }
3983 continue;
3984 }
3985
3986 /* if there are spaces around the equal sign, we need to
3987 * strip them otherwise we'll get trouble for cookie captures,
3988 * or even for rewrites. Since this happens extremely rarely,
3989 * it does not hurt performance.
3990 */
3991 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3992 int stripped_before = 0;
3993 int stripped_after = 0;
3994
3995 if (att_end != equal) {
3996 memmove(att_end, equal, hdr_end - equal);
3997 stripped_before = (att_end - equal);
3998 equal += stripped_before;
3999 val_beg += stripped_before;
4000 }
4001
4002 if (val_beg > equal + 1) {
4003 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4004 stripped_after = (equal + 1) - val_beg;
4005 val_beg += stripped_after;
4006 stripped_before += stripped_after;
4007 }
4008
4009 val_end += stripped_before;
4010 next += stripped_before;
4011 hdr_end += stripped_before;
4012 }
4013 /* now everything is as on the diagram above */
4014
4015 /* First, let's see if we want to capture this cookie. We check
4016 * that we don't already have a client side cookie, because we
4017 * can only capture one. Also as an optimisation, we ignore
4018 * cookies shorter than the declared name.
4019 */
4020 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4021 (val_end - att_beg >= sess->fe->capture_namelen) &&
4022 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4023 int log_len = val_end - att_beg;
4024
4025 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4026 ha_alert("HTTP logging : out of memory.\n");
4027 } else {
4028 if (log_len > sess->fe->capture_len)
4029 log_len = sess->fe->capture_len;
4030 memcpy(txn->cli_cookie, att_beg, log_len);
4031 txn->cli_cookie[log_len] = 0;
4032 }
4033 }
4034
4035 /* Persistence cookies in passive, rewrite or insert mode have the
4036 * following form :
4037 *
4038 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4039 *
4040 * For cookies in prefix mode, the form is :
4041 *
4042 * Cookie: NAME=SRV~VALUE
4043 */
4044 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4045 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4046 struct server *srv = s->be->srv;
4047 char *delim;
4048
4049 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4050 * have the server ID between val_beg and delim, and the original cookie between
4051 * delim+1 and val_end. Otherwise, delim==val_end :
4052 *
4053 * hdr_beg
4054 * |
4055 * v
4056 * NAME=SRV; # in all but prefix modes
4057 * NAME=SRV~OPAQUE ; # in prefix mode
4058 * || || | |+-> next
4059 * || || | +--> val_end
4060 * || || +---------> delim
4061 * || |+------------> val_beg
4062 * || +-------------> att_end = equal
4063 * |+-----------------> att_beg
4064 * +------------------> prev
4065 *
4066 */
4067 if (s->be->ck_opts & PR_CK_PFX) {
4068 for (delim = val_beg; delim < val_end; delim++)
4069 if (*delim == COOKIE_DELIM)
4070 break;
4071 }
4072 else {
4073 char *vbar1;
4074 delim = val_end;
4075 /* Now check if the cookie contains a date field, which would
4076 * appear after a vertical bar ('|') just after the server name
4077 * and before the delimiter.
4078 */
4079 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4080 if (vbar1) {
4081 /* OK, so left of the bar is the server's cookie and
4082 * right is the last seen date. It is a base64 encoded
4083 * 30-bit value representing the UNIX date since the
4084 * epoch in 4-second quantities.
4085 */
4086 int val;
4087 delim = vbar1++;
4088 if (val_end - vbar1 >= 5) {
4089 val = b64tos30(vbar1);
4090 if (val > 0)
4091 txn->cookie_last_date = val << 2;
4092 }
4093 /* look for a second vertical bar */
4094 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4095 if (vbar1 && (val_end - vbar1 > 5)) {
4096 val = b64tos30(vbar1 + 1);
4097 if (val > 0)
4098 txn->cookie_first_date = val << 2;
4099 }
4100 }
4101 }
4102
4103 /* if the cookie has an expiration date and the proxy wants to check
4104 * it, then we do that now. We first check if the cookie is too old,
4105 * then only if it has expired. We detect strict overflow because the
4106 * time resolution here is not great (4 seconds). Cookies with dates
4107 * in the future are ignored if their offset is beyond one day. This
4108 * allows an admin to fix timezone issues without expiring everyone
4109 * and at the same time avoids keeping unwanted side effects for too
4110 * long.
4111 */
4112 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4113 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4114 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4115 txn->flags &= ~TX_CK_MASK;
4116 txn->flags |= TX_CK_OLD;
4117 delim = val_beg; // let's pretend we have not found the cookie
4118 txn->cookie_first_date = 0;
4119 txn->cookie_last_date = 0;
4120 }
4121 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4122 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4123 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4124 txn->flags &= ~TX_CK_MASK;
4125 txn->flags |= TX_CK_EXPIRED;
4126 delim = val_beg; // let's pretend we have not found the cookie
4127 txn->cookie_first_date = 0;
4128 txn->cookie_last_date = 0;
4129 }
4130
4131 /* Here, we'll look for the first running server which supports the cookie.
4132 * This allows to share a same cookie between several servers, for example
4133 * to dedicate backup servers to specific servers only.
4134 * However, to prevent clients from sticking to cookie-less backup server
4135 * when they have incidentely learned an empty cookie, we simply ignore
4136 * empty cookies and mark them as invalid.
4137 * The same behaviour is applied when persistence must be ignored.
4138 */
4139 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4140 srv = NULL;
4141
4142 while (srv) {
4143 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4144 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4145 if ((srv->cur_state != SRV_ST_STOPPED) ||
4146 (s->be->options & PR_O_PERSIST) ||
4147 (s->flags & SF_FORCE_PRST)) {
4148 /* we found the server and we can use it */
4149 txn->flags &= ~TX_CK_MASK;
4150 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4151 s->flags |= SF_DIRECT | SF_ASSIGNED;
4152 s->target = &srv->obj_type;
4153 break;
4154 } else {
4155 /* we found a server, but it's down,
4156 * mark it as such and go on in case
4157 * another one is available.
4158 */
4159 txn->flags &= ~TX_CK_MASK;
4160 txn->flags |= TX_CK_DOWN;
4161 }
4162 }
4163 srv = srv->next;
4164 }
4165
4166 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4167 /* no server matched this cookie or we deliberately skipped it */
4168 txn->flags &= ~TX_CK_MASK;
4169 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4170 txn->flags |= TX_CK_UNUSED;
4171 else
4172 txn->flags |= TX_CK_INVALID;
4173 }
4174
4175 /* depending on the cookie mode, we may have to either :
4176 * - delete the complete cookie if we're in insert+indirect mode, so that
4177 * the server never sees it ;
4178 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004179 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004180 * if we're in cookie prefix mode
4181 */
4182 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4183 int delta; /* negative */
4184
4185 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4186 delta = val_beg - (delim + 1);
4187 val_end += delta;
4188 next += delta;
4189 hdr_end += delta;
4190 del_from = NULL;
4191 preserve_hdr = 1; /* we want to keep this cookie */
4192 }
4193 else if (del_from == NULL &&
4194 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4195 del_from = prev;
4196 }
4197 }
4198 else {
4199 /* This is not our cookie, so we must preserve it. But if we already
4200 * scheduled another cookie for removal, we cannot remove the
4201 * complete header, but we can remove the previous block itself.
4202 */
4203 preserve_hdr = 1;
4204
4205 if (del_from != NULL) {
4206 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4207 if (att_beg >= del_from)
4208 att_beg += delta;
4209 if (att_end >= del_from)
4210 att_end += delta;
4211 val_beg += delta;
4212 val_end += delta;
4213 next += delta;
4214 hdr_end += delta;
4215 prev = del_from;
4216 del_from = NULL;
4217 }
4218 }
4219
4220 /* continue with next cookie on this header line */
4221 att_beg = next;
4222 } /* for each cookie */
4223
4224
4225 /* There are no more cookies on this line.
4226 * We may still have one (or several) marked for deletion at the
4227 * end of the line. We must do this now in two ways :
4228 * - if some cookies must be preserved, we only delete from the
4229 * mark to the end of line ;
4230 * - if nothing needs to be preserved, simply delete the whole header
4231 */
4232 if (del_from) {
4233 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4234 }
4235 if ((hdr_end - hdr_beg) != ctx.value.len) {
4236 if (hdr_beg != hdr_end) {
4237 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004238 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004239 }
4240 else
4241 http_remove_header(htx, &ctx);
4242 }
4243 } /* for each "Cookie header */
4244}
4245
4246/*
4247 * Manage server-side cookies. It can impact performance by about 2% so it is
4248 * desirable to call it only when needed. This function is also used when we
4249 * just need to know if there is a cookie (eg: for check-cache).
4250 */
4251static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4252{
4253 struct session *sess = s->sess;
4254 struct http_txn *txn = s->txn;
4255 struct htx *htx;
4256 struct http_hdr_ctx ctx;
4257 struct server *srv;
4258 char *hdr_beg, *hdr_end;
4259 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4260 int is_cookie2;
4261
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004262 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004263
4264 ctx.blk = NULL;
4265 while (1) {
4266 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4267 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4268 break;
4269 is_cookie2 = 1;
4270 }
4271
4272 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4273 * <prev> points to the colon.
4274 */
4275 txn->flags |= TX_SCK_PRESENT;
4276
4277 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4278 * check-cache is enabled) and we are not interested in checking
4279 * them. Warning, the cookie capture is declared in the frontend.
4280 */
4281 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4282 break;
4283
4284 /* OK so now we know we have to process this response cookie.
4285 * The format of the Set-Cookie header is slightly different
4286 * from the format of the Cookie header in that it does not
4287 * support the comma as a cookie delimiter (thus the header
4288 * cannot be folded) because the Expires attribute described in
4289 * the original Netscape's spec may contain an unquoted date
4290 * with a comma inside. We have to live with this because
4291 * many browsers don't support Max-Age and some browsers don't
4292 * support quoted strings. However the Set-Cookie2 header is
4293 * clean.
4294 *
4295 * We have to keep multiple pointers in order to support cookie
4296 * removal at the beginning, middle or end of header without
4297 * corrupting the header (in case of set-cookie2). A special
4298 * pointer, <scav> points to the beginning of the set-cookie-av
4299 * fields after the first semi-colon. The <next> pointer points
4300 * either to the end of line (set-cookie) or next unquoted comma
4301 * (set-cookie2). All of these headers are valid :
4302 *
4303 * hdr_beg hdr_end
4304 * | |
4305 * v |
4306 * NAME1 = VALUE 1 ; Secure; Path="/" |
4307 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4308 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4309 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4310 * | | | | | | | |
4311 * | | | | | | | +-> next
4312 * | | | | | | +------------> scav
4313 * | | | | | +--------------> val_end
4314 * | | | | +--------------------> val_beg
4315 * | | | +----------------------> equal
4316 * | | +------------------------> att_end
4317 * | +----------------------------> att_beg
4318 * +------------------------------> prev
4319 * -------------------------------> hdr_beg
4320 */
4321 hdr_beg = ctx.value.ptr;
4322 hdr_end = hdr_beg + ctx.value.len;
4323 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4324
4325 /* Iterate through all cookies on this line */
4326
4327 /* find att_beg */
4328 att_beg = prev;
4329 if (prev > hdr_beg)
4330 att_beg++;
4331
4332 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4333 att_beg++;
4334
4335 /* find att_end : this is the first character after the last non
4336 * space before the equal. It may be equal to hdr_end.
4337 */
4338 equal = att_end = att_beg;
4339
4340 while (equal < hdr_end) {
4341 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4342 break;
4343 if (HTTP_IS_SPHT(*equal++))
4344 continue;
4345 att_end = equal;
4346 }
4347
4348 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4349 * is between <att_beg> and <equal>, both may be identical.
4350 */
4351
4352 /* look for end of cookie if there is an equal sign */
4353 if (equal < hdr_end && *equal == '=') {
4354 /* look for the beginning of the value */
4355 val_beg = equal + 1;
4356 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4357 val_beg++;
4358
4359 /* find the end of the value, respecting quotes */
4360 next = http_find_cookie_value_end(val_beg, hdr_end);
4361
4362 /* make val_end point to the first white space or delimitor after the value */
4363 val_end = next;
4364 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4365 val_end--;
4366 }
4367 else {
4368 /* <equal> points to next comma, semi-colon or EOL */
4369 val_beg = val_end = next = equal;
4370 }
4371
4372 if (next < hdr_end) {
4373 /* Set-Cookie2 supports multiple cookies, and <next> points to
4374 * a colon or semi-colon before the end. So skip all attr-value
4375 * pairs and look for the next comma. For Set-Cookie, since
4376 * commas are permitted in values, skip to the end.
4377 */
4378 if (is_cookie2)
4379 next = http_find_hdr_value_end(next, hdr_end);
4380 else
4381 next = hdr_end;
4382 }
4383
4384 /* Now everything is as on the diagram above */
4385
4386 /* Ignore cookies with no equal sign */
4387 if (equal == val_end)
4388 continue;
4389
4390 /* If there are spaces around the equal sign, we need to
4391 * strip them otherwise we'll get trouble for cookie captures,
4392 * or even for rewrites. Since this happens extremely rarely,
4393 * it does not hurt performance.
4394 */
4395 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4396 int stripped_before = 0;
4397 int stripped_after = 0;
4398
4399 if (att_end != equal) {
4400 memmove(att_end, equal, hdr_end - equal);
4401 stripped_before = (att_end - equal);
4402 equal += stripped_before;
4403 val_beg += stripped_before;
4404 }
4405
4406 if (val_beg > equal + 1) {
4407 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4408 stripped_after = (equal + 1) - val_beg;
4409 val_beg += stripped_after;
4410 stripped_before += stripped_after;
4411 }
4412
4413 val_end += stripped_before;
4414 next += stripped_before;
4415 hdr_end += stripped_before;
4416
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004417 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4418 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004419 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004420 }
4421
4422 /* First, let's see if we want to capture this cookie. We check
4423 * that we don't already have a server side cookie, because we
4424 * can only capture one. Also as an optimisation, we ignore
4425 * cookies shorter than the declared name.
4426 */
4427 if (sess->fe->capture_name != NULL &&
4428 txn->srv_cookie == NULL &&
4429 (val_end - att_beg >= sess->fe->capture_namelen) &&
4430 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4431 int log_len = val_end - att_beg;
4432 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4433 ha_alert("HTTP logging : out of memory.\n");
4434 }
4435 else {
4436 if (log_len > sess->fe->capture_len)
4437 log_len = sess->fe->capture_len;
4438 memcpy(txn->srv_cookie, att_beg, log_len);
4439 txn->srv_cookie[log_len] = 0;
4440 }
4441 }
4442
4443 srv = objt_server(s->target);
4444 /* now check if we need to process it for persistence */
4445 if (!(s->flags & SF_IGNORE_PRST) &&
4446 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4447 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4448 /* assume passive cookie by default */
4449 txn->flags &= ~TX_SCK_MASK;
4450 txn->flags |= TX_SCK_FOUND;
4451
4452 /* If the cookie is in insert mode on a known server, we'll delete
4453 * this occurrence because we'll insert another one later.
4454 * We'll delete it too if the "indirect" option is set and we're in
4455 * a direct access.
4456 */
4457 if (s->be->ck_opts & PR_CK_PSV) {
4458 /* The "preserve" flag was set, we don't want to touch the
4459 * server's cookie.
4460 */
4461 }
4462 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4463 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4464 /* this cookie must be deleted */
4465 if (prev == hdr_beg && next == hdr_end) {
4466 /* whole header */
4467 http_remove_header(htx, &ctx);
4468 /* note: while both invalid now, <next> and <hdr_end>
4469 * are still equal, so the for() will stop as expected.
4470 */
4471 } else {
4472 /* just remove the value */
4473 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4474 next = prev;
4475 hdr_end += delta;
4476 }
4477 txn->flags &= ~TX_SCK_MASK;
4478 txn->flags |= TX_SCK_DELETED;
4479 /* and go on with next cookie */
4480 }
4481 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4482 /* replace bytes val_beg->val_end with the cookie name associated
4483 * with this server since we know it.
4484 */
4485 int sliding, delta;
4486
4487 ctx.value = ist2(val_beg, val_end - val_beg);
4488 ctx.lws_before = ctx.lws_after = 0;
4489 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4490 delta = srv->cklen - (val_end - val_beg);
4491 sliding = (ctx.value.ptr - val_beg);
4492 hdr_beg += sliding;
4493 val_beg += sliding;
4494 next += sliding + delta;
4495 hdr_end += sliding + delta;
4496
4497 txn->flags &= ~TX_SCK_MASK;
4498 txn->flags |= TX_SCK_REPLACED;
4499 }
4500 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4501 /* insert the cookie name associated with this server
4502 * before existing cookie, and insert a delimiter between them..
4503 */
4504 int sliding, delta;
4505 ctx.value = ist2(val_beg, 0);
4506 ctx.lws_before = ctx.lws_after = 0;
4507 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4508 delta = srv->cklen + 1;
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 val_beg[srv->cklen] = COOKIE_DELIM;
4516 txn->flags &= ~TX_SCK_MASK;
4517 txn->flags |= TX_SCK_REPLACED;
4518 }
4519 }
4520 /* that's done for this cookie, check the next one on the same
4521 * line when next != hdr_end (only if is_cookie2).
4522 */
4523 }
4524 }
4525}
4526
Christopher Faulet25a02f62018-10-24 12:00:25 +02004527/*
4528 * Parses the Cache-Control and Pragma request header fields to determine if
4529 * the request may be served from the cache and/or if it is cacheable. Updates
4530 * s->txn->flags.
4531 */
4532void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4533{
4534 struct http_txn *txn = s->txn;
4535 struct htx *htx;
4536 int32_t pos;
4537 int pragma_found, cc_found, i;
4538
4539 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4540 return; /* nothing more to do here */
4541
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004542 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004543 pragma_found = cc_found = 0;
4544 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4545 struct htx_blk *blk = htx_get_blk(htx, pos);
4546 enum htx_blk_type type = htx_get_blk_type(blk);
4547 struct ist n, v;
4548
4549 if (type == HTX_BLK_EOH)
4550 break;
4551 if (type != HTX_BLK_HDR)
4552 continue;
4553
4554 n = htx_get_blk_name(htx, blk);
4555 v = htx_get_blk_value(htx, blk);
4556
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004557 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004558 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4559 pragma_found = 1;
4560 continue;
4561 }
4562 }
4563
4564 /* Don't use the cache and don't try to store if we found the
4565 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004566 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004567 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4568 txn->flags |= TX_CACHE_IGNORE;
4569 continue;
4570 }
4571
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004572 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004573 continue;
4574
4575 /* OK, right now we know we have a cache-control header */
4576 cc_found = 1;
4577 if (!v.len) /* no info */
4578 continue;
4579
4580 i = 0;
4581 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4582 !isspace((unsigned char)*(v.ptr+i)))
4583 i++;
4584
4585 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4586 * values after max-age, max-stale nor min-fresh, we simply don't
4587 * use the cache when they're specified.
4588 */
4589 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4590 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4591 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4592 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4593 txn->flags |= TX_CACHE_IGNORE;
4594 continue;
4595 }
4596
4597 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4598 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4599 continue;
4600 }
4601 }
4602
4603 /* RFC7234#5.4:
4604 * When the Cache-Control header field is also present and
4605 * understood in a request, Pragma is ignored.
4606 * When the Cache-Control header field is not present in a
4607 * request, caches MUST consider the no-cache request
4608 * pragma-directive as having the same effect as if
4609 * "Cache-Control: no-cache" were present.
4610 */
4611 if (!cc_found && pragma_found)
4612 txn->flags |= TX_CACHE_IGNORE;
4613}
4614
4615/*
4616 * Check if response is cacheable or not. Updates s->txn->flags.
4617 */
4618void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4619{
4620 struct http_txn *txn = s->txn;
4621 struct htx *htx;
4622 int32_t pos;
4623 int i;
4624
4625 if (txn->status < 200) {
4626 /* do not try to cache interim responses! */
4627 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4628 return;
4629 }
4630
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004631 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004632 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4633 struct htx_blk *blk = htx_get_blk(htx, pos);
4634 enum htx_blk_type type = htx_get_blk_type(blk);
4635 struct ist n, v;
4636
4637 if (type == HTX_BLK_EOH)
4638 break;
4639 if (type != HTX_BLK_HDR)
4640 continue;
4641
4642 n = htx_get_blk_name(htx, blk);
4643 v = htx_get_blk_value(htx, blk);
4644
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004645 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004646 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4647 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4648 return;
4649 }
4650 }
4651
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004652 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004653 continue;
4654
4655 /* OK, right now we know we have a cache-control header */
4656 if (!v.len) /* no info */
4657 continue;
4658
4659 i = 0;
4660 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4661 !isspace((unsigned char)*(v.ptr+i)))
4662 i++;
4663
4664 /* we have a complete value between v.ptr and (v.ptr+i) */
4665 if (i < v.len && *(v.ptr + i) == '=') {
4666 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4667 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4668 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4669 continue;
4670 }
4671
4672 /* we have something of the form no-cache="set-cookie" */
4673 if ((v.len >= 21) &&
4674 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4675 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4676 txn->flags &= ~TX_CACHE_COOK;
4677 continue;
4678 }
4679
4680 /* OK, so we know that either p2 points to the end of string or to a comma */
4681 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4682 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4683 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4684 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4685 return;
4686 }
4687
4688 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4689 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4690 continue;
4691 }
4692 }
4693}
4694
Christopher Faulet64159df2018-10-24 21:15:35 +02004695/* send a server's name with an outgoing request over an established connection.
4696 * Note: this function is designed to be called once the request has been
4697 * scheduled for being forwarded. This is the reason why the number of forwarded
4698 * bytes have to be adjusted.
4699 */
4700int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4701{
4702 struct htx *htx;
4703 struct http_hdr_ctx ctx;
4704 struct ist hdr;
4705 uint32_t data;
4706
4707 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004708 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004709 data = htx->data;
4710
4711 ctx.blk = NULL;
4712 while (http_find_header(htx, hdr, &ctx, 1))
4713 http_remove_header(htx, &ctx);
4714 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4715
4716 if (co_data(&s->req)) {
4717 if (data >= htx->data)
4718 c_rew(&s->req, data - htx->data);
4719 else
4720 c_adv(&s->req, htx->data - data);
4721 }
4722 return 0;
4723}
4724
Christopher Faulet377c5a52018-10-24 21:21:30 +02004725/*
4726 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4727 * for the current backend.
4728 *
4729 * It is assumed that the request is either a HEAD, GET, or POST and that the
4730 * uri_auth field is valid.
4731 *
4732 * Returns 1 if stats should be provided, otherwise 0.
4733 */
4734static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4735{
4736 struct uri_auth *uri_auth = backend->uri_auth;
4737 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004738 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004739 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004740
4741 if (!uri_auth)
4742 return 0;
4743
4744 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4745 return 0;
4746
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004747 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004748 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004749 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004750
4751 /* check URI size */
4752 if (uri_auth->uri_len > uri.len)
4753 return 0;
4754
4755 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4756 return 0;
4757
4758 return 1;
4759}
4760
4761/* This function prepares an applet to handle the stats. It can deal with the
4762 * "100-continue" expectation, check that admin rules are met for POST requests,
4763 * and program a response message if something was unexpected. It cannot fail
4764 * and always relies on the stats applet to complete the job. It does not touch
4765 * analysers nor counters, which are left to the caller. It does not touch
4766 * s->target which is supposed to already point to the stats applet. The caller
4767 * is expected to have already assigned an appctx to the stream.
4768 */
4769static int htx_handle_stats(struct stream *s, struct channel *req)
4770{
4771 struct stats_admin_rule *stats_admin_rule;
4772 struct stream_interface *si = &s->si[1];
4773 struct session *sess = s->sess;
4774 struct http_txn *txn = s->txn;
4775 struct http_msg *msg = &txn->req;
4776 struct uri_auth *uri_auth = s->be->uri_auth;
4777 const char *h, *lookup, *end;
4778 struct appctx *appctx;
4779 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004780 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004781
4782 appctx = si_appctx(si);
4783 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4784 appctx->st1 = appctx->st2 = 0;
4785 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4786 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4787 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4788 appctx->ctx.stats.flags |= STAT_CHUNKED;
4789
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004790 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004791 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004792 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4793 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004794
4795 for (h = lookup; h <= end - 3; h++) {
4796 if (memcmp(h, ";up", 3) == 0) {
4797 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4798 break;
4799 }
4800 }
4801
4802 if (uri_auth->refresh) {
4803 for (h = lookup; h <= end - 10; h++) {
4804 if (memcmp(h, ";norefresh", 10) == 0) {
4805 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4806 break;
4807 }
4808 }
4809 }
4810
4811 for (h = lookup; h <= end - 4; h++) {
4812 if (memcmp(h, ";csv", 4) == 0) {
4813 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4814 break;
4815 }
4816 }
4817
4818 for (h = lookup; h <= end - 6; h++) {
4819 if (memcmp(h, ";typed", 6) == 0) {
4820 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4821 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4822 break;
4823 }
4824 }
4825
4826 for (h = lookup; h <= end - 8; h++) {
4827 if (memcmp(h, ";st=", 4) == 0) {
4828 int i;
4829 h += 4;
4830 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4831 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4832 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4833 appctx->ctx.stats.st_code = i;
4834 break;
4835 }
4836 }
4837 break;
4838 }
4839 }
4840
4841 appctx->ctx.stats.scope_str = 0;
4842 appctx->ctx.stats.scope_len = 0;
4843 for (h = lookup; h <= end - 8; h++) {
4844 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4845 int itx = 0;
4846 const char *h2;
4847 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4848 const char *err;
4849
4850 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4851 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004852 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4853 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004854 if (*h == ';' || *h == '&' || *h == ' ')
4855 break;
4856 itx++;
4857 h++;
4858 }
4859
4860 if (itx > STAT_SCOPE_TXT_MAXLEN)
4861 itx = STAT_SCOPE_TXT_MAXLEN;
4862 appctx->ctx.stats.scope_len = itx;
4863
4864 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4865 memcpy(scope_txt, h2, itx);
4866 scope_txt[itx] = '\0';
4867 err = invalid_char(scope_txt);
4868 if (err) {
4869 /* bad char in search text => clear scope */
4870 appctx->ctx.stats.scope_str = 0;
4871 appctx->ctx.stats.scope_len = 0;
4872 }
4873 break;
4874 }
4875 }
4876
4877 /* now check whether we have some admin rules for this request */
4878 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4879 int ret = 1;
4880
4881 if (stats_admin_rule->cond) {
4882 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4883 ret = acl_pass(ret);
4884 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4885 ret = !ret;
4886 }
4887
4888 if (ret) {
4889 /* no rule, or the rule matches */
4890 appctx->ctx.stats.flags |= STAT_ADMIN;
4891 break;
4892 }
4893 }
4894
Christopher Faulet5d45e382019-02-27 15:15:23 +01004895 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4896 appctx->st0 = STAT_HTTP_HEAD;
4897 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004898 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004899 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004900 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004901 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004902 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4903 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4904 appctx->st0 = STAT_HTTP_LAST;
4905 }
4906 }
4907 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004908 /* Unsupported method */
4909 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4910 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4911 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004912 }
4913
4914 s->task->nice = -32; /* small boost for HTTP statistics */
4915 return 1;
4916}
4917
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004918void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4919{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004920 struct channel *req = &s->req;
4921 struct channel *res = &s->res;
4922 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004923 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004924 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004925 struct ist path, location;
4926 unsigned int flags;
4927 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004928
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004929 /*
4930 * Create the location
4931 */
4932 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004933
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004934 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004935 /* special prefix "/" means don't change URL */
4936 srv = __objt_server(s->target);
4937 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4938 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4939 return;
4940 }
4941
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004942 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004943 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004944 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004945 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004946 if (!path.ptr)
4947 return;
4948
4949 if (!chunk_memcat(&trash, path.ptr, path.len))
4950 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004951 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004952
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004953 /*
4954 * Create the 302 respone
4955 */
4956 htx = htx_from_buf(&res->buf);
4957 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4958 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4959 ist("HTTP/1.1"), ist("302"), ist("Found"));
4960 if (!sl)
4961 goto fail;
4962 sl->info.res.status = 302;
4963 s->txn->status = 302;
4964
4965 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4966 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4967 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4968 !htx_add_header(htx, ist("Location"), location))
4969 goto fail;
4970
4971 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4972 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004973
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004974 /*
4975 * Send the message
4976 */
4977 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004978 c_adv(res, data);
4979 res->total += data;
4980
4981 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004982 si_shutr(si);
4983 si_shutw(si);
4984 si->err_type = SI_ET_NONE;
4985 si->state = SI_ST_CLO;
4986
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004987 channel_auto_read(req);
4988 channel_abort(req);
4989 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004990 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004991 channel_auto_read(res);
4992 channel_auto_close(res);
4993
4994 if (!(s->flags & SF_ERR_MASK))
4995 s->flags |= SF_ERR_LOCAL;
4996 if (!(s->flags & SF_FINST_MASK))
4997 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004998
4999 /* FIXME: we should increase a counter of redirects per server and per backend. */
5000 srv_inc_sess_ctr(srv);
5001 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005002 return;
5003
5004 fail:
5005 /* If an error occurred, remove the incomplete HTTP response from the
5006 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005007 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005008}
5009
Christopher Fauletf2824e62018-10-01 12:12:37 +02005010/* This function terminates the request because it was completly analyzed or
5011 * because an error was triggered during the body forwarding.
5012 */
5013static void htx_end_request(struct stream *s)
5014{
5015 struct channel *chn = &s->req;
5016 struct http_txn *txn = s->txn;
5017
5018 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5019 now_ms, __FUNCTION__, s,
5020 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5021 s->req.analysers, s->res.analysers);
5022
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005023 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5024 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005025 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005026 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005027 goto end;
5028 }
5029
5030 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5031 return;
5032
5033 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005034 /* No need to read anymore, the request was completely parsed.
5035 * We can shut the read side unless we want to abort_on_close,
5036 * or we have a POST request. The issue with POST requests is
5037 * that some browsers still send a CRLF after the request, and
5038 * this CRLF must be read so that it does not remain in the kernel
5039 * buffers, otherwise a close could cause an RST on some systems
5040 * (eg: Linux).
5041 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005042 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005043 channel_dont_read(chn);
5044
5045 /* if the server closes the connection, we want to immediately react
5046 * and close the socket to save packets and syscalls.
5047 */
5048 s->si[1].flags |= SI_FL_NOHALF;
5049
5050 /* In any case we've finished parsing the request so we must
5051 * disable Nagle when sending data because 1) we're not going
5052 * to shut this side, and 2) the server is waiting for us to
5053 * send pending data.
5054 */
5055 chn->flags |= CF_NEVER_WAIT;
5056
Christopher Fauletd01ce402019-01-02 17:44:13 +01005057 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5058 /* The server has not finished to respond, so we
5059 * don't want to move in order not to upset it.
5060 */
5061 return;
5062 }
5063
Christopher Fauletf2824e62018-10-01 12:12:37 +02005064 /* When we get here, it means that both the request and the
5065 * response have finished receiving. Depending on the connection
5066 * mode, we'll have to wait for the last bytes to leave in either
5067 * direction, and sometimes for a close to be effective.
5068 */
5069 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5070 /* Tunnel mode will not have any analyser so it needs to
5071 * poll for reads.
5072 */
5073 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005074 if (b_data(&chn->buf))
5075 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005076 txn->req.msg_state = HTTP_MSG_TUNNEL;
5077 }
5078 else {
5079 /* we're not expecting any new data to come for this
5080 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005081 *
5082 * However, there is an exception if the response
5083 * length is undefined. In this case, we need to wait
5084 * the close from the server. The response will be
5085 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005086 */
5087 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5088 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005089 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005090
5091 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5092 channel_shutr_now(chn);
5093 channel_shutw_now(chn);
5094 }
5095 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005096 goto check_channel_flags;
5097 }
5098
5099 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5100 http_msg_closing:
5101 /* nothing else to forward, just waiting for the output buffer
5102 * to be empty and for the shutw_now to take effect.
5103 */
5104 if (channel_is_empty(chn)) {
5105 txn->req.msg_state = HTTP_MSG_CLOSED;
5106 goto http_msg_closed;
5107 }
5108 else if (chn->flags & CF_SHUTW) {
5109 txn->req.err_state = txn->req.msg_state;
5110 txn->req.msg_state = HTTP_MSG_ERROR;
5111 goto end;
5112 }
5113 return;
5114 }
5115
5116 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5117 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005118 /* if we don't know whether the server will close, we need to hard close */
5119 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5120 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005122 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005123 channel_dont_read(chn);
5124 goto end;
5125 }
5126
5127 check_channel_flags:
5128 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5129 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5130 /* if we've just closed an output, let's switch */
5131 txn->req.msg_state = HTTP_MSG_CLOSING;
5132 goto http_msg_closing;
5133 }
5134
5135 end:
5136 chn->analysers &= AN_REQ_FLT_END;
5137 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5138 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5139 channel_auto_close(chn);
5140 channel_auto_read(chn);
5141}
5142
5143
5144/* This function terminates the response because it was completly analyzed or
5145 * because an error was triggered during the body forwarding.
5146 */
5147static void htx_end_response(struct stream *s)
5148{
5149 struct channel *chn = &s->res;
5150 struct http_txn *txn = s->txn;
5151
5152 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5153 now_ms, __FUNCTION__, s,
5154 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5155 s->req.analysers, s->res.analysers);
5156
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005157 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5158 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005159 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005160 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005161 goto end;
5162 }
5163
5164 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5165 return;
5166
5167 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5168 /* In theory, we don't need to read anymore, but we must
5169 * still monitor the server connection for a possible close
5170 * while the request is being uploaded, so we don't disable
5171 * reading.
5172 */
5173 /* channel_dont_read(chn); */
5174
5175 if (txn->req.msg_state < HTTP_MSG_DONE) {
5176 /* The client seems to still be sending data, probably
5177 * because we got an error response during an upload.
5178 * We have the choice of either breaking the connection
5179 * or letting it pass through. Let's do the later.
5180 */
5181 return;
5182 }
5183
5184 /* When we get here, it means that both the request and the
5185 * response have finished receiving. Depending on the connection
5186 * mode, we'll have to wait for the last bytes to leave in either
5187 * direction, and sometimes for a close to be effective.
5188 */
5189 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5190 channel_auto_read(chn);
5191 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005192 if (b_data(&chn->buf))
5193 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005194 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5195 }
5196 else {
5197 /* we're not expecting any new data to come for this
5198 * transaction, so we can close it.
5199 */
5200 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5201 channel_shutr_now(chn);
5202 channel_shutw_now(chn);
5203 }
5204 }
5205 goto check_channel_flags;
5206 }
5207
5208 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5209 http_msg_closing:
5210 /* nothing else to forward, just waiting for the output buffer
5211 * to be empty and for the shutw_now to take effect.
5212 */
5213 if (channel_is_empty(chn)) {
5214 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5215 goto http_msg_closed;
5216 }
5217 else if (chn->flags & CF_SHUTW) {
5218 txn->rsp.err_state = txn->rsp.msg_state;
5219 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005220 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005221 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005222 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005223 goto end;
5224 }
5225 return;
5226 }
5227
5228 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5229 http_msg_closed:
5230 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005231 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005232 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 goto end;
5234 }
5235
5236 check_channel_flags:
5237 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5238 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5239 /* if we've just closed an output, let's switch */
5240 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5241 goto http_msg_closing;
5242 }
5243
5244 end:
5245 chn->analysers &= AN_RES_FLT_END;
5246 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5247 chn->analysers |= AN_RES_FLT_XFER_DATA;
5248 channel_auto_close(chn);
5249 channel_auto_read(chn);
5250}
5251
Christopher Faulet0f226952018-10-22 09:29:56 +02005252void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5253 int finst, const struct buffer *msg)
5254{
5255 channel_auto_read(si_oc(si));
5256 channel_abort(si_oc(si));
5257 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005258 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005259 channel_auto_close(si_ic(si));
5260 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005261
5262 /* <msg> is an HTX structure. So we copy it in the response's
5263 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005264 if (msg) {
5265 struct channel *chn = si_ic(si);
5266 struct htx *htx;
5267
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005268 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005269 chn->buf.data = msg->data;
5270 memcpy(chn->buf.area, msg->area, msg->data);
5271 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005272 c_adv(chn, htx->data);
5273 chn->total += htx->data;
5274 }
5275 if (!(s->flags & SF_ERR_MASK))
5276 s->flags |= err;
5277 if (!(s->flags & SF_FINST_MASK))
5278 s->flags |= finst;
5279}
5280
5281void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5282{
5283 channel_auto_read(&s->req);
5284 channel_abort(&s->req);
5285 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005286 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5287 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005288
5289 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005290
5291 /* <msg> is an HTX structure. So we copy it in the response's
5292 * channel */
5293 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005294 if (msg) {
5295 struct channel *chn = &s->res;
5296 struct htx *htx;
5297
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005298 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005299 chn->buf.data = msg->data;
5300 memcpy(chn->buf.area, msg->area, msg->data);
5301 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005302 c_adv(chn, htx->data);
5303 chn->total += htx->data;
5304 }
5305
5306 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5307 channel_auto_read(&s->res);
5308 channel_auto_close(&s->res);
5309 channel_shutr_now(&s->res);
5310}
5311
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005312struct buffer *htx_error_message(struct stream *s)
5313{
5314 const int msgnum = http_get_status_idx(s->txn->status);
5315
5316 if (s->be->errmsg[msgnum].area)
5317 return &s->be->errmsg[msgnum];
5318 else if (strm_fe(s)->errmsg[msgnum].area)
5319 return &strm_fe(s)->errmsg[msgnum];
5320 else
5321 return &htx_err_chunks[msgnum];
5322}
5323
5324
Christopher Faulet4a28a532019-03-01 11:19:40 +01005325/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5326 * on success and -1 on error.
5327 */
5328static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5329{
5330 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5331 * then we must send an HTTP/1.1 100 Continue intermediate response.
5332 */
5333 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5334 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5335 struct ist hdr = { .ptr = "Expect", .len = 6 };
5336 struct http_hdr_ctx ctx;
5337
5338 ctx.blk = NULL;
5339 /* Expect is allowed in 1.1, look for it */
5340 if (http_find_header(htx, hdr, &ctx, 0) &&
5341 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5342 if (htx_reply_100_continue(s) == -1)
5343 return -1;
5344 http_remove_header(htx, &ctx);
5345 }
5346 }
5347 return 0;
5348}
5349
Christopher Faulet23a3c792018-11-28 10:01:23 +01005350/* Send a 100-Continue response to the client. It returns 0 on success and -1
5351 * on error. The response channel is updated accordingly.
5352 */
5353static int htx_reply_100_continue(struct stream *s)
5354{
5355 struct channel *res = &s->res;
5356 struct htx *htx = htx_from_buf(&res->buf);
5357 struct htx_sl *sl;
5358 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5359 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5360 size_t data;
5361
5362 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5363 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5364 if (!sl)
5365 goto fail;
5366 sl->info.res.status = 100;
5367
5368 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5369 goto fail;
5370
5371 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005372 c_adv(res, data);
5373 res->total += data;
5374 return 0;
5375
5376 fail:
5377 /* If an error occurred, remove the incomplete HTTP response from the
5378 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005379 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005380 return -1;
5381}
5382
Christopher Faulet12c51e22018-11-28 15:59:42 +01005383
5384/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5385 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5386 * error. The response channel is updated accordingly.
5387 */
5388static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5389{
5390 struct channel *res = &s->res;
5391 struct htx *htx = htx_from_buf(&res->buf);
5392 struct htx_sl *sl;
5393 struct ist code, body;
5394 int status;
5395 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5396 size_t data;
5397
5398 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5399 status = 401;
5400 code = ist("401");
5401 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5402 "You need a valid user and password to access this content.\n"
5403 "</body></html>\n");
5404 }
5405 else {
5406 status = 407;
5407 code = ist("407");
5408 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5409 "You need a valid user and password to access this content.\n"
5410 "</body></html>\n");
5411 }
5412
5413 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5414 ist("HTTP/1.1"), code, ist("Unauthorized"));
5415 if (!sl)
5416 goto fail;
5417 sl->info.res.status = status;
5418 s->txn->status = status;
5419
5420 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5421 goto fail;
5422
5423 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5424 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005425 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5426 goto fail;
5427 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5428 goto fail;
5429 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005430 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005431 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5432 goto fail;
5433
5434 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005435 c_adv(res, data);
5436 res->total += data;
5437
5438 channel_auto_read(&s->req);
5439 channel_abort(&s->req);
5440 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005441 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005442
5443 res->wex = tick_add_ifset(now_ms, res->wto);
5444 channel_auto_read(res);
5445 channel_auto_close(res);
5446 channel_shutr_now(res);
5447 return 0;
5448
5449 fail:
5450 /* If an error occurred, remove the incomplete HTTP response from the
5451 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005452 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005453 return -1;
5454}
5455
Christopher Faulet0f226952018-10-22 09:29:56 +02005456/*
5457 * Capture headers from message <htx> according to header list <cap_hdr>, and
5458 * fill the <cap> pointers appropriately.
5459 */
5460static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5461{
5462 struct cap_hdr *h;
5463 int32_t pos;
5464
5465 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5466 struct htx_blk *blk = htx_get_blk(htx, pos);
5467 enum htx_blk_type type = htx_get_blk_type(blk);
5468 struct ist n, v;
5469
5470 if (type == HTX_BLK_EOH)
5471 break;
5472 if (type != HTX_BLK_HDR)
5473 continue;
5474
5475 n = htx_get_blk_name(htx, blk);
5476
5477 for (h = cap_hdr; h; h = h->next) {
5478 if (h->namelen && (h->namelen == n.len) &&
5479 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5480 if (cap[h->index] == NULL)
5481 cap[h->index] =
5482 pool_alloc(h->pool);
5483
5484 if (cap[h->index] == NULL) {
5485 ha_alert("HTTP capture : out of memory.\n");
5486 break;
5487 }
5488
5489 v = htx_get_blk_value(htx, blk);
5490 if (v.len > h->len)
5491 v.len = h->len;
5492
5493 memcpy(cap[h->index], v.ptr, v.len);
5494 cap[h->index][v.len]=0;
5495 }
5496 }
5497 }
5498}
5499
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005500/* Delete a value in a header between delimiters <from> and <next>. The header
5501 * itself is delimited by <start> and <end> pointers. The number of characters
5502 * displaced is returned, and the pointer to the first delimiter is updated if
5503 * required. The function tries as much as possible to respect the following
5504 * principles :
5505 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5506 * in which case <next> is simply removed
5507 * - set exactly one space character after the new first delimiter, unless there
5508 * are not enough characters in the block being moved to do so.
5509 * - remove unneeded spaces before the previous delimiter and after the new
5510 * one.
5511 *
5512 * It is the caller's responsibility to ensure that :
5513 * - <from> points to a valid delimiter or <start> ;
5514 * - <next> points to a valid delimiter or <end> ;
5515 * - there are non-space chars before <from>.
5516 */
5517static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5518{
5519 char *prev = *from;
5520
5521 if (prev == start) {
5522 /* We're removing the first value. eat the semicolon, if <next>
5523 * is lower than <end> */
5524 if (next < end)
5525 next++;
5526
5527 while (next < end && HTTP_IS_SPHT(*next))
5528 next++;
5529 }
5530 else {
5531 /* Remove useless spaces before the old delimiter. */
5532 while (HTTP_IS_SPHT(*(prev-1)))
5533 prev--;
5534 *from = prev;
5535
5536 /* copy the delimiter and if possible a space if we're
5537 * not at the end of the line.
5538 */
5539 if (next < end) {
5540 *prev++ = *next++;
5541 if (prev + 1 < next)
5542 *prev++ = ' ';
5543 while (next < end && HTTP_IS_SPHT(*next))
5544 next++;
5545 }
5546 }
5547 memmove(prev, next, end - next);
5548 return (prev - next);
5549}
5550
Christopher Faulet0f226952018-10-22 09:29:56 +02005551
5552/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005553 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005554 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005555static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005556{
5557 struct ist dst = ist2(str, 0);
5558
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005559 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005560 goto end;
5561 if (dst.len + 1 > len)
5562 goto end;
5563 dst.ptr[dst.len++] = ' ';
5564
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005565 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005566 goto end;
5567 if (dst.len + 1 > len)
5568 goto end;
5569 dst.ptr[dst.len++] = ' ';
5570
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005571 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005572 end:
5573 return dst.len;
5574}
5575
Christopher Fauletf0523542018-10-24 11:06:58 +02005576/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005577 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005578 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005579static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005580{
5581 struct ist dst = ist2(str, 0);
5582
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005583 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +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 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005590 goto end;
5591 if (dst.len + 1 > len)
5592 goto end;
5593 dst.ptr[dst.len++] = ' ';
5594
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005595 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005596 end:
5597 return dst.len;
5598}
5599
5600
Christopher Faulet0f226952018-10-22 09:29:56 +02005601/*
5602 * Print a debug line with a start line.
5603 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005604static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005605{
5606 struct session *sess = strm_sess(s);
5607 int max;
5608
5609 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5610 dir,
5611 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5612 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5613
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005614 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005615 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005616 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005617 trash.area[trash.data++] = ' ';
5618
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005619 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005620 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005621 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005622 trash.area[trash.data++] = ' ';
5623
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005624 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005625 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005626 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005627 trash.area[trash.data++] = '\n';
5628
5629 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5630}
5631
5632/*
5633 * Print a debug line with a header.
5634 */
5635static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5636{
5637 struct session *sess = strm_sess(s);
5638 int max;
5639
5640 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5641 dir,
5642 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5643 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5644
5645 max = n.len;
5646 UBOUND(max, trash.size - trash.data - 3);
5647 chunk_memcat(&trash, n.ptr, max);
5648 trash.area[trash.data++] = ':';
5649 trash.area[trash.data++] = ' ';
5650
5651 max = v.len;
5652 UBOUND(max, trash.size - trash.data - 1);
5653 chunk_memcat(&trash, v.ptr, max);
5654 trash.area[trash.data++] = '\n';
5655
5656 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5657}
5658
5659
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005660__attribute__((constructor))
5661static void __htx_protocol_init(void)
5662{
5663}
5664
5665
5666/*
5667 * Local variables:
5668 * c-indent-level: 8
5669 * c-basic-offset: 8
5670 * End:
5671 */