blob: bdfd4ba71e4fde15369e4511b5afc12a24b6cd17 [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
412 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
413 * only change if both the request and the config reference something else.
414 * Option httpclose by itself sets tunnel mode where headers are mangled.
415 * However, if another mode is set, it will affect it (eg: server-close/
416 * keep-alive + httpclose = close). Note that we avoid to redo the same work
417 * if FE and BE have the same settings (common). The method consists in
418 * checking if options changed between the two calls (implying that either
419 * one is non-null, or one of them is non-null and we are there for the first
420 * time.
421 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200422 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200423 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200424
425 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200426 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 req->analysers |= AN_REQ_HTTP_BODY;
428
429 /*
430 * RFC7234#4:
431 * A cache MUST write through requests with methods
432 * that are unsafe (Section 4.2.1 of [RFC7231]) to
433 * the origin server; i.e., a cache is not allowed
434 * to generate a reply to such a request before
435 * having forwarded the request and having received
436 * a corresponding response.
437 *
438 * RFC7231#4.2.1:
439 * Of the request methods defined by this
440 * specification, the GET, HEAD, OPTIONS, and TRACE
441 * methods are defined to be safe.
442 */
443 if (likely(txn->meth == HTTP_METH_GET ||
444 txn->meth == HTTP_METH_HEAD ||
445 txn->meth == HTTP_METH_OPTIONS ||
446 txn->meth == HTTP_METH_TRACE))
447 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
448
449 /* end of job, return OK */
450 req->analysers &= ~an_bit;
451 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200452
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 return 1;
454
455 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200456 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200457 txn->req.err_state = txn->req.msg_state;
458 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100459 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100460 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200461 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100462 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200463
464 return_prx_cond:
465 if (!(s->flags & SF_ERR_MASK))
466 s->flags |= SF_ERR_PRXCOND;
467 if (!(s->flags & SF_FINST_MASK))
468 s->flags |= SF_FINST_R;
469
470 req->analysers &= AN_REQ_FLT_END;
471 req->analyse_exp = TICK_ETERNITY;
472 return 0;
473}
474
475
476/* This stream analyser runs all HTTP request processing which is common to
477 * frontends and backends, which means blocking ACLs, filters, connection-close,
478 * reqadd, stats and redirects. This is performed for the designated proxy.
479 * It returns 1 if the processing can continue on next analysers, or zero if it
480 * either needs more data or wants to immediately abort the request (eg: deny,
481 * error, ...).
482 */
483int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
484{
485 struct session *sess = s->sess;
486 struct http_txn *txn = s->txn;
487 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200489 struct redirect_rule *rule;
490 struct cond_wordlist *wl;
491 enum rule_result verdict;
492 int deny_status = HTTP_ERR_403;
493 struct connection *conn = objt_conn(sess->origin);
494
495 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
496 /* we need more data */
497 goto return_prx_yield;
498 }
499
500 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
501 now_ms, __FUNCTION__,
502 s,
503 req,
504 req->rex, req->wex,
505 req->flags,
506 ci_data(req),
507 req->analysers);
508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100509 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200510
Christopher Faulete0768eb2018-10-03 16:38:02 +0200511 /* just in case we have some per-backend tracking */
512 stream_inc_be_http_req_ctr(s);
513
514 /* evaluate http-request rules */
515 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200516 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200517
518 switch (verdict) {
519 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
520 goto return_prx_yield;
521
522 case HTTP_RULE_RES_CONT:
523 case HTTP_RULE_RES_STOP: /* nothing to do */
524 break;
525
526 case HTTP_RULE_RES_DENY: /* deny or tarpit */
527 if (txn->flags & TX_CLTARPIT)
528 goto tarpit;
529 goto deny;
530
531 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
532 goto return_prx_cond;
533
534 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
535 goto done;
536
537 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
538 goto return_bad_req;
539 }
540 }
541
542 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
543 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200544 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 ctx.blk = NULL;
547 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
548 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
552
553 /* OK at this stage, we know that the request was accepted according to
554 * the http-request rules, we can check for the stats. Note that the
555 * URI is detected *before* the req* rules in order not to be affected
556 * by a possible reqrep, while they are processed *after* so that a
557 * reqdeny can still block them. This clearly needs to change in 1.6!
558 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200559 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100561 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200562 txn->status = 500;
563 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200565
566 if (!(s->flags & SF_ERR_MASK))
567 s->flags |= SF_ERR_RESOURCE;
568 goto return_prx_cond;
569 }
570
571 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200572 htx_handle_stats(s, req);
573 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200574 /* not all actions implemented: deny, allow, auth */
575
576 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
577 goto deny;
578
579 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
580 goto return_prx_cond;
581 }
582
583 /* evaluate the req* rules except reqadd */
584 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200585 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200586 goto return_bad_req;
587
588 if (txn->flags & TX_CLDENY)
589 goto deny;
590
591 if (txn->flags & TX_CLTARPIT) {
592 deny_status = HTTP_ERR_500;
593 goto tarpit;
594 }
595 }
596
597 /* add request headers from the rule sets in the same order */
598 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (wl->cond) {
601 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
602 ret = acl_pass(ret);
603 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
604 ret = !ret;
605 if (!ret)
606 continue;
607 }
608
Christopher Fauletff2759f2018-10-24 11:13:16 +0200609 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
610 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 goto return_bad_req;
612 }
613
Christopher Faulet2571bc62019-03-01 11:44:26 +0100614 /* Proceed with the applets now. */
615 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200616 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100617 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100619 if (htx_handle_expect_hdr(s, htx, msg) == -1)
620 goto return_bad_req;
621
Christopher Faulete0768eb2018-10-03 16:38:02 +0200622 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
623 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
624 if (!(s->flags & SF_FINST_MASK))
625 s->flags |= SF_FINST_R;
626
627 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
628 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
629 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
630 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100631
632 req->flags |= CF_SEND_DONTWAIT;
633 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto done;
635 }
636
637 /* check whether we have some ACLs set to redirect this request */
638 list_for_each_entry(rule, &px->redirect_rules, list) {
639 if (rule->cond) {
640 int ret;
641
642 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
643 ret = acl_pass(ret);
644 if (rule->cond->pol == ACL_COND_UNLESS)
645 ret = !ret;
646 if (!ret)
647 continue;
648 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200649 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200650 goto return_bad_req;
651 goto done;
652 }
653
654 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
655 * If this happens, then the data will not come immediately, so we must
656 * send all what we have without waiting. Note that due to the small gain
657 * in waiting for the body of the request, it's easier to simply put the
658 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
659 * itself once used.
660 */
661 req->flags |= CF_SEND_DONTWAIT;
662
663 done: /* done with this analyser, continue with next ones that the calling
664 * points will have set, if any.
665 */
666 req->analyse_exp = TICK_ETERNITY;
667 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
668 req->analysers &= ~an_bit;
669 return 1;
670
671 tarpit:
672 /* Allow cookie logging
673 */
674 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200675 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200676
677 /* When a connection is tarpitted, we use the tarpit timeout,
678 * which may be the same as the connect timeout if unspecified.
679 * If unset, then set it to zero because we really want it to
680 * eventually expire. We build the tarpit as an analyser.
681 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100682 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683
684 /* wipe the request out so that we can drop the connection early
685 * if the client closes first.
686 */
687 channel_dont_connect(req);
688
689 txn->status = http_err_codes[deny_status];
690
691 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
692 req->analysers |= AN_REQ_HTTP_TARPIT;
693 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
694 if (!req->analyse_exp)
695 req->analyse_exp = tick_add(now_ms, 0);
696 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100697 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100699 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100701 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702 goto done_without_exp;
703
704 deny: /* this request was blocked (denied) */
705
706 /* Allow cookie logging
707 */
708 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200709 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710
711 txn->flags |= TX_CLDENY;
712 txn->status = http_err_codes[deny_status];
713 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100714 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100716 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100718 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200719 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100720 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200721 goto return_prx_cond;
722
723 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200724 txn->req.err_state = txn->req.msg_state;
725 txn->req.msg_state = HTTP_MSG_ERROR;
726 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100727 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200728
Olivier Houcharda798bf52019-03-08 18:52:00 +0100729 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200730 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100731 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200732
733 return_prx_cond:
734 if (!(s->flags & SF_ERR_MASK))
735 s->flags |= SF_ERR_PRXCOND;
736 if (!(s->flags & SF_FINST_MASK))
737 s->flags |= SF_FINST_R;
738
739 req->analysers &= AN_REQ_FLT_END;
740 req->analyse_exp = TICK_ETERNITY;
741 return 0;
742
743 return_prx_yield:
744 channel_dont_connect(req);
745 return 0;
746}
747
748/* This function performs all the processing enabled for the current request.
749 * It returns 1 if the processing can continue on next analysers, or zero if it
750 * needs more data, encounters an error, or wants to immediately abort the
751 * request. It relies on buffers flags, and updates s->req.analysers.
752 */
753int htx_process_request(struct stream *s, struct channel *req, int an_bit)
754{
755 struct session *sess = s->sess;
756 struct http_txn *txn = s->txn;
757 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200758 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200759 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
760
761 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
762 /* we need more data */
763 channel_dont_connect(req);
764 return 0;
765 }
766
767 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
768 now_ms, __FUNCTION__,
769 s,
770 req,
771 req->rex, req->wex,
772 req->flags,
773 ci_data(req),
774 req->analysers);
775
776 /*
777 * Right now, we know that we have processed the entire headers
778 * and that unwanted requests have been filtered out. We can do
779 * whatever we want with the remaining request. Also, now we
780 * may have separate values for ->fe, ->be.
781 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100782 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 /*
785 * If HTTP PROXY is set we simply get remote server address parsing
786 * incoming request. Note that this requires that a connection is
787 * allocated on the server side.
788 */
789 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
790 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100791 struct htx_sl *sl;
792 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793
794 /* Note that for now we don't reuse existing proxy connections */
795 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
796 txn->req.err_state = txn->req.msg_state;
797 txn->req.msg_state = HTTP_MSG_ERROR;
798 txn->status = 500;
799 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100800 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200801
802 if (!(s->flags & SF_ERR_MASK))
803 s->flags |= SF_ERR_RESOURCE;
804 if (!(s->flags & SF_FINST_MASK))
805 s->flags |= SF_FINST_R;
806
807 return 0;
808 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200809 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100810 uri = htx_sl_req_uri(sl);
811 path = http_get_path(uri);
812 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 goto return_bad_req;
814
815 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200816 * uri.ptr and path.ptr (excluded). If it was not found, we need
817 * to replace from all the uri by a single "/".
818 *
819 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100820 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200821 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200822 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100823 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200824 }
825
826 /*
827 * 7: Now we can work with the cookies.
828 * Note that doing so might move headers in the request, but
829 * the fields will stay coherent and the URI will not move.
830 * This should only be performed in the backend.
831 */
832 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100833 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834
835 /* add unique-id if "header-unique-id" is specified */
836
837 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
838 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
839 goto return_bad_req;
840 s->unique_id[0] = '\0';
841 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
842 }
843
844 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200845 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
846 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
847
848 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200850 }
851
852 /*
853 * 9: add X-Forwarded-For if either the frontend or the backend
854 * asks for it.
855 */
856 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200857 struct http_hdr_ctx ctx = { .blk = NULL };
858 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
859 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
860
Christopher Faulete0768eb2018-10-03 16:38:02 +0200861 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863 /* The header is set to be added only if none is present
864 * and we found it, so don't do anything.
865 */
866 }
867 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
868 /* Add an X-Forwarded-For header unless the source IP is
869 * in the 'except' network range.
870 */
871 if ((!sess->fe->except_mask.s_addr ||
872 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
873 != sess->fe->except_net.s_addr) &&
874 (!s->be->except_mask.s_addr ||
875 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
876 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878
879 /* Note: we rely on the backend to get the header name to be used for
880 * x-forwarded-for, because the header is really meant for the backends.
881 * However, if the backend did not specify any option, we have to rely
882 * on the frontend's header name.
883 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200884 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
885 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200886 goto return_bad_req;
887 }
888 }
889 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
890 /* FIXME: for the sake of completeness, we should also support
891 * 'except' here, although it is mostly useless in this case.
892 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200893 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200894
Christopher Faulete0768eb2018-10-03 16:38:02 +0200895 inet_ntop(AF_INET6,
896 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
897 pn, sizeof(pn));
898
899 /* Note: we rely on the backend to get the header name to be used for
900 * x-forwarded-for, because the header is really meant for the backends.
901 * However, if the backend did not specify any option, we have to rely
902 * on the frontend's header name.
903 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200904 chunk_printf(&trash, "%s", pn);
905 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200906 goto return_bad_req;
907 }
908 }
909
910 /*
911 * 10: add X-Original-To if either the frontend or the backend
912 * asks for it.
913 */
914 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
915
916 /* FIXME: don't know if IPv6 can handle that case too. */
917 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
918 /* Add an X-Original-To header unless the destination IP is
919 * in the 'except' network range.
920 */
921 conn_get_to_addr(cli_conn);
922
923 if (cli_conn->addr.to.ss_family == AF_INET &&
924 ((!sess->fe->except_mask_to.s_addr ||
925 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
926 != sess->fe->except_to.s_addr) &&
927 (!s->be->except_mask_to.s_addr ||
928 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
929 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200930 struct ist hdr;
931 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932
933 /* Note: we rely on the backend to get the header name to be used for
934 * x-original-to, because the header is really meant for the backends.
935 * However, if the backend did not specify any option, we have to rely
936 * on the frontend's header name.
937 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200938 if (s->be->orgto_hdr_len)
939 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
940 else
941 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200943 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
944 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 goto return_bad_req;
946 }
947 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 }
949
Christopher Faulete0768eb2018-10-03 16:38:02 +0200950 /* If we have no server assigned yet and we're balancing on url_param
951 * with a POST request, we may be interested in checking the body for
952 * that parameter. This will be done in another analyser.
953 */
954 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100955 s->txn->meth == HTTP_METH_POST &&
956 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 channel_dont_connect(req);
958 req->analysers |= AN_REQ_HTTP_BODY;
959 }
960
961 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
962 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100963
Christopher Faulete0768eb2018-10-03 16:38:02 +0200964 /* We expect some data from the client. Unless we know for sure
965 * we already have a full request, we have to re-enable quick-ack
966 * in case we previously disabled it, otherwise we might cause
967 * the client to delay further data.
968 */
969 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200970 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100971 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200972
973 /*************************************************************
974 * OK, that's finished for the headers. We have done what we *
975 * could. Let's switch to the DATA state. *
976 ************************************************************/
977 req->analyse_exp = TICK_ETERNITY;
978 req->analysers &= ~an_bit;
979
980 s->logs.tv_request = now;
981 /* OK let's go on with the BODY now */
982 return 1;
983
984 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200985 txn->req.err_state = txn->req.msg_state;
986 txn->req.msg_state = HTTP_MSG_ERROR;
987 txn->status = 400;
988 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100989 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200990
Olivier Houcharda798bf52019-03-08 18:52:00 +0100991 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200992 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100993 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200994
995 if (!(s->flags & SF_ERR_MASK))
996 s->flags |= SF_ERR_PRXCOND;
997 if (!(s->flags & SF_FINST_MASK))
998 s->flags |= SF_FINST_R;
999 return 0;
1000}
1001
1002/* This function is an analyser which processes the HTTP tarpit. It always
1003 * returns zero, at the beginning because it prevents any other processing
1004 * from occurring, and at the end because it terminates the request.
1005 */
1006int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1007{
1008 struct http_txn *txn = s->txn;
1009
1010 /* This connection is being tarpitted. The CLIENT side has
1011 * already set the connect expiration date to the right
1012 * timeout. We just have to check that the client is still
1013 * there and that the timeout has not expired.
1014 */
1015 channel_dont_connect(req);
1016 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1017 !tick_is_expired(req->analyse_exp, now_ms))
1018 return 0;
1019
1020 /* We will set the queue timer to the time spent, just for
1021 * logging purposes. We fake a 500 server error, so that the
1022 * attacker will not suspect his connection has been tarpitted.
1023 * It will not cause trouble to the logs because we can exclude
1024 * the tarpitted connections by filtering on the 'PT' status flags.
1025 */
1026 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1027
1028 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001029 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001030
1031 req->analysers &= AN_REQ_FLT_END;
1032 req->analyse_exp = TICK_ETERNITY;
1033
1034 if (!(s->flags & SF_ERR_MASK))
1035 s->flags |= SF_ERR_PRXCOND;
1036 if (!(s->flags & SF_FINST_MASK))
1037 s->flags |= SF_FINST_T;
1038 return 0;
1039}
1040
1041/* This function is an analyser which waits for the HTTP request body. It waits
1042 * for either the buffer to be full, or the full advertised contents to have
1043 * reached the buffer. It must only be called after the standard HTTP request
1044 * processing has occurred, because it expects the request to be parsed and will
1045 * look for the Expect header. It may send a 100-Continue interim response. It
1046 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1047 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1048 * needs to read more data, or 1 once it has completed its analysis.
1049 */
1050int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1051{
1052 struct session *sess = s->sess;
1053 struct http_txn *txn = s->txn;
1054 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001055 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001056
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057
1058 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1059 now_ms, __FUNCTION__,
1060 s,
1061 req,
1062 req->rex, req->wex,
1063 req->flags,
1064 ci_data(req),
1065 req->analysers);
1066
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001067 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068
Willy Tarreau4236f032019-03-05 10:43:32 +01001069 if (htx->flags & HTX_FL_PARSING_ERROR)
1070 goto return_bad_req;
1071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 if (msg->msg_state < HTTP_MSG_BODY)
1073 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001074
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075 /* We have to parse the HTTP request body to find any required data.
1076 * "balance url_param check_post" should have been the only way to get
1077 * into this. We were brought here after HTTP header analysis, so all
1078 * related structures are ready.
1079 */
1080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001082 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1083 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 }
1085
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001086 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1089 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001092 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 goto http_end;
1094
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1097 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001098 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001099
1100 if (!(s->flags & SF_ERR_MASK))
1101 s->flags |= SF_ERR_CLITO;
1102 if (!(s->flags & SF_FINST_MASK))
1103 s->flags |= SF_FINST_D;
1104 goto return_err_msg;
1105 }
1106
1107 /* we get here if we need to wait for more data */
1108 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1109 /* Not enough data. We'll re-use the http-request
1110 * timeout here. Ideally, we should set the timeout
1111 * relative to the accept() date. We just set the
1112 * request timeout once at the beginning of the
1113 * request.
1114 */
1115 channel_dont_connect(req);
1116 if (!tick_isset(req->analyse_exp))
1117 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1118 return 0;
1119 }
1120
1121 http_end:
1122 /* The situation will not evolve, so let's give up on the analysis. */
1123 s->logs.tv_request = now; /* update the request timer to reflect full request */
1124 req->analysers &= ~an_bit;
1125 req->analyse_exp = TICK_ETERNITY;
1126 return 1;
1127
1128 return_bad_req: /* let's centralize all bad requests */
1129 txn->req.err_state = txn->req.msg_state;
1130 txn->req.msg_state = HTTP_MSG_ERROR;
1131 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001132 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001133
1134 if (!(s->flags & SF_ERR_MASK))
1135 s->flags |= SF_ERR_PRXCOND;
1136 if (!(s->flags & SF_FINST_MASK))
1137 s->flags |= SF_FINST_R;
1138
1139 return_err_msg:
1140 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001141 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001142 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001143 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001144 return 0;
1145}
1146
1147/* This function is an analyser which forwards request body (including chunk
1148 * sizes if any). It is called as soon as we must forward, even if we forward
1149 * zero byte. The only situation where it must not be called is when we're in
1150 * tunnel mode and we want to forward till the close. It's used both to forward
1151 * remaining data and to resync after end of body. It expects the msg_state to
1152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1153 * read more data, or 1 once we can go on with next request or end the stream.
1154 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1155 * bytes of pending data + the headers if not already done.
1156 */
1157int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1158{
1159 struct session *sess = s->sess;
1160 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001161 struct http_msg *msg = &txn->req;
1162 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001163 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001164 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001165
1166 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1167 now_ms, __FUNCTION__,
1168 s,
1169 req,
1170 req->rex, req->wex,
1171 req->flags,
1172 ci_data(req),
1173 req->analysers);
1174
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001175 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176
1177 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1178 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1179 /* Output closed while we were sending data. We must abort and
1180 * wake the other side up.
1181 */
1182 msg->err_state = msg->msg_state;
1183 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001184 htx_end_request(s);
1185 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186 return 1;
1187 }
1188
1189 /* Note that we don't have to send 100-continue back because we don't
1190 * need the data to complete our job, and it's up to the server to
1191 * decide whether to return 100, 417 or anything else in return of
1192 * an "Expect: 100-continue" header.
1193 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001194 if (msg->msg_state == HTTP_MSG_BODY)
1195 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001196
1197 /* Some post-connect processing might want us to refrain from starting to
1198 * forward data. Currently, the only reason for this is "balance url_param"
1199 * whichs need to parse/process the request after we've enabled forwarding.
1200 */
1201 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1202 if (!(s->res.flags & CF_READ_ATTACHED)) {
1203 channel_auto_connect(req);
1204 req->flags |= CF_WAKE_CONNECT;
1205 channel_dont_close(req); /* don't fail on early shutr */
1206 goto waiting;
1207 }
1208 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1209 }
1210
1211 /* in most states, we should abort in case of early close */
1212 channel_auto_close(req);
1213
1214 if (req->to_forward) {
Willy Tarreau6e8d6a92019-03-21 18:00:30 +01001215 /* We can't process the buffer's contents yet */
1216 req->flags |= CF_WAKE_WRITE;
1217 goto missing_data_or_waiting;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001218 }
1219
Christopher Faulet9768c262018-10-22 09:34:31 +02001220 if (msg->msg_state >= HTTP_MSG_DONE)
1221 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001222 /* Forward input data. We get it by removing all outgoing data not
1223 * forwarded yet from HTX data size. If there are some data filters, we
1224 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001225 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001226 if (HAS_REQ_DATA_FILTERS(s)) {
1227 ret = flt_http_payload(s, msg, htx->data);
1228 if (ret < 0)
1229 goto return_bad_req;
1230 c_adv(req, ret);
1231 if (htx->data != co_data(req) || htx->extra)
1232 goto missing_data_or_waiting;
1233 }
1234 else {
1235 c_adv(req, htx->data - co_data(req));
Willy Tarreau6e8d6a92019-03-21 18:00:30 +01001236
1237 /* To let the function channel_forward work as expected we must update
1238 * the channel's buffer to pretend there is no more input data. The
1239 * right length is then restored. We must do that, because when an HTX
1240 * message is stored into a buffer, it appears as full.
1241 */
1242 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1243 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001244 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001245
Christopher Faulet9768c262018-10-22 09:34:31 +02001246 /* Check if the end-of-message is reached and if so, switch the message
1247 * in HTTP_MSG_DONE state.
1248 */
1249 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1250 goto missing_data_or_waiting;
1251
1252 msg->msg_state = HTTP_MSG_DONE;
1253
1254 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001255 /* other states, DONE...TUNNEL */
1256 /* we don't want to forward closes on DONE except in tunnel mode. */
1257 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1258 channel_dont_close(req);
1259
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001260 if (HAS_REQ_DATA_FILTERS(s)) {
1261 ret = flt_http_end(s, msg);
1262 if (ret <= 0) {
1263 if (!ret)
1264 goto missing_data_or_waiting;
1265 goto return_bad_req;
1266 }
1267 }
1268
Christopher Fauletf2824e62018-10-01 12:12:37 +02001269 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001270 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001271 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001272 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1273 if (req->flags & CF_SHUTW) {
1274 /* request errors are most likely due to the
1275 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001276 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001277 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 goto return_bad_req;
1279 }
1280 return 1;
1281 }
1282
1283 /* If "option abortonclose" is set on the backend, we want to monitor
1284 * the client's connection and forward any shutdown notification to the
1285 * server, which will decide whether to close or to go on processing the
1286 * request. We only do that in tunnel mode, and not in other modes since
1287 * it can be abused to exhaust source ports. */
1288 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1289 channel_auto_read(req);
1290 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1291 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1292 s->si[1].flags |= SI_FL_NOLINGER;
1293 channel_auto_close(req);
1294 }
1295 else if (s->txn->meth == HTTP_METH_POST) {
1296 /* POST requests may require to read extra CRLF sent by broken
1297 * browsers and which could cause an RST to be sent upon close
1298 * on some systems (eg: Linux). */
1299 channel_auto_read(req);
1300 }
1301 return 0;
1302
1303 missing_data_or_waiting:
1304 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001305 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1306 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001307
1308 waiting:
1309 /* waiting for the last bits to leave the buffer */
1310 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001311 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001312
Christopher Faulet47365272018-10-31 17:40:50 +01001313 if (htx->flags & HTX_FL_PARSING_ERROR)
1314 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001315
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316 /* When TE: chunked is used, we need to get there again to parse remaining
1317 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1318 * And when content-length is used, we never want to let the possible
1319 * shutdown be forwarded to the other side, as the state machine will
1320 * take care of it once the client responds. It's also important to
1321 * prevent TIME_WAITs from accumulating on the backend side, and for
1322 * HTTP/2 where the last frame comes with a shutdown.
1323 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001324 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001325 channel_dont_close(req);
1326
1327 /* We know that more data are expected, but we couldn't send more that
1328 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1329 * system knows it must not set a PUSH on this first part. Interactive
1330 * modes are already handled by the stream sock layer. We must not do
1331 * this in content-length mode because it could present the MSG_MORE
1332 * flag with the last block of forwarded data, which would cause an
1333 * additional delay to be observed by the receiver.
1334 */
1335 if (msg->flags & HTTP_MSGF_TE_CHNK)
1336 req->flags |= CF_EXPECT_MORE;
1337
1338 return 0;
1339
Christopher Faulet93e02d82019-03-08 14:18:50 +01001340 return_cli_abort:
1341 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1342 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1343 if (objt_server(s->target))
1344 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1345 if (!(s->flags & SF_ERR_MASK))
1346 s->flags |= SF_ERR_CLICL;
1347 status = 400;
1348 goto return_error;
1349
1350 return_srv_abort:
1351 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1352 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1353 if (objt_server(s->target))
1354 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1355 if (!(s->flags & SF_ERR_MASK))
1356 s->flags |= SF_ERR_SRVCL;
1357 status = 502;
1358 goto return_error;
1359
1360 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001361 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001362 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001363 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001364 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001365 s->flags |= SF_ERR_CLICL;
1366 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367
Christopher Faulet93e02d82019-03-08 14:18:50 +01001368 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001369 txn->req.err_state = txn->req.msg_state;
1370 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001371 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001373 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001375 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001376 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 }
1378 req->analysers &= AN_REQ_FLT_END;
1379 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 +01001380 if (!(s->flags & SF_FINST_MASK))
1381 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001382 return 0;
1383}
1384
1385/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1386 * processing can continue on next analysers, or zero if it either needs more
1387 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1388 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1389 * when it has nothing left to do, and may remove any analyser when it wants to
1390 * abort.
1391 */
1392int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1393{
Christopher Faulet9768c262018-10-22 09:34:31 +02001394 /*
1395 * We will analyze a complete HTTP response to check the its syntax.
1396 *
1397 * Once the start line and all headers are received, we may perform a
1398 * capture of the error (if any), and we will set a few fields. We also
1399 * logging and finally headers capture.
1400 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001401 struct session *sess = s->sess;
1402 struct http_txn *txn = s->txn;
1403 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001404 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001405 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001406 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001407 int n;
1408
1409 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1410 now_ms, __FUNCTION__,
1411 s,
1412 rep,
1413 rep->rex, rep->wex,
1414 rep->flags,
1415 ci_data(rep),
1416 rep->analysers);
1417
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001418 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001419
Willy Tarreau4236f032019-03-05 10:43:32 +01001420 /* Parsing errors are caught here */
1421 if (htx->flags & HTX_FL_PARSING_ERROR)
1422 goto return_bad_res;
1423
Christopher Faulete0768eb2018-10-03 16:38:02 +02001424 /*
1425 * Now we quickly check if we have found a full valid response.
1426 * If not so, we check the FD and buffer states before leaving.
1427 * A full response is indicated by the fact that we have seen
1428 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1429 * responses are checked first.
1430 *
1431 * Depending on whether the client is still there or not, we
1432 * may send an error response back or not. Note that normally
1433 * we should only check for HTTP status there, and check I/O
1434 * errors somewhere else.
1435 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001436 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001437 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001438 * First catch invalid response because of a parsing error or
1439 * because only part of headers have been transfered.
1440 * Multiplexers have the responsibility to emit all headers at
1441 * once. We must be sure to have forwarded all outgoing data
1442 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001443 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001444 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001445 goto return_bad_res;
1446
Christopher Faulet9768c262018-10-22 09:34:31 +02001447 /* 1: have we encountered a read error ? */
1448 if (rep->flags & CF_READ_ERROR) {
1449 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001450 goto abort_keep_alive;
1451
Olivier Houcharda798bf52019-03-08 18:52:00 +01001452 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001453 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001454 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001455 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456 }
1457
Christopher Faulete0768eb2018-10-03 16:38:02 +02001458 rep->analysers &= AN_RES_FLT_END;
1459 txn->status = 502;
1460
1461 /* Check to see if the server refused the early data.
1462 * If so, just send a 425
1463 */
1464 if (objt_cs(s->si[1].end)) {
1465 struct connection *conn = objt_cs(s->si[1].end)->conn;
1466
1467 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1468 txn->status = 425;
1469 }
1470
1471 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001472 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473
1474 if (!(s->flags & SF_ERR_MASK))
1475 s->flags |= SF_ERR_SRVCL;
1476 if (!(s->flags & SF_FINST_MASK))
1477 s->flags |= SF_FINST_H;
1478 return 0;
1479 }
1480
Christopher Faulet9768c262018-10-22 09:34:31 +02001481 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001482 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001483 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001484 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001485 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001486 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001487 }
1488
Christopher Faulete0768eb2018-10-03 16:38:02 +02001489 rep->analysers &= AN_RES_FLT_END;
1490 txn->status = 504;
1491 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001492 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001493
1494 if (!(s->flags & SF_ERR_MASK))
1495 s->flags |= SF_ERR_SRVTO;
1496 if (!(s->flags & SF_FINST_MASK))
1497 s->flags |= SF_FINST_H;
1498 return 0;
1499 }
1500
Christopher Faulet9768c262018-10-22 09:34:31 +02001501 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001502 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001503 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1504 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001506 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507
1508 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001510 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511
1512 if (!(s->flags & SF_ERR_MASK))
1513 s->flags |= SF_ERR_CLICL;
1514 if (!(s->flags & SF_FINST_MASK))
1515 s->flags |= SF_FINST_H;
1516
1517 /* process_stream() will take care of the error */
1518 return 0;
1519 }
1520
Christopher Faulet9768c262018-10-22 09:34:31 +02001521 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001523 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 goto abort_keep_alive;
1525
Olivier Houcharda798bf52019-03-08 18:52:00 +01001526 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001528 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001529 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 }
1531
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532 rep->analysers &= AN_RES_FLT_END;
1533 txn->status = 502;
1534 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001535 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536
1537 if (!(s->flags & SF_ERR_MASK))
1538 s->flags |= SF_ERR_SRVCL;
1539 if (!(s->flags & SF_FINST_MASK))
1540 s->flags |= SF_FINST_H;
1541 return 0;
1542 }
1543
Christopher Faulet9768c262018-10-22 09:34:31 +02001544 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 goto abort_keep_alive;
1548
Olivier Houcharda798bf52019-03-08 18:52:00 +01001549 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551
1552 if (!(s->flags & SF_ERR_MASK))
1553 s->flags |= SF_ERR_CLICL;
1554 if (!(s->flags & SF_FINST_MASK))
1555 s->flags |= SF_FINST_H;
1556
1557 /* process_stream() will take care of the error */
1558 return 0;
1559 }
1560
1561 channel_dont_close(rep);
1562 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1563 return 0;
1564 }
1565
1566 /* More interesting part now : we know that we have a complete
1567 * response which at least looks like HTTP. We have an indicator
1568 * of each header's length, so we can parse them quickly.
1569 */
1570
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001572 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573
Christopher Faulet9768c262018-10-22 09:34:31 +02001574 /* 0: we might have to print this header in debug mode */
1575 if (unlikely((global.mode & MODE_DEBUG) &&
1576 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1577 int32_t pos;
1578
Christopher Faulet03599112018-11-27 11:21:21 +01001579 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001580
1581 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1582 struct htx_blk *blk = htx_get_blk(htx, pos);
1583 enum htx_blk_type type = htx_get_blk_type(blk);
1584
1585 if (type == HTX_BLK_EOH)
1586 break;
1587 if (type != HTX_BLK_HDR)
1588 continue;
1589
1590 htx_debug_hdr("srvhdr", s,
1591 htx_get_blk_name(htx, blk),
1592 htx_get_blk_value(htx, blk));
1593 }
1594 }
1595
Christopher Faulet03599112018-11-27 11:21:21 +01001596 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001597 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001598 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001599 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001600 if (sl->flags & HTX_SL_F_XFER_LEN) {
1601 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001602 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001603 if (sl->flags & HTX_SL_F_BODYLESS)
1604 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001605 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001606
1607 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001608 if (n < 1 || n > 5)
1609 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001610
Christopher Faulete0768eb2018-10-03 16:38:02 +02001611 /* when the client triggers a 4xx from the server, it's most often due
1612 * to a missing object or permission. These events should be tracked
1613 * because if they happen often, it may indicate a brute force or a
1614 * vulnerability scan.
1615 */
1616 if (n == 4)
1617 stream_inc_http_err_ctr(s);
1618
1619 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001620 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622 /* Adjust server's health based on status code. Note: status codes 501
1623 * and 505 are triggered on demand by client request, so we must not
1624 * count them as server failures.
1625 */
1626 if (objt_server(s->target)) {
1627 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001628 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001630 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631 }
1632
1633 /*
1634 * We may be facing a 100-continue response, or any other informational
1635 * 1xx response which is non-final, in which case this is not the right
1636 * response, and we're waiting for the next one. Let's allow this response
1637 * to go to the client and wait for the next one. There's an exception for
1638 * 101 which is used later in the code to switch protocols.
1639 */
1640 if (txn->status < 200 &&
1641 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001642 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001643 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001644 msg->msg_state = HTTP_MSG_RPBEFORE;
1645 txn->status = 0;
1646 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 }
1649
1650 /*
1651 * 2: check for cacheability.
1652 */
1653
1654 switch (txn->status) {
1655 case 200:
1656 case 203:
1657 case 204:
1658 case 206:
1659 case 300:
1660 case 301:
1661 case 404:
1662 case 405:
1663 case 410:
1664 case 414:
1665 case 501:
1666 break;
1667 default:
1668 /* RFC7231#6.1:
1669 * Responses with status codes that are defined as
1670 * cacheable by default (e.g., 200, 203, 204, 206,
1671 * 300, 301, 404, 405, 410, 414, and 501 in this
1672 * specification) can be reused by a cache with
1673 * heuristic expiration unless otherwise indicated
1674 * by the method definition or explicit cache
1675 * controls [RFC7234]; all other status codes are
1676 * not cacheable by default.
1677 */
1678 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1679 break;
1680 }
1681
1682 /*
1683 * 3: we may need to capture headers
1684 */
1685 s->logs.logwait &= ~LW_RESP;
1686 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001687 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001688
Christopher Faulet9768c262018-10-22 09:34:31 +02001689 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001690 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1691 txn->status == 101)) {
1692 /* Either we've established an explicit tunnel, or we're
1693 * switching the protocol. In both cases, we're very unlikely
1694 * to understand the next protocols. We have to switch to tunnel
1695 * mode, so that we transfer the request and responses then let
1696 * this protocol pass unmodified. When we later implement specific
1697 * parsers for such protocols, we'll want to check the Upgrade
1698 * header which contains information about that protocol for
1699 * responses with status 101 (eg: see RFC2817 about TLS).
1700 */
1701 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 }
1703
Christopher Faulet61608322018-11-23 16:23:45 +01001704 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1705 * 407 (Proxy-Authenticate) responses and set the connection to private
1706 */
1707 srv_conn = cs_conn(objt_cs(s->si[1].end));
1708 if (srv_conn) {
1709 struct ist hdr;
1710 struct http_hdr_ctx ctx;
1711
1712 if (txn->status == 401)
1713 hdr = ist("WWW-Authenticate");
1714 else if (txn->status == 407)
1715 hdr = ist("Proxy-Authenticate");
1716 else
1717 goto end;
1718
1719 ctx.blk = NULL;
1720 while (http_find_header(htx, hdr, &ctx, 0)) {
1721 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1722 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1723 srv_conn->flags |= CO_FL_PRIVATE;
1724 }
1725 }
1726
1727 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001728 /* we want to have the response time before we start processing it */
1729 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1730
1731 /* end of job, return OK */
1732 rep->analysers &= ~an_bit;
1733 rep->analyse_exp = TICK_ETERNITY;
1734 channel_auto_close(rep);
1735 return 1;
1736
Christopher Faulet47365272018-10-31 17:40:50 +01001737 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001738 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001739 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001740 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001741 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001742 }
1743 txn->status = 502;
1744 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001745 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001746 rep->analysers &= AN_RES_FLT_END;
1747
1748 if (!(s->flags & SF_ERR_MASK))
1749 s->flags |= SF_ERR_PRXCOND;
1750 if (!(s->flags & SF_FINST_MASK))
1751 s->flags |= SF_FINST_H;
1752 return 0;
1753
Christopher Faulete0768eb2018-10-03 16:38:02 +02001754 abort_keep_alive:
1755 /* A keep-alive request to the server failed on a network error.
1756 * The client is required to retry. We need to close without returning
1757 * any other information so that the client retries.
1758 */
1759 txn->status = 0;
1760 rep->analysers &= AN_RES_FLT_END;
1761 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001762 s->logs.logwait = 0;
1763 s->logs.level = 0;
1764 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001765 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001766 return 0;
1767}
1768
1769/* This function performs all the processing enabled for the current response.
1770 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1771 * and updates s->res.analysers. It might make sense to explode it into several
1772 * other functions. It works like process_request (see indications above).
1773 */
1774int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1775{
1776 struct session *sess = s->sess;
1777 struct http_txn *txn = s->txn;
1778 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001779 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001780 struct proxy *cur_proxy;
1781 struct cond_wordlist *wl;
1782 enum rule_result ret = HTTP_RULE_RES_CONT;
1783
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001784 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1785 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001786
Christopher Faulete0768eb2018-10-03 16:38:02 +02001787 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1788 now_ms, __FUNCTION__,
1789 s,
1790 rep,
1791 rep->rex, rep->wex,
1792 rep->flags,
1793 ci_data(rep),
1794 rep->analysers);
1795
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001796 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001797
1798 /* The stats applet needs to adjust the Connection header but we don't
1799 * apply any filter there.
1800 */
1801 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1802 rep->analysers &= ~an_bit;
1803 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001804 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 }
1806
1807 /*
1808 * We will have to evaluate the filters.
1809 * As opposed to version 1.2, now they will be evaluated in the
1810 * filters order and not in the header order. This means that
1811 * each filter has to be validated among all headers.
1812 *
1813 * Filters are tried with ->be first, then with ->fe if it is
1814 * different from ->be.
1815 *
1816 * Maybe we are in resume condiion. In this case I choose the
1817 * "struct proxy" which contains the rule list matching the resume
1818 * pointer. If none of theses "struct proxy" match, I initialise
1819 * the process with the first one.
1820 *
1821 * In fact, I check only correspondance betwwen the current list
1822 * pointer and the ->fe rule list. If it doesn't match, I initialize
1823 * the loop with the ->be.
1824 */
1825 if (s->current_rule_list == &sess->fe->http_res_rules)
1826 cur_proxy = sess->fe;
1827 else
1828 cur_proxy = s->be;
1829 while (1) {
1830 struct proxy *rule_set = cur_proxy;
1831
1832 /* evaluate http-response rules */
1833 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001834 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001835
1836 if (ret == HTTP_RULE_RES_BADREQ)
1837 goto return_srv_prx_502;
1838
1839 if (ret == HTTP_RULE_RES_DONE) {
1840 rep->analysers &= ~an_bit;
1841 rep->analyse_exp = TICK_ETERNITY;
1842 return 1;
1843 }
1844 }
1845
1846 /* we need to be called again. */
1847 if (ret == HTTP_RULE_RES_YIELD) {
1848 channel_dont_close(rep);
1849 return 0;
1850 }
1851
1852 /* try headers filters */
1853 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001854 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1855 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001856 }
1857
1858 /* has the response been denied ? */
1859 if (txn->flags & TX_SVDENY) {
1860 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001861 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001862
Olivier Houcharda798bf52019-03-08 18:52:00 +01001863 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1864 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001865 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001866 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 goto return_srv_prx_502;
1868 }
1869
1870 /* add response headers from the rule sets in the same order */
1871 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001872 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001873 if (txn->status < 200 && txn->status != 101)
1874 break;
1875 if (wl->cond) {
1876 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1877 ret = acl_pass(ret);
1878 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1879 ret = !ret;
1880 if (!ret)
1881 continue;
1882 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001883
1884 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1885 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001886 goto return_bad_resp;
1887 }
1888
1889 /* check whether we're already working on the frontend */
1890 if (cur_proxy == sess->fe)
1891 break;
1892 cur_proxy = sess->fe;
1893 }
1894
1895 /* After this point, this anayzer can't return yield, so we can
1896 * remove the bit corresponding to this analyzer from the list.
1897 *
1898 * Note that the intermediate returns and goto found previously
1899 * reset the analyzers.
1900 */
1901 rep->analysers &= ~an_bit;
1902 rep->analyse_exp = TICK_ETERNITY;
1903
1904 /* OK that's all we can do for 1xx responses */
1905 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001906 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001907
1908 /*
1909 * Now check for a server cookie.
1910 */
1911 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001912 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001913
1914 /*
1915 * Check for cache-control or pragma headers if required.
1916 */
1917 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1918 check_response_for_cacheability(s, rep);
1919
1920 /*
1921 * Add server cookie in the response if needed
1922 */
1923 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1924 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1925 (!(s->flags & SF_DIRECT) ||
1926 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1927 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1928 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1929 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1930 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1931 !(s->flags & SF_IGNORE_PRST)) {
1932 /* the server is known, it's not the one the client requested, or the
1933 * cookie's last seen date needs to be refreshed. We have to
1934 * insert a set-cookie here, except if we want to insert only on POST
1935 * requests and this one isn't. Note that servers which don't have cookies
1936 * (eg: some backup servers) will return a full cookie removal request.
1937 */
1938 if (!objt_server(s->target)->cookie) {
1939 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001940 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001941 s->be->cookie_name);
1942 }
1943 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001944 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945
1946 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1947 /* emit last_date, which is mandatory */
1948 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1949 s30tob64((date.tv_sec+3) >> 2,
1950 trash.area + trash.data);
1951 trash.data += 5;
1952
1953 if (s->be->cookie_maxlife) {
1954 /* emit first_date, which is either the original one or
1955 * the current date.
1956 */
1957 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1958 s30tob64(txn->cookie_first_date ?
1959 txn->cookie_first_date >> 2 :
1960 (date.tv_sec+3) >> 2,
1961 trash.area + trash.data);
1962 trash.data += 5;
1963 }
1964 }
1965 chunk_appendf(&trash, "; path=/");
1966 }
1967
1968 if (s->be->cookie_domain)
1969 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1970
1971 if (s->be->ck_opts & PR_CK_HTTPONLY)
1972 chunk_appendf(&trash, "; HttpOnly");
1973
1974 if (s->be->ck_opts & PR_CK_SECURE)
1975 chunk_appendf(&trash, "; Secure");
1976
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001977 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001978 goto return_bad_resp;
1979
1980 txn->flags &= ~TX_SCK_MASK;
1981 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1982 /* the server did not change, only the date was updated */
1983 txn->flags |= TX_SCK_UPDATED;
1984 else
1985 txn->flags |= TX_SCK_INSERTED;
1986
1987 /* Here, we will tell an eventual cache on the client side that we don't
1988 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1989 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1990 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1991 */
1992 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1993
1994 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1995
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001996 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001997 goto return_bad_resp;
1998 }
1999 }
2000
2001 /*
2002 * Check if result will be cacheable with a cookie.
2003 * We'll block the response if security checks have caught
2004 * nasty things such as a cacheable cookie.
2005 */
2006 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2007 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2008 (s->be->options & PR_O_CHK_CACHE)) {
2009 /* we're in presence of a cacheable response containing
2010 * a set-cookie header. We'll block it as requested by
2011 * the 'checkcache' option, and send an alert.
2012 */
2013 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002014 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002015
Olivier Houcharda798bf52019-03-08 18:52:00 +01002016 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2017 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002018 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002019 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002020
2021 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2022 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2023 send_log(s->be, LOG_ALERT,
2024 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2025 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2026 goto return_srv_prx_502;
2027 }
2028
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002029 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002030 /* Always enter in the body analyzer */
2031 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2032 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2033
2034 /* if the user wants to log as soon as possible, without counting
2035 * bytes from the server, then this is the right moment. We have
2036 * to temporarily assign bytes_out to log what we currently have.
2037 */
2038 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2039 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002040 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002041 s->do_log(s);
2042 s->logs.bytes_out = 0;
2043 }
2044 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002045
2046 return_bad_resp:
2047 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002048 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002049 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002050 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002051 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002052
2053 return_srv_prx_502:
2054 rep->analysers &= AN_RES_FLT_END;
2055 txn->status = 502;
2056 s->logs.t_data = -1; /* was not a valid response */
2057 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002058 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002059 if (!(s->flags & SF_ERR_MASK))
2060 s->flags |= SF_ERR_PRXCOND;
2061 if (!(s->flags & SF_FINST_MASK))
2062 s->flags |= SF_FINST_H;
2063 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002064}
2065
2066/* This function is an analyser which forwards response body (including chunk
2067 * sizes if any). It is called as soon as we must forward, even if we forward
2068 * zero byte. The only situation where it must not be called is when we're in
2069 * tunnel mode and we want to forward till the close. It's used both to forward
2070 * remaining data and to resync after end of body. It expects the msg_state to
2071 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2072 * read more data, or 1 once we can go on with next request or end the stream.
2073 *
2074 * It is capable of compressing response data both in content-length mode and
2075 * in chunked mode. The state machines follows different flows depending on
2076 * whether content-length and chunked modes are used, since there are no
2077 * trailers in content-length :
2078 *
2079 * chk-mode cl-mode
2080 * ,----- BODY -----.
2081 * / \
2082 * V size > 0 V chk-mode
2083 * .--> SIZE -------------> DATA -------------> CRLF
2084 * | | size == 0 | last byte |
2085 * | v final crlf v inspected |
2086 * | TRAILERS -----------> DONE |
2087 * | |
2088 * `----------------------------------------------'
2089 *
2090 * Compression only happens in the DATA state, and must be flushed in final
2091 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2092 * is performed at once on final states for all bytes parsed, or when leaving
2093 * on missing data.
2094 */
2095int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2096{
2097 struct session *sess = s->sess;
2098 struct http_txn *txn = s->txn;
2099 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002100 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002101 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002102
2103 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2104 now_ms, __FUNCTION__,
2105 s,
2106 res,
2107 res->rex, res->wex,
2108 res->flags,
2109 ci_data(res),
2110 res->analysers);
2111
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002112 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002113
2114 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002115 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002116 /* Output closed while we were sending data. We must abort and
2117 * wake the other side up.
2118 */
2119 msg->err_state = msg->msg_state;
2120 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002121 htx_end_response(s);
2122 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123 return 1;
2124 }
2125
Christopher Faulet9768c262018-10-22 09:34:31 +02002126 if (msg->msg_state == HTTP_MSG_BODY)
2127 msg->msg_state = HTTP_MSG_DATA;
2128
Christopher Faulete0768eb2018-10-03 16:38:02 +02002129 /* in most states, we should abort in case of early close */
2130 channel_auto_close(res);
2131
Christopher Faulete0768eb2018-10-03 16:38:02 +02002132 if (res->to_forward) {
Willy Tarreau6e8d6a92019-03-21 18:00:30 +01002133 /* We can't process the buffer's contents yet */
2134 res->flags |= CF_WAKE_WRITE;
2135 goto missing_data_or_waiting;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 }
2137
Christopher Faulet9768c262018-10-22 09:34:31 +02002138 if (msg->msg_state >= HTTP_MSG_DONE)
2139 goto done;
2140
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002141 /* Forward input data. We get it by removing all outgoing data not
2142 * forwarded yet from HTX data size. If there are some data filters, we
2143 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002144 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002145 if (HAS_RSP_DATA_FILTERS(s)) {
2146 ret = flt_http_payload(s, msg, htx->data);
2147 if (ret < 0)
2148 goto return_bad_res;
2149 c_adv(res, ret);
2150 if (htx->data != co_data(res) || htx->extra)
2151 goto missing_data_or_waiting;
2152 }
2153 else {
2154 c_adv(res, htx->data - co_data(res));
Willy Tarreau6e8d6a92019-03-21 18:00:30 +01002155
2156 /* To let the function channel_forward work as expected we must update
2157 * the channel's buffer to pretend there is no more input data. The
2158 * right length is then restored. We must do that, because when an HTX
2159 * message is stored into a buffer, it appears as full.
2160 */
2161 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2162 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002163 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002164
2165 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2166 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002167 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002168 msg->msg_state = HTTP_MSG_TUNNEL;
2169 goto done;
2170 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002171 }
2172
Christopher Faulet9768c262018-10-22 09:34:31 +02002173 /* Check if the end-of-message is reached and if so, switch the message
2174 * in HTTP_MSG_DONE state.
2175 */
2176 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2177 goto missing_data_or_waiting;
2178
2179 msg->msg_state = HTTP_MSG_DONE;
2180
2181 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002182 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002183 channel_dont_close(res);
2184
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002185 if (HAS_RSP_DATA_FILTERS(s)) {
2186 ret = flt_http_end(s, msg);
2187 if (ret <= 0) {
2188 if (!ret)
2189 goto missing_data_or_waiting;
2190 goto return_bad_res;
2191 }
2192 }
2193
Christopher Fauletf2824e62018-10-01 12:12:37 +02002194 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002195 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002196 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2198 if (res->flags & CF_SHUTW) {
2199 /* response errors are most likely due to the
2200 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002201 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002202 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 goto return_bad_res;
2204 }
2205 return 1;
2206 }
2207 return 0;
2208
2209 missing_data_or_waiting:
2210 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002211 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212
Christopher Faulet47365272018-10-31 17:40:50 +01002213 if (htx->flags & HTX_FL_PARSING_ERROR)
2214 goto return_bad_res;
2215
Christopher Faulete0768eb2018-10-03 16:38:02 +02002216 /* stop waiting for data if the input is closed before the end. If the
2217 * client side was already closed, it means that the client has aborted,
2218 * so we don't want to count this as a server abort. Otherwise it's a
2219 * server abort.
2220 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002221 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002223 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002225 if (htx_is_empty(htx))
2226 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227 }
2228
Christopher Faulete0768eb2018-10-03 16:38:02 +02002229 /* When TE: chunked is used, we need to get there again to parse
2230 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002231 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2232 * are filters registered on the stream, we don't want to forward a
2233 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002235 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002236 channel_dont_close(res);
2237
2238 /* We know that more data are expected, but we couldn't send more that
2239 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2240 * system knows it must not set a PUSH on this first part. Interactive
2241 * modes are already handled by the stream sock layer. We must not do
2242 * this in content-length mode because it could present the MSG_MORE
2243 * flag with the last block of forwarded data, which would cause an
2244 * additional delay to be observed by the receiver.
2245 */
2246 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2247 res->flags |= CF_EXPECT_MORE;
2248
2249 /* the stream handler will take care of timeouts and errors */
2250 return 0;
2251
Christopher Faulet93e02d82019-03-08 14:18:50 +01002252 return_srv_abort:
2253 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2254 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002255 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002256 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2257 if (!(s->flags & SF_ERR_MASK))
2258 s->flags |= SF_ERR_SRVCL;
2259 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260
Christopher Faulet93e02d82019-03-08 14:18:50 +01002261 return_cli_abort:
2262 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2263 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002264 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002265 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2266 if (!(s->flags & SF_ERR_MASK))
2267 s->flags |= SF_ERR_CLICL;
2268 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269
Christopher Faulet93e02d82019-03-08 14:18:50 +01002270 return_bad_res:
2271 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2272 if (objt_server(s->target)) {
2273 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2274 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2275 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002277 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278
Christopher Faulet93e02d82019-03-08 14:18:50 +01002279 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 txn->rsp.err_state = txn->rsp.msg_state;
2281 txn->rsp.msg_state = HTTP_MSG_ERROR;
2282 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002283 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 res->analysers &= AN_RES_FLT_END;
2285 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 +02002286 if (!(s->flags & SF_FINST_MASK))
2287 s->flags |= SF_FINST_D;
2288 return 0;
2289}
2290
Christopher Faulet0f226952018-10-22 09:29:56 +02002291void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002292{
2293 struct proxy *fe = strm_fe(s);
2294 int tmp = TX_CON_WANT_CLO;
2295
2296 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2297 tmp = TX_CON_WANT_TUN;
2298
2299 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002300 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002301}
2302
2303/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002304 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002305 * as too large a request to build a valid response.
2306 */
2307int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2308{
Christopher Faulet99daf282018-11-28 22:58:13 +01002309 struct channel *req = &s->req;
2310 struct channel *res = &s->res;
2311 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002312 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002313 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002314 struct ist status, reason, location;
2315 unsigned int flags;
2316 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002317
2318 chunk = alloc_trash_chunk();
2319 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002320 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002321
Christopher Faulet99daf282018-11-28 22:58:13 +01002322 /*
2323 * Create the location
2324 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002325 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002326 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002327 case REDIRECT_TYPE_SCHEME: {
2328 struct http_hdr_ctx ctx;
2329 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002330
Christopher Faulet99daf282018-11-28 22:58:13 +01002331 host = ist("");
2332 ctx.blk = NULL;
2333 if (http_find_header(htx, ist("Host"), &ctx, 0))
2334 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002335
Christopher Faulet99daf282018-11-28 22:58:13 +01002336 sl = http_find_stline(htx);
2337 path = http_get_path(htx_sl_req_uri(sl));
2338 /* build message using path */
2339 if (path.ptr) {
2340 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2341 int qs = 0;
2342 while (qs < path.len) {
2343 if (*(path.ptr + qs) == '?') {
2344 path.len = qs;
2345 break;
2346 }
2347 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002348 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002349 }
2350 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 else
2352 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353
Christopher Faulet99daf282018-11-28 22:58:13 +01002354 if (rule->rdr_str) { /* this is an old "redirect" rule */
2355 /* add scheme */
2356 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2357 goto fail;
2358 }
2359 else {
2360 /* add scheme with executing log format */
2361 chunk->data += build_logline(s, chunk->area + chunk->data,
2362 chunk->size - chunk->data,
2363 &rule->rdr_fmt);
2364 }
2365 /* add "://" + host + path */
2366 if (!chunk_memcat(chunk, "://", 3) ||
2367 !chunk_memcat(chunk, host.ptr, host.len) ||
2368 !chunk_memcat(chunk, path.ptr, path.len))
2369 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002370
Christopher Faulet99daf282018-11-28 22:58:13 +01002371 /* append a slash at the end of the location if needed and missing */
2372 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2373 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2374 if (chunk->data + 1 >= chunk->size)
2375 goto fail;
2376 chunk->area[chunk->data++] = '/';
2377 }
2378 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002380
Christopher Faulet99daf282018-11-28 22:58:13 +01002381 case REDIRECT_TYPE_PREFIX: {
2382 struct ist path;
2383
2384 sl = http_find_stline(htx);
2385 path = http_get_path(htx_sl_req_uri(sl));
2386 /* build message using path */
2387 if (path.ptr) {
2388 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2389 int qs = 0;
2390 while (qs < path.len) {
2391 if (*(path.ptr + qs) == '?') {
2392 path.len = qs;
2393 break;
2394 }
2395 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002396 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 }
2398 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002399 else
2400 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401
Christopher Faulet99daf282018-11-28 22:58:13 +01002402 if (rule->rdr_str) { /* this is an old "redirect" rule */
2403 /* add prefix. Note that if prefix == "/", we don't want to
2404 * add anything, otherwise it makes it hard for the user to
2405 * configure a self-redirection.
2406 */
2407 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2408 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2409 goto fail;
2410 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 else {
2413 /* add prefix with executing log format */
2414 chunk->data += build_logline(s, chunk->area + chunk->data,
2415 chunk->size - chunk->data,
2416 &rule->rdr_fmt);
2417 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 /* add path */
2420 if (!chunk_memcat(chunk, path.ptr, path.len))
2421 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 /* append a slash at the end of the location if needed and missing */
2424 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2425 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2426 if (chunk->data + 1 >= chunk->size)
2427 goto fail;
2428 chunk->area[chunk->data++] = '/';
2429 }
2430 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002431 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002432 case REDIRECT_TYPE_LOCATION:
2433 default:
2434 if (rule->rdr_str) { /* this is an old "redirect" rule */
2435 /* add location */
2436 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2437 goto fail;
2438 }
2439 else {
2440 /* add location with executing log format */
2441 chunk->data += build_logline(s, chunk->area + chunk->data,
2442 chunk->size - chunk->data,
2443 &rule->rdr_fmt);
2444 }
2445 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 location = ist2(chunk->area, chunk->data);
2448
2449 /*
2450 * Create the 30x response
2451 */
2452 switch (rule->code) {
2453 case 308:
2454 status = ist("308");
2455 reason = ist("Permanent Redirect");
2456 break;
2457 case 307:
2458 status = ist("307");
2459 reason = ist("Temporary Redirect");
2460 break;
2461 case 303:
2462 status = ist("303");
2463 reason = ist("See Other");
2464 break;
2465 case 301:
2466 status = ist("301");
2467 reason = ist("Moved Permanently");
2468 break;
2469 case 302:
2470 default:
2471 status = ist("302");
2472 reason = ist("Found");
2473 break;
2474 }
2475
2476 htx = htx_from_buf(&res->buf);
2477 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2478 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2479 if (!sl)
2480 goto fail;
2481 sl->info.res.status = rule->code;
2482 s->txn->status = rule->code;
2483
2484 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2485 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2486 !htx_add_header(htx, ist("Location"), location))
2487 goto fail;
2488
2489 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2490 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2491 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002492 }
2493
2494 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002495 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2496 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002497 }
2498
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2500 goto fail;
2501
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 /* let's log the request time */
2503 s->logs.tv_request = now;
2504
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002506 c_adv(res, data);
2507 res->total += data;
2508
2509 channel_auto_read(req);
2510 channel_abort(req);
2511 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002512 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002513
2514 res->wex = tick_add_ifset(now_ms, res->wto);
2515 channel_auto_read(res);
2516 channel_auto_close(res);
2517 channel_shutr_now(res);
2518
2519 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002520
2521 if (!(s->flags & SF_ERR_MASK))
2522 s->flags |= SF_ERR_LOCAL;
2523 if (!(s->flags & SF_FINST_MASK))
2524 s->flags |= SF_FINST_R;
2525
Christopher Faulet99daf282018-11-28 22:58:13 +01002526 free_trash_chunk(chunk);
2527 return 1;
2528
2529 fail:
2530 /* If an error occurred, remove the incomplete HTTP response from the
2531 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002532 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002533 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002534 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002535}
2536
Christopher Faulet72333522018-10-24 11:25:02 +02002537int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2538 struct ist name, const char *str, struct my_regex *re, int action)
2539{
2540 struct http_hdr_ctx ctx;
2541 struct buffer *output = get_trash_chunk();
2542
2543 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2544 ctx.blk = NULL;
2545 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2546 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2547 continue;
2548
2549 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2550 if (output->data == -1)
2551 return -1;
2552 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2553 return -1;
2554 }
2555 return 0;
2556}
2557
2558static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2559 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2560{
2561 struct buffer *replace;
2562 int ret = -1;
2563
2564 replace = alloc_trash_chunk();
2565 if (!replace)
2566 goto leave;
2567
2568 replace->data = build_logline(s, replace->area, replace->size, fmt);
2569 if (replace->data >= replace->size - 1)
2570 goto leave;
2571
2572 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2573
2574 leave:
2575 free_trash_chunk(replace);
2576 return ret;
2577}
2578
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002579
2580/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2581 * on success and -1 on error. The response channel is updated accordingly.
2582 */
2583static int htx_reply_103_early_hints(struct channel *res)
2584{
2585 struct htx *htx = htx_from_buf(&res->buf);
2586 size_t data;
2587
2588 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2589 /* If an error occurred during an Early-hint rule,
2590 * remove the incomplete HTTP 103 response from the
2591 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002592 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002593 return -1;
2594 }
2595
2596 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002597 c_adv(res, data);
2598 res->total += data;
2599 return 0;
2600}
2601
Christopher Faulet6eb92892018-11-15 16:39:29 +01002602/*
2603 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2604 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002605 * If <early_hints> is 0, it is starts a new response by adding the start
2606 * line. If an error occurred -1 is returned. On success 0 is returned. The
2607 * channel is not updated here. It must be done calling the function
2608 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002609 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002610static 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 +01002611{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002612 struct channel *res = &s->res;
2613 struct htx *htx = htx_from_buf(&res->buf);
2614 struct buffer *value = alloc_trash_chunk();
2615
Christopher Faulet6eb92892018-11-15 16:39:29 +01002616 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002617 struct htx_sl *sl;
2618 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2619 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2620
2621 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2622 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2623 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002624 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002625 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002626 }
2627
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002628 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2629 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002630 goto fail;
2631
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002632 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002633 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634
2635 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636 /* If an error occurred during an Early-hint rule, remove the incomplete
2637 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002638 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002639 free_trash_chunk(value);
2640 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002641}
2642
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002643/* This function executes one of the set-{method,path,query,uri} actions. It
2644 * takes the string from the variable 'replace' with length 'len', then modifies
2645 * the relevant part of the request line accordingly. Then it updates various
2646 * pointers to the next elements which were moved, and the total buffer length.
2647 * It finds the action to be performed in p[2], previously filled by function
2648 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2649 * error, though this can be revisited when this code is finally exploited.
2650 *
2651 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2652 * query string and 3 to replace uri.
2653 *
2654 * In query string case, the mark question '?' must be set at the start of the
2655 * string by the caller, event if the replacement query string is empty.
2656 */
2657int htx_req_replace_stline(int action, const char *replace, int len,
2658 struct proxy *px, struct stream *s)
2659{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002660 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002661
2662 switch (action) {
2663 case 0: // method
2664 if (!http_replace_req_meth(htx, ist2(replace, len)))
2665 return -1;
2666 break;
2667
2668 case 1: // path
2669 if (!http_replace_req_path(htx, ist2(replace, len)))
2670 return -1;
2671 break;
2672
2673 case 2: // query
2674 if (!http_replace_req_query(htx, ist2(replace, len)))
2675 return -1;
2676 break;
2677
2678 case 3: // uri
2679 if (!http_replace_req_uri(htx, ist2(replace, len)))
2680 return -1;
2681 break;
2682
2683 default:
2684 return -1;
2685 }
2686 return 0;
2687}
2688
2689/* This function replace the HTTP status code and the associated message. The
2690 * variable <status> contains the new status code. This function never fails.
2691 */
2692void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2693{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002694 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002695 char *res;
2696
2697 chunk_reset(&trash);
2698 res = ultoa_o(status, trash.area, trash.size);
2699 trash.data = res - trash.area;
2700
2701 /* Do we have a custom reason format string? */
2702 if (reason == NULL)
2703 reason = http_get_reason(status);
2704
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002705 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002706 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2707}
2708
Christopher Faulet3e964192018-10-24 11:39:23 +02002709/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2710 * transaction <txn>. Returns the verdict of the first rule that prevents
2711 * further processing of the request (auth, deny, ...), and defaults to
2712 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2713 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2714 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2715 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2716 * status.
2717 */
2718static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2719 struct stream *s, int *deny_status)
2720{
2721 struct session *sess = strm_sess(s);
2722 struct http_txn *txn = s->txn;
2723 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002724 struct act_rule *rule;
2725 struct http_hdr_ctx ctx;
2726 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002727 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2728 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002729 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002730
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002731 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002732
2733 /* If "the current_rule_list" match the executed rule list, we are in
2734 * resume condition. If a resume is needed it is always in the action
2735 * and never in the ACL or converters. In this case, we initialise the
2736 * current rule, and go to the action execution point.
2737 */
2738 if (s->current_rule) {
2739 rule = s->current_rule;
2740 s->current_rule = NULL;
2741 if (s->current_rule_list == rules)
2742 goto resume_execution;
2743 }
2744 s->current_rule_list = rules;
2745
2746 list_for_each_entry(rule, rules, list) {
2747 /* check optional condition */
2748 if (rule->cond) {
2749 int ret;
2750
2751 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2752 ret = acl_pass(ret);
2753
2754 if (rule->cond->pol == ACL_COND_UNLESS)
2755 ret = !ret;
2756
2757 if (!ret) /* condition not matched */
2758 continue;
2759 }
2760
2761 act_flags |= ACT_FLAG_FIRST;
2762 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002763 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2764 early_hints = 0;
2765 if (htx_reply_103_early_hints(&s->res) == -1) {
2766 rule_ret = HTTP_RULE_RES_BADREQ;
2767 goto end;
2768 }
2769 }
2770
Christopher Faulet3e964192018-10-24 11:39:23 +02002771 switch (rule->action) {
2772 case ACT_ACTION_ALLOW:
2773 rule_ret = HTTP_RULE_RES_STOP;
2774 goto end;
2775
2776 case ACT_ACTION_DENY:
2777 if (deny_status)
2778 *deny_status = rule->deny_status;
2779 rule_ret = HTTP_RULE_RES_DENY;
2780 goto end;
2781
2782 case ACT_HTTP_REQ_TARPIT:
2783 txn->flags |= TX_CLTARPIT;
2784 if (deny_status)
2785 *deny_status = rule->deny_status;
2786 rule_ret = HTTP_RULE_RES_DENY;
2787 goto end;
2788
2789 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002790 /* Auth might be performed on regular http-req rules as well as on stats */
2791 auth_realm = rule->arg.auth.realm;
2792 if (!auth_realm) {
2793 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2794 auth_realm = STATS_DEFAULT_REALM;
2795 else
2796 auth_realm = px->id;
2797 }
2798 /* send 401/407 depending on whether we use a proxy or not. We still
2799 * count one error, because normal browsing won't significantly
2800 * increase the counter but brute force attempts will.
2801 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002802 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002803 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2804 rule_ret = HTTP_RULE_RES_BADREQ;
2805 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002806 goto end;
2807
2808 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002809 rule_ret = HTTP_RULE_RES_DONE;
2810 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2811 rule_ret = HTTP_RULE_RES_BADREQ;
2812 goto end;
2813
2814 case ACT_HTTP_SET_NICE:
2815 s->task->nice = rule->arg.nice;
2816 break;
2817
2818 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002819 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002820 break;
2821
2822 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002823 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 break;
2825
2826 case ACT_HTTP_SET_LOGL:
2827 s->logs.level = rule->arg.loglevel;
2828 break;
2829
2830 case ACT_HTTP_REPLACE_HDR:
2831 case ACT_HTTP_REPLACE_VAL:
2832 if (htx_transform_header(s, &s->req, htx,
2833 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2834 &rule->arg.hdr_add.fmt,
2835 &rule->arg.hdr_add.re, rule->action)) {
2836 rule_ret = HTTP_RULE_RES_BADREQ;
2837 goto end;
2838 }
2839 break;
2840
2841 case ACT_HTTP_DEL_HDR:
2842 /* remove all occurrences of the header */
2843 ctx.blk = NULL;
2844 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2845 http_remove_header(htx, &ctx);
2846 break;
2847
2848 case ACT_HTTP_SET_HDR:
2849 case ACT_HTTP_ADD_HDR: {
2850 /* The scope of the trash buffer must be limited to this function. The
2851 * build_logline() function can execute a lot of other function which
2852 * can use the trash buffer. So for limiting the scope of this global
2853 * buffer, we build first the header value using build_logline, and
2854 * after we store the header name.
2855 */
2856 struct buffer *replace;
2857 struct ist n, v;
2858
2859 replace = alloc_trash_chunk();
2860 if (!replace) {
2861 rule_ret = HTTP_RULE_RES_BADREQ;
2862 goto end;
2863 }
2864
2865 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2866 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2867 v = ist2(replace->area, replace->data);
2868
2869 if (rule->action == ACT_HTTP_SET_HDR) {
2870 /* remove all occurrences of the header */
2871 ctx.blk = NULL;
2872 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2873 http_remove_header(htx, &ctx);
2874 }
2875
2876 if (!http_add_header(htx, n, v)) {
2877 static unsigned char rate_limit = 0;
2878
2879 if ((rate_limit++ & 255) == 0) {
2880 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);
2881 }
2882
Olivier Houcharda798bf52019-03-08 18:52:00 +01002883 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002884 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002885 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002886 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002887 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002888 }
2889 free_trash_chunk(replace);
2890 break;
2891 }
2892
2893 case ACT_HTTP_DEL_ACL:
2894 case ACT_HTTP_DEL_MAP: {
2895 struct pat_ref *ref;
2896 struct buffer *key;
2897
2898 /* collect reference */
2899 ref = pat_ref_lookup(rule->arg.map.ref);
2900 if (!ref)
2901 continue;
2902
2903 /* allocate key */
2904 key = alloc_trash_chunk();
2905 if (!key) {
2906 rule_ret = HTTP_RULE_RES_BADREQ;
2907 goto end;
2908 }
2909
2910 /* collect key */
2911 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2912 key->area[key->data] = '\0';
2913
2914 /* perform update */
2915 /* returned code: 1=ok, 0=ko */
2916 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2917 pat_ref_delete(ref, key->area);
2918 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2919
2920 free_trash_chunk(key);
2921 break;
2922 }
2923
2924 case ACT_HTTP_ADD_ACL: {
2925 struct pat_ref *ref;
2926 struct buffer *key;
2927
2928 /* collect reference */
2929 ref = pat_ref_lookup(rule->arg.map.ref);
2930 if (!ref)
2931 continue;
2932
2933 /* allocate key */
2934 key = alloc_trash_chunk();
2935 if (!key) {
2936 rule_ret = HTTP_RULE_RES_BADREQ;
2937 goto end;
2938 }
2939
2940 /* collect key */
2941 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2942 key->area[key->data] = '\0';
2943
2944 /* perform update */
2945 /* add entry only if it does not already exist */
2946 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2947 if (pat_ref_find_elt(ref, key->area) == NULL)
2948 pat_ref_add(ref, key->area, NULL, NULL);
2949 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2950
2951 free_trash_chunk(key);
2952 break;
2953 }
2954
2955 case ACT_HTTP_SET_MAP: {
2956 struct pat_ref *ref;
2957 struct buffer *key, *value;
2958
2959 /* collect reference */
2960 ref = pat_ref_lookup(rule->arg.map.ref);
2961 if (!ref)
2962 continue;
2963
2964 /* allocate key */
2965 key = alloc_trash_chunk();
2966 if (!key) {
2967 rule_ret = HTTP_RULE_RES_BADREQ;
2968 goto end;
2969 }
2970
2971 /* allocate value */
2972 value = alloc_trash_chunk();
2973 if (!value) {
2974 free_trash_chunk(key);
2975 rule_ret = HTTP_RULE_RES_BADREQ;
2976 goto end;
2977 }
2978
2979 /* collect key */
2980 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2981 key->area[key->data] = '\0';
2982
2983 /* collect value */
2984 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2985 value->area[value->data] = '\0';
2986
2987 /* perform update */
2988 if (pat_ref_find_elt(ref, key->area) != NULL)
2989 /* update entry if it exists */
2990 pat_ref_set(ref, key->area, value->area, NULL);
2991 else
2992 /* insert a new entry */
2993 pat_ref_add(ref, key->area, value->area, NULL);
2994
2995 free_trash_chunk(key);
2996 free_trash_chunk(value);
2997 break;
2998 }
2999
3000 case ACT_HTTP_EARLY_HINT:
3001 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3002 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003003 early_hints = htx_add_early_hint_header(s, early_hints,
3004 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003005 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003006 if (early_hints == -1) {
3007 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003008 goto end;
3009 }
3010 break;
3011
3012 case ACT_CUSTOM:
3013 if ((s->req.flags & CF_READ_ERROR) ||
3014 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3015 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3016 (px->options & PR_O_ABRT_CLOSE)))
3017 act_flags |= ACT_FLAG_FINAL;
3018
3019 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3020 case ACT_RET_ERR:
3021 case ACT_RET_CONT:
3022 break;
3023 case ACT_RET_STOP:
3024 rule_ret = HTTP_RULE_RES_DONE;
3025 goto end;
3026 case ACT_RET_YIELD:
3027 s->current_rule = rule;
3028 rule_ret = HTTP_RULE_RES_YIELD;
3029 goto end;
3030 }
3031 break;
3032
3033 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3034 /* Note: only the first valid tracking parameter of each
3035 * applies.
3036 */
3037
3038 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3039 struct stktable *t;
3040 struct stksess *ts;
3041 struct stktable_key *key;
3042 void *ptr1, *ptr2;
3043
3044 t = rule->arg.trk_ctr.table.t;
3045 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3046 rule->arg.trk_ctr.expr, NULL);
3047
3048 if (key && (ts = stktable_get_entry(t, key))) {
3049 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3050
3051 /* let's count a new HTTP request as it's the first time we do it */
3052 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3053 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3054 if (ptr1 || ptr2) {
3055 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3056
3057 if (ptr1)
3058 stktable_data_cast(ptr1, http_req_cnt)++;
3059
3060 if (ptr2)
3061 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3062 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3063
3064 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3065
3066 /* If data was modified, we need to touch to re-schedule sync */
3067 stktable_touch_local(t, ts, 0);
3068 }
3069
3070 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3071 if (sess->fe != s->be)
3072 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3073 }
3074 }
3075 break;
3076
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003077 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003078 default:
3079 break;
3080 }
3081 }
3082
3083 end:
3084 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003085 if (htx_reply_103_early_hints(&s->res) == -1)
3086 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003087 }
3088
3089 /* we reached the end of the rules, nothing to report */
3090 return rule_ret;
3091}
3092
3093/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3094 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3095 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3096 * is returned, the process can continue the evaluation of next rule list. If
3097 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3098 * is returned, it means the operation could not be processed and a server error
3099 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3100 * deny rule. If *YIELD is returned, the caller must call again the function
3101 * with the same context.
3102 */
3103static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3104 struct stream *s)
3105{
3106 struct session *sess = strm_sess(s);
3107 struct http_txn *txn = s->txn;
3108 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003109 struct act_rule *rule;
3110 struct http_hdr_ctx ctx;
3111 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3112 int act_flags = 0;
3113
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003114 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003115
3116 /* If "the current_rule_list" match the executed rule list, we are in
3117 * resume condition. If a resume is needed it is always in the action
3118 * and never in the ACL or converters. In this case, we initialise the
3119 * current rule, and go to the action execution point.
3120 */
3121 if (s->current_rule) {
3122 rule = s->current_rule;
3123 s->current_rule = NULL;
3124 if (s->current_rule_list == rules)
3125 goto resume_execution;
3126 }
3127 s->current_rule_list = rules;
3128
3129 list_for_each_entry(rule, rules, list) {
3130 /* check optional condition */
3131 if (rule->cond) {
3132 int ret;
3133
3134 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3135 ret = acl_pass(ret);
3136
3137 if (rule->cond->pol == ACL_COND_UNLESS)
3138 ret = !ret;
3139
3140 if (!ret) /* condition not matched */
3141 continue;
3142 }
3143
3144 act_flags |= ACT_FLAG_FIRST;
3145resume_execution:
3146 switch (rule->action) {
3147 case ACT_ACTION_ALLOW:
3148 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3149 goto end;
3150
3151 case ACT_ACTION_DENY:
3152 txn->flags |= TX_SVDENY;
3153 rule_ret = HTTP_RULE_RES_STOP;
3154 goto end;
3155
3156 case ACT_HTTP_SET_NICE:
3157 s->task->nice = rule->arg.nice;
3158 break;
3159
3160 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003161 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003162 break;
3163
3164 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003165 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003166 break;
3167
3168 case ACT_HTTP_SET_LOGL:
3169 s->logs.level = rule->arg.loglevel;
3170 break;
3171
3172 case ACT_HTTP_REPLACE_HDR:
3173 case ACT_HTTP_REPLACE_VAL:
3174 if (htx_transform_header(s, &s->res, htx,
3175 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3176 &rule->arg.hdr_add.fmt,
3177 &rule->arg.hdr_add.re, rule->action)) {
3178 rule_ret = HTTP_RULE_RES_BADREQ;
3179 goto end;
3180 }
3181 break;
3182
3183 case ACT_HTTP_DEL_HDR:
3184 /* remove all occurrences of the header */
3185 ctx.blk = NULL;
3186 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3187 http_remove_header(htx, &ctx);
3188 break;
3189
3190 case ACT_HTTP_SET_HDR:
3191 case ACT_HTTP_ADD_HDR: {
3192 struct buffer *replace;
3193 struct ist n, v;
3194
3195 replace = alloc_trash_chunk();
3196 if (!replace) {
3197 rule_ret = HTTP_RULE_RES_BADREQ;
3198 goto end;
3199 }
3200
3201 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3202 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3203 v = ist2(replace->area, replace->data);
3204
3205 if (rule->action == ACT_HTTP_SET_HDR) {
3206 /* remove all occurrences of the header */
3207 ctx.blk = NULL;
3208 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3209 http_remove_header(htx, &ctx);
3210 }
3211
3212 if (!http_add_header(htx, n, v)) {
3213 static unsigned char rate_limit = 0;
3214
3215 if ((rate_limit++ & 255) == 0) {
3216 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);
3217 }
3218
Olivier Houcharda798bf52019-03-08 18:52:00 +01003219 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003220 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003221 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003223 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003224 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003225 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003226 }
3227 free_trash_chunk(replace);
3228 break;
3229 }
3230
3231 case ACT_HTTP_DEL_ACL:
3232 case ACT_HTTP_DEL_MAP: {
3233 struct pat_ref *ref;
3234 struct buffer *key;
3235
3236 /* collect reference */
3237 ref = pat_ref_lookup(rule->arg.map.ref);
3238 if (!ref)
3239 continue;
3240
3241 /* allocate key */
3242 key = alloc_trash_chunk();
3243 if (!key) {
3244 rule_ret = HTTP_RULE_RES_BADREQ;
3245 goto end;
3246 }
3247
3248 /* collect key */
3249 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3250 key->area[key->data] = '\0';
3251
3252 /* perform update */
3253 /* returned code: 1=ok, 0=ko */
3254 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3255 pat_ref_delete(ref, key->area);
3256 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3257
3258 free_trash_chunk(key);
3259 break;
3260 }
3261
3262 case ACT_HTTP_ADD_ACL: {
3263 struct pat_ref *ref;
3264 struct buffer *key;
3265
3266 /* collect reference */
3267 ref = pat_ref_lookup(rule->arg.map.ref);
3268 if (!ref)
3269 continue;
3270
3271 /* allocate key */
3272 key = alloc_trash_chunk();
3273 if (!key) {
3274 rule_ret = HTTP_RULE_RES_BADREQ;
3275 goto end;
3276 }
3277
3278 /* collect key */
3279 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3280 key->area[key->data] = '\0';
3281
3282 /* perform update */
3283 /* check if the entry already exists */
3284 if (pat_ref_find_elt(ref, key->area) == NULL)
3285 pat_ref_add(ref, key->area, NULL, NULL);
3286
3287 free_trash_chunk(key);
3288 break;
3289 }
3290
3291 case ACT_HTTP_SET_MAP: {
3292 struct pat_ref *ref;
3293 struct buffer *key, *value;
3294
3295 /* collect reference */
3296 ref = pat_ref_lookup(rule->arg.map.ref);
3297 if (!ref)
3298 continue;
3299
3300 /* allocate key */
3301 key = alloc_trash_chunk();
3302 if (!key) {
3303 rule_ret = HTTP_RULE_RES_BADREQ;
3304 goto end;
3305 }
3306
3307 /* allocate value */
3308 value = alloc_trash_chunk();
3309 if (!value) {
3310 free_trash_chunk(key);
3311 rule_ret = HTTP_RULE_RES_BADREQ;
3312 goto end;
3313 }
3314
3315 /* collect key */
3316 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3317 key->area[key->data] = '\0';
3318
3319 /* collect value */
3320 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3321 value->area[value->data] = '\0';
3322
3323 /* perform update */
3324 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3325 if (pat_ref_find_elt(ref, key->area) != NULL)
3326 /* update entry if it exists */
3327 pat_ref_set(ref, key->area, value->area, NULL);
3328 else
3329 /* insert a new entry */
3330 pat_ref_add(ref, key->area, value->area, NULL);
3331 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3332 free_trash_chunk(key);
3333 free_trash_chunk(value);
3334 break;
3335 }
3336
3337 case ACT_HTTP_REDIR:
3338 rule_ret = HTTP_RULE_RES_DONE;
3339 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3340 rule_ret = HTTP_RULE_RES_BADREQ;
3341 goto end;
3342
3343 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3344 /* Note: only the first valid tracking parameter of each
3345 * applies.
3346 */
3347 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3348 struct stktable *t;
3349 struct stksess *ts;
3350 struct stktable_key *key;
3351 void *ptr;
3352
3353 t = rule->arg.trk_ctr.table.t;
3354 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3355 rule->arg.trk_ctr.expr, NULL);
3356
3357 if (key && (ts = stktable_get_entry(t, key))) {
3358 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3359
3360 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3361
3362 /* let's count a new HTTP request as it's the first time we do it */
3363 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3364 if (ptr)
3365 stktable_data_cast(ptr, http_req_cnt)++;
3366
3367 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3368 if (ptr)
3369 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3370 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3371
3372 /* When the client triggers a 4xx from the server, it's most often due
3373 * to a missing object or permission. These events should be tracked
3374 * because if they happen often, it may indicate a brute force or a
3375 * vulnerability scan. Normally this is done when receiving the response
3376 * but here we're tracking after this ought to have been done so we have
3377 * to do it on purpose.
3378 */
3379 if ((unsigned)(txn->status - 400) < 100) {
3380 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3381 if (ptr)
3382 stktable_data_cast(ptr, http_err_cnt)++;
3383
3384 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3385 if (ptr)
3386 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3387 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3388 }
3389
3390 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3391
3392 /* If data was modified, we need to touch to re-schedule sync */
3393 stktable_touch_local(t, ts, 0);
3394
3395 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3396 if (sess->fe != s->be)
3397 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3398 }
3399 }
3400 break;
3401
3402 case ACT_CUSTOM:
3403 if ((s->req.flags & CF_READ_ERROR) ||
3404 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3405 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3406 (px->options & PR_O_ABRT_CLOSE)))
3407 act_flags |= ACT_FLAG_FINAL;
3408
3409 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3410 case ACT_RET_ERR:
3411 case ACT_RET_CONT:
3412 break;
3413 case ACT_RET_STOP:
3414 rule_ret = HTTP_RULE_RES_STOP;
3415 goto end;
3416 case ACT_RET_YIELD:
3417 s->current_rule = rule;
3418 rule_ret = HTTP_RULE_RES_YIELD;
3419 goto end;
3420 }
3421 break;
3422
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003423 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003424 default:
3425 break;
3426 }
3427 }
3428
3429 end:
3430 /* we reached the end of the rules, nothing to report */
3431 return rule_ret;
3432}
3433
Christopher Faulet33640082018-10-24 11:53:01 +02003434/* Iterate the same filter through all request headers.
3435 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3436 * Since it can manage the switch to another backend, it updates the per-proxy
3437 * DENY stats.
3438 */
3439static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3440{
3441 struct http_txn *txn = s->txn;
3442 struct htx *htx;
3443 struct buffer *hdr = get_trash_chunk();
3444 int32_t pos;
3445
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003446 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003447
3448 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3449 struct htx_blk *blk = htx_get_blk(htx, pos);
3450 enum htx_blk_type type;
3451 struct ist n, v;
3452
3453 next_hdr:
3454 type = htx_get_blk_type(blk);
3455 if (type == HTX_BLK_EOH)
3456 break;
3457 if (type != HTX_BLK_HDR)
3458 continue;
3459
3460 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3461 return 1;
3462 else if (unlikely(txn->flags & TX_CLALLOW) &&
3463 (exp->action == ACT_ALLOW ||
3464 exp->action == ACT_DENY ||
3465 exp->action == ACT_TARPIT))
3466 return 0;
3467
3468 n = htx_get_blk_name(htx, blk);
3469 v = htx_get_blk_value(htx, blk);
3470
Christopher Faulet02e771a2019-02-26 15:36:05 +01003471 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003472 hdr->area[hdr->data++] = ':';
3473 hdr->area[hdr->data++] = ' ';
3474 chunk_memcat(hdr, v.ptr, v.len);
3475
3476 /* Now we have one header in <hdr> */
3477
3478 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3479 struct http_hdr_ctx ctx;
3480 int len;
3481
3482 switch (exp->action) {
3483 case ACT_ALLOW:
3484 txn->flags |= TX_CLALLOW;
3485 goto end;
3486
3487 case ACT_DENY:
3488 txn->flags |= TX_CLDENY;
3489 goto end;
3490
3491 case ACT_TARPIT:
3492 txn->flags |= TX_CLTARPIT;
3493 goto end;
3494
3495 case ACT_REPLACE:
3496 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3497 if (len < 0)
3498 return -1;
3499
3500 http_parse_header(ist2(trash.area, len), &n, &v);
3501 ctx.blk = blk;
3502 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003503 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003504 if (!http_replace_header(htx, &ctx, n, v))
3505 return -1;
3506 if (!ctx.blk)
3507 goto end;
3508 pos = htx_get_blk_pos(htx, blk);
3509 break;
3510
3511 case ACT_REMOVE:
3512 ctx.blk = blk;
3513 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003514 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003515 if (!http_remove_header(htx, &ctx))
3516 return -1;
3517 if (!ctx.blk)
3518 goto end;
3519 pos = htx_get_blk_pos(htx, blk);
3520 goto next_hdr;
3521
3522 }
3523 }
3524 }
3525 end:
3526 return 0;
3527}
3528
3529/* Apply the filter to the request line.
3530 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3531 * or -1 if a replacement resulted in an invalid request line.
3532 * Since it can manage the switch to another backend, it updates the per-proxy
3533 * DENY stats.
3534 */
3535static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3536{
3537 struct http_txn *txn = s->txn;
3538 struct htx *htx;
3539 struct buffer *reqline = get_trash_chunk();
3540 int done;
3541
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003542 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003543
3544 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3545 return 1;
3546 else if (unlikely(txn->flags & TX_CLALLOW) &&
3547 (exp->action == ACT_ALLOW ||
3548 exp->action == ACT_DENY ||
3549 exp->action == ACT_TARPIT))
3550 return 0;
3551 else if (exp->action == ACT_REMOVE)
3552 return 0;
3553
3554 done = 0;
3555
3556 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3557
3558 /* Now we have the request line between cur_ptr and cur_end */
3559 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003560 struct htx_sl *sl = http_find_stline(htx);
3561 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003562 int len;
3563
3564 switch (exp->action) {
3565 case ACT_ALLOW:
3566 txn->flags |= TX_CLALLOW;
3567 done = 1;
3568 break;
3569
3570 case ACT_DENY:
3571 txn->flags |= TX_CLDENY;
3572 done = 1;
3573 break;
3574
3575 case ACT_TARPIT:
3576 txn->flags |= TX_CLTARPIT;
3577 done = 1;
3578 break;
3579
3580 case ACT_REPLACE:
3581 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3582 if (len < 0)
3583 return -1;
3584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003585 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3586 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3587 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003588 return -1;
3589 done = 1;
3590 break;
3591 }
3592 }
3593 return done;
3594}
3595
3596/*
3597 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3598 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3599 * unparsable request. Since it can manage the switch to another backend, it
3600 * updates the per-proxy DENY stats.
3601 */
3602static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3603{
3604 struct session *sess = s->sess;
3605 struct http_txn *txn = s->txn;
3606 struct hdr_exp *exp;
3607
3608 for (exp = px->req_exp; exp; exp = exp->next) {
3609 int ret;
3610
3611 /*
3612 * The interleaving of transformations and verdicts
3613 * makes it difficult to decide to continue or stop
3614 * the evaluation.
3615 */
3616
3617 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3618 break;
3619
3620 if ((txn->flags & TX_CLALLOW) &&
3621 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3622 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3623 continue;
3624
3625 /* if this filter had a condition, evaluate it now and skip to
3626 * next filter if the condition does not match.
3627 */
3628 if (exp->cond) {
3629 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3630 ret = acl_pass(ret);
3631 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3632 ret = !ret;
3633
3634 if (!ret)
3635 continue;
3636 }
3637
3638 /* Apply the filter to the request line. */
3639 ret = htx_apply_filter_to_req_line(s, req, exp);
3640 if (unlikely(ret < 0))
3641 return -1;
3642
3643 if (likely(ret == 0)) {
3644 /* The filter did not match the request, it can be
3645 * iterated through all headers.
3646 */
3647 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3648 return -1;
3649 }
3650 }
3651 return 0;
3652}
3653
3654/* Iterate the same filter through all response headers contained in <res>.
3655 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3656 */
3657static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3658{
3659 struct http_txn *txn = s->txn;
3660 struct htx *htx;
3661 struct buffer *hdr = get_trash_chunk();
3662 int32_t pos;
3663
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003664 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003665
3666 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3667 struct htx_blk *blk = htx_get_blk(htx, pos);
3668 enum htx_blk_type type;
3669 struct ist n, v;
3670
3671 next_hdr:
3672 type = htx_get_blk_type(blk);
3673 if (type == HTX_BLK_EOH)
3674 break;
3675 if (type != HTX_BLK_HDR)
3676 continue;
3677
3678 if (unlikely(txn->flags & TX_SVDENY))
3679 return 1;
3680 else if (unlikely(txn->flags & TX_SVALLOW) &&
3681 (exp->action == ACT_ALLOW ||
3682 exp->action == ACT_DENY))
3683 return 0;
3684
3685 n = htx_get_blk_name(htx, blk);
3686 v = htx_get_blk_value(htx, blk);
3687
Christopher Faulet02e771a2019-02-26 15:36:05 +01003688 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003689 hdr->area[hdr->data++] = ':';
3690 hdr->area[hdr->data++] = ' ';
3691 chunk_memcat(hdr, v.ptr, v.len);
3692
3693 /* Now we have one header in <hdr> */
3694
3695 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3696 struct http_hdr_ctx ctx;
3697 int len;
3698
3699 switch (exp->action) {
3700 case ACT_ALLOW:
3701 txn->flags |= TX_SVALLOW;
3702 goto end;
3703 break;
3704
3705 case ACT_DENY:
3706 txn->flags |= TX_SVDENY;
3707 goto end;
3708 break;
3709
3710 case ACT_REPLACE:
3711 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3712 if (len < 0)
3713 return -1;
3714
3715 http_parse_header(ist2(trash.area, len), &n, &v);
3716 ctx.blk = blk;
3717 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003718 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003719 if (!http_replace_header(htx, &ctx, n, v))
3720 return -1;
3721 if (!ctx.blk)
3722 goto end;
3723 pos = htx_get_blk_pos(htx, blk);
3724 break;
3725
3726 case ACT_REMOVE:
3727 ctx.blk = blk;
3728 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003729 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003730 if (!http_remove_header(htx, &ctx))
3731 return -1;
3732 if (!ctx.blk)
3733 goto end;
3734 pos = htx_get_blk_pos(htx, blk);
3735 goto next_hdr;
3736 }
3737 }
3738
3739 }
3740 end:
3741 return 0;
3742}
3743
3744/* Apply the filter to the status line in the response buffer <res>.
3745 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3746 * or -1 if a replacement resulted in an invalid status line.
3747 */
3748static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3749{
3750 struct http_txn *txn = s->txn;
3751 struct htx *htx;
3752 struct buffer *resline = get_trash_chunk();
3753 int done;
3754
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003755 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003756
3757 if (unlikely(txn->flags & TX_SVDENY))
3758 return 1;
3759 else if (unlikely(txn->flags & TX_SVALLOW) &&
3760 (exp->action == ACT_ALLOW ||
3761 exp->action == ACT_DENY))
3762 return 0;
3763 else if (exp->action == ACT_REMOVE)
3764 return 0;
3765
3766 done = 0;
3767 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3768
3769 /* Now we have the status line between cur_ptr and cur_end */
3770 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003771 struct htx_sl *sl = http_find_stline(htx);
3772 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003773 int len;
3774
3775 switch (exp->action) {
3776 case ACT_ALLOW:
3777 txn->flags |= TX_SVALLOW;
3778 done = 1;
3779 break;
3780
3781 case ACT_DENY:
3782 txn->flags |= TX_SVDENY;
3783 done = 1;
3784 break;
3785
3786 case ACT_REPLACE:
3787 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3788 if (len < 0)
3789 return -1;
3790
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003791 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3792 sl->info.res.status = strl2ui(code.ptr, code.len);
3793 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003794 return -1;
3795
3796 done = 1;
3797 return 1;
3798 }
3799 }
3800 return done;
3801}
3802
3803/*
3804 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3805 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3806 * unparsable response.
3807 */
3808static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3809{
3810 struct session *sess = s->sess;
3811 struct http_txn *txn = s->txn;
3812 struct hdr_exp *exp;
3813
3814 for (exp = px->rsp_exp; exp; exp = exp->next) {
3815 int ret;
3816
3817 /*
3818 * The interleaving of transformations and verdicts
3819 * makes it difficult to decide to continue or stop
3820 * the evaluation.
3821 */
3822
3823 if (txn->flags & TX_SVDENY)
3824 break;
3825
3826 if ((txn->flags & TX_SVALLOW) &&
3827 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3828 exp->action == ACT_PASS)) {
3829 exp = exp->next;
3830 continue;
3831 }
3832
3833 /* if this filter had a condition, evaluate it now and skip to
3834 * next filter if the condition does not match.
3835 */
3836 if (exp->cond) {
3837 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3838 ret = acl_pass(ret);
3839 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3840 ret = !ret;
3841 if (!ret)
3842 continue;
3843 }
3844
3845 /* Apply the filter to the status line. */
3846 ret = htx_apply_filter_to_sts_line(s, res, exp);
3847 if (unlikely(ret < 0))
3848 return -1;
3849
3850 if (likely(ret == 0)) {
3851 /* The filter did not match the response, it can be
3852 * iterated through all headers.
3853 */
3854 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3855 return -1;
3856 }
3857 }
3858 return 0;
3859}
3860
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003861/*
3862 * Manage client-side cookie. It can impact performance by about 2% so it is
3863 * desirable to call it only when needed. This code is quite complex because
3864 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3865 * highly recommended not to touch this part without a good reason !
3866 */
3867static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3868{
3869 struct session *sess = s->sess;
3870 struct http_txn *txn = s->txn;
3871 struct htx *htx;
3872 struct http_hdr_ctx ctx;
3873 char *hdr_beg, *hdr_end, *del_from;
3874 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3875 int preserve_hdr;
3876
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003877 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003878 ctx.blk = NULL;
3879 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3880 del_from = NULL; /* nothing to be deleted */
3881 preserve_hdr = 0; /* assume we may kill the whole header */
3882
3883 /* Now look for cookies. Conforming to RFC2109, we have to support
3884 * attributes whose name begin with a '$', and associate them with
3885 * the right cookie, if we want to delete this cookie.
3886 * So there are 3 cases for each cookie read :
3887 * 1) it's a special attribute, beginning with a '$' : ignore it.
3888 * 2) it's a server id cookie that we *MAY* want to delete : save
3889 * some pointers on it (last semi-colon, beginning of cookie...)
3890 * 3) it's an application cookie : we *MAY* have to delete a previous
3891 * "special" cookie.
3892 * At the end of loop, if a "special" cookie remains, we may have to
3893 * remove it. If no application cookie persists in the header, we
3894 * *MUST* delete it.
3895 *
3896 * Note: RFC2965 is unclear about the processing of spaces around
3897 * the equal sign in the ATTR=VALUE form. A careful inspection of
3898 * the RFC explicitly allows spaces before it, and not within the
3899 * tokens (attrs or values). An inspection of RFC2109 allows that
3900 * too but section 10.1.3 lets one think that spaces may be allowed
3901 * after the equal sign too, resulting in some (rare) buggy
3902 * implementations trying to do that. So let's do what servers do.
3903 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3904 * allowed quoted strings in values, with any possible character
3905 * after a backslash, including control chars and delimitors, which
3906 * causes parsing to become ambiguous. Browsers also allow spaces
3907 * within values even without quotes.
3908 *
3909 * We have to keep multiple pointers in order to support cookie
3910 * removal at the beginning, middle or end of header without
3911 * corrupting the header. All of these headers are valid :
3912 *
3913 * hdr_beg hdr_end
3914 * | |
3915 * v |
3916 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3917 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3918 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3919 * | | | | | | |
3920 * | | | | | | |
3921 * | | | | | | +--> next
3922 * | | | | | +----> val_end
3923 * | | | | +-----------> val_beg
3924 * | | | +--------------> equal
3925 * | | +----------------> att_end
3926 * | +---------------------> att_beg
3927 * +--------------------------> prev
3928 *
3929 */
3930 hdr_beg = ctx.value.ptr;
3931 hdr_end = hdr_beg + ctx.value.len;
3932 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3933 /* Iterate through all cookies on this line */
3934
3935 /* find att_beg */
3936 att_beg = prev;
3937 if (prev > hdr_beg)
3938 att_beg++;
3939
3940 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3941 att_beg++;
3942
3943 /* find att_end : this is the first character after the last non
3944 * space before the equal. It may be equal to hdr_end.
3945 */
3946 equal = att_end = att_beg;
3947 while (equal < hdr_end) {
3948 if (*equal == '=' || *equal == ',' || *equal == ';')
3949 break;
3950 if (HTTP_IS_SPHT(*equal++))
3951 continue;
3952 att_end = equal;
3953 }
3954
3955 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3956 * is between <att_beg> and <equal>, both may be identical.
3957 */
3958 /* look for end of cookie if there is an equal sign */
3959 if (equal < hdr_end && *equal == '=') {
3960 /* look for the beginning of the value */
3961 val_beg = equal + 1;
3962 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3963 val_beg++;
3964
3965 /* find the end of the value, respecting quotes */
3966 next = http_find_cookie_value_end(val_beg, hdr_end);
3967
3968 /* make val_end point to the first white space or delimitor after the value */
3969 val_end = next;
3970 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3971 val_end--;
3972 }
3973 else
3974 val_beg = val_end = next = equal;
3975
3976 /* We have nothing to do with attributes beginning with
3977 * '$'. However, they will automatically be removed if a
3978 * header before them is removed, since they're supposed
3979 * to be linked together.
3980 */
3981 if (*att_beg == '$')
3982 continue;
3983
3984 /* Ignore cookies with no equal sign */
3985 if (equal == next) {
3986 /* This is not our cookie, so we must preserve it. But if we already
3987 * scheduled another cookie for removal, we cannot remove the
3988 * complete header, but we can remove the previous block itself.
3989 */
3990 preserve_hdr = 1;
3991 if (del_from != NULL) {
3992 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3993 val_end += delta;
3994 next += delta;
3995 hdr_end += delta;
3996 prev = del_from;
3997 del_from = NULL;
3998 }
3999 continue;
4000 }
4001
4002 /* if there are spaces around the equal sign, we need to
4003 * strip them otherwise we'll get trouble for cookie captures,
4004 * or even for rewrites. Since this happens extremely rarely,
4005 * it does not hurt performance.
4006 */
4007 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4008 int stripped_before = 0;
4009 int stripped_after = 0;
4010
4011 if (att_end != equal) {
4012 memmove(att_end, equal, hdr_end - equal);
4013 stripped_before = (att_end - equal);
4014 equal += stripped_before;
4015 val_beg += stripped_before;
4016 }
4017
4018 if (val_beg > equal + 1) {
4019 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4020 stripped_after = (equal + 1) - val_beg;
4021 val_beg += stripped_after;
4022 stripped_before += stripped_after;
4023 }
4024
4025 val_end += stripped_before;
4026 next += stripped_before;
4027 hdr_end += stripped_before;
4028 }
4029 /* now everything is as on the diagram above */
4030
4031 /* First, let's see if we want to capture this cookie. We check
4032 * that we don't already have a client side cookie, because we
4033 * can only capture one. Also as an optimisation, we ignore
4034 * cookies shorter than the declared name.
4035 */
4036 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4037 (val_end - att_beg >= sess->fe->capture_namelen) &&
4038 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4039 int log_len = val_end - att_beg;
4040
4041 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4042 ha_alert("HTTP logging : out of memory.\n");
4043 } else {
4044 if (log_len > sess->fe->capture_len)
4045 log_len = sess->fe->capture_len;
4046 memcpy(txn->cli_cookie, att_beg, log_len);
4047 txn->cli_cookie[log_len] = 0;
4048 }
4049 }
4050
4051 /* Persistence cookies in passive, rewrite or insert mode have the
4052 * following form :
4053 *
4054 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4055 *
4056 * For cookies in prefix mode, the form is :
4057 *
4058 * Cookie: NAME=SRV~VALUE
4059 */
4060 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4061 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4062 struct server *srv = s->be->srv;
4063 char *delim;
4064
4065 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4066 * have the server ID between val_beg and delim, and the original cookie between
4067 * delim+1 and val_end. Otherwise, delim==val_end :
4068 *
4069 * hdr_beg
4070 * |
4071 * v
4072 * NAME=SRV; # in all but prefix modes
4073 * NAME=SRV~OPAQUE ; # in prefix mode
4074 * || || | |+-> next
4075 * || || | +--> val_end
4076 * || || +---------> delim
4077 * || |+------------> val_beg
4078 * || +-------------> att_end = equal
4079 * |+-----------------> att_beg
4080 * +------------------> prev
4081 *
4082 */
4083 if (s->be->ck_opts & PR_CK_PFX) {
4084 for (delim = val_beg; delim < val_end; delim++)
4085 if (*delim == COOKIE_DELIM)
4086 break;
4087 }
4088 else {
4089 char *vbar1;
4090 delim = val_end;
4091 /* Now check if the cookie contains a date field, which would
4092 * appear after a vertical bar ('|') just after the server name
4093 * and before the delimiter.
4094 */
4095 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4096 if (vbar1) {
4097 /* OK, so left of the bar is the server's cookie and
4098 * right is the last seen date. It is a base64 encoded
4099 * 30-bit value representing the UNIX date since the
4100 * epoch in 4-second quantities.
4101 */
4102 int val;
4103 delim = vbar1++;
4104 if (val_end - vbar1 >= 5) {
4105 val = b64tos30(vbar1);
4106 if (val > 0)
4107 txn->cookie_last_date = val << 2;
4108 }
4109 /* look for a second vertical bar */
4110 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4111 if (vbar1 && (val_end - vbar1 > 5)) {
4112 val = b64tos30(vbar1 + 1);
4113 if (val > 0)
4114 txn->cookie_first_date = val << 2;
4115 }
4116 }
4117 }
4118
4119 /* if the cookie has an expiration date and the proxy wants to check
4120 * it, then we do that now. We first check if the cookie is too old,
4121 * then only if it has expired. We detect strict overflow because the
4122 * time resolution here is not great (4 seconds). Cookies with dates
4123 * in the future are ignored if their offset is beyond one day. This
4124 * allows an admin to fix timezone issues without expiring everyone
4125 * and at the same time avoids keeping unwanted side effects for too
4126 * long.
4127 */
4128 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4129 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4130 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4131 txn->flags &= ~TX_CK_MASK;
4132 txn->flags |= TX_CK_OLD;
4133 delim = val_beg; // let's pretend we have not found the cookie
4134 txn->cookie_first_date = 0;
4135 txn->cookie_last_date = 0;
4136 }
4137 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4138 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4139 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4140 txn->flags &= ~TX_CK_MASK;
4141 txn->flags |= TX_CK_EXPIRED;
4142 delim = val_beg; // let's pretend we have not found the cookie
4143 txn->cookie_first_date = 0;
4144 txn->cookie_last_date = 0;
4145 }
4146
4147 /* Here, we'll look for the first running server which supports the cookie.
4148 * This allows to share a same cookie between several servers, for example
4149 * to dedicate backup servers to specific servers only.
4150 * However, to prevent clients from sticking to cookie-less backup server
4151 * when they have incidentely learned an empty cookie, we simply ignore
4152 * empty cookies and mark them as invalid.
4153 * The same behaviour is applied when persistence must be ignored.
4154 */
4155 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4156 srv = NULL;
4157
4158 while (srv) {
4159 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4160 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4161 if ((srv->cur_state != SRV_ST_STOPPED) ||
4162 (s->be->options & PR_O_PERSIST) ||
4163 (s->flags & SF_FORCE_PRST)) {
4164 /* we found the server and we can use it */
4165 txn->flags &= ~TX_CK_MASK;
4166 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4167 s->flags |= SF_DIRECT | SF_ASSIGNED;
4168 s->target = &srv->obj_type;
4169 break;
4170 } else {
4171 /* we found a server, but it's down,
4172 * mark it as such and go on in case
4173 * another one is available.
4174 */
4175 txn->flags &= ~TX_CK_MASK;
4176 txn->flags |= TX_CK_DOWN;
4177 }
4178 }
4179 srv = srv->next;
4180 }
4181
4182 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4183 /* no server matched this cookie or we deliberately skipped it */
4184 txn->flags &= ~TX_CK_MASK;
4185 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4186 txn->flags |= TX_CK_UNUSED;
4187 else
4188 txn->flags |= TX_CK_INVALID;
4189 }
4190
4191 /* depending on the cookie mode, we may have to either :
4192 * - delete the complete cookie if we're in insert+indirect mode, so that
4193 * the server never sees it ;
4194 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004195 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004196 * if we're in cookie prefix mode
4197 */
4198 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4199 int delta; /* negative */
4200
4201 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4202 delta = val_beg - (delim + 1);
4203 val_end += delta;
4204 next += delta;
4205 hdr_end += delta;
4206 del_from = NULL;
4207 preserve_hdr = 1; /* we want to keep this cookie */
4208 }
4209 else if (del_from == NULL &&
4210 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4211 del_from = prev;
4212 }
4213 }
4214 else {
4215 /* This is not our cookie, so we must preserve it. But if we already
4216 * scheduled another cookie for removal, we cannot remove the
4217 * complete header, but we can remove the previous block itself.
4218 */
4219 preserve_hdr = 1;
4220
4221 if (del_from != NULL) {
4222 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4223 if (att_beg >= del_from)
4224 att_beg += delta;
4225 if (att_end >= del_from)
4226 att_end += delta;
4227 val_beg += delta;
4228 val_end += delta;
4229 next += delta;
4230 hdr_end += delta;
4231 prev = del_from;
4232 del_from = NULL;
4233 }
4234 }
4235
4236 /* continue with next cookie on this header line */
4237 att_beg = next;
4238 } /* for each cookie */
4239
4240
4241 /* There are no more cookies on this line.
4242 * We may still have one (or several) marked for deletion at the
4243 * end of the line. We must do this now in two ways :
4244 * - if some cookies must be preserved, we only delete from the
4245 * mark to the end of line ;
4246 * - if nothing needs to be preserved, simply delete the whole header
4247 */
4248 if (del_from) {
4249 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4250 }
4251 if ((hdr_end - hdr_beg) != ctx.value.len) {
4252 if (hdr_beg != hdr_end) {
4253 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004254 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004255 }
4256 else
4257 http_remove_header(htx, &ctx);
4258 }
4259 } /* for each "Cookie header */
4260}
4261
4262/*
4263 * Manage server-side cookies. It can impact performance by about 2% so it is
4264 * desirable to call it only when needed. This function is also used when we
4265 * just need to know if there is a cookie (eg: for check-cache).
4266 */
4267static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4268{
4269 struct session *sess = s->sess;
4270 struct http_txn *txn = s->txn;
4271 struct htx *htx;
4272 struct http_hdr_ctx ctx;
4273 struct server *srv;
4274 char *hdr_beg, *hdr_end;
4275 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4276 int is_cookie2;
4277
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004278 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004279
4280 ctx.blk = NULL;
4281 while (1) {
4282 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4283 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4284 break;
4285 is_cookie2 = 1;
4286 }
4287
4288 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4289 * <prev> points to the colon.
4290 */
4291 txn->flags |= TX_SCK_PRESENT;
4292
4293 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4294 * check-cache is enabled) and we are not interested in checking
4295 * them. Warning, the cookie capture is declared in the frontend.
4296 */
4297 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4298 break;
4299
4300 /* OK so now we know we have to process this response cookie.
4301 * The format of the Set-Cookie header is slightly different
4302 * from the format of the Cookie header in that it does not
4303 * support the comma as a cookie delimiter (thus the header
4304 * cannot be folded) because the Expires attribute described in
4305 * the original Netscape's spec may contain an unquoted date
4306 * with a comma inside. We have to live with this because
4307 * many browsers don't support Max-Age and some browsers don't
4308 * support quoted strings. However the Set-Cookie2 header is
4309 * clean.
4310 *
4311 * We have to keep multiple pointers in order to support cookie
4312 * removal at the beginning, middle or end of header without
4313 * corrupting the header (in case of set-cookie2). A special
4314 * pointer, <scav> points to the beginning of the set-cookie-av
4315 * fields after the first semi-colon. The <next> pointer points
4316 * either to the end of line (set-cookie) or next unquoted comma
4317 * (set-cookie2). All of these headers are valid :
4318 *
4319 * hdr_beg hdr_end
4320 * | |
4321 * v |
4322 * NAME1 = VALUE 1 ; Secure; Path="/" |
4323 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4324 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4325 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4326 * | | | | | | | |
4327 * | | | | | | | +-> next
4328 * | | | | | | +------------> scav
4329 * | | | | | +--------------> val_end
4330 * | | | | +--------------------> val_beg
4331 * | | | +----------------------> equal
4332 * | | +------------------------> att_end
4333 * | +----------------------------> att_beg
4334 * +------------------------------> prev
4335 * -------------------------------> hdr_beg
4336 */
4337 hdr_beg = ctx.value.ptr;
4338 hdr_end = hdr_beg + ctx.value.len;
4339 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4340
4341 /* Iterate through all cookies on this line */
4342
4343 /* find att_beg */
4344 att_beg = prev;
4345 if (prev > hdr_beg)
4346 att_beg++;
4347
4348 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4349 att_beg++;
4350
4351 /* find att_end : this is the first character after the last non
4352 * space before the equal. It may be equal to hdr_end.
4353 */
4354 equal = att_end = att_beg;
4355
4356 while (equal < hdr_end) {
4357 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4358 break;
4359 if (HTTP_IS_SPHT(*equal++))
4360 continue;
4361 att_end = equal;
4362 }
4363
4364 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4365 * is between <att_beg> and <equal>, both may be identical.
4366 */
4367
4368 /* look for end of cookie if there is an equal sign */
4369 if (equal < hdr_end && *equal == '=') {
4370 /* look for the beginning of the value */
4371 val_beg = equal + 1;
4372 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4373 val_beg++;
4374
4375 /* find the end of the value, respecting quotes */
4376 next = http_find_cookie_value_end(val_beg, hdr_end);
4377
4378 /* make val_end point to the first white space or delimitor after the value */
4379 val_end = next;
4380 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4381 val_end--;
4382 }
4383 else {
4384 /* <equal> points to next comma, semi-colon or EOL */
4385 val_beg = val_end = next = equal;
4386 }
4387
4388 if (next < hdr_end) {
4389 /* Set-Cookie2 supports multiple cookies, and <next> points to
4390 * a colon or semi-colon before the end. So skip all attr-value
4391 * pairs and look for the next comma. For Set-Cookie, since
4392 * commas are permitted in values, skip to the end.
4393 */
4394 if (is_cookie2)
4395 next = http_find_hdr_value_end(next, hdr_end);
4396 else
4397 next = hdr_end;
4398 }
4399
4400 /* Now everything is as on the diagram above */
4401
4402 /* Ignore cookies with no equal sign */
4403 if (equal == val_end)
4404 continue;
4405
4406 /* If there are spaces around the equal sign, we need to
4407 * strip them otherwise we'll get trouble for cookie captures,
4408 * or even for rewrites. Since this happens extremely rarely,
4409 * it does not hurt performance.
4410 */
4411 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4412 int stripped_before = 0;
4413 int stripped_after = 0;
4414
4415 if (att_end != equal) {
4416 memmove(att_end, equal, hdr_end - equal);
4417 stripped_before = (att_end - equal);
4418 equal += stripped_before;
4419 val_beg += stripped_before;
4420 }
4421
4422 if (val_beg > equal + 1) {
4423 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4424 stripped_after = (equal + 1) - val_beg;
4425 val_beg += stripped_after;
4426 stripped_before += stripped_after;
4427 }
4428
4429 val_end += stripped_before;
4430 next += stripped_before;
4431 hdr_end += stripped_before;
4432
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004433 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4434 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004435 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004436 }
4437
4438 /* First, let's see if we want to capture this cookie. We check
4439 * that we don't already have a server side cookie, because we
4440 * can only capture one. Also as an optimisation, we ignore
4441 * cookies shorter than the declared name.
4442 */
4443 if (sess->fe->capture_name != NULL &&
4444 txn->srv_cookie == NULL &&
4445 (val_end - att_beg >= sess->fe->capture_namelen) &&
4446 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4447 int log_len = val_end - att_beg;
4448 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4449 ha_alert("HTTP logging : out of memory.\n");
4450 }
4451 else {
4452 if (log_len > sess->fe->capture_len)
4453 log_len = sess->fe->capture_len;
4454 memcpy(txn->srv_cookie, att_beg, log_len);
4455 txn->srv_cookie[log_len] = 0;
4456 }
4457 }
4458
4459 srv = objt_server(s->target);
4460 /* now check if we need to process it for persistence */
4461 if (!(s->flags & SF_IGNORE_PRST) &&
4462 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4463 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4464 /* assume passive cookie by default */
4465 txn->flags &= ~TX_SCK_MASK;
4466 txn->flags |= TX_SCK_FOUND;
4467
4468 /* If the cookie is in insert mode on a known server, we'll delete
4469 * this occurrence because we'll insert another one later.
4470 * We'll delete it too if the "indirect" option is set and we're in
4471 * a direct access.
4472 */
4473 if (s->be->ck_opts & PR_CK_PSV) {
4474 /* The "preserve" flag was set, we don't want to touch the
4475 * server's cookie.
4476 */
4477 }
4478 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4479 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4480 /* this cookie must be deleted */
4481 if (prev == hdr_beg && next == hdr_end) {
4482 /* whole header */
4483 http_remove_header(htx, &ctx);
4484 /* note: while both invalid now, <next> and <hdr_end>
4485 * are still equal, so the for() will stop as expected.
4486 */
4487 } else {
4488 /* just remove the value */
4489 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4490 next = prev;
4491 hdr_end += delta;
4492 }
4493 txn->flags &= ~TX_SCK_MASK;
4494 txn->flags |= TX_SCK_DELETED;
4495 /* and go on with next cookie */
4496 }
4497 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4498 /* replace bytes val_beg->val_end with the cookie name associated
4499 * with this server since we know it.
4500 */
4501 int sliding, delta;
4502
4503 ctx.value = ist2(val_beg, val_end - val_beg);
4504 ctx.lws_before = ctx.lws_after = 0;
4505 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4506 delta = srv->cklen - (val_end - val_beg);
4507 sliding = (ctx.value.ptr - val_beg);
4508 hdr_beg += sliding;
4509 val_beg += sliding;
4510 next += sliding + delta;
4511 hdr_end += sliding + delta;
4512
4513 txn->flags &= ~TX_SCK_MASK;
4514 txn->flags |= TX_SCK_REPLACED;
4515 }
4516 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4517 /* insert the cookie name associated with this server
4518 * before existing cookie, and insert a delimiter between them..
4519 */
4520 int sliding, delta;
4521 ctx.value = ist2(val_beg, 0);
4522 ctx.lws_before = ctx.lws_after = 0;
4523 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4524 delta = srv->cklen + 1;
4525 sliding = (ctx.value.ptr - val_beg);
4526 hdr_beg += sliding;
4527 val_beg += sliding;
4528 next += sliding + delta;
4529 hdr_end += sliding + delta;
4530
4531 val_beg[srv->cklen] = COOKIE_DELIM;
4532 txn->flags &= ~TX_SCK_MASK;
4533 txn->flags |= TX_SCK_REPLACED;
4534 }
4535 }
4536 /* that's done for this cookie, check the next one on the same
4537 * line when next != hdr_end (only if is_cookie2).
4538 */
4539 }
4540 }
4541}
4542
Christopher Faulet25a02f62018-10-24 12:00:25 +02004543/*
4544 * Parses the Cache-Control and Pragma request header fields to determine if
4545 * the request may be served from the cache and/or if it is cacheable. Updates
4546 * s->txn->flags.
4547 */
4548void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4549{
4550 struct http_txn *txn = s->txn;
4551 struct htx *htx;
4552 int32_t pos;
4553 int pragma_found, cc_found, i;
4554
4555 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4556 return; /* nothing more to do here */
4557
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004558 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004559 pragma_found = cc_found = 0;
4560 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4561 struct htx_blk *blk = htx_get_blk(htx, pos);
4562 enum htx_blk_type type = htx_get_blk_type(blk);
4563 struct ist n, v;
4564
4565 if (type == HTX_BLK_EOH)
4566 break;
4567 if (type != HTX_BLK_HDR)
4568 continue;
4569
4570 n = htx_get_blk_name(htx, blk);
4571 v = htx_get_blk_value(htx, blk);
4572
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004573 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004574 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4575 pragma_found = 1;
4576 continue;
4577 }
4578 }
4579
4580 /* Don't use the cache and don't try to store if we found the
4581 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004582 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004583 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4584 txn->flags |= TX_CACHE_IGNORE;
4585 continue;
4586 }
4587
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004588 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004589 continue;
4590
4591 /* OK, right now we know we have a cache-control header */
4592 cc_found = 1;
4593 if (!v.len) /* no info */
4594 continue;
4595
4596 i = 0;
4597 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4598 !isspace((unsigned char)*(v.ptr+i)))
4599 i++;
4600
4601 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4602 * values after max-age, max-stale nor min-fresh, we simply don't
4603 * use the cache when they're specified.
4604 */
4605 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4606 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4607 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4608 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4609 txn->flags |= TX_CACHE_IGNORE;
4610 continue;
4611 }
4612
4613 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4614 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4615 continue;
4616 }
4617 }
4618
4619 /* RFC7234#5.4:
4620 * When the Cache-Control header field is also present and
4621 * understood in a request, Pragma is ignored.
4622 * When the Cache-Control header field is not present in a
4623 * request, caches MUST consider the no-cache request
4624 * pragma-directive as having the same effect as if
4625 * "Cache-Control: no-cache" were present.
4626 */
4627 if (!cc_found && pragma_found)
4628 txn->flags |= TX_CACHE_IGNORE;
4629}
4630
4631/*
4632 * Check if response is cacheable or not. Updates s->txn->flags.
4633 */
4634void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4635{
4636 struct http_txn *txn = s->txn;
4637 struct htx *htx;
4638 int32_t pos;
4639 int i;
4640
4641 if (txn->status < 200) {
4642 /* do not try to cache interim responses! */
4643 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4644 return;
4645 }
4646
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004647 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004648 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4649 struct htx_blk *blk = htx_get_blk(htx, pos);
4650 enum htx_blk_type type = htx_get_blk_type(blk);
4651 struct ist n, v;
4652
4653 if (type == HTX_BLK_EOH)
4654 break;
4655 if (type != HTX_BLK_HDR)
4656 continue;
4657
4658 n = htx_get_blk_name(htx, blk);
4659 v = htx_get_blk_value(htx, blk);
4660
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004661 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004662 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4663 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4664 return;
4665 }
4666 }
4667
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004668 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004669 continue;
4670
4671 /* OK, right now we know we have a cache-control header */
4672 if (!v.len) /* no info */
4673 continue;
4674
4675 i = 0;
4676 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4677 !isspace((unsigned char)*(v.ptr+i)))
4678 i++;
4679
4680 /* we have a complete value between v.ptr and (v.ptr+i) */
4681 if (i < v.len && *(v.ptr + i) == '=') {
4682 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4683 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4684 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4685 continue;
4686 }
4687
4688 /* we have something of the form no-cache="set-cookie" */
4689 if ((v.len >= 21) &&
4690 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4691 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4692 txn->flags &= ~TX_CACHE_COOK;
4693 continue;
4694 }
4695
4696 /* OK, so we know that either p2 points to the end of string or to a comma */
4697 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4698 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4699 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4700 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4701 return;
4702 }
4703
4704 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4705 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4706 continue;
4707 }
4708 }
4709}
4710
Christopher Faulet64159df2018-10-24 21:15:35 +02004711/* send a server's name with an outgoing request over an established connection.
4712 * Note: this function is designed to be called once the request has been
4713 * scheduled for being forwarded. This is the reason why the number of forwarded
4714 * bytes have to be adjusted.
4715 */
4716int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4717{
4718 struct htx *htx;
4719 struct http_hdr_ctx ctx;
4720 struct ist hdr;
4721 uint32_t data;
4722
4723 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004724 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004725 data = htx->data;
4726
4727 ctx.blk = NULL;
4728 while (http_find_header(htx, hdr, &ctx, 1))
4729 http_remove_header(htx, &ctx);
4730 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4731
4732 if (co_data(&s->req)) {
4733 if (data >= htx->data)
4734 c_rew(&s->req, data - htx->data);
4735 else
4736 c_adv(&s->req, htx->data - data);
4737 }
4738 return 0;
4739}
4740
Christopher Faulet377c5a52018-10-24 21:21:30 +02004741/*
4742 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4743 * for the current backend.
4744 *
4745 * It is assumed that the request is either a HEAD, GET, or POST and that the
4746 * uri_auth field is valid.
4747 *
4748 * Returns 1 if stats should be provided, otherwise 0.
4749 */
4750static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4751{
4752 struct uri_auth *uri_auth = backend->uri_auth;
4753 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004754 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004755 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004756
4757 if (!uri_auth)
4758 return 0;
4759
4760 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4761 return 0;
4762
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004763 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004764 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004765 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004766
4767 /* check URI size */
4768 if (uri_auth->uri_len > uri.len)
4769 return 0;
4770
4771 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4772 return 0;
4773
4774 return 1;
4775}
4776
4777/* This function prepares an applet to handle the stats. It can deal with the
4778 * "100-continue" expectation, check that admin rules are met for POST requests,
4779 * and program a response message if something was unexpected. It cannot fail
4780 * and always relies on the stats applet to complete the job. It does not touch
4781 * analysers nor counters, which are left to the caller. It does not touch
4782 * s->target which is supposed to already point to the stats applet. The caller
4783 * is expected to have already assigned an appctx to the stream.
4784 */
4785static int htx_handle_stats(struct stream *s, struct channel *req)
4786{
4787 struct stats_admin_rule *stats_admin_rule;
4788 struct stream_interface *si = &s->si[1];
4789 struct session *sess = s->sess;
4790 struct http_txn *txn = s->txn;
4791 struct http_msg *msg = &txn->req;
4792 struct uri_auth *uri_auth = s->be->uri_auth;
4793 const char *h, *lookup, *end;
4794 struct appctx *appctx;
4795 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004796 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797
4798 appctx = si_appctx(si);
4799 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4800 appctx->st1 = appctx->st2 = 0;
4801 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4802 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4803 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4804 appctx->ctx.stats.flags |= STAT_CHUNKED;
4805
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004806 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004807 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004808 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4809 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004810
4811 for (h = lookup; h <= end - 3; h++) {
4812 if (memcmp(h, ";up", 3) == 0) {
4813 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4814 break;
4815 }
4816 }
4817
4818 if (uri_auth->refresh) {
4819 for (h = lookup; h <= end - 10; h++) {
4820 if (memcmp(h, ";norefresh", 10) == 0) {
4821 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4822 break;
4823 }
4824 }
4825 }
4826
4827 for (h = lookup; h <= end - 4; h++) {
4828 if (memcmp(h, ";csv", 4) == 0) {
4829 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4830 break;
4831 }
4832 }
4833
4834 for (h = lookup; h <= end - 6; h++) {
4835 if (memcmp(h, ";typed", 6) == 0) {
4836 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4837 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4838 break;
4839 }
4840 }
4841
4842 for (h = lookup; h <= end - 8; h++) {
4843 if (memcmp(h, ";st=", 4) == 0) {
4844 int i;
4845 h += 4;
4846 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4847 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4848 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4849 appctx->ctx.stats.st_code = i;
4850 break;
4851 }
4852 }
4853 break;
4854 }
4855 }
4856
4857 appctx->ctx.stats.scope_str = 0;
4858 appctx->ctx.stats.scope_len = 0;
4859 for (h = lookup; h <= end - 8; h++) {
4860 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4861 int itx = 0;
4862 const char *h2;
4863 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4864 const char *err;
4865
4866 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4867 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004868 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4869 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004870 if (*h == ';' || *h == '&' || *h == ' ')
4871 break;
4872 itx++;
4873 h++;
4874 }
4875
4876 if (itx > STAT_SCOPE_TXT_MAXLEN)
4877 itx = STAT_SCOPE_TXT_MAXLEN;
4878 appctx->ctx.stats.scope_len = itx;
4879
4880 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4881 memcpy(scope_txt, h2, itx);
4882 scope_txt[itx] = '\0';
4883 err = invalid_char(scope_txt);
4884 if (err) {
4885 /* bad char in search text => clear scope */
4886 appctx->ctx.stats.scope_str = 0;
4887 appctx->ctx.stats.scope_len = 0;
4888 }
4889 break;
4890 }
4891 }
4892
4893 /* now check whether we have some admin rules for this request */
4894 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4895 int ret = 1;
4896
4897 if (stats_admin_rule->cond) {
4898 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4899 ret = acl_pass(ret);
4900 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4901 ret = !ret;
4902 }
4903
4904 if (ret) {
4905 /* no rule, or the rule matches */
4906 appctx->ctx.stats.flags |= STAT_ADMIN;
4907 break;
4908 }
4909 }
4910
Christopher Faulet5d45e382019-02-27 15:15:23 +01004911 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4912 appctx->st0 = STAT_HTTP_HEAD;
4913 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004914 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004915 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004916 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004917 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004918 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4919 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4920 appctx->st0 = STAT_HTTP_LAST;
4921 }
4922 }
4923 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004924 /* Unsupported method */
4925 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4926 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4927 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004928 }
4929
4930 s->task->nice = -32; /* small boost for HTTP statistics */
4931 return 1;
4932}
4933
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004934void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4935{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004936 struct channel *req = &s->req;
4937 struct channel *res = &s->res;
4938 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004939 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004940 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004941 struct ist path, location;
4942 unsigned int flags;
4943 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004944
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004945 /*
4946 * Create the location
4947 */
4948 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004949
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004950 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004951 /* special prefix "/" means don't change URL */
4952 srv = __objt_server(s->target);
4953 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4954 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4955 return;
4956 }
4957
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004958 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004959 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004960 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004961 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004962 if (!path.ptr)
4963 return;
4964
4965 if (!chunk_memcat(&trash, path.ptr, path.len))
4966 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004967 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004968
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004969 /*
4970 * Create the 302 respone
4971 */
4972 htx = htx_from_buf(&res->buf);
4973 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4974 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4975 ist("HTTP/1.1"), ist("302"), ist("Found"));
4976 if (!sl)
4977 goto fail;
4978 sl->info.res.status = 302;
4979 s->txn->status = 302;
4980
4981 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4982 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4983 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4984 !htx_add_header(htx, ist("Location"), location))
4985 goto fail;
4986
4987 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4988 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004989
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004990 /*
4991 * Send the message
4992 */
4993 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004994 c_adv(res, data);
4995 res->total += data;
4996
4997 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004998 si_shutr(si);
4999 si_shutw(si);
5000 si->err_type = SI_ET_NONE;
5001 si->state = SI_ST_CLO;
5002
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 channel_auto_read(req);
5004 channel_abort(req);
5005 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005006 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005007 channel_auto_read(res);
5008 channel_auto_close(res);
5009
5010 if (!(s->flags & SF_ERR_MASK))
5011 s->flags |= SF_ERR_LOCAL;
5012 if (!(s->flags & SF_FINST_MASK))
5013 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005014
5015 /* FIXME: we should increase a counter of redirects per server and per backend. */
5016 srv_inc_sess_ctr(srv);
5017 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005018 return;
5019
5020 fail:
5021 /* If an error occurred, remove the incomplete HTTP response from the
5022 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005023 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024}
5025
Christopher Fauletf2824e62018-10-01 12:12:37 +02005026/* This function terminates the request because it was completly analyzed or
5027 * because an error was triggered during the body forwarding.
5028 */
5029static void htx_end_request(struct stream *s)
5030{
5031 struct channel *chn = &s->req;
5032 struct http_txn *txn = s->txn;
5033
5034 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5035 now_ms, __FUNCTION__, s,
5036 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5037 s->req.analysers, s->res.analysers);
5038
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005039 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5040 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005041 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005042 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005043 goto end;
5044 }
5045
5046 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5047 return;
5048
5049 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005050 /* No need to read anymore, the request was completely parsed.
5051 * We can shut the read side unless we want to abort_on_close,
5052 * or we have a POST request. The issue with POST requests is
5053 * that some browsers still send a CRLF after the request, and
5054 * this CRLF must be read so that it does not remain in the kernel
5055 * buffers, otherwise a close could cause an RST on some systems
5056 * (eg: Linux).
5057 */
5058 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5059 txn->meth != HTTP_METH_POST)
5060 channel_dont_read(chn);
5061
5062 /* if the server closes the connection, we want to immediately react
5063 * and close the socket to save packets and syscalls.
5064 */
5065 s->si[1].flags |= SI_FL_NOHALF;
5066
5067 /* In any case we've finished parsing the request so we must
5068 * disable Nagle when sending data because 1) we're not going
5069 * to shut this side, and 2) the server is waiting for us to
5070 * send pending data.
5071 */
5072 chn->flags |= CF_NEVER_WAIT;
5073
Christopher Fauletd01ce402019-01-02 17:44:13 +01005074 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5075 /* The server has not finished to respond, so we
5076 * don't want to move in order not to upset it.
5077 */
5078 return;
5079 }
5080
Christopher Fauletf2824e62018-10-01 12:12:37 +02005081 /* When we get here, it means that both the request and the
5082 * response have finished receiving. Depending on the connection
5083 * mode, we'll have to wait for the last bytes to leave in either
5084 * direction, and sometimes for a close to be effective.
5085 */
5086 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5087 /* Tunnel mode will not have any analyser so it needs to
5088 * poll for reads.
5089 */
5090 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005091 if (b_data(&chn->buf))
5092 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005093 txn->req.msg_state = HTTP_MSG_TUNNEL;
5094 }
5095 else {
5096 /* we're not expecting any new data to come for this
5097 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005098 *
5099 * However, there is an exception if the response
5100 * length is undefined. In this case, we need to wait
5101 * the close from the server. The response will be
5102 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 */
5104 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5105 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005106 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005107
5108 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5109 channel_shutr_now(chn);
5110 channel_shutw_now(chn);
5111 }
5112 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005113 goto check_channel_flags;
5114 }
5115
5116 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5117 http_msg_closing:
5118 /* nothing else to forward, just waiting for the output buffer
5119 * to be empty and for the shutw_now to take effect.
5120 */
5121 if (channel_is_empty(chn)) {
5122 txn->req.msg_state = HTTP_MSG_CLOSED;
5123 goto http_msg_closed;
5124 }
5125 else if (chn->flags & CF_SHUTW) {
5126 txn->req.err_state = txn->req.msg_state;
5127 txn->req.msg_state = HTTP_MSG_ERROR;
5128 goto end;
5129 }
5130 return;
5131 }
5132
5133 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5134 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005135 /* if we don't know whether the server will close, we need to hard close */
5136 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5137 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005138 /* see above in MSG_DONE why we only do this in these states */
5139 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5140 channel_dont_read(chn);
5141 goto end;
5142 }
5143
5144 check_channel_flags:
5145 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5146 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5147 /* if we've just closed an output, let's switch */
5148 txn->req.msg_state = HTTP_MSG_CLOSING;
5149 goto http_msg_closing;
5150 }
5151
5152 end:
5153 chn->analysers &= AN_REQ_FLT_END;
5154 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5155 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5156 channel_auto_close(chn);
5157 channel_auto_read(chn);
5158}
5159
5160
5161/* This function terminates the response because it was completly analyzed or
5162 * because an error was triggered during the body forwarding.
5163 */
5164static void htx_end_response(struct stream *s)
5165{
5166 struct channel *chn = &s->res;
5167 struct http_txn *txn = s->txn;
5168
5169 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5170 now_ms, __FUNCTION__, s,
5171 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5172 s->req.analysers, s->res.analysers);
5173
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005174 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5175 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005176 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005177 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005178 goto end;
5179 }
5180
5181 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5182 return;
5183
5184 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5185 /* In theory, we don't need to read anymore, but we must
5186 * still monitor the server connection for a possible close
5187 * while the request is being uploaded, so we don't disable
5188 * reading.
5189 */
5190 /* channel_dont_read(chn); */
5191
5192 if (txn->req.msg_state < HTTP_MSG_DONE) {
5193 /* The client seems to still be sending data, probably
5194 * because we got an error response during an upload.
5195 * We have the choice of either breaking the connection
5196 * or letting it pass through. Let's do the later.
5197 */
5198 return;
5199 }
5200
5201 /* When we get here, it means that both the request and the
5202 * response have finished receiving. Depending on the connection
5203 * mode, we'll have to wait for the last bytes to leave in either
5204 * direction, and sometimes for a close to be effective.
5205 */
5206 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5207 channel_auto_read(chn);
5208 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005209 if (b_data(&chn->buf))
5210 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005211 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5212 }
5213 else {
5214 /* we're not expecting any new data to come for this
5215 * transaction, so we can close it.
5216 */
5217 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5218 channel_shutr_now(chn);
5219 channel_shutw_now(chn);
5220 }
5221 }
5222 goto check_channel_flags;
5223 }
5224
5225 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5226 http_msg_closing:
5227 /* nothing else to forward, just waiting for the output buffer
5228 * to be empty and for the shutw_now to take effect.
5229 */
5230 if (channel_is_empty(chn)) {
5231 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5232 goto http_msg_closed;
5233 }
5234 else if (chn->flags & CF_SHUTW) {
5235 txn->rsp.err_state = txn->rsp.msg_state;
5236 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005237 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005238 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005239 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005240 goto end;
5241 }
5242 return;
5243 }
5244
5245 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5246 http_msg_closed:
5247 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005248 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005249 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005250 goto end;
5251 }
5252
5253 check_channel_flags:
5254 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5255 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5256 /* if we've just closed an output, let's switch */
5257 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5258 goto http_msg_closing;
5259 }
5260
5261 end:
5262 chn->analysers &= AN_RES_FLT_END;
5263 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5264 chn->analysers |= AN_RES_FLT_XFER_DATA;
5265 channel_auto_close(chn);
5266 channel_auto_read(chn);
5267}
5268
Christopher Faulet0f226952018-10-22 09:29:56 +02005269void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5270 int finst, const struct buffer *msg)
5271{
5272 channel_auto_read(si_oc(si));
5273 channel_abort(si_oc(si));
5274 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005275 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005276 channel_auto_close(si_ic(si));
5277 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005278
5279 /* <msg> is an HTX structure. So we copy it in the response's
5280 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005281 if (msg) {
5282 struct channel *chn = si_ic(si);
5283 struct htx *htx;
5284
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005285 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005286 chn->buf.data = msg->data;
5287 memcpy(chn->buf.area, msg->area, msg->data);
5288 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005289 c_adv(chn, htx->data);
5290 chn->total += htx->data;
5291 }
5292 if (!(s->flags & SF_ERR_MASK))
5293 s->flags |= err;
5294 if (!(s->flags & SF_FINST_MASK))
5295 s->flags |= finst;
5296}
5297
5298void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5299{
5300 channel_auto_read(&s->req);
5301 channel_abort(&s->req);
5302 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005303 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5304 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005305
5306 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005307
5308 /* <msg> is an HTX structure. So we copy it in the response's
5309 * channel */
5310 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005311 if (msg) {
5312 struct channel *chn = &s->res;
5313 struct htx *htx;
5314
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005315 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005316 chn->buf.data = msg->data;
5317 memcpy(chn->buf.area, msg->area, msg->data);
5318 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005319 c_adv(chn, htx->data);
5320 chn->total += htx->data;
5321 }
5322
5323 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5324 channel_auto_read(&s->res);
5325 channel_auto_close(&s->res);
5326 channel_shutr_now(&s->res);
5327}
5328
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005329struct buffer *htx_error_message(struct stream *s)
5330{
5331 const int msgnum = http_get_status_idx(s->txn->status);
5332
5333 if (s->be->errmsg[msgnum].area)
5334 return &s->be->errmsg[msgnum];
5335 else if (strm_fe(s)->errmsg[msgnum].area)
5336 return &strm_fe(s)->errmsg[msgnum];
5337 else
5338 return &htx_err_chunks[msgnum];
5339}
5340
5341
Christopher Faulet4a28a532019-03-01 11:19:40 +01005342/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5343 * on success and -1 on error.
5344 */
5345static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5346{
5347 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5348 * then we must send an HTTP/1.1 100 Continue intermediate response.
5349 */
5350 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5351 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5352 struct ist hdr = { .ptr = "Expect", .len = 6 };
5353 struct http_hdr_ctx ctx;
5354
5355 ctx.blk = NULL;
5356 /* Expect is allowed in 1.1, look for it */
5357 if (http_find_header(htx, hdr, &ctx, 0) &&
5358 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5359 if (htx_reply_100_continue(s) == -1)
5360 return -1;
5361 http_remove_header(htx, &ctx);
5362 }
5363 }
5364 return 0;
5365}
5366
Christopher Faulet23a3c792018-11-28 10:01:23 +01005367/* Send a 100-Continue response to the client. It returns 0 on success and -1
5368 * on error. The response channel is updated accordingly.
5369 */
5370static int htx_reply_100_continue(struct stream *s)
5371{
5372 struct channel *res = &s->res;
5373 struct htx *htx = htx_from_buf(&res->buf);
5374 struct htx_sl *sl;
5375 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5376 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5377 size_t data;
5378
5379 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5380 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5381 if (!sl)
5382 goto fail;
5383 sl->info.res.status = 100;
5384
5385 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5386 goto fail;
5387
5388 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005389 c_adv(res, data);
5390 res->total += data;
5391 return 0;
5392
5393 fail:
5394 /* If an error occurred, remove the incomplete HTTP response from the
5395 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005396 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005397 return -1;
5398}
5399
Christopher Faulet12c51e22018-11-28 15:59:42 +01005400
5401/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5402 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5403 * error. The response channel is updated accordingly.
5404 */
5405static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5406{
5407 struct channel *res = &s->res;
5408 struct htx *htx = htx_from_buf(&res->buf);
5409 struct htx_sl *sl;
5410 struct ist code, body;
5411 int status;
5412 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5413 size_t data;
5414
5415 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5416 status = 401;
5417 code = ist("401");
5418 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5419 "You need a valid user and password to access this content.\n"
5420 "</body></html>\n");
5421 }
5422 else {
5423 status = 407;
5424 code = ist("407");
5425 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5426 "You need a valid user and password to access this content.\n"
5427 "</body></html>\n");
5428 }
5429
5430 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5431 ist("HTTP/1.1"), code, ist("Unauthorized"));
5432 if (!sl)
5433 goto fail;
5434 sl->info.res.status = status;
5435 s->txn->status = status;
5436
5437 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5438 goto fail;
5439
5440 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5441 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005442 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5443 goto fail;
5444 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5445 goto fail;
5446 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005447 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005448 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5449 goto fail;
5450
5451 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005452 c_adv(res, data);
5453 res->total += data;
5454
5455 channel_auto_read(&s->req);
5456 channel_abort(&s->req);
5457 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005458 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005459
5460 res->wex = tick_add_ifset(now_ms, res->wto);
5461 channel_auto_read(res);
5462 channel_auto_close(res);
5463 channel_shutr_now(res);
5464 return 0;
5465
5466 fail:
5467 /* If an error occurred, remove the incomplete HTTP response from the
5468 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005469 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005470 return -1;
5471}
5472
Christopher Faulet0f226952018-10-22 09:29:56 +02005473/*
5474 * Capture headers from message <htx> according to header list <cap_hdr>, and
5475 * fill the <cap> pointers appropriately.
5476 */
5477static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5478{
5479 struct cap_hdr *h;
5480 int32_t pos;
5481
5482 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5483 struct htx_blk *blk = htx_get_blk(htx, pos);
5484 enum htx_blk_type type = htx_get_blk_type(blk);
5485 struct ist n, v;
5486
5487 if (type == HTX_BLK_EOH)
5488 break;
5489 if (type != HTX_BLK_HDR)
5490 continue;
5491
5492 n = htx_get_blk_name(htx, blk);
5493
5494 for (h = cap_hdr; h; h = h->next) {
5495 if (h->namelen && (h->namelen == n.len) &&
5496 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5497 if (cap[h->index] == NULL)
5498 cap[h->index] =
5499 pool_alloc(h->pool);
5500
5501 if (cap[h->index] == NULL) {
5502 ha_alert("HTTP capture : out of memory.\n");
5503 break;
5504 }
5505
5506 v = htx_get_blk_value(htx, blk);
5507 if (v.len > h->len)
5508 v.len = h->len;
5509
5510 memcpy(cap[h->index], v.ptr, v.len);
5511 cap[h->index][v.len]=0;
5512 }
5513 }
5514 }
5515}
5516
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005517/* Delete a value in a header between delimiters <from> and <next>. The header
5518 * itself is delimited by <start> and <end> pointers. The number of characters
5519 * displaced is returned, and the pointer to the first delimiter is updated if
5520 * required. The function tries as much as possible to respect the following
5521 * principles :
5522 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5523 * in which case <next> is simply removed
5524 * - set exactly one space character after the new first delimiter, unless there
5525 * are not enough characters in the block being moved to do so.
5526 * - remove unneeded spaces before the previous delimiter and after the new
5527 * one.
5528 *
5529 * It is the caller's responsibility to ensure that :
5530 * - <from> points to a valid delimiter or <start> ;
5531 * - <next> points to a valid delimiter or <end> ;
5532 * - there are non-space chars before <from>.
5533 */
5534static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5535{
5536 char *prev = *from;
5537
5538 if (prev == start) {
5539 /* We're removing the first value. eat the semicolon, if <next>
5540 * is lower than <end> */
5541 if (next < end)
5542 next++;
5543
5544 while (next < end && HTTP_IS_SPHT(*next))
5545 next++;
5546 }
5547 else {
5548 /* Remove useless spaces before the old delimiter. */
5549 while (HTTP_IS_SPHT(*(prev-1)))
5550 prev--;
5551 *from = prev;
5552
5553 /* copy the delimiter and if possible a space if we're
5554 * not at the end of the line.
5555 */
5556 if (next < end) {
5557 *prev++ = *next++;
5558 if (prev + 1 < next)
5559 *prev++ = ' ';
5560 while (next < end && HTTP_IS_SPHT(*next))
5561 next++;
5562 }
5563 }
5564 memmove(prev, next, end - next);
5565 return (prev - next);
5566}
5567
Christopher Faulet0f226952018-10-22 09:29:56 +02005568
5569/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005570 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005571 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005572static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005573{
5574 struct ist dst = ist2(str, 0);
5575
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005576 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005577 goto end;
5578 if (dst.len + 1 > len)
5579 goto end;
5580 dst.ptr[dst.len++] = ' ';
5581
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005582 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005583 goto end;
5584 if (dst.len + 1 > len)
5585 goto end;
5586 dst.ptr[dst.len++] = ' ';
5587
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005588 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005589 end:
5590 return dst.len;
5591}
5592
Christopher Fauletf0523542018-10-24 11:06:58 +02005593/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005594 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005595 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005596static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005597{
5598 struct ist dst = ist2(str, 0);
5599
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005600 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005601 goto end;
5602 if (dst.len + 1 > len)
5603 goto end;
5604 dst.ptr[dst.len++] = ' ';
5605
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005606 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005607 goto end;
5608 if (dst.len + 1 > len)
5609 goto end;
5610 dst.ptr[dst.len++] = ' ';
5611
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005612 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005613 end:
5614 return dst.len;
5615}
5616
5617
Christopher Faulet0f226952018-10-22 09:29:56 +02005618/*
5619 * Print a debug line with a start line.
5620 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005621static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005622{
5623 struct session *sess = strm_sess(s);
5624 int max;
5625
5626 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5627 dir,
5628 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5629 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5630
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005631 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005632 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005634 trash.area[trash.data++] = ' ';
5635
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005636 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005637 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 trash.area[trash.data++] = ' ';
5640
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005641 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005642 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 trash.area[trash.data++] = '\n';
5645
5646 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5647}
5648
5649/*
5650 * Print a debug line with a header.
5651 */
5652static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5653{
5654 struct session *sess = strm_sess(s);
5655 int max;
5656
5657 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5658 dir,
5659 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5660 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5661
5662 max = n.len;
5663 UBOUND(max, trash.size - trash.data - 3);
5664 chunk_memcat(&trash, n.ptr, max);
5665 trash.area[trash.data++] = ':';
5666 trash.area[trash.data++] = ' ';
5667
5668 max = v.len;
5669 UBOUND(max, trash.size - trash.data - 1);
5670 chunk_memcat(&trash, v.ptr, max);
5671 trash.area[trash.data++] = '\n';
5672
5673 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5674}
5675
5676
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005677__attribute__((constructor))
5678static void __htx_protocol_init(void)
5679{
5680}
5681
5682
5683/*
5684 * Local variables:
5685 * c-indent-level: 8
5686 * c-basic-offset: 8
5687 * End:
5688 */