blob: 23a6faea2926d6dddac4c42774282ee5e9ab743b [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
412 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
413 * only change if both the request and the config reference something else.
414 * Option httpclose by itself sets tunnel mode where headers are mangled.
415 * However, if another mode is set, it will affect it (eg: server-close/
416 * keep-alive + httpclose = close). Note that we avoid to redo the same work
417 * if FE and BE have the same settings (common). The method consists in
418 * checking if options changed between the two calls (implying that either
419 * one is non-null, or one of them is non-null and we are there for the first
420 * time.
421 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200422 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200423 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200424
425 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200426 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 req->analysers |= AN_REQ_HTTP_BODY;
428
429 /*
430 * RFC7234#4:
431 * A cache MUST write through requests with methods
432 * that are unsafe (Section 4.2.1 of [RFC7231]) to
433 * the origin server; i.e., a cache is not allowed
434 * to generate a reply to such a request before
435 * having forwarded the request and having received
436 * a corresponding response.
437 *
438 * RFC7231#4.2.1:
439 * Of the request methods defined by this
440 * specification, the GET, HEAD, OPTIONS, and TRACE
441 * methods are defined to be safe.
442 */
443 if (likely(txn->meth == HTTP_METH_GET ||
444 txn->meth == HTTP_METH_HEAD ||
445 txn->meth == HTTP_METH_OPTIONS ||
446 txn->meth == HTTP_METH_TRACE))
447 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
448
449 /* end of job, return OK */
450 req->analysers &= ~an_bit;
451 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200452
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 return 1;
454
455 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200456 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200457 txn->req.err_state = txn->req.msg_state;
458 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100459 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100460 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200461 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100462 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200463
464 return_prx_cond:
465 if (!(s->flags & SF_ERR_MASK))
466 s->flags |= SF_ERR_PRXCOND;
467 if (!(s->flags & SF_FINST_MASK))
468 s->flags |= SF_FINST_R;
469
470 req->analysers &= AN_REQ_FLT_END;
471 req->analyse_exp = TICK_ETERNITY;
472 return 0;
473}
474
475
476/* This stream analyser runs all HTTP request processing which is common to
477 * frontends and backends, which means blocking ACLs, filters, connection-close,
478 * reqadd, stats and redirects. This is performed for the designated proxy.
479 * It returns 1 if the processing can continue on next analysers, or zero if it
480 * either needs more data or wants to immediately abort the request (eg: deny,
481 * error, ...).
482 */
483int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
484{
485 struct session *sess = s->sess;
486 struct http_txn *txn = s->txn;
487 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200489 struct redirect_rule *rule;
490 struct cond_wordlist *wl;
491 enum rule_result verdict;
492 int deny_status = HTTP_ERR_403;
493 struct connection *conn = objt_conn(sess->origin);
494
495 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
496 /* we need more data */
497 goto return_prx_yield;
498 }
499
500 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
501 now_ms, __FUNCTION__,
502 s,
503 req,
504 req->rex, req->wex,
505 req->flags,
506 ci_data(req),
507 req->analysers);
508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100509 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200510
Christopher Faulete0768eb2018-10-03 16:38:02 +0200511 /* just in case we have some per-backend tracking */
512 stream_inc_be_http_req_ctr(s);
513
514 /* evaluate http-request rules */
515 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200516 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200517
518 switch (verdict) {
519 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
520 goto return_prx_yield;
521
522 case HTTP_RULE_RES_CONT:
523 case HTTP_RULE_RES_STOP: /* nothing to do */
524 break;
525
526 case HTTP_RULE_RES_DENY: /* deny or tarpit */
527 if (txn->flags & TX_CLTARPIT)
528 goto tarpit;
529 goto deny;
530
531 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
532 goto return_prx_cond;
533
534 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
535 goto done;
536
537 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
538 goto return_bad_req;
539 }
540 }
541
542 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
543 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200544 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 ctx.blk = NULL;
547 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
548 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
552
553 /* OK at this stage, we know that the request was accepted according to
554 * the http-request rules, we can check for the stats. Note that the
555 * URI is detected *before* the req* rules in order not to be affected
556 * by a possible reqrep, while they are processed *after* so that a
557 * reqdeny can still block them. This clearly needs to change in 1.6!
558 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200559 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100561 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200562 txn->status = 500;
563 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200565
566 if (!(s->flags & SF_ERR_MASK))
567 s->flags |= SF_ERR_RESOURCE;
568 goto return_prx_cond;
569 }
570
571 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200572 htx_handle_stats(s, req);
573 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200574 /* not all actions implemented: deny, allow, auth */
575
576 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
577 goto deny;
578
579 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
580 goto return_prx_cond;
581 }
582
583 /* evaluate the req* rules except reqadd */
584 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200585 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200586 goto return_bad_req;
587
588 if (txn->flags & TX_CLDENY)
589 goto deny;
590
591 if (txn->flags & TX_CLTARPIT) {
592 deny_status = HTTP_ERR_500;
593 goto tarpit;
594 }
595 }
596
597 /* add request headers from the rule sets in the same order */
598 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (wl->cond) {
601 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
602 ret = acl_pass(ret);
603 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
604 ret = !ret;
605 if (!ret)
606 continue;
607 }
608
Christopher Fauletff2759f2018-10-24 11:13:16 +0200609 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
610 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 goto return_bad_req;
612 }
613
Christopher Faulet2571bc62019-03-01 11:44:26 +0100614 /* Proceed with the applets now. */
615 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200616 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100617 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100619 if (htx_handle_expect_hdr(s, htx, msg) == -1)
620 goto return_bad_req;
621
Christopher Faulete0768eb2018-10-03 16:38:02 +0200622 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
623 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
624 if (!(s->flags & SF_FINST_MASK))
625 s->flags |= SF_FINST_R;
626
627 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
628 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
629 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
630 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100631
632 req->flags |= CF_SEND_DONTWAIT;
633 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto done;
635 }
636
637 /* check whether we have some ACLs set to redirect this request */
638 list_for_each_entry(rule, &px->redirect_rules, list) {
639 if (rule->cond) {
640 int ret;
641
642 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
643 ret = acl_pass(ret);
644 if (rule->cond->pol == ACL_COND_UNLESS)
645 ret = !ret;
646 if (!ret)
647 continue;
648 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200649 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200650 goto return_bad_req;
651 goto done;
652 }
653
654 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
655 * If this happens, then the data will not come immediately, so we must
656 * send all what we have without waiting. Note that due to the small gain
657 * in waiting for the body of the request, it's easier to simply put the
658 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
659 * itself once used.
660 */
661 req->flags |= CF_SEND_DONTWAIT;
662
663 done: /* done with this analyser, continue with next ones that the calling
664 * points will have set, if any.
665 */
666 req->analyse_exp = TICK_ETERNITY;
667 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
668 req->analysers &= ~an_bit;
669 return 1;
670
671 tarpit:
672 /* Allow cookie logging
673 */
674 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200675 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200676
677 /* When a connection is tarpitted, we use the tarpit timeout,
678 * which may be the same as the connect timeout if unspecified.
679 * If unset, then set it to zero because we really want it to
680 * eventually expire. We build the tarpit as an analyser.
681 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100682 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683
684 /* wipe the request out so that we can drop the connection early
685 * if the client closes first.
686 */
687 channel_dont_connect(req);
688
689 txn->status = http_err_codes[deny_status];
690
691 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
692 req->analysers |= AN_REQ_HTTP_TARPIT;
693 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
694 if (!req->analyse_exp)
695 req->analyse_exp = tick_add(now_ms, 0);
696 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100697 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100699 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100701 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702 goto done_without_exp;
703
704 deny: /* this request was blocked (denied) */
705
706 /* Allow cookie logging
707 */
708 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200709 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710
711 txn->flags |= TX_CLDENY;
712 txn->status = http_err_codes[deny_status];
713 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100714 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100716 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100718 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200719 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100720 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200721 goto return_prx_cond;
722
723 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200724 txn->req.err_state = txn->req.msg_state;
725 txn->req.msg_state = HTTP_MSG_ERROR;
726 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100727 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200728
Olivier Houcharda798bf52019-03-08 18:52:00 +0100729 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200730 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100731 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200732
733 return_prx_cond:
734 if (!(s->flags & SF_ERR_MASK))
735 s->flags |= SF_ERR_PRXCOND;
736 if (!(s->flags & SF_FINST_MASK))
737 s->flags |= SF_FINST_R;
738
739 req->analysers &= AN_REQ_FLT_END;
740 req->analyse_exp = TICK_ETERNITY;
741 return 0;
742
743 return_prx_yield:
744 channel_dont_connect(req);
745 return 0;
746}
747
748/* This function performs all the processing enabled for the current request.
749 * It returns 1 if the processing can continue on next analysers, or zero if it
750 * needs more data, encounters an error, or wants to immediately abort the
751 * request. It relies on buffers flags, and updates s->req.analysers.
752 */
753int htx_process_request(struct stream *s, struct channel *req, int an_bit)
754{
755 struct session *sess = s->sess;
756 struct http_txn *txn = s->txn;
757 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200758 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200759 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
760
761 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
762 /* we need more data */
763 channel_dont_connect(req);
764 return 0;
765 }
766
767 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
768 now_ms, __FUNCTION__,
769 s,
770 req,
771 req->rex, req->wex,
772 req->flags,
773 ci_data(req),
774 req->analysers);
775
776 /*
777 * Right now, we know that we have processed the entire headers
778 * and that unwanted requests have been filtered out. We can do
779 * whatever we want with the remaining request. Also, now we
780 * may have separate values for ->fe, ->be.
781 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100782 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 /*
785 * If HTTP PROXY is set we simply get remote server address parsing
786 * incoming request. Note that this requires that a connection is
787 * allocated on the server side.
788 */
789 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
790 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100791 struct htx_sl *sl;
792 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793
794 /* Note that for now we don't reuse existing proxy connections */
795 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
796 txn->req.err_state = txn->req.msg_state;
797 txn->req.msg_state = HTTP_MSG_ERROR;
798 txn->status = 500;
799 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100800 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200801
802 if (!(s->flags & SF_ERR_MASK))
803 s->flags |= SF_ERR_RESOURCE;
804 if (!(s->flags & SF_FINST_MASK))
805 s->flags |= SF_FINST_R;
806
807 return 0;
808 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200809 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100810 uri = htx_sl_req_uri(sl);
811 path = http_get_path(uri);
812 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 goto return_bad_req;
814
815 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200816 * uri.ptr and path.ptr (excluded). If it was not found, we need
817 * to replace from all the uri by a single "/".
818 *
819 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100820 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200821 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200822 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100823 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200824 }
825
826 /*
827 * 7: Now we can work with the cookies.
828 * Note that doing so might move headers in the request, but
829 * the fields will stay coherent and the URI will not move.
830 * This should only be performed in the backend.
831 */
832 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100833 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834
835 /* add unique-id if "header-unique-id" is specified */
836
837 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
838 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
839 goto return_bad_req;
840 s->unique_id[0] = '\0';
841 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
842 }
843
844 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200845 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
846 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
847
848 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200850 }
851
852 /*
853 * 9: add X-Forwarded-For if either the frontend or the backend
854 * asks for it.
855 */
856 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200857 struct http_hdr_ctx ctx = { .blk = NULL };
858 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
859 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
860
Christopher Faulete0768eb2018-10-03 16:38:02 +0200861 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863 /* The header is set to be added only if none is present
864 * and we found it, so don't do anything.
865 */
866 }
867 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
868 /* Add an X-Forwarded-For header unless the source IP is
869 * in the 'except' network range.
870 */
871 if ((!sess->fe->except_mask.s_addr ||
872 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
873 != sess->fe->except_net.s_addr) &&
874 (!s->be->except_mask.s_addr ||
875 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
876 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200877 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878
879 /* Note: we rely on the backend to get the header name to be used for
880 * x-forwarded-for, because the header is really meant for the backends.
881 * However, if the backend did not specify any option, we have to rely
882 * on the frontend's header name.
883 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200884 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
885 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200886 goto return_bad_req;
887 }
888 }
889 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
890 /* FIXME: for the sake of completeness, we should also support
891 * 'except' here, although it is mostly useless in this case.
892 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200893 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200894
Christopher Faulete0768eb2018-10-03 16:38:02 +0200895 inet_ntop(AF_INET6,
896 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
897 pn, sizeof(pn));
898
899 /* Note: we rely on the backend to get the header name to be used for
900 * x-forwarded-for, because the header is really meant for the backends.
901 * However, if the backend did not specify any option, we have to rely
902 * on the frontend's header name.
903 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200904 chunk_printf(&trash, "%s", pn);
905 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200906 goto return_bad_req;
907 }
908 }
909
910 /*
911 * 10: add X-Original-To if either the frontend or the backend
912 * asks for it.
913 */
914 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
915
916 /* FIXME: don't know if IPv6 can handle that case too. */
917 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
918 /* Add an X-Original-To header unless the destination IP is
919 * in the 'except' network range.
920 */
921 conn_get_to_addr(cli_conn);
922
923 if (cli_conn->addr.to.ss_family == AF_INET &&
924 ((!sess->fe->except_mask_to.s_addr ||
925 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
926 != sess->fe->except_to.s_addr) &&
927 (!s->be->except_mask_to.s_addr ||
928 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
929 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200930 struct ist hdr;
931 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932
933 /* Note: we rely on the backend to get the header name to be used for
934 * x-original-to, because the header is really meant for the backends.
935 * However, if the backend did not specify any option, we have to rely
936 * on the frontend's header name.
937 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200938 if (s->be->orgto_hdr_len)
939 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
940 else
941 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200943 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
944 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 goto return_bad_req;
946 }
947 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 }
949
Christopher Faulete0768eb2018-10-03 16:38:02 +0200950 /* If we have no server assigned yet and we're balancing on url_param
951 * with a POST request, we may be interested in checking the body for
952 * that parameter. This will be done in another analyser.
953 */
954 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100955 s->txn->meth == HTTP_METH_POST &&
956 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 channel_dont_connect(req);
958 req->analysers |= AN_REQ_HTTP_BODY;
959 }
960
961 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
962 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100963
Christopher Faulete0768eb2018-10-03 16:38:02 +0200964 /* We expect some data from the client. Unless we know for sure
965 * we already have a full request, we have to re-enable quick-ack
966 * in case we previously disabled it, otherwise we might cause
967 * the client to delay further data.
968 */
969 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200970 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100971 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200972
973 /*************************************************************
974 * OK, that's finished for the headers. We have done what we *
975 * could. Let's switch to the DATA state. *
976 ************************************************************/
977 req->analyse_exp = TICK_ETERNITY;
978 req->analysers &= ~an_bit;
979
980 s->logs.tv_request = now;
981 /* OK let's go on with the BODY now */
982 return 1;
983
984 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200985 txn->req.err_state = txn->req.msg_state;
986 txn->req.msg_state = HTTP_MSG_ERROR;
987 txn->status = 400;
988 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100989 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200990
Olivier Houcharda798bf52019-03-08 18:52:00 +0100991 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200992 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100993 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200994
995 if (!(s->flags & SF_ERR_MASK))
996 s->flags |= SF_ERR_PRXCOND;
997 if (!(s->flags & SF_FINST_MASK))
998 s->flags |= SF_FINST_R;
999 return 0;
1000}
1001
1002/* This function is an analyser which processes the HTTP tarpit. It always
1003 * returns zero, at the beginning because it prevents any other processing
1004 * from occurring, and at the end because it terminates the request.
1005 */
1006int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1007{
1008 struct http_txn *txn = s->txn;
1009
1010 /* This connection is being tarpitted. The CLIENT side has
1011 * already set the connect expiration date to the right
1012 * timeout. We just have to check that the client is still
1013 * there and that the timeout has not expired.
1014 */
1015 channel_dont_connect(req);
1016 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1017 !tick_is_expired(req->analyse_exp, now_ms))
1018 return 0;
1019
1020 /* We will set the queue timer to the time spent, just for
1021 * logging purposes. We fake a 500 server error, so that the
1022 * attacker will not suspect his connection has been tarpitted.
1023 * It will not cause trouble to the logs because we can exclude
1024 * the tarpitted connections by filtering on the 'PT' status flags.
1025 */
1026 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1027
1028 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001029 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001030
1031 req->analysers &= AN_REQ_FLT_END;
1032 req->analyse_exp = TICK_ETERNITY;
1033
1034 if (!(s->flags & SF_ERR_MASK))
1035 s->flags |= SF_ERR_PRXCOND;
1036 if (!(s->flags & SF_FINST_MASK))
1037 s->flags |= SF_FINST_T;
1038 return 0;
1039}
1040
1041/* This function is an analyser which waits for the HTTP request body. It waits
1042 * for either the buffer to be full, or the full advertised contents to have
1043 * reached the buffer. It must only be called after the standard HTTP request
1044 * processing has occurred, because it expects the request to be parsed and will
1045 * look for the Expect header. It may send a 100-Continue interim response. It
1046 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1047 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1048 * needs to read more data, or 1 once it has completed its analysis.
1049 */
1050int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1051{
1052 struct session *sess = s->sess;
1053 struct http_txn *txn = s->txn;
1054 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001055 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001056
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057
1058 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1059 now_ms, __FUNCTION__,
1060 s,
1061 req,
1062 req->rex, req->wex,
1063 req->flags,
1064 ci_data(req),
1065 req->analysers);
1066
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001067 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068
Willy Tarreau4236f032019-03-05 10:43:32 +01001069 if (htx->flags & HTX_FL_PARSING_ERROR)
1070 goto return_bad_req;
1071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 if (msg->msg_state < HTTP_MSG_BODY)
1073 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001074
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075 /* We have to parse the HTTP request body to find any required data.
1076 * "balance url_param check_post" should have been the only way to get
1077 * into this. We were brought here after HTTP header analysis, so all
1078 * related structures are ready.
1079 */
1080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001082 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1083 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 }
1085
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001086 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1089 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001092 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 goto http_end;
1094
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1097 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001098 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001099
1100 if (!(s->flags & SF_ERR_MASK))
1101 s->flags |= SF_ERR_CLITO;
1102 if (!(s->flags & SF_FINST_MASK))
1103 s->flags |= SF_FINST_D;
1104 goto return_err_msg;
1105 }
1106
1107 /* we get here if we need to wait for more data */
1108 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1109 /* Not enough data. We'll re-use the http-request
1110 * timeout here. Ideally, we should set the timeout
1111 * relative to the accept() date. We just set the
1112 * request timeout once at the beginning of the
1113 * request.
1114 */
1115 channel_dont_connect(req);
1116 if (!tick_isset(req->analyse_exp))
1117 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1118 return 0;
1119 }
1120
1121 http_end:
1122 /* The situation will not evolve, so let's give up on the analysis. */
1123 s->logs.tv_request = now; /* update the request timer to reflect full request */
1124 req->analysers &= ~an_bit;
1125 req->analyse_exp = TICK_ETERNITY;
1126 return 1;
1127
1128 return_bad_req: /* let's centralize all bad requests */
1129 txn->req.err_state = txn->req.msg_state;
1130 txn->req.msg_state = HTTP_MSG_ERROR;
1131 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001132 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001133
1134 if (!(s->flags & SF_ERR_MASK))
1135 s->flags |= SF_ERR_PRXCOND;
1136 if (!(s->flags & SF_FINST_MASK))
1137 s->flags |= SF_FINST_R;
1138
1139 return_err_msg:
1140 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001141 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001142 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001143 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001144 return 0;
1145}
1146
1147/* This function is an analyser which forwards request body (including chunk
1148 * sizes if any). It is called as soon as we must forward, even if we forward
1149 * zero byte. The only situation where it must not be called is when we're in
1150 * tunnel mode and we want to forward till the close. It's used both to forward
1151 * remaining data and to resync after end of body. It expects the msg_state to
1152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1153 * read more data, or 1 once we can go on with next request or end the stream.
1154 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1155 * bytes of pending data + the headers if not already done.
1156 */
1157int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1158{
1159 struct session *sess = s->sess;
1160 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001161 struct http_msg *msg = &txn->req;
1162 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001163 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001164 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001165
1166 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1167 now_ms, __FUNCTION__,
1168 s,
1169 req,
1170 req->rex, req->wex,
1171 req->flags,
1172 ci_data(req),
1173 req->analysers);
1174
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001175 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176
1177 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1178 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1179 /* Output closed while we were sending data. We must abort and
1180 * wake the other side up.
1181 */
1182 msg->err_state = msg->msg_state;
1183 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001184 htx_end_request(s);
1185 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186 return 1;
1187 }
1188
1189 /* Note that we don't have to send 100-continue back because we don't
1190 * need the data to complete our job, and it's up to the server to
1191 * decide whether to return 100, 417 or anything else in return of
1192 * an "Expect: 100-continue" header.
1193 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001194 if (msg->msg_state == HTTP_MSG_BODY)
1195 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001196
1197 /* Some post-connect processing might want us to refrain from starting to
1198 * forward data. Currently, the only reason for this is "balance url_param"
1199 * whichs need to parse/process the request after we've enabled forwarding.
1200 */
1201 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1202 if (!(s->res.flags & CF_READ_ATTACHED)) {
1203 channel_auto_connect(req);
1204 req->flags |= CF_WAKE_CONNECT;
1205 channel_dont_close(req); /* don't fail on early shutr */
1206 goto waiting;
1207 }
1208 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1209 }
1210
1211 /* in most states, we should abort in case of early close */
1212 channel_auto_close(req);
1213
1214 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001215 if (req->to_forward == CHN_INFINITE_FORWARD) {
1216 if (req->flags & (CF_SHUTR|CF_EOI)) {
1217 msg->msg_state = HTTP_MSG_DONE;
1218 req->to_forward = 0;
1219 goto done;
1220 }
1221 }
1222 else {
1223 /* We can't process the buffer's contents yet */
1224 req->flags |= CF_WAKE_WRITE;
1225 goto missing_data_or_waiting;
1226 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001227 }
1228
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 if (msg->msg_state >= HTTP_MSG_DONE)
1230 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001231 /* Forward input data. We get it by removing all outgoing data not
1232 * forwarded yet from HTX data size. If there are some data filters, we
1233 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001234 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001235 if (HAS_REQ_DATA_FILTERS(s)) {
1236 ret = flt_http_payload(s, msg, htx->data);
1237 if (ret < 0)
1238 goto return_bad_req;
1239 c_adv(req, ret);
1240 if (htx->data != co_data(req) || htx->extra)
1241 goto missing_data_or_waiting;
1242 }
1243 else {
1244 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001245 if (msg->flags & HTTP_MSGF_XFER_LEN)
1246 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001247 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001248
Christopher Faulet9768c262018-10-22 09:34:31 +02001249 /* Check if the end-of-message is reached and if so, switch the message
1250 * in HTTP_MSG_DONE state.
1251 */
1252 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1253 goto missing_data_or_waiting;
1254
1255 msg->msg_state = HTTP_MSG_DONE;
1256
1257 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258 /* other states, DONE...TUNNEL */
1259 /* we don't want to forward closes on DONE except in tunnel mode. */
1260 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1261 channel_dont_close(req);
1262
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001263 if (HAS_REQ_DATA_FILTERS(s)) {
1264 ret = flt_http_end(s, msg);
1265 if (ret <= 0) {
1266 if (!ret)
1267 goto missing_data_or_waiting;
1268 goto return_bad_req;
1269 }
1270 }
1271
Christopher Fauletf2824e62018-10-01 12:12:37 +02001272 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001273 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001274 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001275 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1276 if (req->flags & CF_SHUTW) {
1277 /* request errors are most likely due to the
1278 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001279 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 goto return_bad_req;
1282 }
1283 return 1;
1284 }
1285
1286 /* If "option abortonclose" is set on the backend, we want to monitor
1287 * the client's connection and forward any shutdown notification to the
1288 * server, which will decide whether to close or to go on processing the
1289 * request. We only do that in tunnel mode, and not in other modes since
1290 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001291 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001292 channel_auto_read(req);
1293 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1294 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1295 s->si[1].flags |= SI_FL_NOLINGER;
1296 channel_auto_close(req);
1297 }
1298 else if (s->txn->meth == HTTP_METH_POST) {
1299 /* POST requests may require to read extra CRLF sent by broken
1300 * browsers and which could cause an RST to be sent upon close
1301 * on some systems (eg: Linux). */
1302 channel_auto_read(req);
1303 }
1304 return 0;
1305
1306 missing_data_or_waiting:
1307 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001308 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1309 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001310
1311 waiting:
1312 /* waiting for the last bits to leave the buffer */
1313 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001314 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001315
Christopher Faulet47365272018-10-31 17:40:50 +01001316 if (htx->flags & HTX_FL_PARSING_ERROR)
1317 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001318
Christopher Faulete0768eb2018-10-03 16:38:02 +02001319 /* When TE: chunked is used, we need to get there again to parse remaining
1320 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1321 * And when content-length is used, we never want to let the possible
1322 * shutdown be forwarded to the other side, as the state machine will
1323 * take care of it once the client responds. It's also important to
1324 * prevent TIME_WAITs from accumulating on the backend side, and for
1325 * HTTP/2 where the last frame comes with a shutdown.
1326 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001327 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001328 channel_dont_close(req);
1329
1330 /* We know that more data are expected, but we couldn't send more that
1331 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1332 * system knows it must not set a PUSH on this first part. Interactive
1333 * modes are already handled by the stream sock layer. We must not do
1334 * this in content-length mode because it could present the MSG_MORE
1335 * flag with the last block of forwarded data, which would cause an
1336 * additional delay to be observed by the receiver.
1337 */
1338 if (msg->flags & HTTP_MSGF_TE_CHNK)
1339 req->flags |= CF_EXPECT_MORE;
1340
1341 return 0;
1342
Christopher Faulet93e02d82019-03-08 14:18:50 +01001343 return_cli_abort:
1344 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1345 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1346 if (objt_server(s->target))
1347 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1348 if (!(s->flags & SF_ERR_MASK))
1349 s->flags |= SF_ERR_CLICL;
1350 status = 400;
1351 goto return_error;
1352
1353 return_srv_abort:
1354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1355 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1356 if (objt_server(s->target))
1357 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1358 if (!(s->flags & SF_ERR_MASK))
1359 s->flags |= SF_ERR_SRVCL;
1360 status = 502;
1361 goto return_error;
1362
1363 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001364 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001366 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001368 s->flags |= SF_ERR_CLICL;
1369 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370
Christopher Faulet93e02d82019-03-08 14:18:50 +01001371 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 txn->req.err_state = txn->req.msg_state;
1373 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001374 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001376 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001378 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001379 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001380 }
1381 req->analysers &= AN_REQ_FLT_END;
1382 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 +01001383 if (!(s->flags & SF_FINST_MASK))
1384 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001385 return 0;
1386}
1387
1388/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1389 * processing can continue on next analysers, or zero if it either needs more
1390 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1391 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1392 * when it has nothing left to do, and may remove any analyser when it wants to
1393 * abort.
1394 */
1395int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1396{
Christopher Faulet9768c262018-10-22 09:34:31 +02001397 /*
1398 * We will analyze a complete HTTP response to check the its syntax.
1399 *
1400 * Once the start line and all headers are received, we may perform a
1401 * capture of the error (if any), and we will set a few fields. We also
1402 * logging and finally headers capture.
1403 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001404 struct session *sess = s->sess;
1405 struct http_txn *txn = s->txn;
1406 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001407 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001408 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001409 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001410 int n;
1411
1412 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1413 now_ms, __FUNCTION__,
1414 s,
1415 rep,
1416 rep->rex, rep->wex,
1417 rep->flags,
1418 ci_data(rep),
1419 rep->analysers);
1420
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001421 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001422
Willy Tarreau4236f032019-03-05 10:43:32 +01001423 /* Parsing errors are caught here */
1424 if (htx->flags & HTX_FL_PARSING_ERROR)
1425 goto return_bad_res;
1426
Christopher Faulete0768eb2018-10-03 16:38:02 +02001427 /*
1428 * Now we quickly check if we have found a full valid response.
1429 * If not so, we check the FD and buffer states before leaving.
1430 * A full response is indicated by the fact that we have seen
1431 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1432 * responses are checked first.
1433 *
1434 * Depending on whether the client is still there or not, we
1435 * may send an error response back or not. Note that normally
1436 * we should only check for HTTP status there, and check I/O
1437 * errors somewhere else.
1438 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001439 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001440 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001441 * First catch invalid response because of a parsing error or
1442 * because only part of headers have been transfered.
1443 * Multiplexers have the responsibility to emit all headers at
1444 * once. We must be sure to have forwarded all outgoing data
1445 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001446 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001447 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001448 goto return_bad_res;
1449
Christopher Faulet9768c262018-10-22 09:34:31 +02001450 /* 1: have we encountered a read error ? */
1451 if (rep->flags & CF_READ_ERROR) {
1452 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001453 goto abort_keep_alive;
1454
Olivier Houcharda798bf52019-03-08 18:52:00 +01001455 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001457 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001458 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001459 }
1460
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 rep->analysers &= AN_RES_FLT_END;
1462 txn->status = 502;
1463
1464 /* Check to see if the server refused the early data.
1465 * If so, just send a 425
1466 */
1467 if (objt_cs(s->si[1].end)) {
1468 struct connection *conn = objt_cs(s->si[1].end)->conn;
1469
1470 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1471 txn->status = 425;
1472 }
1473
1474 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001475 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001476
1477 if (!(s->flags & SF_ERR_MASK))
1478 s->flags |= SF_ERR_SRVCL;
1479 if (!(s->flags & SF_FINST_MASK))
1480 s->flags |= SF_FINST_H;
1481 return 0;
1482 }
1483
Christopher Faulet9768c262018-10-22 09:34:31 +02001484 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001486 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001487 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001488 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001489 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001490 }
1491
Christopher Faulete0768eb2018-10-03 16:38:02 +02001492 rep->analysers &= AN_RES_FLT_END;
1493 txn->status = 504;
1494 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001495 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496
1497 if (!(s->flags & SF_ERR_MASK))
1498 s->flags |= SF_ERR_SRVTO;
1499 if (!(s->flags & SF_FINST_MASK))
1500 s->flags |= SF_FINST_H;
1501 return 0;
1502 }
1503
Christopher Faulet9768c262018-10-22 09:34:31 +02001504 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001506 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1507 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001509 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510
1511 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001513 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514
1515 if (!(s->flags & SF_ERR_MASK))
1516 s->flags |= SF_ERR_CLICL;
1517 if (!(s->flags & SF_FINST_MASK))
1518 s->flags |= SF_FINST_H;
1519
1520 /* process_stream() will take care of the error */
1521 return 0;
1522 }
1523
Christopher Faulet9768c262018-10-22 09:34:31 +02001524 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001526 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 goto abort_keep_alive;
1528
Olivier Houcharda798bf52019-03-08 18:52:00 +01001529 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001531 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001532 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001533 }
1534
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 rep->analysers &= AN_RES_FLT_END;
1536 txn->status = 502;
1537 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001538 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539
1540 if (!(s->flags & SF_ERR_MASK))
1541 s->flags |= SF_ERR_SRVCL;
1542 if (!(s->flags & SF_FINST_MASK))
1543 s->flags |= SF_FINST_H;
1544 return 0;
1545 }
1546
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001549 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 goto abort_keep_alive;
1551
Olivier Houcharda798bf52019-03-08 18:52:00 +01001552 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554
1555 if (!(s->flags & SF_ERR_MASK))
1556 s->flags |= SF_ERR_CLICL;
1557 if (!(s->flags & SF_FINST_MASK))
1558 s->flags |= SF_FINST_H;
1559
1560 /* process_stream() will take care of the error */
1561 return 0;
1562 }
1563
1564 channel_dont_close(rep);
1565 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1566 return 0;
1567 }
1568
1569 /* More interesting part now : we know that we have a complete
1570 * response which at least looks like HTTP. We have an indicator
1571 * of each header's length, so we can parse them quickly.
1572 */
1573
Christopher Faulet9768c262018-10-22 09:34:31 +02001574 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001575 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576
Christopher Faulet9768c262018-10-22 09:34:31 +02001577 /* 0: we might have to print this header in debug mode */
1578 if (unlikely((global.mode & MODE_DEBUG) &&
1579 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1580 int32_t pos;
1581
Christopher Faulet03599112018-11-27 11:21:21 +01001582 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001583
1584 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1585 struct htx_blk *blk = htx_get_blk(htx, pos);
1586 enum htx_blk_type type = htx_get_blk_type(blk);
1587
1588 if (type == HTX_BLK_EOH)
1589 break;
1590 if (type != HTX_BLK_HDR)
1591 continue;
1592
1593 htx_debug_hdr("srvhdr", s,
1594 htx_get_blk_name(htx, blk),
1595 htx_get_blk_value(htx, blk));
1596 }
1597 }
1598
Christopher Faulet03599112018-11-27 11:21:21 +01001599 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001600 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001601 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001602 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001603 if (sl->flags & HTX_SL_F_XFER_LEN) {
1604 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001605 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001606 if (sl->flags & HTX_SL_F_BODYLESS)
1607 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001608 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001609
1610 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001611 if (n < 1 || n > 5)
1612 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001613
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614 /* when the client triggers a 4xx from the server, it's most often due
1615 * to a missing object or permission. These events should be tracked
1616 * because if they happen often, it may indicate a brute force or a
1617 * vulnerability scan.
1618 */
1619 if (n == 4)
1620 stream_inc_http_err_ctr(s);
1621
1622 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001623 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625 /* Adjust server's health based on status code. Note: status codes 501
1626 * and 505 are triggered on demand by client request, so we must not
1627 * count them as server failures.
1628 */
1629 if (objt_server(s->target)) {
1630 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001631 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001632 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001633 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 }
1635
1636 /*
1637 * We may be facing a 100-continue response, or any other informational
1638 * 1xx response which is non-final, in which case this is not the right
1639 * response, and we're waiting for the next one. Let's allow this response
1640 * to go to the client and wait for the next one. There's an exception for
1641 * 101 which is used later in the code to switch protocols.
1642 */
1643 if (txn->status < 200 &&
1644 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001645 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001646 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647 msg->msg_state = HTTP_MSG_RPBEFORE;
1648 txn->status = 0;
1649 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001650 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001651 }
1652
1653 /*
1654 * 2: check for cacheability.
1655 */
1656
1657 switch (txn->status) {
1658 case 200:
1659 case 203:
1660 case 204:
1661 case 206:
1662 case 300:
1663 case 301:
1664 case 404:
1665 case 405:
1666 case 410:
1667 case 414:
1668 case 501:
1669 break;
1670 default:
1671 /* RFC7231#6.1:
1672 * Responses with status codes that are defined as
1673 * cacheable by default (e.g., 200, 203, 204, 206,
1674 * 300, 301, 404, 405, 410, 414, and 501 in this
1675 * specification) can be reused by a cache with
1676 * heuristic expiration unless otherwise indicated
1677 * by the method definition or explicit cache
1678 * controls [RFC7234]; all other status codes are
1679 * not cacheable by default.
1680 */
1681 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1682 break;
1683 }
1684
1685 /*
1686 * 3: we may need to capture headers
1687 */
1688 s->logs.logwait &= ~LW_RESP;
1689 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001690 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001691
Christopher Faulet9768c262018-10-22 09:34:31 +02001692 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001693 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1694 txn->status == 101)) {
1695 /* Either we've established an explicit tunnel, or we're
1696 * switching the protocol. In both cases, we're very unlikely
1697 * to understand the next protocols. We have to switch to tunnel
1698 * mode, so that we transfer the request and responses then let
1699 * this protocol pass unmodified. When we later implement specific
1700 * parsers for such protocols, we'll want to check the Upgrade
1701 * header which contains information about that protocol for
1702 * responses with status 101 (eg: see RFC2817 about TLS).
1703 */
1704 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705 }
1706
Christopher Faulet61608322018-11-23 16:23:45 +01001707 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1708 * 407 (Proxy-Authenticate) responses and set the connection to private
1709 */
1710 srv_conn = cs_conn(objt_cs(s->si[1].end));
1711 if (srv_conn) {
1712 struct ist hdr;
1713 struct http_hdr_ctx ctx;
1714
1715 if (txn->status == 401)
1716 hdr = ist("WWW-Authenticate");
1717 else if (txn->status == 407)
1718 hdr = ist("Proxy-Authenticate");
1719 else
1720 goto end;
1721
1722 ctx.blk = NULL;
1723 while (http_find_header(htx, hdr, &ctx, 0)) {
1724 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1725 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1726 srv_conn->flags |= CO_FL_PRIVATE;
1727 }
1728 }
1729
1730 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001731 /* we want to have the response time before we start processing it */
1732 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1733
1734 /* end of job, return OK */
1735 rep->analysers &= ~an_bit;
1736 rep->analyse_exp = TICK_ETERNITY;
1737 channel_auto_close(rep);
1738 return 1;
1739
Christopher Faulet47365272018-10-31 17:40:50 +01001740 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001741 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001742 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001743 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001744 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001745 }
1746 txn->status = 502;
1747 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001748 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001749 rep->analysers &= AN_RES_FLT_END;
1750
1751 if (!(s->flags & SF_ERR_MASK))
1752 s->flags |= SF_ERR_PRXCOND;
1753 if (!(s->flags & SF_FINST_MASK))
1754 s->flags |= SF_FINST_H;
1755 return 0;
1756
Christopher Faulete0768eb2018-10-03 16:38:02 +02001757 abort_keep_alive:
1758 /* A keep-alive request to the server failed on a network error.
1759 * The client is required to retry. We need to close without returning
1760 * any other information so that the client retries.
1761 */
1762 txn->status = 0;
1763 rep->analysers &= AN_RES_FLT_END;
1764 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001765 s->logs.logwait = 0;
1766 s->logs.level = 0;
1767 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001768 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001769 return 0;
1770}
1771
1772/* This function performs all the processing enabled for the current response.
1773 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1774 * and updates s->res.analysers. It might make sense to explode it into several
1775 * other functions. It works like process_request (see indications above).
1776 */
1777int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1778{
1779 struct session *sess = s->sess;
1780 struct http_txn *txn = s->txn;
1781 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001782 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001783 struct proxy *cur_proxy;
1784 struct cond_wordlist *wl;
1785 enum rule_result ret = HTTP_RULE_RES_CONT;
1786
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001787 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1788 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001789
Christopher Faulete0768eb2018-10-03 16:38:02 +02001790 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1791 now_ms, __FUNCTION__,
1792 s,
1793 rep,
1794 rep->rex, rep->wex,
1795 rep->flags,
1796 ci_data(rep),
1797 rep->analysers);
1798
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001799 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001800
1801 /* The stats applet needs to adjust the Connection header but we don't
1802 * apply any filter there.
1803 */
1804 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1805 rep->analysers &= ~an_bit;
1806 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001807 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001808 }
1809
1810 /*
1811 * We will have to evaluate the filters.
1812 * As opposed to version 1.2, now they will be evaluated in the
1813 * filters order and not in the header order. This means that
1814 * each filter has to be validated among all headers.
1815 *
1816 * Filters are tried with ->be first, then with ->fe if it is
1817 * different from ->be.
1818 *
1819 * Maybe we are in resume condiion. In this case I choose the
1820 * "struct proxy" which contains the rule list matching the resume
1821 * pointer. If none of theses "struct proxy" match, I initialise
1822 * the process with the first one.
1823 *
1824 * In fact, I check only correspondance betwwen the current list
1825 * pointer and the ->fe rule list. If it doesn't match, I initialize
1826 * the loop with the ->be.
1827 */
1828 if (s->current_rule_list == &sess->fe->http_res_rules)
1829 cur_proxy = sess->fe;
1830 else
1831 cur_proxy = s->be;
1832 while (1) {
1833 struct proxy *rule_set = cur_proxy;
1834
1835 /* evaluate http-response rules */
1836 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001837 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001838
1839 if (ret == HTTP_RULE_RES_BADREQ)
1840 goto return_srv_prx_502;
1841
1842 if (ret == HTTP_RULE_RES_DONE) {
1843 rep->analysers &= ~an_bit;
1844 rep->analyse_exp = TICK_ETERNITY;
1845 return 1;
1846 }
1847 }
1848
1849 /* we need to be called again. */
1850 if (ret == HTTP_RULE_RES_YIELD) {
1851 channel_dont_close(rep);
1852 return 0;
1853 }
1854
1855 /* try headers filters */
1856 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001857 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1858 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 }
1860
1861 /* has the response been denied ? */
1862 if (txn->flags & TX_SVDENY) {
1863 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001864 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001865
Olivier Houcharda798bf52019-03-08 18:52:00 +01001866 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1867 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001868 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001869 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001870 goto return_srv_prx_502;
1871 }
1872
1873 /* add response headers from the rule sets in the same order */
1874 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001875 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001876 if (txn->status < 200 && txn->status != 101)
1877 break;
1878 if (wl->cond) {
1879 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1880 ret = acl_pass(ret);
1881 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1882 ret = !ret;
1883 if (!ret)
1884 continue;
1885 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001886
1887 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1888 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001889 goto return_bad_resp;
1890 }
1891
1892 /* check whether we're already working on the frontend */
1893 if (cur_proxy == sess->fe)
1894 break;
1895 cur_proxy = sess->fe;
1896 }
1897
1898 /* After this point, this anayzer can't return yield, so we can
1899 * remove the bit corresponding to this analyzer from the list.
1900 *
1901 * Note that the intermediate returns and goto found previously
1902 * reset the analyzers.
1903 */
1904 rep->analysers &= ~an_bit;
1905 rep->analyse_exp = TICK_ETERNITY;
1906
1907 /* OK that's all we can do for 1xx responses */
1908 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001909 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001910
1911 /*
1912 * Now check for a server cookie.
1913 */
1914 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001915 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001916
1917 /*
1918 * Check for cache-control or pragma headers if required.
1919 */
1920 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1921 check_response_for_cacheability(s, rep);
1922
1923 /*
1924 * Add server cookie in the response if needed
1925 */
1926 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1927 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1928 (!(s->flags & SF_DIRECT) ||
1929 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1930 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1931 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1932 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1933 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1934 !(s->flags & SF_IGNORE_PRST)) {
1935 /* the server is known, it's not the one the client requested, or the
1936 * cookie's last seen date needs to be refreshed. We have to
1937 * insert a set-cookie here, except if we want to insert only on POST
1938 * requests and this one isn't. Note that servers which don't have cookies
1939 * (eg: some backup servers) will return a full cookie removal request.
1940 */
1941 if (!objt_server(s->target)->cookie) {
1942 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944 s->be->cookie_name);
1945 }
1946 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001947 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001948
1949 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1950 /* emit last_date, which is mandatory */
1951 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1952 s30tob64((date.tv_sec+3) >> 2,
1953 trash.area + trash.data);
1954 trash.data += 5;
1955
1956 if (s->be->cookie_maxlife) {
1957 /* emit first_date, which is either the original one or
1958 * the current date.
1959 */
1960 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1961 s30tob64(txn->cookie_first_date ?
1962 txn->cookie_first_date >> 2 :
1963 (date.tv_sec+3) >> 2,
1964 trash.area + trash.data);
1965 trash.data += 5;
1966 }
1967 }
1968 chunk_appendf(&trash, "; path=/");
1969 }
1970
1971 if (s->be->cookie_domain)
1972 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1973
1974 if (s->be->ck_opts & PR_CK_HTTPONLY)
1975 chunk_appendf(&trash, "; HttpOnly");
1976
1977 if (s->be->ck_opts & PR_CK_SECURE)
1978 chunk_appendf(&trash, "; Secure");
1979
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001980 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001981 goto return_bad_resp;
1982
1983 txn->flags &= ~TX_SCK_MASK;
1984 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1985 /* the server did not change, only the date was updated */
1986 txn->flags |= TX_SCK_UPDATED;
1987 else
1988 txn->flags |= TX_SCK_INSERTED;
1989
1990 /* Here, we will tell an eventual cache on the client side that we don't
1991 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1992 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1993 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1994 */
1995 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1996
1997 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1998
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001999 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002000 goto return_bad_resp;
2001 }
2002 }
2003
2004 /*
2005 * Check if result will be cacheable with a cookie.
2006 * We'll block the response if security checks have caught
2007 * nasty things such as a cacheable cookie.
2008 */
2009 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2010 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2011 (s->be->options & PR_O_CHK_CACHE)) {
2012 /* we're in presence of a cacheable response containing
2013 * a set-cookie header. We'll block it as requested by
2014 * the 'checkcache' option, and send an alert.
2015 */
2016 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002017 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002018
Olivier Houcharda798bf52019-03-08 18:52:00 +01002019 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2020 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002021 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002022 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002023
2024 ha_alert("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 send_log(s->be, LOG_ALERT,
2027 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2028 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2029 goto return_srv_prx_502;
2030 }
2031
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002032 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002033 /* Always enter in the body analyzer */
2034 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2035 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2036
2037 /* if the user wants to log as soon as possible, without counting
2038 * bytes from the server, then this is the right moment. We have
2039 * to temporarily assign bytes_out to log what we currently have.
2040 */
2041 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2042 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002043 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002044 s->do_log(s);
2045 s->logs.bytes_out = 0;
2046 }
2047 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002048
2049 return_bad_resp:
2050 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002051 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002052 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002053 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002054 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002055
2056 return_srv_prx_502:
2057 rep->analysers &= AN_RES_FLT_END;
2058 txn->status = 502;
2059 s->logs.t_data = -1; /* was not a valid response */
2060 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002061 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062 if (!(s->flags & SF_ERR_MASK))
2063 s->flags |= SF_ERR_PRXCOND;
2064 if (!(s->flags & SF_FINST_MASK))
2065 s->flags |= SF_FINST_H;
2066 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002067}
2068
2069/* This function is an analyser which forwards response body (including chunk
2070 * sizes if any). It is called as soon as we must forward, even if we forward
2071 * zero byte. The only situation where it must not be called is when we're in
2072 * tunnel mode and we want to forward till the close. It's used both to forward
2073 * remaining data and to resync after end of body. It expects the msg_state to
2074 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2075 * read more data, or 1 once we can go on with next request or end the stream.
2076 *
2077 * It is capable of compressing response data both in content-length mode and
2078 * in chunked mode. The state machines follows different flows depending on
2079 * whether content-length and chunked modes are used, since there are no
2080 * trailers in content-length :
2081 *
2082 * chk-mode cl-mode
2083 * ,----- BODY -----.
2084 * / \
2085 * V size > 0 V chk-mode
2086 * .--> SIZE -------------> DATA -------------> CRLF
2087 * | | size == 0 | last byte |
2088 * | v final crlf v inspected |
2089 * | TRAILERS -----------> DONE |
2090 * | |
2091 * `----------------------------------------------'
2092 *
2093 * Compression only happens in the DATA state, and must be flushed in final
2094 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2095 * is performed at once on final states for all bytes parsed, or when leaving
2096 * on missing data.
2097 */
2098int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2099{
2100 struct session *sess = s->sess;
2101 struct http_txn *txn = s->txn;
2102 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002103 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002104 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002105
2106 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2107 now_ms, __FUNCTION__,
2108 s,
2109 res,
2110 res->rex, res->wex,
2111 res->flags,
2112 ci_data(res),
2113 res->analysers);
2114
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002115 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002116
2117 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002118 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002119 /* Output closed while we were sending data. We must abort and
2120 * wake the other side up.
2121 */
2122 msg->err_state = msg->msg_state;
2123 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002124 htx_end_response(s);
2125 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 return 1;
2127 }
2128
Christopher Faulet9768c262018-10-22 09:34:31 +02002129 if (msg->msg_state == HTTP_MSG_BODY)
2130 msg->msg_state = HTTP_MSG_DATA;
2131
Christopher Faulete0768eb2018-10-03 16:38:02 +02002132 /* in most states, we should abort in case of early close */
2133 channel_auto_close(res);
2134
Christopher Faulete0768eb2018-10-03 16:38:02 +02002135 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002136 if (res->to_forward == CHN_INFINITE_FORWARD) {
2137 if (res->flags & (CF_SHUTR|CF_EOI)) {
2138 msg->msg_state = HTTP_MSG_DONE;
2139 res->to_forward = 0;
2140 goto done;
2141 }
2142 }
2143 else {
2144 /* We can't process the buffer's contents yet */
2145 res->flags |= CF_WAKE_WRITE;
2146 goto missing_data_or_waiting;
2147 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002148 }
2149
Christopher Faulet9768c262018-10-22 09:34:31 +02002150 if (msg->msg_state >= HTTP_MSG_DONE)
2151 goto done;
2152
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002153 /* Forward input data. We get it by removing all outgoing data not
2154 * forwarded yet from HTX data size. If there are some data filters, we
2155 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002156 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002157 if (HAS_RSP_DATA_FILTERS(s)) {
2158 ret = flt_http_payload(s, msg, htx->data);
2159 if (ret < 0)
2160 goto return_bad_res;
2161 c_adv(res, ret);
2162 if (htx->data != co_data(res) || htx->extra)
2163 goto missing_data_or_waiting;
2164 }
2165 else {
2166 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002167 if (msg->flags & HTTP_MSGF_XFER_LEN)
2168 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002169 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002170
2171 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2172 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002173 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002174 msg->msg_state = HTTP_MSG_TUNNEL;
2175 goto done;
2176 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002177 }
2178
Christopher Faulet9768c262018-10-22 09:34:31 +02002179 /* Check if the end-of-message is reached and if so, switch the message
2180 * in HTTP_MSG_DONE state.
2181 */
2182 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2183 goto missing_data_or_waiting;
2184
2185 msg->msg_state = HTTP_MSG_DONE;
2186
2187 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002188 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002189 channel_dont_close(res);
2190
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002191 if (HAS_RSP_DATA_FILTERS(s)) {
2192 ret = flt_http_end(s, msg);
2193 if (ret <= 0) {
2194 if (!ret)
2195 goto missing_data_or_waiting;
2196 goto return_bad_res;
2197 }
2198 }
2199
Christopher Fauletf2824e62018-10-01 12:12:37 +02002200 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002202 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2204 if (res->flags & CF_SHUTW) {
2205 /* response errors are most likely due to the
2206 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002207 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002208 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002209 goto return_bad_res;
2210 }
2211 return 1;
2212 }
2213 return 0;
2214
2215 missing_data_or_waiting:
2216 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002217 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002218
Christopher Faulet47365272018-10-31 17:40:50 +01002219 if (htx->flags & HTX_FL_PARSING_ERROR)
2220 goto return_bad_res;
2221
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222 /* stop waiting for data if the input is closed before the end. If the
2223 * client side was already closed, it means that the client has aborted,
2224 * so we don't want to count this as a server abort. Otherwise it's a
2225 * server abort.
2226 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002227 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002229 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002231 if (htx_is_empty(htx))
2232 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002233 }
2234
Christopher Faulete0768eb2018-10-03 16:38:02 +02002235 /* When TE: chunked is used, we need to get there again to parse
2236 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002237 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2238 * are filters registered on the stream, we don't want to forward a
2239 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002240 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002241 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 channel_dont_close(res);
2243
2244 /* We know that more data are expected, but we couldn't send more that
2245 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2246 * system knows it must not set a PUSH on this first part. Interactive
2247 * modes are already handled by the stream sock layer. We must not do
2248 * this in content-length mode because it could present the MSG_MORE
2249 * flag with the last block of forwarded data, which would cause an
2250 * additional delay to be observed by the receiver.
2251 */
2252 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2253 res->flags |= CF_EXPECT_MORE;
2254
2255 /* the stream handler will take care of timeouts and errors */
2256 return 0;
2257
Christopher Faulet93e02d82019-03-08 14:18:50 +01002258 return_srv_abort:
2259 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2260 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002262 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2263 if (!(s->flags & SF_ERR_MASK))
2264 s->flags |= SF_ERR_SRVCL;
2265 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266
Christopher Faulet93e02d82019-03-08 14:18:50 +01002267 return_cli_abort:
2268 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2269 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002270 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002271 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2272 if (!(s->flags & SF_ERR_MASK))
2273 s->flags |= SF_ERR_CLICL;
2274 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002275
Christopher Faulet93e02d82019-03-08 14:18:50 +01002276 return_bad_res:
2277 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2278 if (objt_server(s->target)) {
2279 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2280 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2281 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002283 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284
Christopher Faulet93e02d82019-03-08 14:18:50 +01002285 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 txn->rsp.err_state = txn->rsp.msg_state;
2287 txn->rsp.msg_state = HTTP_MSG_ERROR;
2288 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002289 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 res->analysers &= AN_RES_FLT_END;
2291 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 +02002292 if (!(s->flags & SF_FINST_MASK))
2293 s->flags |= SF_FINST_D;
2294 return 0;
2295}
2296
Christopher Faulet0f226952018-10-22 09:29:56 +02002297void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002298{
2299 struct proxy *fe = strm_fe(s);
2300 int tmp = TX_CON_WANT_CLO;
2301
2302 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2303 tmp = TX_CON_WANT_TUN;
2304
2305 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002306 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002307}
2308
2309/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002310 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002311 * as too large a request to build a valid response.
2312 */
2313int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2314{
Christopher Faulet99daf282018-11-28 22:58:13 +01002315 struct channel *req = &s->req;
2316 struct channel *res = &s->res;
2317 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002318 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002319 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002320 struct ist status, reason, location;
2321 unsigned int flags;
2322 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323
2324 chunk = alloc_trash_chunk();
2325 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002326 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327
Christopher Faulet99daf282018-11-28 22:58:13 +01002328 /*
2329 * Create the location
2330 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002331 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002332 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002333 case REDIRECT_TYPE_SCHEME: {
2334 struct http_hdr_ctx ctx;
2335 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002336
Christopher Faulet99daf282018-11-28 22:58:13 +01002337 host = ist("");
2338 ctx.blk = NULL;
2339 if (http_find_header(htx, ist("Host"), &ctx, 0))
2340 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002341
Christopher Faulet99daf282018-11-28 22:58:13 +01002342 sl = http_find_stline(htx);
2343 path = http_get_path(htx_sl_req_uri(sl));
2344 /* build message using path */
2345 if (path.ptr) {
2346 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2347 int qs = 0;
2348 while (qs < path.len) {
2349 if (*(path.ptr + qs) == '?') {
2350 path.len = qs;
2351 break;
2352 }
2353 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355 }
2356 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 else
2358 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359
Christopher Faulet99daf282018-11-28 22:58:13 +01002360 if (rule->rdr_str) { /* this is an old "redirect" rule */
2361 /* add scheme */
2362 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2363 goto fail;
2364 }
2365 else {
2366 /* add scheme with executing log format */
2367 chunk->data += build_logline(s, chunk->area + chunk->data,
2368 chunk->size - chunk->data,
2369 &rule->rdr_fmt);
2370 }
2371 /* add "://" + host + path */
2372 if (!chunk_memcat(chunk, "://", 3) ||
2373 !chunk_memcat(chunk, host.ptr, host.len) ||
2374 !chunk_memcat(chunk, path.ptr, path.len))
2375 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002376
Christopher Faulet99daf282018-11-28 22:58:13 +01002377 /* append a slash at the end of the location if needed and missing */
2378 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2379 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2380 if (chunk->data + 1 >= chunk->size)
2381 goto fail;
2382 chunk->area[chunk->data++] = '/';
2383 }
2384 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386
Christopher Faulet99daf282018-11-28 22:58:13 +01002387 case REDIRECT_TYPE_PREFIX: {
2388 struct ist path;
2389
2390 sl = http_find_stline(htx);
2391 path = http_get_path(htx_sl_req_uri(sl));
2392 /* build message using path */
2393 if (path.ptr) {
2394 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2395 int qs = 0;
2396 while (qs < path.len) {
2397 if (*(path.ptr + qs) == '?') {
2398 path.len = qs;
2399 break;
2400 }
2401 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002403 }
2404 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 else
2406 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407
Christopher Faulet99daf282018-11-28 22:58:13 +01002408 if (rule->rdr_str) { /* this is an old "redirect" rule */
2409 /* add prefix. Note that if prefix == "/", we don't want to
2410 * add anything, otherwise it makes it hard for the user to
2411 * configure a self-redirection.
2412 */
2413 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2414 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2415 goto fail;
2416 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002418 else {
2419 /* add prefix with executing log format */
2420 chunk->data += build_logline(s, chunk->area + chunk->data,
2421 chunk->size - chunk->data,
2422 &rule->rdr_fmt);
2423 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002424
Christopher Faulet99daf282018-11-28 22:58:13 +01002425 /* add path */
2426 if (!chunk_memcat(chunk, path.ptr, path.len))
2427 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428
Christopher Faulet99daf282018-11-28 22:58:13 +01002429 /* append a slash at the end of the location if needed and missing */
2430 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2431 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2432 if (chunk->data + 1 >= chunk->size)
2433 goto fail;
2434 chunk->area[chunk->data++] = '/';
2435 }
2436 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002437 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 case REDIRECT_TYPE_LOCATION:
2439 default:
2440 if (rule->rdr_str) { /* this is an old "redirect" rule */
2441 /* add location */
2442 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2443 goto fail;
2444 }
2445 else {
2446 /* add location with executing log format */
2447 chunk->data += build_logline(s, chunk->area + chunk->data,
2448 chunk->size - chunk->data,
2449 &rule->rdr_fmt);
2450 }
2451 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002453 location = ist2(chunk->area, chunk->data);
2454
2455 /*
2456 * Create the 30x response
2457 */
2458 switch (rule->code) {
2459 case 308:
2460 status = ist("308");
2461 reason = ist("Permanent Redirect");
2462 break;
2463 case 307:
2464 status = ist("307");
2465 reason = ist("Temporary Redirect");
2466 break;
2467 case 303:
2468 status = ist("303");
2469 reason = ist("See Other");
2470 break;
2471 case 301:
2472 status = ist("301");
2473 reason = ist("Moved Permanently");
2474 break;
2475 case 302:
2476 default:
2477 status = ist("302");
2478 reason = ist("Found");
2479 break;
2480 }
2481
2482 htx = htx_from_buf(&res->buf);
2483 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2484 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2485 if (!sl)
2486 goto fail;
2487 sl->info.res.status = rule->code;
2488 s->txn->status = rule->code;
2489
2490 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2491 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2492 !htx_add_header(htx, ist("Location"), location))
2493 goto fail;
2494
2495 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2496 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2497 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002498 }
2499
2500 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002501 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2502 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002503 }
2504
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2506 goto fail;
2507
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508 /* let's log the request time */
2509 s->logs.tv_request = now;
2510
Christopher Faulet99daf282018-11-28 22:58:13 +01002511 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002512 c_adv(res, data);
2513 res->total += data;
2514
2515 channel_auto_read(req);
2516 channel_abort(req);
2517 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002518 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002519
2520 res->wex = tick_add_ifset(now_ms, res->wto);
2521 channel_auto_read(res);
2522 channel_auto_close(res);
2523 channel_shutr_now(res);
2524
2525 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002526
2527 if (!(s->flags & SF_ERR_MASK))
2528 s->flags |= SF_ERR_LOCAL;
2529 if (!(s->flags & SF_FINST_MASK))
2530 s->flags |= SF_FINST_R;
2531
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 free_trash_chunk(chunk);
2533 return 1;
2534
2535 fail:
2536 /* If an error occurred, remove the incomplete HTTP response from the
2537 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002538 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002540 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002541}
2542
Christopher Faulet72333522018-10-24 11:25:02 +02002543int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2544 struct ist name, const char *str, struct my_regex *re, int action)
2545{
2546 struct http_hdr_ctx ctx;
2547 struct buffer *output = get_trash_chunk();
2548
2549 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2550 ctx.blk = NULL;
2551 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2552 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2553 continue;
2554
2555 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2556 if (output->data == -1)
2557 return -1;
2558 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2559 return -1;
2560 }
2561 return 0;
2562}
2563
2564static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2565 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2566{
2567 struct buffer *replace;
2568 int ret = -1;
2569
2570 replace = alloc_trash_chunk();
2571 if (!replace)
2572 goto leave;
2573
2574 replace->data = build_logline(s, replace->area, replace->size, fmt);
2575 if (replace->data >= replace->size - 1)
2576 goto leave;
2577
2578 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2579
2580 leave:
2581 free_trash_chunk(replace);
2582 return ret;
2583}
2584
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002585
2586/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2587 * on success and -1 on error. The response channel is updated accordingly.
2588 */
2589static int htx_reply_103_early_hints(struct channel *res)
2590{
2591 struct htx *htx = htx_from_buf(&res->buf);
2592 size_t data;
2593
2594 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2595 /* If an error occurred during an Early-hint rule,
2596 * remove the incomplete HTTP 103 response from the
2597 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002598 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002599 return -1;
2600 }
2601
2602 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002603 c_adv(res, data);
2604 res->total += data;
2605 return 0;
2606}
2607
Christopher Faulet6eb92892018-11-15 16:39:29 +01002608/*
2609 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2610 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002611 * If <early_hints> is 0, it is starts a new response by adding the start
2612 * line. If an error occurred -1 is returned. On success 0 is returned. The
2613 * channel is not updated here. It must be done calling the function
2614 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002615 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002616static 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 +01002617{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002618 struct channel *res = &s->res;
2619 struct htx *htx = htx_from_buf(&res->buf);
2620 struct buffer *value = alloc_trash_chunk();
2621
Christopher Faulet6eb92892018-11-15 16:39:29 +01002622 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002623 struct htx_sl *sl;
2624 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2625 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2626
2627 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2628 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2629 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002630 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002631 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002632 }
2633
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002634 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2635 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002636 goto fail;
2637
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002639 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002640
2641 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 /* If an error occurred during an Early-hint rule, remove the incomplete
2643 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002644 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002645 free_trash_chunk(value);
2646 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002647}
2648
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002649/* This function executes one of the set-{method,path,query,uri} actions. It
2650 * takes the string from the variable 'replace' with length 'len', then modifies
2651 * the relevant part of the request line accordingly. Then it updates various
2652 * pointers to the next elements which were moved, and the total buffer length.
2653 * It finds the action to be performed in p[2], previously filled by function
2654 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2655 * error, though this can be revisited when this code is finally exploited.
2656 *
2657 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2658 * query string and 3 to replace uri.
2659 *
2660 * In query string case, the mark question '?' must be set at the start of the
2661 * string by the caller, event if the replacement query string is empty.
2662 */
2663int htx_req_replace_stline(int action, const char *replace, int len,
2664 struct proxy *px, struct stream *s)
2665{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002666 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002667
2668 switch (action) {
2669 case 0: // method
2670 if (!http_replace_req_meth(htx, ist2(replace, len)))
2671 return -1;
2672 break;
2673
2674 case 1: // path
2675 if (!http_replace_req_path(htx, ist2(replace, len)))
2676 return -1;
2677 break;
2678
2679 case 2: // query
2680 if (!http_replace_req_query(htx, ist2(replace, len)))
2681 return -1;
2682 break;
2683
2684 case 3: // uri
2685 if (!http_replace_req_uri(htx, ist2(replace, len)))
2686 return -1;
2687 break;
2688
2689 default:
2690 return -1;
2691 }
2692 return 0;
2693}
2694
2695/* This function replace the HTTP status code and the associated message. The
2696 * variable <status> contains the new status code. This function never fails.
2697 */
2698void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2699{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002700 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002701 char *res;
2702
2703 chunk_reset(&trash);
2704 res = ultoa_o(status, trash.area, trash.size);
2705 trash.data = res - trash.area;
2706
2707 /* Do we have a custom reason format string? */
2708 if (reason == NULL)
2709 reason = http_get_reason(status);
2710
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002711 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002712 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2713}
2714
Christopher Faulet3e964192018-10-24 11:39:23 +02002715/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2716 * transaction <txn>. Returns the verdict of the first rule that prevents
2717 * further processing of the request (auth, deny, ...), and defaults to
2718 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2719 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2720 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2721 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2722 * status.
2723 */
2724static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2725 struct stream *s, int *deny_status)
2726{
2727 struct session *sess = strm_sess(s);
2728 struct http_txn *txn = s->txn;
2729 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002730 struct act_rule *rule;
2731 struct http_hdr_ctx ctx;
2732 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002733 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2734 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002735 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002736
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002737 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002738
2739 /* If "the current_rule_list" match the executed rule list, we are in
2740 * resume condition. If a resume is needed it is always in the action
2741 * and never in the ACL or converters. In this case, we initialise the
2742 * current rule, and go to the action execution point.
2743 */
2744 if (s->current_rule) {
2745 rule = s->current_rule;
2746 s->current_rule = NULL;
2747 if (s->current_rule_list == rules)
2748 goto resume_execution;
2749 }
2750 s->current_rule_list = rules;
2751
2752 list_for_each_entry(rule, rules, list) {
2753 /* check optional condition */
2754 if (rule->cond) {
2755 int ret;
2756
2757 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2758 ret = acl_pass(ret);
2759
2760 if (rule->cond->pol == ACL_COND_UNLESS)
2761 ret = !ret;
2762
2763 if (!ret) /* condition not matched */
2764 continue;
2765 }
2766
2767 act_flags |= ACT_FLAG_FIRST;
2768 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002769 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2770 early_hints = 0;
2771 if (htx_reply_103_early_hints(&s->res) == -1) {
2772 rule_ret = HTTP_RULE_RES_BADREQ;
2773 goto end;
2774 }
2775 }
2776
Christopher Faulet3e964192018-10-24 11:39:23 +02002777 switch (rule->action) {
2778 case ACT_ACTION_ALLOW:
2779 rule_ret = HTTP_RULE_RES_STOP;
2780 goto end;
2781
2782 case ACT_ACTION_DENY:
2783 if (deny_status)
2784 *deny_status = rule->deny_status;
2785 rule_ret = HTTP_RULE_RES_DENY;
2786 goto end;
2787
2788 case ACT_HTTP_REQ_TARPIT:
2789 txn->flags |= TX_CLTARPIT;
2790 if (deny_status)
2791 *deny_status = rule->deny_status;
2792 rule_ret = HTTP_RULE_RES_DENY;
2793 goto end;
2794
2795 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002796 /* Auth might be performed on regular http-req rules as well as on stats */
2797 auth_realm = rule->arg.auth.realm;
2798 if (!auth_realm) {
2799 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2800 auth_realm = STATS_DEFAULT_REALM;
2801 else
2802 auth_realm = px->id;
2803 }
2804 /* send 401/407 depending on whether we use a proxy or not. We still
2805 * count one error, because normal browsing won't significantly
2806 * increase the counter but brute force attempts will.
2807 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002808 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002809 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2810 rule_ret = HTTP_RULE_RES_BADREQ;
2811 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002812 goto end;
2813
2814 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002815 rule_ret = HTTP_RULE_RES_DONE;
2816 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2817 rule_ret = HTTP_RULE_RES_BADREQ;
2818 goto end;
2819
2820 case ACT_HTTP_SET_NICE:
2821 s->task->nice = rule->arg.nice;
2822 break;
2823
2824 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002825 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002826 break;
2827
2828 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002829 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002830 break;
2831
2832 case ACT_HTTP_SET_LOGL:
2833 s->logs.level = rule->arg.loglevel;
2834 break;
2835
2836 case ACT_HTTP_REPLACE_HDR:
2837 case ACT_HTTP_REPLACE_VAL:
2838 if (htx_transform_header(s, &s->req, htx,
2839 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2840 &rule->arg.hdr_add.fmt,
2841 &rule->arg.hdr_add.re, rule->action)) {
2842 rule_ret = HTTP_RULE_RES_BADREQ;
2843 goto end;
2844 }
2845 break;
2846
2847 case ACT_HTTP_DEL_HDR:
2848 /* remove all occurrences of the header */
2849 ctx.blk = NULL;
2850 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2851 http_remove_header(htx, &ctx);
2852 break;
2853
2854 case ACT_HTTP_SET_HDR:
2855 case ACT_HTTP_ADD_HDR: {
2856 /* The scope of the trash buffer must be limited to this function. The
2857 * build_logline() function can execute a lot of other function which
2858 * can use the trash buffer. So for limiting the scope of this global
2859 * buffer, we build first the header value using build_logline, and
2860 * after we store the header name.
2861 */
2862 struct buffer *replace;
2863 struct ist n, v;
2864
2865 replace = alloc_trash_chunk();
2866 if (!replace) {
2867 rule_ret = HTTP_RULE_RES_BADREQ;
2868 goto end;
2869 }
2870
2871 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2872 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2873 v = ist2(replace->area, replace->data);
2874
2875 if (rule->action == ACT_HTTP_SET_HDR) {
2876 /* remove all occurrences of the header */
2877 ctx.blk = NULL;
2878 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2879 http_remove_header(htx, &ctx);
2880 }
2881
2882 if (!http_add_header(htx, n, v)) {
2883 static unsigned char rate_limit = 0;
2884
2885 if ((rate_limit++ & 255) == 0) {
2886 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);
2887 }
2888
Olivier Houcharda798bf52019-03-08 18:52:00 +01002889 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002890 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002891 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002893 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002894 }
2895 free_trash_chunk(replace);
2896 break;
2897 }
2898
2899 case ACT_HTTP_DEL_ACL:
2900 case ACT_HTTP_DEL_MAP: {
2901 struct pat_ref *ref;
2902 struct buffer *key;
2903
2904 /* collect reference */
2905 ref = pat_ref_lookup(rule->arg.map.ref);
2906 if (!ref)
2907 continue;
2908
2909 /* allocate key */
2910 key = alloc_trash_chunk();
2911 if (!key) {
2912 rule_ret = HTTP_RULE_RES_BADREQ;
2913 goto end;
2914 }
2915
2916 /* collect key */
2917 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2918 key->area[key->data] = '\0';
2919
2920 /* perform update */
2921 /* returned code: 1=ok, 0=ko */
2922 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2923 pat_ref_delete(ref, key->area);
2924 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2925
2926 free_trash_chunk(key);
2927 break;
2928 }
2929
2930 case ACT_HTTP_ADD_ACL: {
2931 struct pat_ref *ref;
2932 struct buffer *key;
2933
2934 /* collect reference */
2935 ref = pat_ref_lookup(rule->arg.map.ref);
2936 if (!ref)
2937 continue;
2938
2939 /* allocate key */
2940 key = alloc_trash_chunk();
2941 if (!key) {
2942 rule_ret = HTTP_RULE_RES_BADREQ;
2943 goto end;
2944 }
2945
2946 /* collect key */
2947 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2948 key->area[key->data] = '\0';
2949
2950 /* perform update */
2951 /* add entry only if it does not already exist */
2952 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2953 if (pat_ref_find_elt(ref, key->area) == NULL)
2954 pat_ref_add(ref, key->area, NULL, NULL);
2955 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2956
2957 free_trash_chunk(key);
2958 break;
2959 }
2960
2961 case ACT_HTTP_SET_MAP: {
2962 struct pat_ref *ref;
2963 struct buffer *key, *value;
2964
2965 /* collect reference */
2966 ref = pat_ref_lookup(rule->arg.map.ref);
2967 if (!ref)
2968 continue;
2969
2970 /* allocate key */
2971 key = alloc_trash_chunk();
2972 if (!key) {
2973 rule_ret = HTTP_RULE_RES_BADREQ;
2974 goto end;
2975 }
2976
2977 /* allocate value */
2978 value = alloc_trash_chunk();
2979 if (!value) {
2980 free_trash_chunk(key);
2981 rule_ret = HTTP_RULE_RES_BADREQ;
2982 goto end;
2983 }
2984
2985 /* collect key */
2986 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2987 key->area[key->data] = '\0';
2988
2989 /* collect value */
2990 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2991 value->area[value->data] = '\0';
2992
2993 /* perform update */
2994 if (pat_ref_find_elt(ref, key->area) != NULL)
2995 /* update entry if it exists */
2996 pat_ref_set(ref, key->area, value->area, NULL);
2997 else
2998 /* insert a new entry */
2999 pat_ref_add(ref, key->area, value->area, NULL);
3000
3001 free_trash_chunk(key);
3002 free_trash_chunk(value);
3003 break;
3004 }
3005
3006 case ACT_HTTP_EARLY_HINT:
3007 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3008 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003009 early_hints = htx_add_early_hint_header(s, early_hints,
3010 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003011 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003012 if (early_hints == -1) {
3013 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003014 goto end;
3015 }
3016 break;
3017
3018 case ACT_CUSTOM:
3019 if ((s->req.flags & CF_READ_ERROR) ||
3020 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003021 (px->options & PR_O_ABRT_CLOSE)))
3022 act_flags |= ACT_FLAG_FINAL;
3023
3024 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3025 case ACT_RET_ERR:
3026 case ACT_RET_CONT:
3027 break;
3028 case ACT_RET_STOP:
3029 rule_ret = HTTP_RULE_RES_DONE;
3030 goto end;
3031 case ACT_RET_YIELD:
3032 s->current_rule = rule;
3033 rule_ret = HTTP_RULE_RES_YIELD;
3034 goto end;
3035 }
3036 break;
3037
3038 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3039 /* Note: only the first valid tracking parameter of each
3040 * applies.
3041 */
3042
3043 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3044 struct stktable *t;
3045 struct stksess *ts;
3046 struct stktable_key *key;
3047 void *ptr1, *ptr2;
3048
3049 t = rule->arg.trk_ctr.table.t;
3050 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3051 rule->arg.trk_ctr.expr, NULL);
3052
3053 if (key && (ts = stktable_get_entry(t, key))) {
3054 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3055
3056 /* let's count a new HTTP request as it's the first time we do it */
3057 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3058 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3059 if (ptr1 || ptr2) {
3060 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3061
3062 if (ptr1)
3063 stktable_data_cast(ptr1, http_req_cnt)++;
3064
3065 if (ptr2)
3066 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3067 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3068
3069 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3070
3071 /* If data was modified, we need to touch to re-schedule sync */
3072 stktable_touch_local(t, ts, 0);
3073 }
3074
3075 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3076 if (sess->fe != s->be)
3077 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3078 }
3079 }
3080 break;
3081
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003082 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003083 default:
3084 break;
3085 }
3086 }
3087
3088 end:
3089 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003090 if (htx_reply_103_early_hints(&s->res) == -1)
3091 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003092 }
3093
3094 /* we reached the end of the rules, nothing to report */
3095 return rule_ret;
3096}
3097
3098/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3099 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3100 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3101 * is returned, the process can continue the evaluation of next rule list. If
3102 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3103 * is returned, it means the operation could not be processed and a server error
3104 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3105 * deny rule. If *YIELD is returned, the caller must call again the function
3106 * with the same context.
3107 */
3108static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3109 struct stream *s)
3110{
3111 struct session *sess = strm_sess(s);
3112 struct http_txn *txn = s->txn;
3113 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003114 struct act_rule *rule;
3115 struct http_hdr_ctx ctx;
3116 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3117 int act_flags = 0;
3118
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003119 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003120
3121 /* If "the current_rule_list" match the executed rule list, we are in
3122 * resume condition. If a resume is needed it is always in the action
3123 * and never in the ACL or converters. In this case, we initialise the
3124 * current rule, and go to the action execution point.
3125 */
3126 if (s->current_rule) {
3127 rule = s->current_rule;
3128 s->current_rule = NULL;
3129 if (s->current_rule_list == rules)
3130 goto resume_execution;
3131 }
3132 s->current_rule_list = rules;
3133
3134 list_for_each_entry(rule, rules, list) {
3135 /* check optional condition */
3136 if (rule->cond) {
3137 int ret;
3138
3139 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3140 ret = acl_pass(ret);
3141
3142 if (rule->cond->pol == ACL_COND_UNLESS)
3143 ret = !ret;
3144
3145 if (!ret) /* condition not matched */
3146 continue;
3147 }
3148
3149 act_flags |= ACT_FLAG_FIRST;
3150resume_execution:
3151 switch (rule->action) {
3152 case ACT_ACTION_ALLOW:
3153 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3154 goto end;
3155
3156 case ACT_ACTION_DENY:
3157 txn->flags |= TX_SVDENY;
3158 rule_ret = HTTP_RULE_RES_STOP;
3159 goto end;
3160
3161 case ACT_HTTP_SET_NICE:
3162 s->task->nice = rule->arg.nice;
3163 break;
3164
3165 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003166 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003167 break;
3168
3169 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003170 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003171 break;
3172
3173 case ACT_HTTP_SET_LOGL:
3174 s->logs.level = rule->arg.loglevel;
3175 break;
3176
3177 case ACT_HTTP_REPLACE_HDR:
3178 case ACT_HTTP_REPLACE_VAL:
3179 if (htx_transform_header(s, &s->res, htx,
3180 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3181 &rule->arg.hdr_add.fmt,
3182 &rule->arg.hdr_add.re, rule->action)) {
3183 rule_ret = HTTP_RULE_RES_BADREQ;
3184 goto end;
3185 }
3186 break;
3187
3188 case ACT_HTTP_DEL_HDR:
3189 /* remove all occurrences of the header */
3190 ctx.blk = NULL;
3191 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3192 http_remove_header(htx, &ctx);
3193 break;
3194
3195 case ACT_HTTP_SET_HDR:
3196 case ACT_HTTP_ADD_HDR: {
3197 struct buffer *replace;
3198 struct ist n, v;
3199
3200 replace = alloc_trash_chunk();
3201 if (!replace) {
3202 rule_ret = HTTP_RULE_RES_BADREQ;
3203 goto end;
3204 }
3205
3206 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3207 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3208 v = ist2(replace->area, replace->data);
3209
3210 if (rule->action == ACT_HTTP_SET_HDR) {
3211 /* remove all occurrences of the header */
3212 ctx.blk = NULL;
3213 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3214 http_remove_header(htx, &ctx);
3215 }
3216
3217 if (!http_add_header(htx, n, v)) {
3218 static unsigned char rate_limit = 0;
3219
3220 if ((rate_limit++ & 255) == 0) {
3221 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);
3222 }
3223
Olivier Houcharda798bf52019-03-08 18:52:00 +01003224 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003225 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003226 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003227 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003228 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003229 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003230 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003231 }
3232 free_trash_chunk(replace);
3233 break;
3234 }
3235
3236 case ACT_HTTP_DEL_ACL:
3237 case ACT_HTTP_DEL_MAP: {
3238 struct pat_ref *ref;
3239 struct buffer *key;
3240
3241 /* collect reference */
3242 ref = pat_ref_lookup(rule->arg.map.ref);
3243 if (!ref)
3244 continue;
3245
3246 /* allocate key */
3247 key = alloc_trash_chunk();
3248 if (!key) {
3249 rule_ret = HTTP_RULE_RES_BADREQ;
3250 goto end;
3251 }
3252
3253 /* collect key */
3254 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3255 key->area[key->data] = '\0';
3256
3257 /* perform update */
3258 /* returned code: 1=ok, 0=ko */
3259 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3260 pat_ref_delete(ref, key->area);
3261 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3262
3263 free_trash_chunk(key);
3264 break;
3265 }
3266
3267 case ACT_HTTP_ADD_ACL: {
3268 struct pat_ref *ref;
3269 struct buffer *key;
3270
3271 /* collect reference */
3272 ref = pat_ref_lookup(rule->arg.map.ref);
3273 if (!ref)
3274 continue;
3275
3276 /* allocate key */
3277 key = alloc_trash_chunk();
3278 if (!key) {
3279 rule_ret = HTTP_RULE_RES_BADREQ;
3280 goto end;
3281 }
3282
3283 /* collect key */
3284 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3285 key->area[key->data] = '\0';
3286
3287 /* perform update */
3288 /* check if the entry already exists */
3289 if (pat_ref_find_elt(ref, key->area) == NULL)
3290 pat_ref_add(ref, key->area, NULL, NULL);
3291
3292 free_trash_chunk(key);
3293 break;
3294 }
3295
3296 case ACT_HTTP_SET_MAP: {
3297 struct pat_ref *ref;
3298 struct buffer *key, *value;
3299
3300 /* collect reference */
3301 ref = pat_ref_lookup(rule->arg.map.ref);
3302 if (!ref)
3303 continue;
3304
3305 /* allocate key */
3306 key = alloc_trash_chunk();
3307 if (!key) {
3308 rule_ret = HTTP_RULE_RES_BADREQ;
3309 goto end;
3310 }
3311
3312 /* allocate value */
3313 value = alloc_trash_chunk();
3314 if (!value) {
3315 free_trash_chunk(key);
3316 rule_ret = HTTP_RULE_RES_BADREQ;
3317 goto end;
3318 }
3319
3320 /* collect key */
3321 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3322 key->area[key->data] = '\0';
3323
3324 /* collect value */
3325 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3326 value->area[value->data] = '\0';
3327
3328 /* perform update */
3329 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3330 if (pat_ref_find_elt(ref, key->area) != NULL)
3331 /* update entry if it exists */
3332 pat_ref_set(ref, key->area, value->area, NULL);
3333 else
3334 /* insert a new entry */
3335 pat_ref_add(ref, key->area, value->area, NULL);
3336 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3337 free_trash_chunk(key);
3338 free_trash_chunk(value);
3339 break;
3340 }
3341
3342 case ACT_HTTP_REDIR:
3343 rule_ret = HTTP_RULE_RES_DONE;
3344 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3345 rule_ret = HTTP_RULE_RES_BADREQ;
3346 goto end;
3347
3348 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3349 /* Note: only the first valid tracking parameter of each
3350 * applies.
3351 */
3352 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3353 struct stktable *t;
3354 struct stksess *ts;
3355 struct stktable_key *key;
3356 void *ptr;
3357
3358 t = rule->arg.trk_ctr.table.t;
3359 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3360 rule->arg.trk_ctr.expr, NULL);
3361
3362 if (key && (ts = stktable_get_entry(t, key))) {
3363 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3364
3365 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3366
3367 /* let's count a new HTTP request as it's the first time we do it */
3368 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3369 if (ptr)
3370 stktable_data_cast(ptr, http_req_cnt)++;
3371
3372 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3373 if (ptr)
3374 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3375 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3376
3377 /* When the client triggers a 4xx from the server, it's most often due
3378 * to a missing object or permission. These events should be tracked
3379 * because if they happen often, it may indicate a brute force or a
3380 * vulnerability scan. Normally this is done when receiving the response
3381 * but here we're tracking after this ought to have been done so we have
3382 * to do it on purpose.
3383 */
3384 if ((unsigned)(txn->status - 400) < 100) {
3385 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3386 if (ptr)
3387 stktable_data_cast(ptr, http_err_cnt)++;
3388
3389 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3390 if (ptr)
3391 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3392 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3393 }
3394
3395 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3396
3397 /* If data was modified, we need to touch to re-schedule sync */
3398 stktable_touch_local(t, ts, 0);
3399
3400 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3401 if (sess->fe != s->be)
3402 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3403 }
3404 }
3405 break;
3406
3407 case ACT_CUSTOM:
3408 if ((s->req.flags & CF_READ_ERROR) ||
3409 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003410 (px->options & PR_O_ABRT_CLOSE)))
3411 act_flags |= ACT_FLAG_FINAL;
3412
3413 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3414 case ACT_RET_ERR:
3415 case ACT_RET_CONT:
3416 break;
3417 case ACT_RET_STOP:
3418 rule_ret = HTTP_RULE_RES_STOP;
3419 goto end;
3420 case ACT_RET_YIELD:
3421 s->current_rule = rule;
3422 rule_ret = HTTP_RULE_RES_YIELD;
3423 goto end;
3424 }
3425 break;
3426
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003427 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003428 default:
3429 break;
3430 }
3431 }
3432
3433 end:
3434 /* we reached the end of the rules, nothing to report */
3435 return rule_ret;
3436}
3437
Christopher Faulet33640082018-10-24 11:53:01 +02003438/* Iterate the same filter through all request headers.
3439 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3440 * Since it can manage the switch to another backend, it updates the per-proxy
3441 * DENY stats.
3442 */
3443static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3444{
3445 struct http_txn *txn = s->txn;
3446 struct htx *htx;
3447 struct buffer *hdr = get_trash_chunk();
3448 int32_t pos;
3449
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003450 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003451
3452 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3453 struct htx_blk *blk = htx_get_blk(htx, pos);
3454 enum htx_blk_type type;
3455 struct ist n, v;
3456
3457 next_hdr:
3458 type = htx_get_blk_type(blk);
3459 if (type == HTX_BLK_EOH)
3460 break;
3461 if (type != HTX_BLK_HDR)
3462 continue;
3463
3464 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3465 return 1;
3466 else if (unlikely(txn->flags & TX_CLALLOW) &&
3467 (exp->action == ACT_ALLOW ||
3468 exp->action == ACT_DENY ||
3469 exp->action == ACT_TARPIT))
3470 return 0;
3471
3472 n = htx_get_blk_name(htx, blk);
3473 v = htx_get_blk_value(htx, blk);
3474
Christopher Faulet02e771a2019-02-26 15:36:05 +01003475 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003476 hdr->area[hdr->data++] = ':';
3477 hdr->area[hdr->data++] = ' ';
3478 chunk_memcat(hdr, v.ptr, v.len);
3479
3480 /* Now we have one header in <hdr> */
3481
3482 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3483 struct http_hdr_ctx ctx;
3484 int len;
3485
3486 switch (exp->action) {
3487 case ACT_ALLOW:
3488 txn->flags |= TX_CLALLOW;
3489 goto end;
3490
3491 case ACT_DENY:
3492 txn->flags |= TX_CLDENY;
3493 goto end;
3494
3495 case ACT_TARPIT:
3496 txn->flags |= TX_CLTARPIT;
3497 goto end;
3498
3499 case ACT_REPLACE:
3500 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3501 if (len < 0)
3502 return -1;
3503
3504 http_parse_header(ist2(trash.area, len), &n, &v);
3505 ctx.blk = blk;
3506 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003507 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003508 if (!http_replace_header(htx, &ctx, n, v))
3509 return -1;
3510 if (!ctx.blk)
3511 goto end;
3512 pos = htx_get_blk_pos(htx, blk);
3513 break;
3514
3515 case ACT_REMOVE:
3516 ctx.blk = blk;
3517 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003518 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003519 if (!http_remove_header(htx, &ctx))
3520 return -1;
3521 if (!ctx.blk)
3522 goto end;
3523 pos = htx_get_blk_pos(htx, blk);
3524 goto next_hdr;
3525
3526 }
3527 }
3528 }
3529 end:
3530 return 0;
3531}
3532
3533/* Apply the filter to the request line.
3534 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3535 * or -1 if a replacement resulted in an invalid request line.
3536 * Since it can manage the switch to another backend, it updates the per-proxy
3537 * DENY stats.
3538 */
3539static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3540{
3541 struct http_txn *txn = s->txn;
3542 struct htx *htx;
3543 struct buffer *reqline = get_trash_chunk();
3544 int done;
3545
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003546 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003547
3548 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3549 return 1;
3550 else if (unlikely(txn->flags & TX_CLALLOW) &&
3551 (exp->action == ACT_ALLOW ||
3552 exp->action == ACT_DENY ||
3553 exp->action == ACT_TARPIT))
3554 return 0;
3555 else if (exp->action == ACT_REMOVE)
3556 return 0;
3557
3558 done = 0;
3559
3560 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3561
3562 /* Now we have the request line between cur_ptr and cur_end */
3563 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003564 struct htx_sl *sl = http_find_stline(htx);
3565 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003566 int len;
3567
3568 switch (exp->action) {
3569 case ACT_ALLOW:
3570 txn->flags |= TX_CLALLOW;
3571 done = 1;
3572 break;
3573
3574 case ACT_DENY:
3575 txn->flags |= TX_CLDENY;
3576 done = 1;
3577 break;
3578
3579 case ACT_TARPIT:
3580 txn->flags |= TX_CLTARPIT;
3581 done = 1;
3582 break;
3583
3584 case ACT_REPLACE:
3585 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3586 if (len < 0)
3587 return -1;
3588
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003589 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3590 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3591 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003592 return -1;
3593 done = 1;
3594 break;
3595 }
3596 }
3597 return done;
3598}
3599
3600/*
3601 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3602 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3603 * unparsable request. Since it can manage the switch to another backend, it
3604 * updates the per-proxy DENY stats.
3605 */
3606static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3607{
3608 struct session *sess = s->sess;
3609 struct http_txn *txn = s->txn;
3610 struct hdr_exp *exp;
3611
3612 for (exp = px->req_exp; exp; exp = exp->next) {
3613 int ret;
3614
3615 /*
3616 * The interleaving of transformations and verdicts
3617 * makes it difficult to decide to continue or stop
3618 * the evaluation.
3619 */
3620
3621 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3622 break;
3623
3624 if ((txn->flags & TX_CLALLOW) &&
3625 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3626 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3627 continue;
3628
3629 /* if this filter had a condition, evaluate it now and skip to
3630 * next filter if the condition does not match.
3631 */
3632 if (exp->cond) {
3633 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3634 ret = acl_pass(ret);
3635 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3636 ret = !ret;
3637
3638 if (!ret)
3639 continue;
3640 }
3641
3642 /* Apply the filter to the request line. */
3643 ret = htx_apply_filter_to_req_line(s, req, exp);
3644 if (unlikely(ret < 0))
3645 return -1;
3646
3647 if (likely(ret == 0)) {
3648 /* The filter did not match the request, it can be
3649 * iterated through all headers.
3650 */
3651 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3652 return -1;
3653 }
3654 }
3655 return 0;
3656}
3657
3658/* Iterate the same filter through all response headers contained in <res>.
3659 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3660 */
3661static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3662{
3663 struct http_txn *txn = s->txn;
3664 struct htx *htx;
3665 struct buffer *hdr = get_trash_chunk();
3666 int32_t pos;
3667
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003668 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003669
3670 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3671 struct htx_blk *blk = htx_get_blk(htx, pos);
3672 enum htx_blk_type type;
3673 struct ist n, v;
3674
3675 next_hdr:
3676 type = htx_get_blk_type(blk);
3677 if (type == HTX_BLK_EOH)
3678 break;
3679 if (type != HTX_BLK_HDR)
3680 continue;
3681
3682 if (unlikely(txn->flags & TX_SVDENY))
3683 return 1;
3684 else if (unlikely(txn->flags & TX_SVALLOW) &&
3685 (exp->action == ACT_ALLOW ||
3686 exp->action == ACT_DENY))
3687 return 0;
3688
3689 n = htx_get_blk_name(htx, blk);
3690 v = htx_get_blk_value(htx, blk);
3691
Christopher Faulet02e771a2019-02-26 15:36:05 +01003692 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003693 hdr->area[hdr->data++] = ':';
3694 hdr->area[hdr->data++] = ' ';
3695 chunk_memcat(hdr, v.ptr, v.len);
3696
3697 /* Now we have one header in <hdr> */
3698
3699 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3700 struct http_hdr_ctx ctx;
3701 int len;
3702
3703 switch (exp->action) {
3704 case ACT_ALLOW:
3705 txn->flags |= TX_SVALLOW;
3706 goto end;
3707 break;
3708
3709 case ACT_DENY:
3710 txn->flags |= TX_SVDENY;
3711 goto end;
3712 break;
3713
3714 case ACT_REPLACE:
3715 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3716 if (len < 0)
3717 return -1;
3718
3719 http_parse_header(ist2(trash.area, len), &n, &v);
3720 ctx.blk = blk;
3721 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003722 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003723 if (!http_replace_header(htx, &ctx, n, v))
3724 return -1;
3725 if (!ctx.blk)
3726 goto end;
3727 pos = htx_get_blk_pos(htx, blk);
3728 break;
3729
3730 case ACT_REMOVE:
3731 ctx.blk = blk;
3732 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003733 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003734 if (!http_remove_header(htx, &ctx))
3735 return -1;
3736 if (!ctx.blk)
3737 goto end;
3738 pos = htx_get_blk_pos(htx, blk);
3739 goto next_hdr;
3740 }
3741 }
3742
3743 }
3744 end:
3745 return 0;
3746}
3747
3748/* Apply the filter to the status line in the response buffer <res>.
3749 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3750 * or -1 if a replacement resulted in an invalid status line.
3751 */
3752static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3753{
3754 struct http_txn *txn = s->txn;
3755 struct htx *htx;
3756 struct buffer *resline = get_trash_chunk();
3757 int done;
3758
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003759 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003760
3761 if (unlikely(txn->flags & TX_SVDENY))
3762 return 1;
3763 else if (unlikely(txn->flags & TX_SVALLOW) &&
3764 (exp->action == ACT_ALLOW ||
3765 exp->action == ACT_DENY))
3766 return 0;
3767 else if (exp->action == ACT_REMOVE)
3768 return 0;
3769
3770 done = 0;
3771 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3772
3773 /* Now we have the status line between cur_ptr and cur_end */
3774 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003775 struct htx_sl *sl = http_find_stline(htx);
3776 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003777 int len;
3778
3779 switch (exp->action) {
3780 case ACT_ALLOW:
3781 txn->flags |= TX_SVALLOW;
3782 done = 1;
3783 break;
3784
3785 case ACT_DENY:
3786 txn->flags |= TX_SVDENY;
3787 done = 1;
3788 break;
3789
3790 case ACT_REPLACE:
3791 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3792 if (len < 0)
3793 return -1;
3794
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003795 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3796 sl->info.res.status = strl2ui(code.ptr, code.len);
3797 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003798 return -1;
3799
3800 done = 1;
3801 return 1;
3802 }
3803 }
3804 return done;
3805}
3806
3807/*
3808 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3809 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3810 * unparsable response.
3811 */
3812static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3813{
3814 struct session *sess = s->sess;
3815 struct http_txn *txn = s->txn;
3816 struct hdr_exp *exp;
3817
3818 for (exp = px->rsp_exp; exp; exp = exp->next) {
3819 int ret;
3820
3821 /*
3822 * The interleaving of transformations and verdicts
3823 * makes it difficult to decide to continue or stop
3824 * the evaluation.
3825 */
3826
3827 if (txn->flags & TX_SVDENY)
3828 break;
3829
3830 if ((txn->flags & TX_SVALLOW) &&
3831 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3832 exp->action == ACT_PASS)) {
3833 exp = exp->next;
3834 continue;
3835 }
3836
3837 /* if this filter had a condition, evaluate it now and skip to
3838 * next filter if the condition does not match.
3839 */
3840 if (exp->cond) {
3841 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3842 ret = acl_pass(ret);
3843 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3844 ret = !ret;
3845 if (!ret)
3846 continue;
3847 }
3848
3849 /* Apply the filter to the status line. */
3850 ret = htx_apply_filter_to_sts_line(s, res, exp);
3851 if (unlikely(ret < 0))
3852 return -1;
3853
3854 if (likely(ret == 0)) {
3855 /* The filter did not match the response, it can be
3856 * iterated through all headers.
3857 */
3858 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3859 return -1;
3860 }
3861 }
3862 return 0;
3863}
3864
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003865/*
3866 * Manage client-side cookie. It can impact performance by about 2% so it is
3867 * desirable to call it only when needed. This code is quite complex because
3868 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3869 * highly recommended not to touch this part without a good reason !
3870 */
3871static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3872{
3873 struct session *sess = s->sess;
3874 struct http_txn *txn = s->txn;
3875 struct htx *htx;
3876 struct http_hdr_ctx ctx;
3877 char *hdr_beg, *hdr_end, *del_from;
3878 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3879 int preserve_hdr;
3880
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003881 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003882 ctx.blk = NULL;
3883 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3884 del_from = NULL; /* nothing to be deleted */
3885 preserve_hdr = 0; /* assume we may kill the whole header */
3886
3887 /* Now look for cookies. Conforming to RFC2109, we have to support
3888 * attributes whose name begin with a '$', and associate them with
3889 * the right cookie, if we want to delete this cookie.
3890 * So there are 3 cases for each cookie read :
3891 * 1) it's a special attribute, beginning with a '$' : ignore it.
3892 * 2) it's a server id cookie that we *MAY* want to delete : save
3893 * some pointers on it (last semi-colon, beginning of cookie...)
3894 * 3) it's an application cookie : we *MAY* have to delete a previous
3895 * "special" cookie.
3896 * At the end of loop, if a "special" cookie remains, we may have to
3897 * remove it. If no application cookie persists in the header, we
3898 * *MUST* delete it.
3899 *
3900 * Note: RFC2965 is unclear about the processing of spaces around
3901 * the equal sign in the ATTR=VALUE form. A careful inspection of
3902 * the RFC explicitly allows spaces before it, and not within the
3903 * tokens (attrs or values). An inspection of RFC2109 allows that
3904 * too but section 10.1.3 lets one think that spaces may be allowed
3905 * after the equal sign too, resulting in some (rare) buggy
3906 * implementations trying to do that. So let's do what servers do.
3907 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3908 * allowed quoted strings in values, with any possible character
3909 * after a backslash, including control chars and delimitors, which
3910 * causes parsing to become ambiguous. Browsers also allow spaces
3911 * within values even without quotes.
3912 *
3913 * We have to keep multiple pointers in order to support cookie
3914 * removal at the beginning, middle or end of header without
3915 * corrupting the header. All of these headers are valid :
3916 *
3917 * hdr_beg hdr_end
3918 * | |
3919 * v |
3920 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3921 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3922 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3923 * | | | | | | |
3924 * | | | | | | |
3925 * | | | | | | +--> next
3926 * | | | | | +----> val_end
3927 * | | | | +-----------> val_beg
3928 * | | | +--------------> equal
3929 * | | +----------------> att_end
3930 * | +---------------------> att_beg
3931 * +--------------------------> prev
3932 *
3933 */
3934 hdr_beg = ctx.value.ptr;
3935 hdr_end = hdr_beg + ctx.value.len;
3936 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3937 /* Iterate through all cookies on this line */
3938
3939 /* find att_beg */
3940 att_beg = prev;
3941 if (prev > hdr_beg)
3942 att_beg++;
3943
3944 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3945 att_beg++;
3946
3947 /* find att_end : this is the first character after the last non
3948 * space before the equal. It may be equal to hdr_end.
3949 */
3950 equal = att_end = att_beg;
3951 while (equal < hdr_end) {
3952 if (*equal == '=' || *equal == ',' || *equal == ';')
3953 break;
3954 if (HTTP_IS_SPHT(*equal++))
3955 continue;
3956 att_end = equal;
3957 }
3958
3959 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3960 * is between <att_beg> and <equal>, both may be identical.
3961 */
3962 /* look for end of cookie if there is an equal sign */
3963 if (equal < hdr_end && *equal == '=') {
3964 /* look for the beginning of the value */
3965 val_beg = equal + 1;
3966 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3967 val_beg++;
3968
3969 /* find the end of the value, respecting quotes */
3970 next = http_find_cookie_value_end(val_beg, hdr_end);
3971
3972 /* make val_end point to the first white space or delimitor after the value */
3973 val_end = next;
3974 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3975 val_end--;
3976 }
3977 else
3978 val_beg = val_end = next = equal;
3979
3980 /* We have nothing to do with attributes beginning with
3981 * '$'. However, they will automatically be removed if a
3982 * header before them is removed, since they're supposed
3983 * to be linked together.
3984 */
3985 if (*att_beg == '$')
3986 continue;
3987
3988 /* Ignore cookies with no equal sign */
3989 if (equal == next) {
3990 /* This is not our cookie, so we must preserve it. But if we already
3991 * scheduled another cookie for removal, we cannot remove the
3992 * complete header, but we can remove the previous block itself.
3993 */
3994 preserve_hdr = 1;
3995 if (del_from != NULL) {
3996 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3997 val_end += delta;
3998 next += delta;
3999 hdr_end += delta;
4000 prev = del_from;
4001 del_from = NULL;
4002 }
4003 continue;
4004 }
4005
4006 /* if there are spaces around the equal sign, we need to
4007 * strip them otherwise we'll get trouble for cookie captures,
4008 * or even for rewrites. Since this happens extremely rarely,
4009 * it does not hurt performance.
4010 */
4011 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4012 int stripped_before = 0;
4013 int stripped_after = 0;
4014
4015 if (att_end != equal) {
4016 memmove(att_end, equal, hdr_end - equal);
4017 stripped_before = (att_end - equal);
4018 equal += stripped_before;
4019 val_beg += stripped_before;
4020 }
4021
4022 if (val_beg > equal + 1) {
4023 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4024 stripped_after = (equal + 1) - val_beg;
4025 val_beg += stripped_after;
4026 stripped_before += stripped_after;
4027 }
4028
4029 val_end += stripped_before;
4030 next += stripped_before;
4031 hdr_end += stripped_before;
4032 }
4033 /* now everything is as on the diagram above */
4034
4035 /* First, let's see if we want to capture this cookie. We check
4036 * that we don't already have a client side cookie, because we
4037 * can only capture one. Also as an optimisation, we ignore
4038 * cookies shorter than the declared name.
4039 */
4040 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4041 (val_end - att_beg >= sess->fe->capture_namelen) &&
4042 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4043 int log_len = val_end - att_beg;
4044
4045 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4046 ha_alert("HTTP logging : out of memory.\n");
4047 } else {
4048 if (log_len > sess->fe->capture_len)
4049 log_len = sess->fe->capture_len;
4050 memcpy(txn->cli_cookie, att_beg, log_len);
4051 txn->cli_cookie[log_len] = 0;
4052 }
4053 }
4054
4055 /* Persistence cookies in passive, rewrite or insert mode have the
4056 * following form :
4057 *
4058 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4059 *
4060 * For cookies in prefix mode, the form is :
4061 *
4062 * Cookie: NAME=SRV~VALUE
4063 */
4064 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4065 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4066 struct server *srv = s->be->srv;
4067 char *delim;
4068
4069 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4070 * have the server ID between val_beg and delim, and the original cookie between
4071 * delim+1 and val_end. Otherwise, delim==val_end :
4072 *
4073 * hdr_beg
4074 * |
4075 * v
4076 * NAME=SRV; # in all but prefix modes
4077 * NAME=SRV~OPAQUE ; # in prefix mode
4078 * || || | |+-> next
4079 * || || | +--> val_end
4080 * || || +---------> delim
4081 * || |+------------> val_beg
4082 * || +-------------> att_end = equal
4083 * |+-----------------> att_beg
4084 * +------------------> prev
4085 *
4086 */
4087 if (s->be->ck_opts & PR_CK_PFX) {
4088 for (delim = val_beg; delim < val_end; delim++)
4089 if (*delim == COOKIE_DELIM)
4090 break;
4091 }
4092 else {
4093 char *vbar1;
4094 delim = val_end;
4095 /* Now check if the cookie contains a date field, which would
4096 * appear after a vertical bar ('|') just after the server name
4097 * and before the delimiter.
4098 */
4099 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4100 if (vbar1) {
4101 /* OK, so left of the bar is the server's cookie and
4102 * right is the last seen date. It is a base64 encoded
4103 * 30-bit value representing the UNIX date since the
4104 * epoch in 4-second quantities.
4105 */
4106 int val;
4107 delim = vbar1++;
4108 if (val_end - vbar1 >= 5) {
4109 val = b64tos30(vbar1);
4110 if (val > 0)
4111 txn->cookie_last_date = val << 2;
4112 }
4113 /* look for a second vertical bar */
4114 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4115 if (vbar1 && (val_end - vbar1 > 5)) {
4116 val = b64tos30(vbar1 + 1);
4117 if (val > 0)
4118 txn->cookie_first_date = val << 2;
4119 }
4120 }
4121 }
4122
4123 /* if the cookie has an expiration date and the proxy wants to check
4124 * it, then we do that now. We first check if the cookie is too old,
4125 * then only if it has expired. We detect strict overflow because the
4126 * time resolution here is not great (4 seconds). Cookies with dates
4127 * in the future are ignored if their offset is beyond one day. This
4128 * allows an admin to fix timezone issues without expiring everyone
4129 * and at the same time avoids keeping unwanted side effects for too
4130 * long.
4131 */
4132 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4133 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4134 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4135 txn->flags &= ~TX_CK_MASK;
4136 txn->flags |= TX_CK_OLD;
4137 delim = val_beg; // let's pretend we have not found the cookie
4138 txn->cookie_first_date = 0;
4139 txn->cookie_last_date = 0;
4140 }
4141 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4142 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4143 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4144 txn->flags &= ~TX_CK_MASK;
4145 txn->flags |= TX_CK_EXPIRED;
4146 delim = val_beg; // let's pretend we have not found the cookie
4147 txn->cookie_first_date = 0;
4148 txn->cookie_last_date = 0;
4149 }
4150
4151 /* Here, we'll look for the first running server which supports the cookie.
4152 * This allows to share a same cookie between several servers, for example
4153 * to dedicate backup servers to specific servers only.
4154 * However, to prevent clients from sticking to cookie-less backup server
4155 * when they have incidentely learned an empty cookie, we simply ignore
4156 * empty cookies and mark them as invalid.
4157 * The same behaviour is applied when persistence must be ignored.
4158 */
4159 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4160 srv = NULL;
4161
4162 while (srv) {
4163 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4164 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4165 if ((srv->cur_state != SRV_ST_STOPPED) ||
4166 (s->be->options & PR_O_PERSIST) ||
4167 (s->flags & SF_FORCE_PRST)) {
4168 /* we found the server and we can use it */
4169 txn->flags &= ~TX_CK_MASK;
4170 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4171 s->flags |= SF_DIRECT | SF_ASSIGNED;
4172 s->target = &srv->obj_type;
4173 break;
4174 } else {
4175 /* we found a server, but it's down,
4176 * mark it as such and go on in case
4177 * another one is available.
4178 */
4179 txn->flags &= ~TX_CK_MASK;
4180 txn->flags |= TX_CK_DOWN;
4181 }
4182 }
4183 srv = srv->next;
4184 }
4185
4186 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4187 /* no server matched this cookie or we deliberately skipped it */
4188 txn->flags &= ~TX_CK_MASK;
4189 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4190 txn->flags |= TX_CK_UNUSED;
4191 else
4192 txn->flags |= TX_CK_INVALID;
4193 }
4194
4195 /* depending on the cookie mode, we may have to either :
4196 * - delete the complete cookie if we're in insert+indirect mode, so that
4197 * the server never sees it ;
4198 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004199 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004200 * if we're in cookie prefix mode
4201 */
4202 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4203 int delta; /* negative */
4204
4205 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4206 delta = val_beg - (delim + 1);
4207 val_end += delta;
4208 next += delta;
4209 hdr_end += delta;
4210 del_from = NULL;
4211 preserve_hdr = 1; /* we want to keep this cookie */
4212 }
4213 else if (del_from == NULL &&
4214 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4215 del_from = prev;
4216 }
4217 }
4218 else {
4219 /* This is not our cookie, so we must preserve it. But if we already
4220 * scheduled another cookie for removal, we cannot remove the
4221 * complete header, but we can remove the previous block itself.
4222 */
4223 preserve_hdr = 1;
4224
4225 if (del_from != NULL) {
4226 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4227 if (att_beg >= del_from)
4228 att_beg += delta;
4229 if (att_end >= del_from)
4230 att_end += delta;
4231 val_beg += delta;
4232 val_end += delta;
4233 next += delta;
4234 hdr_end += delta;
4235 prev = del_from;
4236 del_from = NULL;
4237 }
4238 }
4239
4240 /* continue with next cookie on this header line */
4241 att_beg = next;
4242 } /* for each cookie */
4243
4244
4245 /* There are no more cookies on this line.
4246 * We may still have one (or several) marked for deletion at the
4247 * end of the line. We must do this now in two ways :
4248 * - if some cookies must be preserved, we only delete from the
4249 * mark to the end of line ;
4250 * - if nothing needs to be preserved, simply delete the whole header
4251 */
4252 if (del_from) {
4253 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4254 }
4255 if ((hdr_end - hdr_beg) != ctx.value.len) {
4256 if (hdr_beg != hdr_end) {
4257 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004258 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004259 }
4260 else
4261 http_remove_header(htx, &ctx);
4262 }
4263 } /* for each "Cookie header */
4264}
4265
4266/*
4267 * Manage server-side cookies. It can impact performance by about 2% so it is
4268 * desirable to call it only when needed. This function is also used when we
4269 * just need to know if there is a cookie (eg: for check-cache).
4270 */
4271static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4272{
4273 struct session *sess = s->sess;
4274 struct http_txn *txn = s->txn;
4275 struct htx *htx;
4276 struct http_hdr_ctx ctx;
4277 struct server *srv;
4278 char *hdr_beg, *hdr_end;
4279 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4280 int is_cookie2;
4281
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004282 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004283
4284 ctx.blk = NULL;
4285 while (1) {
4286 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4287 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4288 break;
4289 is_cookie2 = 1;
4290 }
4291
4292 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4293 * <prev> points to the colon.
4294 */
4295 txn->flags |= TX_SCK_PRESENT;
4296
4297 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4298 * check-cache is enabled) and we are not interested in checking
4299 * them. Warning, the cookie capture is declared in the frontend.
4300 */
4301 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4302 break;
4303
4304 /* OK so now we know we have to process this response cookie.
4305 * The format of the Set-Cookie header is slightly different
4306 * from the format of the Cookie header in that it does not
4307 * support the comma as a cookie delimiter (thus the header
4308 * cannot be folded) because the Expires attribute described in
4309 * the original Netscape's spec may contain an unquoted date
4310 * with a comma inside. We have to live with this because
4311 * many browsers don't support Max-Age and some browsers don't
4312 * support quoted strings. However the Set-Cookie2 header is
4313 * clean.
4314 *
4315 * We have to keep multiple pointers in order to support cookie
4316 * removal at the beginning, middle or end of header without
4317 * corrupting the header (in case of set-cookie2). A special
4318 * pointer, <scav> points to the beginning of the set-cookie-av
4319 * fields after the first semi-colon. The <next> pointer points
4320 * either to the end of line (set-cookie) or next unquoted comma
4321 * (set-cookie2). All of these headers are valid :
4322 *
4323 * hdr_beg hdr_end
4324 * | |
4325 * v |
4326 * NAME1 = VALUE 1 ; Secure; Path="/" |
4327 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4328 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4329 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4330 * | | | | | | | |
4331 * | | | | | | | +-> next
4332 * | | | | | | +------------> scav
4333 * | | | | | +--------------> val_end
4334 * | | | | +--------------------> val_beg
4335 * | | | +----------------------> equal
4336 * | | +------------------------> att_end
4337 * | +----------------------------> att_beg
4338 * +------------------------------> prev
4339 * -------------------------------> hdr_beg
4340 */
4341 hdr_beg = ctx.value.ptr;
4342 hdr_end = hdr_beg + ctx.value.len;
4343 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4344
4345 /* Iterate through all cookies on this line */
4346
4347 /* find att_beg */
4348 att_beg = prev;
4349 if (prev > hdr_beg)
4350 att_beg++;
4351
4352 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4353 att_beg++;
4354
4355 /* find att_end : this is the first character after the last non
4356 * space before the equal. It may be equal to hdr_end.
4357 */
4358 equal = att_end = att_beg;
4359
4360 while (equal < hdr_end) {
4361 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4362 break;
4363 if (HTTP_IS_SPHT(*equal++))
4364 continue;
4365 att_end = equal;
4366 }
4367
4368 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4369 * is between <att_beg> and <equal>, both may be identical.
4370 */
4371
4372 /* look for end of cookie if there is an equal sign */
4373 if (equal < hdr_end && *equal == '=') {
4374 /* look for the beginning of the value */
4375 val_beg = equal + 1;
4376 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4377 val_beg++;
4378
4379 /* find the end of the value, respecting quotes */
4380 next = http_find_cookie_value_end(val_beg, hdr_end);
4381
4382 /* make val_end point to the first white space or delimitor after the value */
4383 val_end = next;
4384 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4385 val_end--;
4386 }
4387 else {
4388 /* <equal> points to next comma, semi-colon or EOL */
4389 val_beg = val_end = next = equal;
4390 }
4391
4392 if (next < hdr_end) {
4393 /* Set-Cookie2 supports multiple cookies, and <next> points to
4394 * a colon or semi-colon before the end. So skip all attr-value
4395 * pairs and look for the next comma. For Set-Cookie, since
4396 * commas are permitted in values, skip to the end.
4397 */
4398 if (is_cookie2)
4399 next = http_find_hdr_value_end(next, hdr_end);
4400 else
4401 next = hdr_end;
4402 }
4403
4404 /* Now everything is as on the diagram above */
4405
4406 /* Ignore cookies with no equal sign */
4407 if (equal == val_end)
4408 continue;
4409
4410 /* If there are spaces around the equal sign, we need to
4411 * strip them otherwise we'll get trouble for cookie captures,
4412 * or even for rewrites. Since this happens extremely rarely,
4413 * it does not hurt performance.
4414 */
4415 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4416 int stripped_before = 0;
4417 int stripped_after = 0;
4418
4419 if (att_end != equal) {
4420 memmove(att_end, equal, hdr_end - equal);
4421 stripped_before = (att_end - equal);
4422 equal += stripped_before;
4423 val_beg += stripped_before;
4424 }
4425
4426 if (val_beg > equal + 1) {
4427 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4428 stripped_after = (equal + 1) - val_beg;
4429 val_beg += stripped_after;
4430 stripped_before += stripped_after;
4431 }
4432
4433 val_end += stripped_before;
4434 next += stripped_before;
4435 hdr_end += stripped_before;
4436
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004437 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4438 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004439 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004440 }
4441
4442 /* First, let's see if we want to capture this cookie. We check
4443 * that we don't already have a server side cookie, because we
4444 * can only capture one. Also as an optimisation, we ignore
4445 * cookies shorter than the declared name.
4446 */
4447 if (sess->fe->capture_name != NULL &&
4448 txn->srv_cookie == NULL &&
4449 (val_end - att_beg >= sess->fe->capture_namelen) &&
4450 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4451 int log_len = val_end - att_beg;
4452 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4453 ha_alert("HTTP logging : out of memory.\n");
4454 }
4455 else {
4456 if (log_len > sess->fe->capture_len)
4457 log_len = sess->fe->capture_len;
4458 memcpy(txn->srv_cookie, att_beg, log_len);
4459 txn->srv_cookie[log_len] = 0;
4460 }
4461 }
4462
4463 srv = objt_server(s->target);
4464 /* now check if we need to process it for persistence */
4465 if (!(s->flags & SF_IGNORE_PRST) &&
4466 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4467 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4468 /* assume passive cookie by default */
4469 txn->flags &= ~TX_SCK_MASK;
4470 txn->flags |= TX_SCK_FOUND;
4471
4472 /* If the cookie is in insert mode on a known server, we'll delete
4473 * this occurrence because we'll insert another one later.
4474 * We'll delete it too if the "indirect" option is set and we're in
4475 * a direct access.
4476 */
4477 if (s->be->ck_opts & PR_CK_PSV) {
4478 /* The "preserve" flag was set, we don't want to touch the
4479 * server's cookie.
4480 */
4481 }
4482 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4483 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4484 /* this cookie must be deleted */
4485 if (prev == hdr_beg && next == hdr_end) {
4486 /* whole header */
4487 http_remove_header(htx, &ctx);
4488 /* note: while both invalid now, <next> and <hdr_end>
4489 * are still equal, so the for() will stop as expected.
4490 */
4491 } else {
4492 /* just remove the value */
4493 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4494 next = prev;
4495 hdr_end += delta;
4496 }
4497 txn->flags &= ~TX_SCK_MASK;
4498 txn->flags |= TX_SCK_DELETED;
4499 /* and go on with next cookie */
4500 }
4501 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4502 /* replace bytes val_beg->val_end with the cookie name associated
4503 * with this server since we know it.
4504 */
4505 int sliding, delta;
4506
4507 ctx.value = ist2(val_beg, val_end - val_beg);
4508 ctx.lws_before = ctx.lws_after = 0;
4509 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4510 delta = srv->cklen - (val_end - val_beg);
4511 sliding = (ctx.value.ptr - val_beg);
4512 hdr_beg += sliding;
4513 val_beg += sliding;
4514 next += sliding + delta;
4515 hdr_end += sliding + delta;
4516
4517 txn->flags &= ~TX_SCK_MASK;
4518 txn->flags |= TX_SCK_REPLACED;
4519 }
4520 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4521 /* insert the cookie name associated with this server
4522 * before existing cookie, and insert a delimiter between them..
4523 */
4524 int sliding, delta;
4525 ctx.value = ist2(val_beg, 0);
4526 ctx.lws_before = ctx.lws_after = 0;
4527 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4528 delta = srv->cklen + 1;
4529 sliding = (ctx.value.ptr - val_beg);
4530 hdr_beg += sliding;
4531 val_beg += sliding;
4532 next += sliding + delta;
4533 hdr_end += sliding + delta;
4534
4535 val_beg[srv->cklen] = COOKIE_DELIM;
4536 txn->flags &= ~TX_SCK_MASK;
4537 txn->flags |= TX_SCK_REPLACED;
4538 }
4539 }
4540 /* that's done for this cookie, check the next one on the same
4541 * line when next != hdr_end (only if is_cookie2).
4542 */
4543 }
4544 }
4545}
4546
Christopher Faulet25a02f62018-10-24 12:00:25 +02004547/*
4548 * Parses the Cache-Control and Pragma request header fields to determine if
4549 * the request may be served from the cache and/or if it is cacheable. Updates
4550 * s->txn->flags.
4551 */
4552void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4553{
4554 struct http_txn *txn = s->txn;
4555 struct htx *htx;
4556 int32_t pos;
4557 int pragma_found, cc_found, i;
4558
4559 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4560 return; /* nothing more to do here */
4561
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004562 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004563 pragma_found = cc_found = 0;
4564 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4565 struct htx_blk *blk = htx_get_blk(htx, pos);
4566 enum htx_blk_type type = htx_get_blk_type(blk);
4567 struct ist n, v;
4568
4569 if (type == HTX_BLK_EOH)
4570 break;
4571 if (type != HTX_BLK_HDR)
4572 continue;
4573
4574 n = htx_get_blk_name(htx, blk);
4575 v = htx_get_blk_value(htx, blk);
4576
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004577 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004578 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4579 pragma_found = 1;
4580 continue;
4581 }
4582 }
4583
4584 /* Don't use the cache and don't try to store if we found the
4585 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004586 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004587 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4588 txn->flags |= TX_CACHE_IGNORE;
4589 continue;
4590 }
4591
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004592 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004593 continue;
4594
4595 /* OK, right now we know we have a cache-control header */
4596 cc_found = 1;
4597 if (!v.len) /* no info */
4598 continue;
4599
4600 i = 0;
4601 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4602 !isspace((unsigned char)*(v.ptr+i)))
4603 i++;
4604
4605 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4606 * values after max-age, max-stale nor min-fresh, we simply don't
4607 * use the cache when they're specified.
4608 */
4609 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4610 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4611 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4612 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4613 txn->flags |= TX_CACHE_IGNORE;
4614 continue;
4615 }
4616
4617 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4618 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4619 continue;
4620 }
4621 }
4622
4623 /* RFC7234#5.4:
4624 * When the Cache-Control header field is also present and
4625 * understood in a request, Pragma is ignored.
4626 * When the Cache-Control header field is not present in a
4627 * request, caches MUST consider the no-cache request
4628 * pragma-directive as having the same effect as if
4629 * "Cache-Control: no-cache" were present.
4630 */
4631 if (!cc_found && pragma_found)
4632 txn->flags |= TX_CACHE_IGNORE;
4633}
4634
4635/*
4636 * Check if response is cacheable or not. Updates s->txn->flags.
4637 */
4638void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4639{
4640 struct http_txn *txn = s->txn;
4641 struct htx *htx;
4642 int32_t pos;
4643 int i;
4644
4645 if (txn->status < 200) {
4646 /* do not try to cache interim responses! */
4647 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4648 return;
4649 }
4650
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004651 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004652 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4653 struct htx_blk *blk = htx_get_blk(htx, pos);
4654 enum htx_blk_type type = htx_get_blk_type(blk);
4655 struct ist n, v;
4656
4657 if (type == HTX_BLK_EOH)
4658 break;
4659 if (type != HTX_BLK_HDR)
4660 continue;
4661
4662 n = htx_get_blk_name(htx, blk);
4663 v = htx_get_blk_value(htx, blk);
4664
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004665 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004666 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4667 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4668 return;
4669 }
4670 }
4671
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004672 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004673 continue;
4674
4675 /* OK, right now we know we have a cache-control header */
4676 if (!v.len) /* no info */
4677 continue;
4678
4679 i = 0;
4680 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4681 !isspace((unsigned char)*(v.ptr+i)))
4682 i++;
4683
4684 /* we have a complete value between v.ptr and (v.ptr+i) */
4685 if (i < v.len && *(v.ptr + i) == '=') {
4686 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4687 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4688 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4689 continue;
4690 }
4691
4692 /* we have something of the form no-cache="set-cookie" */
4693 if ((v.len >= 21) &&
4694 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4695 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4696 txn->flags &= ~TX_CACHE_COOK;
4697 continue;
4698 }
4699
4700 /* OK, so we know that either p2 points to the end of string or to a comma */
4701 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4702 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4703 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4704 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4705 return;
4706 }
4707
4708 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4709 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4710 continue;
4711 }
4712 }
4713}
4714
Christopher Faulet64159df2018-10-24 21:15:35 +02004715/* send a server's name with an outgoing request over an established connection.
4716 * Note: this function is designed to be called once the request has been
4717 * scheduled for being forwarded. This is the reason why the number of forwarded
4718 * bytes have to be adjusted.
4719 */
4720int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4721{
4722 struct htx *htx;
4723 struct http_hdr_ctx ctx;
4724 struct ist hdr;
4725 uint32_t data;
4726
4727 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004728 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004729 data = htx->data;
4730
4731 ctx.blk = NULL;
4732 while (http_find_header(htx, hdr, &ctx, 1))
4733 http_remove_header(htx, &ctx);
4734 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4735
4736 if (co_data(&s->req)) {
4737 if (data >= htx->data)
4738 c_rew(&s->req, data - htx->data);
4739 else
4740 c_adv(&s->req, htx->data - data);
4741 }
4742 return 0;
4743}
4744
Christopher Faulet377c5a52018-10-24 21:21:30 +02004745/*
4746 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4747 * for the current backend.
4748 *
4749 * It is assumed that the request is either a HEAD, GET, or POST and that the
4750 * uri_auth field is valid.
4751 *
4752 * Returns 1 if stats should be provided, otherwise 0.
4753 */
4754static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4755{
4756 struct uri_auth *uri_auth = backend->uri_auth;
4757 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004758 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004759 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004760
4761 if (!uri_auth)
4762 return 0;
4763
4764 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4765 return 0;
4766
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004767 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004768 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004769 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004770
4771 /* check URI size */
4772 if (uri_auth->uri_len > uri.len)
4773 return 0;
4774
4775 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4776 return 0;
4777
4778 return 1;
4779}
4780
4781/* This function prepares an applet to handle the stats. It can deal with the
4782 * "100-continue" expectation, check that admin rules are met for POST requests,
4783 * and program a response message if something was unexpected. It cannot fail
4784 * and always relies on the stats applet to complete the job. It does not touch
4785 * analysers nor counters, which are left to the caller. It does not touch
4786 * s->target which is supposed to already point to the stats applet. The caller
4787 * is expected to have already assigned an appctx to the stream.
4788 */
4789static int htx_handle_stats(struct stream *s, struct channel *req)
4790{
4791 struct stats_admin_rule *stats_admin_rule;
4792 struct stream_interface *si = &s->si[1];
4793 struct session *sess = s->sess;
4794 struct http_txn *txn = s->txn;
4795 struct http_msg *msg = &txn->req;
4796 struct uri_auth *uri_auth = s->be->uri_auth;
4797 const char *h, *lookup, *end;
4798 struct appctx *appctx;
4799 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004800 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004801
4802 appctx = si_appctx(si);
4803 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4804 appctx->st1 = appctx->st2 = 0;
4805 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4806 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4807 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4808 appctx->ctx.stats.flags |= STAT_CHUNKED;
4809
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004810 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004811 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004812 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4813 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004814
4815 for (h = lookup; h <= end - 3; h++) {
4816 if (memcmp(h, ";up", 3) == 0) {
4817 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4818 break;
4819 }
4820 }
4821
4822 if (uri_auth->refresh) {
4823 for (h = lookup; h <= end - 10; h++) {
4824 if (memcmp(h, ";norefresh", 10) == 0) {
4825 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4826 break;
4827 }
4828 }
4829 }
4830
4831 for (h = lookup; h <= end - 4; h++) {
4832 if (memcmp(h, ";csv", 4) == 0) {
4833 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4834 break;
4835 }
4836 }
4837
4838 for (h = lookup; h <= end - 6; h++) {
4839 if (memcmp(h, ";typed", 6) == 0) {
4840 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4841 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4842 break;
4843 }
4844 }
4845
4846 for (h = lookup; h <= end - 8; h++) {
4847 if (memcmp(h, ";st=", 4) == 0) {
4848 int i;
4849 h += 4;
4850 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4851 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4852 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4853 appctx->ctx.stats.st_code = i;
4854 break;
4855 }
4856 }
4857 break;
4858 }
4859 }
4860
4861 appctx->ctx.stats.scope_str = 0;
4862 appctx->ctx.stats.scope_len = 0;
4863 for (h = lookup; h <= end - 8; h++) {
4864 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4865 int itx = 0;
4866 const char *h2;
4867 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4868 const char *err;
4869
4870 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4871 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004872 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4873 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004874 if (*h == ';' || *h == '&' || *h == ' ')
4875 break;
4876 itx++;
4877 h++;
4878 }
4879
4880 if (itx > STAT_SCOPE_TXT_MAXLEN)
4881 itx = STAT_SCOPE_TXT_MAXLEN;
4882 appctx->ctx.stats.scope_len = itx;
4883
4884 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4885 memcpy(scope_txt, h2, itx);
4886 scope_txt[itx] = '\0';
4887 err = invalid_char(scope_txt);
4888 if (err) {
4889 /* bad char in search text => clear scope */
4890 appctx->ctx.stats.scope_str = 0;
4891 appctx->ctx.stats.scope_len = 0;
4892 }
4893 break;
4894 }
4895 }
4896
4897 /* now check whether we have some admin rules for this request */
4898 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4899 int ret = 1;
4900
4901 if (stats_admin_rule->cond) {
4902 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4903 ret = acl_pass(ret);
4904 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4905 ret = !ret;
4906 }
4907
4908 if (ret) {
4909 /* no rule, or the rule matches */
4910 appctx->ctx.stats.flags |= STAT_ADMIN;
4911 break;
4912 }
4913 }
4914
Christopher Faulet5d45e382019-02-27 15:15:23 +01004915 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4916 appctx->st0 = STAT_HTTP_HEAD;
4917 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004918 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004919 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004920 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004921 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004922 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4923 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4924 appctx->st0 = STAT_HTTP_LAST;
4925 }
4926 }
4927 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004928 /* Unsupported method */
4929 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4930 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4931 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004932 }
4933
4934 s->task->nice = -32; /* small boost for HTTP statistics */
4935 return 1;
4936}
4937
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004938void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4939{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004940 struct channel *req = &s->req;
4941 struct channel *res = &s->res;
4942 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004943 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004944 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004945 struct ist path, location;
4946 unsigned int flags;
4947 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004948
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004949 /*
4950 * Create the location
4951 */
4952 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004953
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004954 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004955 /* special prefix "/" means don't change URL */
4956 srv = __objt_server(s->target);
4957 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4958 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4959 return;
4960 }
4961
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004962 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004963 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004964 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004965 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004966 if (!path.ptr)
4967 return;
4968
4969 if (!chunk_memcat(&trash, path.ptr, path.len))
4970 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004971 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004972
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004973 /*
4974 * Create the 302 respone
4975 */
4976 htx = htx_from_buf(&res->buf);
4977 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4978 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4979 ist("HTTP/1.1"), ist("302"), ist("Found"));
4980 if (!sl)
4981 goto fail;
4982 sl->info.res.status = 302;
4983 s->txn->status = 302;
4984
4985 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4986 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4987 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4988 !htx_add_header(htx, ist("Location"), location))
4989 goto fail;
4990
4991 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4992 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004993
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004994 /*
4995 * Send the message
4996 */
4997 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004998 c_adv(res, data);
4999 res->total += data;
5000
5001 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005002 si_shutr(si);
5003 si_shutw(si);
5004 si->err_type = SI_ET_NONE;
5005 si->state = SI_ST_CLO;
5006
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005007 channel_auto_read(req);
5008 channel_abort(req);
5009 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005010 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005011 channel_auto_read(res);
5012 channel_auto_close(res);
5013
5014 if (!(s->flags & SF_ERR_MASK))
5015 s->flags |= SF_ERR_LOCAL;
5016 if (!(s->flags & SF_FINST_MASK))
5017 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018
5019 /* FIXME: we should increase a counter of redirects per server and per backend. */
5020 srv_inc_sess_ctr(srv);
5021 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005022 return;
5023
5024 fail:
5025 /* If an error occurred, remove the incomplete HTTP response from the
5026 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005027 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028}
5029
Christopher Fauletf2824e62018-10-01 12:12:37 +02005030/* This function terminates the request because it was completly analyzed or
5031 * because an error was triggered during the body forwarding.
5032 */
5033static void htx_end_request(struct stream *s)
5034{
5035 struct channel *chn = &s->req;
5036 struct http_txn *txn = s->txn;
5037
5038 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5039 now_ms, __FUNCTION__, s,
5040 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5041 s->req.analysers, s->res.analysers);
5042
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005043 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5044 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005045 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005046 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005047 goto end;
5048 }
5049
5050 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5051 return;
5052
5053 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005054 /* No need to read anymore, the request was completely parsed.
5055 * We can shut the read side unless we want to abort_on_close,
5056 * or we have a POST request. The issue with POST requests is
5057 * that some browsers still send a CRLF after the request, and
5058 * this CRLF must be read so that it does not remain in the kernel
5059 * buffers, otherwise a close could cause an RST on some systems
5060 * (eg: Linux).
5061 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005062 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005063 channel_dont_read(chn);
5064
5065 /* if the server closes the connection, we want to immediately react
5066 * and close the socket to save packets and syscalls.
5067 */
5068 s->si[1].flags |= SI_FL_NOHALF;
5069
5070 /* In any case we've finished parsing the request so we must
5071 * disable Nagle when sending data because 1) we're not going
5072 * to shut this side, and 2) the server is waiting for us to
5073 * send pending data.
5074 */
5075 chn->flags |= CF_NEVER_WAIT;
5076
Christopher Fauletd01ce402019-01-02 17:44:13 +01005077 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5078 /* The server has not finished to respond, so we
5079 * don't want to move in order not to upset it.
5080 */
5081 return;
5082 }
5083
Christopher Fauletf2824e62018-10-01 12:12:37 +02005084 /* When we get here, it means that both the request and the
5085 * response have finished receiving. Depending on the connection
5086 * mode, we'll have to wait for the last bytes to leave in either
5087 * direction, and sometimes for a close to be effective.
5088 */
5089 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5090 /* Tunnel mode will not have any analyser so it needs to
5091 * poll for reads.
5092 */
5093 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005094 if (b_data(&chn->buf))
5095 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005096 txn->req.msg_state = HTTP_MSG_TUNNEL;
5097 }
5098 else {
5099 /* we're not expecting any new data to come for this
5100 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005101 *
5102 * However, there is an exception if the response
5103 * length is undefined. In this case, we need to wait
5104 * the close from the server. The response will be
5105 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005106 */
5107 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5108 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005109 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005110
5111 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5112 channel_shutr_now(chn);
5113 channel_shutw_now(chn);
5114 }
5115 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005116 goto check_channel_flags;
5117 }
5118
5119 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5120 http_msg_closing:
5121 /* nothing else to forward, just waiting for the output buffer
5122 * to be empty and for the shutw_now to take effect.
5123 */
5124 if (channel_is_empty(chn)) {
5125 txn->req.msg_state = HTTP_MSG_CLOSED;
5126 goto http_msg_closed;
5127 }
5128 else if (chn->flags & CF_SHUTW) {
5129 txn->req.err_state = txn->req.msg_state;
5130 txn->req.msg_state = HTTP_MSG_ERROR;
5131 goto end;
5132 }
5133 return;
5134 }
5135
5136 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5137 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005138 /* if we don't know whether the server will close, we need to hard close */
5139 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5140 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005141 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005142 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005143 channel_dont_read(chn);
5144 goto end;
5145 }
5146
5147 check_channel_flags:
5148 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5149 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5150 /* if we've just closed an output, let's switch */
5151 txn->req.msg_state = HTTP_MSG_CLOSING;
5152 goto http_msg_closing;
5153 }
5154
5155 end:
5156 chn->analysers &= AN_REQ_FLT_END;
5157 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5158 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5159 channel_auto_close(chn);
5160 channel_auto_read(chn);
5161}
5162
5163
5164/* This function terminates the response because it was completly analyzed or
5165 * because an error was triggered during the body forwarding.
5166 */
5167static void htx_end_response(struct stream *s)
5168{
5169 struct channel *chn = &s->res;
5170 struct http_txn *txn = s->txn;
5171
5172 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5173 now_ms, __FUNCTION__, s,
5174 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5175 s->req.analysers, s->res.analysers);
5176
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005177 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5178 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005179 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005180 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005181 goto end;
5182 }
5183
5184 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5185 return;
5186
5187 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5188 /* In theory, we don't need to read anymore, but we must
5189 * still monitor the server connection for a possible close
5190 * while the request is being uploaded, so we don't disable
5191 * reading.
5192 */
5193 /* channel_dont_read(chn); */
5194
5195 if (txn->req.msg_state < HTTP_MSG_DONE) {
5196 /* The client seems to still be sending data, probably
5197 * because we got an error response during an upload.
5198 * We have the choice of either breaking the connection
5199 * or letting it pass through. Let's do the later.
5200 */
5201 return;
5202 }
5203
5204 /* When we get here, it means that both the request and the
5205 * response have finished receiving. Depending on the connection
5206 * mode, we'll have to wait for the last bytes to leave in either
5207 * direction, and sometimes for a close to be effective.
5208 */
5209 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5210 channel_auto_read(chn);
5211 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005212 if (b_data(&chn->buf))
5213 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005214 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5215 }
5216 else {
5217 /* we're not expecting any new data to come for this
5218 * transaction, so we can close it.
5219 */
5220 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5221 channel_shutr_now(chn);
5222 channel_shutw_now(chn);
5223 }
5224 }
5225 goto check_channel_flags;
5226 }
5227
5228 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5229 http_msg_closing:
5230 /* nothing else to forward, just waiting for the output buffer
5231 * to be empty and for the shutw_now to take effect.
5232 */
5233 if (channel_is_empty(chn)) {
5234 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5235 goto http_msg_closed;
5236 }
5237 else if (chn->flags & CF_SHUTW) {
5238 txn->rsp.err_state = txn->rsp.msg_state;
5239 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005240 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005241 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005242 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005243 goto end;
5244 }
5245 return;
5246 }
5247
5248 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5249 http_msg_closed:
5250 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005251 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005252 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005253 goto end;
5254 }
5255
5256 check_channel_flags:
5257 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5258 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5259 /* if we've just closed an output, let's switch */
5260 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5261 goto http_msg_closing;
5262 }
5263
5264 end:
5265 chn->analysers &= AN_RES_FLT_END;
5266 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5267 chn->analysers |= AN_RES_FLT_XFER_DATA;
5268 channel_auto_close(chn);
5269 channel_auto_read(chn);
5270}
5271
Christopher Faulet0f226952018-10-22 09:29:56 +02005272void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5273 int finst, const struct buffer *msg)
5274{
5275 channel_auto_read(si_oc(si));
5276 channel_abort(si_oc(si));
5277 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005278 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005279 channel_auto_close(si_ic(si));
5280 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005281
5282 /* <msg> is an HTX structure. So we copy it in the response's
5283 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005284 if (msg) {
5285 struct channel *chn = si_ic(si);
5286 struct htx *htx;
5287
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005288 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005289 chn->buf.data = msg->data;
5290 memcpy(chn->buf.area, msg->area, msg->data);
5291 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005292 c_adv(chn, htx->data);
5293 chn->total += htx->data;
5294 }
5295 if (!(s->flags & SF_ERR_MASK))
5296 s->flags |= err;
5297 if (!(s->flags & SF_FINST_MASK))
5298 s->flags |= finst;
5299}
5300
5301void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5302{
5303 channel_auto_read(&s->req);
5304 channel_abort(&s->req);
5305 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005306 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5307 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005308
5309 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005310
5311 /* <msg> is an HTX structure. So we copy it in the response's
5312 * channel */
5313 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005314 if (msg) {
5315 struct channel *chn = &s->res;
5316 struct htx *htx;
5317
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005318 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005319 chn->buf.data = msg->data;
5320 memcpy(chn->buf.area, msg->area, msg->data);
5321 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005322 c_adv(chn, htx->data);
5323 chn->total += htx->data;
5324 }
5325
5326 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5327 channel_auto_read(&s->res);
5328 channel_auto_close(&s->res);
5329 channel_shutr_now(&s->res);
5330}
5331
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005332struct buffer *htx_error_message(struct stream *s)
5333{
5334 const int msgnum = http_get_status_idx(s->txn->status);
5335
5336 if (s->be->errmsg[msgnum].area)
5337 return &s->be->errmsg[msgnum];
5338 else if (strm_fe(s)->errmsg[msgnum].area)
5339 return &strm_fe(s)->errmsg[msgnum];
5340 else
5341 return &htx_err_chunks[msgnum];
5342}
5343
5344
Christopher Faulet4a28a532019-03-01 11:19:40 +01005345/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5346 * on success and -1 on error.
5347 */
5348static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5349{
5350 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5351 * then we must send an HTTP/1.1 100 Continue intermediate response.
5352 */
5353 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5354 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5355 struct ist hdr = { .ptr = "Expect", .len = 6 };
5356 struct http_hdr_ctx ctx;
5357
5358 ctx.blk = NULL;
5359 /* Expect is allowed in 1.1, look for it */
5360 if (http_find_header(htx, hdr, &ctx, 0) &&
5361 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5362 if (htx_reply_100_continue(s) == -1)
5363 return -1;
5364 http_remove_header(htx, &ctx);
5365 }
5366 }
5367 return 0;
5368}
5369
Christopher Faulet23a3c792018-11-28 10:01:23 +01005370/* Send a 100-Continue response to the client. It returns 0 on success and -1
5371 * on error. The response channel is updated accordingly.
5372 */
5373static int htx_reply_100_continue(struct stream *s)
5374{
5375 struct channel *res = &s->res;
5376 struct htx *htx = htx_from_buf(&res->buf);
5377 struct htx_sl *sl;
5378 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5379 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5380 size_t data;
5381
5382 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5383 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5384 if (!sl)
5385 goto fail;
5386 sl->info.res.status = 100;
5387
5388 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5389 goto fail;
5390
5391 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005392 c_adv(res, data);
5393 res->total += data;
5394 return 0;
5395
5396 fail:
5397 /* If an error occurred, remove the incomplete HTTP response from the
5398 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005399 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005400 return -1;
5401}
5402
Christopher Faulet12c51e22018-11-28 15:59:42 +01005403
5404/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5405 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5406 * error. The response channel is updated accordingly.
5407 */
5408static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5409{
5410 struct channel *res = &s->res;
5411 struct htx *htx = htx_from_buf(&res->buf);
5412 struct htx_sl *sl;
5413 struct ist code, body;
5414 int status;
5415 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5416 size_t data;
5417
5418 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5419 status = 401;
5420 code = ist("401");
5421 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5422 "You need a valid user and password to access this content.\n"
5423 "</body></html>\n");
5424 }
5425 else {
5426 status = 407;
5427 code = ist("407");
5428 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5429 "You need a valid user and password to access this content.\n"
5430 "</body></html>\n");
5431 }
5432
5433 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5434 ist("HTTP/1.1"), code, ist("Unauthorized"));
5435 if (!sl)
5436 goto fail;
5437 sl->info.res.status = status;
5438 s->txn->status = status;
5439
5440 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5441 goto fail;
5442
5443 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5444 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005445 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5446 goto fail;
5447 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5448 goto fail;
5449 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005450 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005451 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5452 goto fail;
5453
5454 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005455 c_adv(res, data);
5456 res->total += data;
5457
5458 channel_auto_read(&s->req);
5459 channel_abort(&s->req);
5460 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005461 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005462
5463 res->wex = tick_add_ifset(now_ms, res->wto);
5464 channel_auto_read(res);
5465 channel_auto_close(res);
5466 channel_shutr_now(res);
5467 return 0;
5468
5469 fail:
5470 /* If an error occurred, remove the incomplete HTTP response from the
5471 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005472 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005473 return -1;
5474}
5475
Christopher Faulet0f226952018-10-22 09:29:56 +02005476/*
5477 * Capture headers from message <htx> according to header list <cap_hdr>, and
5478 * fill the <cap> pointers appropriately.
5479 */
5480static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5481{
5482 struct cap_hdr *h;
5483 int32_t pos;
5484
5485 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5486 struct htx_blk *blk = htx_get_blk(htx, pos);
5487 enum htx_blk_type type = htx_get_blk_type(blk);
5488 struct ist n, v;
5489
5490 if (type == HTX_BLK_EOH)
5491 break;
5492 if (type != HTX_BLK_HDR)
5493 continue;
5494
5495 n = htx_get_blk_name(htx, blk);
5496
5497 for (h = cap_hdr; h; h = h->next) {
5498 if (h->namelen && (h->namelen == n.len) &&
5499 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5500 if (cap[h->index] == NULL)
5501 cap[h->index] =
5502 pool_alloc(h->pool);
5503
5504 if (cap[h->index] == NULL) {
5505 ha_alert("HTTP capture : out of memory.\n");
5506 break;
5507 }
5508
5509 v = htx_get_blk_value(htx, blk);
5510 if (v.len > h->len)
5511 v.len = h->len;
5512
5513 memcpy(cap[h->index], v.ptr, v.len);
5514 cap[h->index][v.len]=0;
5515 }
5516 }
5517 }
5518}
5519
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005520/* Delete a value in a header between delimiters <from> and <next>. The header
5521 * itself is delimited by <start> and <end> pointers. The number of characters
5522 * displaced is returned, and the pointer to the first delimiter is updated if
5523 * required. The function tries as much as possible to respect the following
5524 * principles :
5525 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5526 * in which case <next> is simply removed
5527 * - set exactly one space character after the new first delimiter, unless there
5528 * are not enough characters in the block being moved to do so.
5529 * - remove unneeded spaces before the previous delimiter and after the new
5530 * one.
5531 *
5532 * It is the caller's responsibility to ensure that :
5533 * - <from> points to a valid delimiter or <start> ;
5534 * - <next> points to a valid delimiter or <end> ;
5535 * - there are non-space chars before <from>.
5536 */
5537static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5538{
5539 char *prev = *from;
5540
5541 if (prev == start) {
5542 /* We're removing the first value. eat the semicolon, if <next>
5543 * is lower than <end> */
5544 if (next < end)
5545 next++;
5546
5547 while (next < end && HTTP_IS_SPHT(*next))
5548 next++;
5549 }
5550 else {
5551 /* Remove useless spaces before the old delimiter. */
5552 while (HTTP_IS_SPHT(*(prev-1)))
5553 prev--;
5554 *from = prev;
5555
5556 /* copy the delimiter and if possible a space if we're
5557 * not at the end of the line.
5558 */
5559 if (next < end) {
5560 *prev++ = *next++;
5561 if (prev + 1 < next)
5562 *prev++ = ' ';
5563 while (next < end && HTTP_IS_SPHT(*next))
5564 next++;
5565 }
5566 }
5567 memmove(prev, next, end - next);
5568 return (prev - next);
5569}
5570
Christopher Faulet0f226952018-10-22 09:29:56 +02005571
5572/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005573 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005574 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005575static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005576{
5577 struct ist dst = ist2(str, 0);
5578
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005579 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005580 goto end;
5581 if (dst.len + 1 > len)
5582 goto end;
5583 dst.ptr[dst.len++] = ' ';
5584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005586 goto end;
5587 if (dst.len + 1 > len)
5588 goto end;
5589 dst.ptr[dst.len++] = ' ';
5590
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005591 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005592 end:
5593 return dst.len;
5594}
5595
Christopher Fauletf0523542018-10-24 11:06:58 +02005596/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005597 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005598 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005599static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005600{
5601 struct ist dst = ist2(str, 0);
5602
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005603 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005604 goto end;
5605 if (dst.len + 1 > len)
5606 goto end;
5607 dst.ptr[dst.len++] = ' ';
5608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005609 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005610 goto end;
5611 if (dst.len + 1 > len)
5612 goto end;
5613 dst.ptr[dst.len++] = ' ';
5614
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005615 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005616 end:
5617 return dst.len;
5618}
5619
5620
Christopher Faulet0f226952018-10-22 09:29:56 +02005621/*
5622 * Print a debug line with a start line.
5623 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005624static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005625{
5626 struct session *sess = strm_sess(s);
5627 int max;
5628
5629 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5630 dir,
5631 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5632 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5633
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005634 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005635 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005636 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005637 trash.area[trash.data++] = ' ';
5638
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005639 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005640 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005641 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005642 trash.area[trash.data++] = ' ';
5643
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005644 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005645 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005646 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005647 trash.area[trash.data++] = '\n';
5648
5649 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5650}
5651
5652/*
5653 * Print a debug line with a header.
5654 */
5655static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5656{
5657 struct session *sess = strm_sess(s);
5658 int max;
5659
5660 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5661 dir,
5662 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5663 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5664
5665 max = n.len;
5666 UBOUND(max, trash.size - trash.data - 3);
5667 chunk_memcat(&trash, n.ptr, max);
5668 trash.area[trash.data++] = ':';
5669 trash.area[trash.data++] = ' ';
5670
5671 max = v.len;
5672 UBOUND(max, trash.size - trash.data - 1);
5673 chunk_memcat(&trash, v.ptr, max);
5674 trash.area[trash.data++] = '\n';
5675
5676 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5677}
5678
5679
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005680__attribute__((constructor))
5681static void __htx_protocol_init(void)
5682{
5683}
5684
5685
5686/*
5687 * Local variables:
5688 * c-indent-level: 8
5689 * c-basic-offset: 8
5690 * End:
5691 */