blob: 80d7fa15c38d8ea4d583abc87d6d297c38b7db09 [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 Fauletf52170d2019-03-08 15:45:26 +01001215 if (req->to_forward == CHN_INFINITE_FORWARD) {
1216 if (req->flags & CF_SHUTR) {
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 Fauletf52170d2019-03-08 15:45:26 +01001245 if (msg->flags & HTTP_MSGF_XFER_LEN)
1246 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001247 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001248
Christopher Faulet9768c262018-10-22 09:34:31 +02001249 /* Check if the end-of-message is reached and if so, switch the message
1250 * in HTTP_MSG_DONE state.
1251 */
1252 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1253 goto missing_data_or_waiting;
1254
1255 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01001256 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001257
1258 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001259 /* other states, DONE...TUNNEL */
1260 /* we don't want to forward closes on DONE except in tunnel mode. */
1261 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1262 channel_dont_close(req);
1263
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001264 if (HAS_REQ_DATA_FILTERS(s)) {
1265 ret = flt_http_end(s, msg);
1266 if (ret <= 0) {
1267 if (!ret)
1268 goto missing_data_or_waiting;
1269 goto return_bad_req;
1270 }
1271 }
1272
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001275 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1277 if (req->flags & CF_SHUTW) {
1278 /* request errors are most likely due to the
1279 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001280 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 goto return_bad_req;
1283 }
1284 return 1;
1285 }
1286
1287 /* If "option abortonclose" is set on the backend, we want to monitor
1288 * the client's connection and forward any shutdown notification to the
1289 * server, which will decide whether to close or to go on processing the
1290 * request. We only do that in tunnel mode, and not in other modes since
1291 * it can be abused to exhaust source ports. */
1292 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1293 channel_auto_read(req);
1294 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1295 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1296 s->si[1].flags |= SI_FL_NOLINGER;
1297 channel_auto_close(req);
1298 }
1299 else if (s->txn->meth == HTTP_METH_POST) {
1300 /* POST requests may require to read extra CRLF sent by broken
1301 * browsers and which could cause an RST to be sent upon close
1302 * on some systems (eg: Linux). */
1303 channel_auto_read(req);
1304 }
1305 return 0;
1306
1307 missing_data_or_waiting:
1308 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001309 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1310 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001311
1312 waiting:
1313 /* waiting for the last bits to leave the buffer */
1314 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316
Christopher Faulet47365272018-10-31 17:40:50 +01001317 if (htx->flags & HTX_FL_PARSING_ERROR)
1318 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001319
Christopher Faulete0768eb2018-10-03 16:38:02 +02001320 /* When TE: chunked is used, we need to get there again to parse remaining
1321 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1322 * And when content-length is used, we never want to let the possible
1323 * shutdown be forwarded to the other side, as the state machine will
1324 * take care of it once the client responds. It's also important to
1325 * prevent TIME_WAITs from accumulating on the backend side, and for
1326 * HTTP/2 where the last frame comes with a shutdown.
1327 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001328 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 channel_dont_close(req);
1330
1331 /* We know that more data are expected, but we couldn't send more that
1332 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1333 * system knows it must not set a PUSH on this first part. Interactive
1334 * modes are already handled by the stream sock layer. We must not do
1335 * this in content-length mode because it could present the MSG_MORE
1336 * flag with the last block of forwarded data, which would cause an
1337 * additional delay to be observed by the receiver.
1338 */
1339 if (msg->flags & HTTP_MSGF_TE_CHNK)
1340 req->flags |= CF_EXPECT_MORE;
1341
1342 return 0;
1343
Christopher Faulet93e02d82019-03-08 14:18:50 +01001344 return_cli_abort:
1345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1346 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1347 if (objt_server(s->target))
1348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1349 if (!(s->flags & SF_ERR_MASK))
1350 s->flags |= SF_ERR_CLICL;
1351 status = 400;
1352 goto return_error;
1353
1354 return_srv_abort:
1355 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1356 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1357 if (objt_server(s->target))
1358 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1359 if (!(s->flags & SF_ERR_MASK))
1360 s->flags |= SF_ERR_SRVCL;
1361 status = 502;
1362 goto return_error;
1363
1364 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001365 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001367 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001369 s->flags |= SF_ERR_CLICL;
1370 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371
Christopher Faulet93e02d82019-03-08 14:18:50 +01001372 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 txn->req.err_state = txn->req.msg_state;
1374 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001375 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001377 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001379 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001380 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 }
1382 req->analysers &= AN_REQ_FLT_END;
1383 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001384 if (!(s->flags & SF_FINST_MASK))
1385 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 return 0;
1387}
1388
1389/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1390 * processing can continue on next analysers, or zero if it either needs more
1391 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1392 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1393 * when it has nothing left to do, and may remove any analyser when it wants to
1394 * abort.
1395 */
1396int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1397{
Christopher Faulet9768c262018-10-22 09:34:31 +02001398 /*
1399 * We will analyze a complete HTTP response to check the its syntax.
1400 *
1401 * Once the start line and all headers are received, we may perform a
1402 * capture of the error (if any), and we will set a few fields. We also
1403 * logging and finally headers capture.
1404 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001405 struct session *sess = s->sess;
1406 struct http_txn *txn = s->txn;
1407 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001408 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001409 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001410 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001411 int n;
1412
1413 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1414 now_ms, __FUNCTION__,
1415 s,
1416 rep,
1417 rep->rex, rep->wex,
1418 rep->flags,
1419 ci_data(rep),
1420 rep->analysers);
1421
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001422 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001423
Willy Tarreau4236f032019-03-05 10:43:32 +01001424 /* Parsing errors are caught here */
1425 if (htx->flags & HTX_FL_PARSING_ERROR)
1426 goto return_bad_res;
1427
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428 /*
1429 * Now we quickly check if we have found a full valid response.
1430 * If not so, we check the FD and buffer states before leaving.
1431 * A full response is indicated by the fact that we have seen
1432 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1433 * responses are checked first.
1434 *
1435 * Depending on whether the client is still there or not, we
1436 * may send an error response back or not. Note that normally
1437 * we should only check for HTTP status there, and check I/O
1438 * errors somewhere else.
1439 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001440 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001441 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001442 * First catch invalid response because of a parsing error or
1443 * because only part of headers have been transfered.
1444 * Multiplexers have the responsibility to emit all headers at
1445 * once. We must be sure to have forwarded all outgoing data
1446 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001447 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001448 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001449 goto return_bad_res;
1450
Christopher Faulet9768c262018-10-22 09:34:31 +02001451 /* 1: have we encountered a read error ? */
1452 if (rep->flags & CF_READ_ERROR) {
1453 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 goto abort_keep_alive;
1455
Olivier Houcharda798bf52019-03-08 18:52:00 +01001456 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001458 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001459 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 }
1461
Christopher Faulete0768eb2018-10-03 16:38:02 +02001462 rep->analysers &= AN_RES_FLT_END;
1463 txn->status = 502;
1464
1465 /* Check to see if the server refused the early data.
1466 * If so, just send a 425
1467 */
1468 if (objt_cs(s->si[1].end)) {
1469 struct connection *conn = objt_cs(s->si[1].end)->conn;
1470
1471 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1472 txn->status = 425;
1473 }
1474
1475 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001476 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477
1478 if (!(s->flags & SF_ERR_MASK))
1479 s->flags |= SF_ERR_SRVCL;
1480 if (!(s->flags & SF_FINST_MASK))
1481 s->flags |= SF_FINST_H;
1482 return 0;
1483 }
1484
Christopher Faulet9768c262018-10-22 09:34:31 +02001485 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001486 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001487 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001488 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001489 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001490 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001491 }
1492
Christopher Faulete0768eb2018-10-03 16:38:02 +02001493 rep->analysers &= AN_RES_FLT_END;
1494 txn->status = 504;
1495 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001496 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001497
1498 if (!(s->flags & SF_ERR_MASK))
1499 s->flags |= SF_ERR_SRVTO;
1500 if (!(s->flags & SF_FINST_MASK))
1501 s->flags |= SF_FINST_H;
1502 return 0;
1503 }
1504
Christopher Faulet9768c262018-10-22 09:34:31 +02001505 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001507 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1508 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001510 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511
1512 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001514 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515
1516 if (!(s->flags & SF_ERR_MASK))
1517 s->flags |= SF_ERR_CLICL;
1518 if (!(s->flags & SF_FINST_MASK))
1519 s->flags |= SF_FINST_H;
1520
1521 /* process_stream() will take care of the error */
1522 return 0;
1523 }
1524
Christopher Faulet9768c262018-10-22 09:34:31 +02001525 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001527 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 goto abort_keep_alive;
1529
Olivier Houcharda798bf52019-03-08 18:52:00 +01001530 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001532 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001533 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 rep->analysers &= AN_RES_FLT_END;
1537 txn->status = 502;
1538 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001539 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540
1541 if (!(s->flags & SF_ERR_MASK))
1542 s->flags |= SF_ERR_SRVCL;
1543 if (!(s->flags & SF_FINST_MASK))
1544 s->flags |= SF_FINST_H;
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001550 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 goto abort_keep_alive;
1552
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555
1556 if (!(s->flags & SF_ERR_MASK))
1557 s->flags |= SF_ERR_CLICL;
1558 if (!(s->flags & SF_FINST_MASK))
1559 s->flags |= SF_FINST_H;
1560
1561 /* process_stream() will take care of the error */
1562 return 0;
1563 }
1564
1565 channel_dont_close(rep);
1566 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1567 return 0;
1568 }
1569
1570 /* More interesting part now : we know that we have a complete
1571 * response which at least looks like HTTP. We have an indicator
1572 * of each header's length, so we can parse them quickly.
1573 */
1574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001576 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577
Christopher Faulet9768c262018-10-22 09:34:31 +02001578 /* 0: we might have to print this header in debug mode */
1579 if (unlikely((global.mode & MODE_DEBUG) &&
1580 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1581 int32_t pos;
1582
Christopher Faulet03599112018-11-27 11:21:21 +01001583 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001584
1585 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1586 struct htx_blk *blk = htx_get_blk(htx, pos);
1587 enum htx_blk_type type = htx_get_blk_type(blk);
1588
1589 if (type == HTX_BLK_EOH)
1590 break;
1591 if (type != HTX_BLK_HDR)
1592 continue;
1593
1594 htx_debug_hdr("srvhdr", s,
1595 htx_get_blk_name(htx, blk),
1596 htx_get_blk_value(htx, blk));
1597 }
1598 }
1599
Christopher Faulet03599112018-11-27 11:21:21 +01001600 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001601 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001602 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001603 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001604 if (sl->flags & HTX_SL_F_XFER_LEN) {
1605 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001606 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001607 if (sl->flags & HTX_SL_F_BODYLESS)
1608 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001609 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001610
1611 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 if (n < 1 || n > 5)
1613 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001614
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 /* when the client triggers a 4xx from the server, it's most often due
1616 * to a missing object or permission. These events should be tracked
1617 * because if they happen often, it may indicate a brute force or a
1618 * vulnerability scan.
1619 */
1620 if (n == 4)
1621 stream_inc_http_err_ctr(s);
1622
1623 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001624 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626 /* Adjust server's health based on status code. Note: status codes 501
1627 * and 505 are triggered on demand by client request, so we must not
1628 * count them as server failures.
1629 */
1630 if (objt_server(s->target)) {
1631 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001632 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001633 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001634 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 }
1636
1637 /*
1638 * We may be facing a 100-continue response, or any other informational
1639 * 1xx response which is non-final, in which case this is not the right
1640 * response, and we're waiting for the next one. Let's allow this response
1641 * to go to the client and wait for the next one. There's an exception for
1642 * 101 which is used later in the code to switch protocols.
1643 */
1644 if (txn->status < 200 &&
1645 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001646 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 msg->msg_state = HTTP_MSG_RPBEFORE;
1649 txn->status = 0;
1650 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001651 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001652 }
1653
1654 /*
1655 * 2: check for cacheability.
1656 */
1657
1658 switch (txn->status) {
1659 case 200:
1660 case 203:
1661 case 204:
1662 case 206:
1663 case 300:
1664 case 301:
1665 case 404:
1666 case 405:
1667 case 410:
1668 case 414:
1669 case 501:
1670 break;
1671 default:
1672 /* RFC7231#6.1:
1673 * Responses with status codes that are defined as
1674 * cacheable by default (e.g., 200, 203, 204, 206,
1675 * 300, 301, 404, 405, 410, 414, and 501 in this
1676 * specification) can be reused by a cache with
1677 * heuristic expiration unless otherwise indicated
1678 * by the method definition or explicit cache
1679 * controls [RFC7234]; all other status codes are
1680 * not cacheable by default.
1681 */
1682 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1683 break;
1684 }
1685
1686 /*
1687 * 3: we may need to capture headers
1688 */
1689 s->logs.logwait &= ~LW_RESP;
1690 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001691 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692
Christopher Faulet9768c262018-10-22 09:34:31 +02001693 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1695 txn->status == 101)) {
1696 /* Either we've established an explicit tunnel, or we're
1697 * switching the protocol. In both cases, we're very unlikely
1698 * to understand the next protocols. We have to switch to tunnel
1699 * mode, so that we transfer the request and responses then let
1700 * this protocol pass unmodified. When we later implement specific
1701 * parsers for such protocols, we'll want to check the Upgrade
1702 * header which contains information about that protocol for
1703 * responses with status 101 (eg: see RFC2817 about TLS).
1704 */
1705 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 }
1707
Christopher Faulet61608322018-11-23 16:23:45 +01001708 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1709 * 407 (Proxy-Authenticate) responses and set the connection to private
1710 */
1711 srv_conn = cs_conn(objt_cs(s->si[1].end));
1712 if (srv_conn) {
1713 struct ist hdr;
1714 struct http_hdr_ctx ctx;
1715
1716 if (txn->status == 401)
1717 hdr = ist("WWW-Authenticate");
1718 else if (txn->status == 407)
1719 hdr = ist("Proxy-Authenticate");
1720 else
1721 goto end;
1722
1723 ctx.blk = NULL;
1724 while (http_find_header(htx, hdr, &ctx, 0)) {
1725 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1726 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1727 srv_conn->flags |= CO_FL_PRIVATE;
1728 }
1729 }
1730
1731 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001732 /* we want to have the response time before we start processing it */
1733 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1734
1735 /* end of job, return OK */
1736 rep->analysers &= ~an_bit;
1737 rep->analyse_exp = TICK_ETERNITY;
1738 channel_auto_close(rep);
1739 return 1;
1740
Christopher Faulet47365272018-10-31 17:40:50 +01001741 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001742 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001743 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001744 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001745 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001746 }
1747 txn->status = 502;
1748 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001749 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001750 rep->analysers &= AN_RES_FLT_END;
1751
1752 if (!(s->flags & SF_ERR_MASK))
1753 s->flags |= SF_ERR_PRXCOND;
1754 if (!(s->flags & SF_FINST_MASK))
1755 s->flags |= SF_FINST_H;
1756 return 0;
1757
Christopher Faulete0768eb2018-10-03 16:38:02 +02001758 abort_keep_alive:
1759 /* A keep-alive request to the server failed on a network error.
1760 * The client is required to retry. We need to close without returning
1761 * any other information so that the client retries.
1762 */
1763 txn->status = 0;
1764 rep->analysers &= AN_RES_FLT_END;
1765 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001766 s->logs.logwait = 0;
1767 s->logs.level = 0;
1768 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001769 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001770 return 0;
1771}
1772
1773/* This function performs all the processing enabled for the current response.
1774 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1775 * and updates s->res.analysers. It might make sense to explode it into several
1776 * other functions. It works like process_request (see indications above).
1777 */
1778int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1779{
1780 struct session *sess = s->sess;
1781 struct http_txn *txn = s->txn;
1782 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001783 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 struct proxy *cur_proxy;
1785 struct cond_wordlist *wl;
1786 enum rule_result ret = HTTP_RULE_RES_CONT;
1787
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001788 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1789 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001790
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1792 now_ms, __FUNCTION__,
1793 s,
1794 rep,
1795 rep->rex, rep->wex,
1796 rep->flags,
1797 ci_data(rep),
1798 rep->analysers);
1799
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001800 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001801
1802 /* The stats applet needs to adjust the Connection header but we don't
1803 * apply any filter there.
1804 */
1805 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1806 rep->analysers &= ~an_bit;
1807 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001808 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001809 }
1810
1811 /*
1812 * We will have to evaluate the filters.
1813 * As opposed to version 1.2, now they will be evaluated in the
1814 * filters order and not in the header order. This means that
1815 * each filter has to be validated among all headers.
1816 *
1817 * Filters are tried with ->be first, then with ->fe if it is
1818 * different from ->be.
1819 *
1820 * Maybe we are in resume condiion. In this case I choose the
1821 * "struct proxy" which contains the rule list matching the resume
1822 * pointer. If none of theses "struct proxy" match, I initialise
1823 * the process with the first one.
1824 *
1825 * In fact, I check only correspondance betwwen the current list
1826 * pointer and the ->fe rule list. If it doesn't match, I initialize
1827 * the loop with the ->be.
1828 */
1829 if (s->current_rule_list == &sess->fe->http_res_rules)
1830 cur_proxy = sess->fe;
1831 else
1832 cur_proxy = s->be;
1833 while (1) {
1834 struct proxy *rule_set = cur_proxy;
1835
1836 /* evaluate http-response rules */
1837 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001838 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001839
1840 if (ret == HTTP_RULE_RES_BADREQ)
1841 goto return_srv_prx_502;
1842
1843 if (ret == HTTP_RULE_RES_DONE) {
1844 rep->analysers &= ~an_bit;
1845 rep->analyse_exp = TICK_ETERNITY;
1846 return 1;
1847 }
1848 }
1849
1850 /* we need to be called again. */
1851 if (ret == HTTP_RULE_RES_YIELD) {
1852 channel_dont_close(rep);
1853 return 0;
1854 }
1855
1856 /* try headers filters */
1857 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001858 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1859 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001860 }
1861
1862 /* has the response been denied ? */
1863 if (txn->flags & TX_SVDENY) {
1864 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001865 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866
Olivier Houcharda798bf52019-03-08 18:52:00 +01001867 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1868 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001870 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 goto return_srv_prx_502;
1872 }
1873
1874 /* add response headers from the rule sets in the same order */
1875 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001876 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001877 if (txn->status < 200 && txn->status != 101)
1878 break;
1879 if (wl->cond) {
1880 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1881 ret = acl_pass(ret);
1882 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1883 ret = !ret;
1884 if (!ret)
1885 continue;
1886 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001887
1888 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1889 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890 goto return_bad_resp;
1891 }
1892
1893 /* check whether we're already working on the frontend */
1894 if (cur_proxy == sess->fe)
1895 break;
1896 cur_proxy = sess->fe;
1897 }
1898
1899 /* After this point, this anayzer can't return yield, so we can
1900 * remove the bit corresponding to this analyzer from the list.
1901 *
1902 * Note that the intermediate returns and goto found previously
1903 * reset the analyzers.
1904 */
1905 rep->analysers &= ~an_bit;
1906 rep->analyse_exp = TICK_ETERNITY;
1907
1908 /* OK that's all we can do for 1xx responses */
1909 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001910 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001911
1912 /*
1913 * Now check for a server cookie.
1914 */
1915 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001916 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001917
1918 /*
1919 * Check for cache-control or pragma headers if required.
1920 */
1921 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1922 check_response_for_cacheability(s, rep);
1923
1924 /*
1925 * Add server cookie in the response if needed
1926 */
1927 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1928 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1929 (!(s->flags & SF_DIRECT) ||
1930 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1931 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1932 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1933 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1934 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1935 !(s->flags & SF_IGNORE_PRST)) {
1936 /* the server is known, it's not the one the client requested, or the
1937 * cookie's last seen date needs to be refreshed. We have to
1938 * insert a set-cookie here, except if we want to insert only on POST
1939 * requests and this one isn't. Note that servers which don't have cookies
1940 * (eg: some backup servers) will return a full cookie removal request.
1941 */
1942 if (!objt_server(s->target)->cookie) {
1943 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001944 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945 s->be->cookie_name);
1946 }
1947 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001948 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001949
1950 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1951 /* emit last_date, which is mandatory */
1952 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1953 s30tob64((date.tv_sec+3) >> 2,
1954 trash.area + trash.data);
1955 trash.data += 5;
1956
1957 if (s->be->cookie_maxlife) {
1958 /* emit first_date, which is either the original one or
1959 * the current date.
1960 */
1961 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1962 s30tob64(txn->cookie_first_date ?
1963 txn->cookie_first_date >> 2 :
1964 (date.tv_sec+3) >> 2,
1965 trash.area + trash.data);
1966 trash.data += 5;
1967 }
1968 }
1969 chunk_appendf(&trash, "; path=/");
1970 }
1971
1972 if (s->be->cookie_domain)
1973 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1974
1975 if (s->be->ck_opts & PR_CK_HTTPONLY)
1976 chunk_appendf(&trash, "; HttpOnly");
1977
1978 if (s->be->ck_opts & PR_CK_SECURE)
1979 chunk_appendf(&trash, "; Secure");
1980
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001981 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001982 goto return_bad_resp;
1983
1984 txn->flags &= ~TX_SCK_MASK;
1985 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1986 /* the server did not change, only the date was updated */
1987 txn->flags |= TX_SCK_UPDATED;
1988 else
1989 txn->flags |= TX_SCK_INSERTED;
1990
1991 /* Here, we will tell an eventual cache on the client side that we don't
1992 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1993 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1994 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1995 */
1996 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1997
1998 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1999
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002000 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002001 goto return_bad_resp;
2002 }
2003 }
2004
2005 /*
2006 * Check if result will be cacheable with a cookie.
2007 * We'll block the response if security checks have caught
2008 * nasty things such as a cacheable cookie.
2009 */
2010 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2011 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2012 (s->be->options & PR_O_CHK_CACHE)) {
2013 /* we're in presence of a cacheable response containing
2014 * a set-cookie header. We'll block it as requested by
2015 * the 'checkcache' option, and send an alert.
2016 */
2017 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002018 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019
Olivier Houcharda798bf52019-03-08 18:52:00 +01002020 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2021 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002023 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024
2025 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2026 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2027 send_log(s->be, LOG_ALERT,
2028 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2029 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2030 goto return_srv_prx_502;
2031 }
2032
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002033 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002034 /* Always enter in the body analyzer */
2035 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2036 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2037
2038 /* if the user wants to log as soon as possible, without counting
2039 * bytes from the server, then this is the right moment. We have
2040 * to temporarily assign bytes_out to log what we currently have.
2041 */
2042 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2043 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002044 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002045 s->do_log(s);
2046 s->logs.bytes_out = 0;
2047 }
2048 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049
2050 return_bad_resp:
2051 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002052 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002053 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002054 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002055 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056
2057 return_srv_prx_502:
2058 rep->analysers &= AN_RES_FLT_END;
2059 txn->status = 502;
2060 s->logs.t_data = -1; /* was not a valid response */
2061 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002062 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002063 if (!(s->flags & SF_ERR_MASK))
2064 s->flags |= SF_ERR_PRXCOND;
2065 if (!(s->flags & SF_FINST_MASK))
2066 s->flags |= SF_FINST_H;
2067 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002068}
2069
2070/* This function is an analyser which forwards response body (including chunk
2071 * sizes if any). It is called as soon as we must forward, even if we forward
2072 * zero byte. The only situation where it must not be called is when we're in
2073 * tunnel mode and we want to forward till the close. It's used both to forward
2074 * remaining data and to resync after end of body. It expects the msg_state to
2075 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2076 * read more data, or 1 once we can go on with next request or end the stream.
2077 *
2078 * It is capable of compressing response data both in content-length mode and
2079 * in chunked mode. The state machines follows different flows depending on
2080 * whether content-length and chunked modes are used, since there are no
2081 * trailers in content-length :
2082 *
2083 * chk-mode cl-mode
2084 * ,----- BODY -----.
2085 * / \
2086 * V size > 0 V chk-mode
2087 * .--> SIZE -------------> DATA -------------> CRLF
2088 * | | size == 0 | last byte |
2089 * | v final crlf v inspected |
2090 * | TRAILERS -----------> DONE |
2091 * | |
2092 * `----------------------------------------------'
2093 *
2094 * Compression only happens in the DATA state, and must be flushed in final
2095 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2096 * is performed at once on final states for all bytes parsed, or when leaving
2097 * on missing data.
2098 */
2099int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2100{
2101 struct session *sess = s->sess;
2102 struct http_txn *txn = s->txn;
2103 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002104 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002105 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002106
2107 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2108 now_ms, __FUNCTION__,
2109 s,
2110 res,
2111 res->rex, res->wex,
2112 res->flags,
2113 ci_data(res),
2114 res->analysers);
2115
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002116 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002117
2118 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002119 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120 /* Output closed while we were sending data. We must abort and
2121 * wake the other side up.
2122 */
2123 msg->err_state = msg->msg_state;
2124 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002125 htx_end_response(s);
2126 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002127 return 1;
2128 }
2129
Christopher Faulet9768c262018-10-22 09:34:31 +02002130 if (msg->msg_state == HTTP_MSG_BODY)
2131 msg->msg_state = HTTP_MSG_DATA;
2132
Christopher Faulete0768eb2018-10-03 16:38:02 +02002133 /* in most states, we should abort in case of early close */
2134 channel_auto_close(res);
2135
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 if (res->to_forward) {
Christopher Fauletf52170d2019-03-08 15:45:26 +01002137 if (res->to_forward == CHN_INFINITE_FORWARD) {
2138 if (res->flags & CF_SHUTR) {
2139 msg->msg_state = HTTP_MSG_DONE;
2140 res->to_forward = 0;
2141 goto done;
2142 }
2143 }
2144 else {
2145 /* We can't process the buffer's contents yet */
2146 res->flags |= CF_WAKE_WRITE;
2147 goto missing_data_or_waiting;
2148 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 }
2150
Christopher Faulet9768c262018-10-22 09:34:31 +02002151 if (msg->msg_state >= HTTP_MSG_DONE)
2152 goto done;
2153
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002154 /* Forward input data. We get it by removing all outgoing data not
2155 * forwarded yet from HTX data size. If there are some data filters, we
2156 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002157 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002158 if (HAS_RSP_DATA_FILTERS(s)) {
2159 ret = flt_http_payload(s, msg, htx->data);
2160 if (ret < 0)
2161 goto return_bad_res;
2162 c_adv(res, ret);
2163 if (htx->data != co_data(res) || htx->extra)
2164 goto missing_data_or_waiting;
2165 }
2166 else {
2167 c_adv(res, htx->data - co_data(res));
Christopher Fauletf52170d2019-03-08 15:45:26 +01002168 if (msg->flags & HTTP_MSGF_XFER_LEN)
2169 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002170 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002171
2172 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2173 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002174 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002175 msg->msg_state = HTTP_MSG_TUNNEL;
2176 goto done;
2177 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002178 }
2179
Christopher Faulet9768c262018-10-22 09:34:31 +02002180 /* Check if the end-of-message is reached and if so, switch the message
2181 * in HTTP_MSG_DONE state.
2182 */
2183 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2184 goto missing_data_or_waiting;
2185
2186 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletf52170d2019-03-08 15:45:26 +01002187 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002188
2189 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002191 channel_dont_close(res);
2192
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002193 if (HAS_RSP_DATA_FILTERS(s)) {
2194 ret = flt_http_end(s, msg);
2195 if (ret <= 0) {
2196 if (!ret)
2197 goto missing_data_or_waiting;
2198 goto return_bad_res;
2199 }
2200 }
2201
Christopher Fauletf2824e62018-10-01 12:12:37 +02002202 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002204 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2206 if (res->flags & CF_SHUTW) {
2207 /* response errors are most likely due to the
2208 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002209 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 goto return_bad_res;
2212 }
2213 return 1;
2214 }
2215 return 0;
2216
2217 missing_data_or_waiting:
2218 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002219 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220
Christopher Faulet47365272018-10-31 17:40:50 +01002221 if (htx->flags & HTX_FL_PARSING_ERROR)
2222 goto return_bad_res;
2223
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 /* stop waiting for data if the input is closed before the end. If the
2225 * client side was already closed, it means that the client has aborted,
2226 * so we don't want to count this as a server abort. Otherwise it's a
2227 * server abort.
2228 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002229 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002231 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002233 if (htx_is_empty(htx))
2234 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002235 }
2236
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 /* When TE: chunked is used, we need to get there again to parse
2238 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2240 * are filters registered on the stream, we don't want to forward a
2241 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002243 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 channel_dont_close(res);
2245
2246 /* We know that more data are expected, but we couldn't send more that
2247 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2248 * system knows it must not set a PUSH on this first part. Interactive
2249 * modes are already handled by the stream sock layer. We must not do
2250 * this in content-length mode because it could present the MSG_MORE
2251 * flag with the last block of forwarded data, which would cause an
2252 * additional delay to be observed by the receiver.
2253 */
2254 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2255 res->flags |= CF_EXPECT_MORE;
2256
2257 /* the stream handler will take care of timeouts and errors */
2258 return 0;
2259
Christopher Faulet93e02d82019-03-08 14:18:50 +01002260 return_srv_abort:
2261 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2262 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002264 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2265 if (!(s->flags & SF_ERR_MASK))
2266 s->flags |= SF_ERR_SRVCL;
2267 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268
Christopher Faulet93e02d82019-03-08 14:18:50 +01002269 return_cli_abort:
2270 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2271 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002272 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002273 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2274 if (!(s->flags & SF_ERR_MASK))
2275 s->flags |= SF_ERR_CLICL;
2276 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002277
Christopher Faulet93e02d82019-03-08 14:18:50 +01002278 return_bad_res:
2279 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2280 if (objt_server(s->target)) {
2281 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2282 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2283 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002285 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 txn->rsp.err_state = txn->rsp.msg_state;
2289 txn->rsp.msg_state = HTTP_MSG_ERROR;
2290 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002291 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002292 res->analysers &= AN_RES_FLT_END;
2293 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulete0768eb2018-10-03 16:38:02 +02002294 if (!(s->flags & SF_FINST_MASK))
2295 s->flags |= SF_FINST_D;
2296 return 0;
2297}
2298
Christopher Faulet0f226952018-10-22 09:29:56 +02002299void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002300{
2301 struct proxy *fe = strm_fe(s);
2302 int tmp = TX_CON_WANT_CLO;
2303
2304 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2305 tmp = TX_CON_WANT_TUN;
2306
2307 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002308 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002309}
2310
2311/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002312 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002313 * as too large a request to build a valid response.
2314 */
2315int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2316{
Christopher Faulet99daf282018-11-28 22:58:13 +01002317 struct channel *req = &s->req;
2318 struct channel *res = &s->res;
2319 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002320 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002321 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002322 struct ist status, reason, location;
2323 unsigned int flags;
2324 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002325
2326 chunk = alloc_trash_chunk();
2327 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002328 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002329
Christopher Faulet99daf282018-11-28 22:58:13 +01002330 /*
2331 * Create the location
2332 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002333 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002334 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002335 case REDIRECT_TYPE_SCHEME: {
2336 struct http_hdr_ctx ctx;
2337 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338
Christopher Faulet99daf282018-11-28 22:58:13 +01002339 host = ist("");
2340 ctx.blk = NULL;
2341 if (http_find_header(htx, ist("Host"), &ctx, 0))
2342 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002343
Christopher Faulet99daf282018-11-28 22:58:13 +01002344 sl = http_find_stline(htx);
2345 path = http_get_path(htx_sl_req_uri(sl));
2346 /* build message using path */
2347 if (path.ptr) {
2348 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2349 int qs = 0;
2350 while (qs < path.len) {
2351 if (*(path.ptr + qs) == '?') {
2352 path.len = qs;
2353 break;
2354 }
2355 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357 }
2358 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002359 else
2360 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002361
Christopher Faulet99daf282018-11-28 22:58:13 +01002362 if (rule->rdr_str) { /* this is an old "redirect" rule */
2363 /* add scheme */
2364 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2365 goto fail;
2366 }
2367 else {
2368 /* add scheme with executing log format */
2369 chunk->data += build_logline(s, chunk->area + chunk->data,
2370 chunk->size - chunk->data,
2371 &rule->rdr_fmt);
2372 }
2373 /* add "://" + host + path */
2374 if (!chunk_memcat(chunk, "://", 3) ||
2375 !chunk_memcat(chunk, host.ptr, host.len) ||
2376 !chunk_memcat(chunk, path.ptr, path.len))
2377 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002378
Christopher Faulet99daf282018-11-28 22:58:13 +01002379 /* append a slash at the end of the location if needed and missing */
2380 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2381 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2382 if (chunk->data + 1 >= chunk->size)
2383 goto fail;
2384 chunk->area[chunk->data++] = '/';
2385 }
2386 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002387 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 case REDIRECT_TYPE_PREFIX: {
2390 struct ist path;
2391
2392 sl = http_find_stline(htx);
2393 path = http_get_path(htx_sl_req_uri(sl));
2394 /* build message using path */
2395 if (path.ptr) {
2396 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2397 int qs = 0;
2398 while (qs < path.len) {
2399 if (*(path.ptr + qs) == '?') {
2400 path.len = qs;
2401 break;
2402 }
2403 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405 }
2406 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 else
2408 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409
Christopher Faulet99daf282018-11-28 22:58:13 +01002410 if (rule->rdr_str) { /* this is an old "redirect" rule */
2411 /* add prefix. Note that if prefix == "/", we don't want to
2412 * add anything, otherwise it makes it hard for the user to
2413 * configure a self-redirection.
2414 */
2415 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2416 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2417 goto fail;
2418 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002419 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002420 else {
2421 /* add prefix with executing log format */
2422 chunk->data += build_logline(s, chunk->area + chunk->data,
2423 chunk->size - chunk->data,
2424 &rule->rdr_fmt);
2425 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 /* add path */
2428 if (!chunk_memcat(chunk, path.ptr, path.len))
2429 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430
Christopher Faulet99daf282018-11-28 22:58:13 +01002431 /* append a slash at the end of the location if needed and missing */
2432 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2433 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2434 if (chunk->data + 1 >= chunk->size)
2435 goto fail;
2436 chunk->area[chunk->data++] = '/';
2437 }
2438 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002440 case REDIRECT_TYPE_LOCATION:
2441 default:
2442 if (rule->rdr_str) { /* this is an old "redirect" rule */
2443 /* add location */
2444 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2445 goto fail;
2446 }
2447 else {
2448 /* add location with executing log format */
2449 chunk->data += build_logline(s, chunk->area + chunk->data,
2450 chunk->size - chunk->data,
2451 &rule->rdr_fmt);
2452 }
2453 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002454 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 location = ist2(chunk->area, chunk->data);
2456
2457 /*
2458 * Create the 30x response
2459 */
2460 switch (rule->code) {
2461 case 308:
2462 status = ist("308");
2463 reason = ist("Permanent Redirect");
2464 break;
2465 case 307:
2466 status = ist("307");
2467 reason = ist("Temporary Redirect");
2468 break;
2469 case 303:
2470 status = ist("303");
2471 reason = ist("See Other");
2472 break;
2473 case 301:
2474 status = ist("301");
2475 reason = ist("Moved Permanently");
2476 break;
2477 case 302:
2478 default:
2479 status = ist("302");
2480 reason = ist("Found");
2481 break;
2482 }
2483
2484 htx = htx_from_buf(&res->buf);
2485 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2486 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2487 if (!sl)
2488 goto fail;
2489 sl->info.res.status = rule->code;
2490 s->txn->status = rule->code;
2491
2492 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2493 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2494 !htx_add_header(htx, ist("Location"), location))
2495 goto fail;
2496
2497 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2498 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2499 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002500 }
2501
2502 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002503 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2504 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002505 }
2506
Christopher Faulet99daf282018-11-28 22:58:13 +01002507 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2508 goto fail;
2509
Christopher Fauletf2824e62018-10-01 12:12:37 +02002510 /* let's log the request time */
2511 s->logs.tv_request = now;
2512
Christopher Faulet99daf282018-11-28 22:58:13 +01002513 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002514 c_adv(res, data);
2515 res->total += data;
2516
2517 channel_auto_read(req);
2518 channel_abort(req);
2519 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002520 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002521
2522 res->wex = tick_add_ifset(now_ms, res->wto);
2523 channel_auto_read(res);
2524 channel_auto_close(res);
2525 channel_shutr_now(res);
2526
2527 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002528
2529 if (!(s->flags & SF_ERR_MASK))
2530 s->flags |= SF_ERR_LOCAL;
2531 if (!(s->flags & SF_FINST_MASK))
2532 s->flags |= SF_FINST_R;
2533
Christopher Faulet99daf282018-11-28 22:58:13 +01002534 free_trash_chunk(chunk);
2535 return 1;
2536
2537 fail:
2538 /* If an error occurred, remove the incomplete HTTP response from the
2539 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002540 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002541 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002542 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002543}
2544
Christopher Faulet72333522018-10-24 11:25:02 +02002545int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2546 struct ist name, const char *str, struct my_regex *re, int action)
2547{
2548 struct http_hdr_ctx ctx;
2549 struct buffer *output = get_trash_chunk();
2550
2551 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2552 ctx.blk = NULL;
2553 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2554 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2555 continue;
2556
2557 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2558 if (output->data == -1)
2559 return -1;
2560 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2561 return -1;
2562 }
2563 return 0;
2564}
2565
2566static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2567 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2568{
2569 struct buffer *replace;
2570 int ret = -1;
2571
2572 replace = alloc_trash_chunk();
2573 if (!replace)
2574 goto leave;
2575
2576 replace->data = build_logline(s, replace->area, replace->size, fmt);
2577 if (replace->data >= replace->size - 1)
2578 goto leave;
2579
2580 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2581
2582 leave:
2583 free_trash_chunk(replace);
2584 return ret;
2585}
2586
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002587
2588/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2589 * on success and -1 on error. The response channel is updated accordingly.
2590 */
2591static int htx_reply_103_early_hints(struct channel *res)
2592{
2593 struct htx *htx = htx_from_buf(&res->buf);
2594 size_t data;
2595
2596 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2597 /* If an error occurred during an Early-hint rule,
2598 * remove the incomplete HTTP 103 response from the
2599 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002600 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002601 return -1;
2602 }
2603
2604 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002605 c_adv(res, data);
2606 res->total += data;
2607 return 0;
2608}
2609
Christopher Faulet6eb92892018-11-15 16:39:29 +01002610/*
2611 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2612 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002613 * If <early_hints> is 0, it is starts a new response by adding the start
2614 * line. If an error occurred -1 is returned. On success 0 is returned. The
2615 * channel is not updated here. It must be done calling the function
2616 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002617 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002618static 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 +01002619{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002620 struct channel *res = &s->res;
2621 struct htx *htx = htx_from_buf(&res->buf);
2622 struct buffer *value = alloc_trash_chunk();
2623
Christopher Faulet6eb92892018-11-15 16:39:29 +01002624 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002625 struct htx_sl *sl;
2626 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2627 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2628
2629 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2630 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2631 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002632 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002633 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 }
2635
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2637 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002638 goto fail;
2639
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002640 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002641 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002642
2643 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002644 /* If an error occurred during an Early-hint rule, remove the incomplete
2645 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002646 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002647 free_trash_chunk(value);
2648 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002649}
2650
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002651/* This function executes one of the set-{method,path,query,uri} actions. It
2652 * takes the string from the variable 'replace' with length 'len', then modifies
2653 * the relevant part of the request line accordingly. Then it updates various
2654 * pointers to the next elements which were moved, and the total buffer length.
2655 * It finds the action to be performed in p[2], previously filled by function
2656 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2657 * error, though this can be revisited when this code is finally exploited.
2658 *
2659 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2660 * query string and 3 to replace uri.
2661 *
2662 * In query string case, the mark question '?' must be set at the start of the
2663 * string by the caller, event if the replacement query string is empty.
2664 */
2665int htx_req_replace_stline(int action, const char *replace, int len,
2666 struct proxy *px, struct stream *s)
2667{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002668 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002669
2670 switch (action) {
2671 case 0: // method
2672 if (!http_replace_req_meth(htx, ist2(replace, len)))
2673 return -1;
2674 break;
2675
2676 case 1: // path
2677 if (!http_replace_req_path(htx, ist2(replace, len)))
2678 return -1;
2679 break;
2680
2681 case 2: // query
2682 if (!http_replace_req_query(htx, ist2(replace, len)))
2683 return -1;
2684 break;
2685
2686 case 3: // uri
2687 if (!http_replace_req_uri(htx, ist2(replace, len)))
2688 return -1;
2689 break;
2690
2691 default:
2692 return -1;
2693 }
2694 return 0;
2695}
2696
2697/* This function replace the HTTP status code and the associated message. The
2698 * variable <status> contains the new status code. This function never fails.
2699 */
2700void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2701{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002702 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002703 char *res;
2704
2705 chunk_reset(&trash);
2706 res = ultoa_o(status, trash.area, trash.size);
2707 trash.data = res - trash.area;
2708
2709 /* Do we have a custom reason format string? */
2710 if (reason == NULL)
2711 reason = http_get_reason(status);
2712
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002713 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002714 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2715}
2716
Christopher Faulet3e964192018-10-24 11:39:23 +02002717/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2718 * transaction <txn>. Returns the verdict of the first rule that prevents
2719 * further processing of the request (auth, deny, ...), and defaults to
2720 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2721 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2722 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2723 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2724 * status.
2725 */
2726static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2727 struct stream *s, int *deny_status)
2728{
2729 struct session *sess = strm_sess(s);
2730 struct http_txn *txn = s->txn;
2731 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002732 struct act_rule *rule;
2733 struct http_hdr_ctx ctx;
2734 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002735 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2736 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002737 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002738
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002739 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002740
2741 /* If "the current_rule_list" match the executed rule list, we are in
2742 * resume condition. If a resume is needed it is always in the action
2743 * and never in the ACL or converters. In this case, we initialise the
2744 * current rule, and go to the action execution point.
2745 */
2746 if (s->current_rule) {
2747 rule = s->current_rule;
2748 s->current_rule = NULL;
2749 if (s->current_rule_list == rules)
2750 goto resume_execution;
2751 }
2752 s->current_rule_list = rules;
2753
2754 list_for_each_entry(rule, rules, list) {
2755 /* check optional condition */
2756 if (rule->cond) {
2757 int ret;
2758
2759 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2760 ret = acl_pass(ret);
2761
2762 if (rule->cond->pol == ACL_COND_UNLESS)
2763 ret = !ret;
2764
2765 if (!ret) /* condition not matched */
2766 continue;
2767 }
2768
2769 act_flags |= ACT_FLAG_FIRST;
2770 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002771 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2772 early_hints = 0;
2773 if (htx_reply_103_early_hints(&s->res) == -1) {
2774 rule_ret = HTTP_RULE_RES_BADREQ;
2775 goto end;
2776 }
2777 }
2778
Christopher Faulet3e964192018-10-24 11:39:23 +02002779 switch (rule->action) {
2780 case ACT_ACTION_ALLOW:
2781 rule_ret = HTTP_RULE_RES_STOP;
2782 goto end;
2783
2784 case ACT_ACTION_DENY:
2785 if (deny_status)
2786 *deny_status = rule->deny_status;
2787 rule_ret = HTTP_RULE_RES_DENY;
2788 goto end;
2789
2790 case ACT_HTTP_REQ_TARPIT:
2791 txn->flags |= TX_CLTARPIT;
2792 if (deny_status)
2793 *deny_status = rule->deny_status;
2794 rule_ret = HTTP_RULE_RES_DENY;
2795 goto end;
2796
2797 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002798 /* Auth might be performed on regular http-req rules as well as on stats */
2799 auth_realm = rule->arg.auth.realm;
2800 if (!auth_realm) {
2801 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2802 auth_realm = STATS_DEFAULT_REALM;
2803 else
2804 auth_realm = px->id;
2805 }
2806 /* send 401/407 depending on whether we use a proxy or not. We still
2807 * count one error, because normal browsing won't significantly
2808 * increase the counter but brute force attempts will.
2809 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002810 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002811 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2812 rule_ret = HTTP_RULE_RES_BADREQ;
2813 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002814 goto end;
2815
2816 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002817 rule_ret = HTTP_RULE_RES_DONE;
2818 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2819 rule_ret = HTTP_RULE_RES_BADREQ;
2820 goto end;
2821
2822 case ACT_HTTP_SET_NICE:
2823 s->task->nice = rule->arg.nice;
2824 break;
2825
2826 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002827 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 break;
2829
2830 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002831 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002832 break;
2833
2834 case ACT_HTTP_SET_LOGL:
2835 s->logs.level = rule->arg.loglevel;
2836 break;
2837
2838 case ACT_HTTP_REPLACE_HDR:
2839 case ACT_HTTP_REPLACE_VAL:
2840 if (htx_transform_header(s, &s->req, htx,
2841 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2842 &rule->arg.hdr_add.fmt,
2843 &rule->arg.hdr_add.re, rule->action)) {
2844 rule_ret = HTTP_RULE_RES_BADREQ;
2845 goto end;
2846 }
2847 break;
2848
2849 case ACT_HTTP_DEL_HDR:
2850 /* remove all occurrences of the header */
2851 ctx.blk = NULL;
2852 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2853 http_remove_header(htx, &ctx);
2854 break;
2855
2856 case ACT_HTTP_SET_HDR:
2857 case ACT_HTTP_ADD_HDR: {
2858 /* The scope of the trash buffer must be limited to this function. The
2859 * build_logline() function can execute a lot of other function which
2860 * can use the trash buffer. So for limiting the scope of this global
2861 * buffer, we build first the header value using build_logline, and
2862 * after we store the header name.
2863 */
2864 struct buffer *replace;
2865 struct ist n, v;
2866
2867 replace = alloc_trash_chunk();
2868 if (!replace) {
2869 rule_ret = HTTP_RULE_RES_BADREQ;
2870 goto end;
2871 }
2872
2873 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2874 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2875 v = ist2(replace->area, replace->data);
2876
2877 if (rule->action == ACT_HTTP_SET_HDR) {
2878 /* remove all occurrences of the header */
2879 ctx.blk = NULL;
2880 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2881 http_remove_header(htx, &ctx);
2882 }
2883
2884 if (!http_add_header(htx, n, v)) {
2885 static unsigned char rate_limit = 0;
2886
2887 if ((rate_limit++ & 255) == 0) {
2888 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);
2889 }
2890
Olivier Houcharda798bf52019-03-08 18:52:00 +01002891 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002893 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002894 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002895 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002896 }
2897 free_trash_chunk(replace);
2898 break;
2899 }
2900
2901 case ACT_HTTP_DEL_ACL:
2902 case ACT_HTTP_DEL_MAP: {
2903 struct pat_ref *ref;
2904 struct buffer *key;
2905
2906 /* collect reference */
2907 ref = pat_ref_lookup(rule->arg.map.ref);
2908 if (!ref)
2909 continue;
2910
2911 /* allocate key */
2912 key = alloc_trash_chunk();
2913 if (!key) {
2914 rule_ret = HTTP_RULE_RES_BADREQ;
2915 goto end;
2916 }
2917
2918 /* collect key */
2919 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2920 key->area[key->data] = '\0';
2921
2922 /* perform update */
2923 /* returned code: 1=ok, 0=ko */
2924 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2925 pat_ref_delete(ref, key->area);
2926 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2927
2928 free_trash_chunk(key);
2929 break;
2930 }
2931
2932 case ACT_HTTP_ADD_ACL: {
2933 struct pat_ref *ref;
2934 struct buffer *key;
2935
2936 /* collect reference */
2937 ref = pat_ref_lookup(rule->arg.map.ref);
2938 if (!ref)
2939 continue;
2940
2941 /* allocate key */
2942 key = alloc_trash_chunk();
2943 if (!key) {
2944 rule_ret = HTTP_RULE_RES_BADREQ;
2945 goto end;
2946 }
2947
2948 /* collect key */
2949 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2950 key->area[key->data] = '\0';
2951
2952 /* perform update */
2953 /* add entry only if it does not already exist */
2954 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2955 if (pat_ref_find_elt(ref, key->area) == NULL)
2956 pat_ref_add(ref, key->area, NULL, NULL);
2957 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2958
2959 free_trash_chunk(key);
2960 break;
2961 }
2962
2963 case ACT_HTTP_SET_MAP: {
2964 struct pat_ref *ref;
2965 struct buffer *key, *value;
2966
2967 /* collect reference */
2968 ref = pat_ref_lookup(rule->arg.map.ref);
2969 if (!ref)
2970 continue;
2971
2972 /* allocate key */
2973 key = alloc_trash_chunk();
2974 if (!key) {
2975 rule_ret = HTTP_RULE_RES_BADREQ;
2976 goto end;
2977 }
2978
2979 /* allocate value */
2980 value = alloc_trash_chunk();
2981 if (!value) {
2982 free_trash_chunk(key);
2983 rule_ret = HTTP_RULE_RES_BADREQ;
2984 goto end;
2985 }
2986
2987 /* collect key */
2988 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2989 key->area[key->data] = '\0';
2990
2991 /* collect value */
2992 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2993 value->area[value->data] = '\0';
2994
2995 /* perform update */
2996 if (pat_ref_find_elt(ref, key->area) != NULL)
2997 /* update entry if it exists */
2998 pat_ref_set(ref, key->area, value->area, NULL);
2999 else
3000 /* insert a new entry */
3001 pat_ref_add(ref, key->area, value->area, NULL);
3002
3003 free_trash_chunk(key);
3004 free_trash_chunk(value);
3005 break;
3006 }
3007
3008 case ACT_HTTP_EARLY_HINT:
3009 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3010 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003011 early_hints = htx_add_early_hint_header(s, early_hints,
3012 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003013 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003014 if (early_hints == -1) {
3015 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003016 goto end;
3017 }
3018 break;
3019
3020 case ACT_CUSTOM:
3021 if ((s->req.flags & CF_READ_ERROR) ||
3022 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3023 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3024 (px->options & PR_O_ABRT_CLOSE)))
3025 act_flags |= ACT_FLAG_FINAL;
3026
3027 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3028 case ACT_RET_ERR:
3029 case ACT_RET_CONT:
3030 break;
3031 case ACT_RET_STOP:
3032 rule_ret = HTTP_RULE_RES_DONE;
3033 goto end;
3034 case ACT_RET_YIELD:
3035 s->current_rule = rule;
3036 rule_ret = HTTP_RULE_RES_YIELD;
3037 goto end;
3038 }
3039 break;
3040
3041 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3042 /* Note: only the first valid tracking parameter of each
3043 * applies.
3044 */
3045
3046 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3047 struct stktable *t;
3048 struct stksess *ts;
3049 struct stktable_key *key;
3050 void *ptr1, *ptr2;
3051
3052 t = rule->arg.trk_ctr.table.t;
3053 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3054 rule->arg.trk_ctr.expr, NULL);
3055
3056 if (key && (ts = stktable_get_entry(t, key))) {
3057 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3058
3059 /* let's count a new HTTP request as it's the first time we do it */
3060 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3061 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3062 if (ptr1 || ptr2) {
3063 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3064
3065 if (ptr1)
3066 stktable_data_cast(ptr1, http_req_cnt)++;
3067
3068 if (ptr2)
3069 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3070 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3071
3072 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3073
3074 /* If data was modified, we need to touch to re-schedule sync */
3075 stktable_touch_local(t, ts, 0);
3076 }
3077
3078 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3079 if (sess->fe != s->be)
3080 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3081 }
3082 }
3083 break;
3084
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003085 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003086 default:
3087 break;
3088 }
3089 }
3090
3091 end:
3092 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003093 if (htx_reply_103_early_hints(&s->res) == -1)
3094 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003095 }
3096
3097 /* we reached the end of the rules, nothing to report */
3098 return rule_ret;
3099}
3100
3101/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3102 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3103 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3104 * is returned, the process can continue the evaluation of next rule list. If
3105 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3106 * is returned, it means the operation could not be processed and a server error
3107 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3108 * deny rule. If *YIELD is returned, the caller must call again the function
3109 * with the same context.
3110 */
3111static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3112 struct stream *s)
3113{
3114 struct session *sess = strm_sess(s);
3115 struct http_txn *txn = s->txn;
3116 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003117 struct act_rule *rule;
3118 struct http_hdr_ctx ctx;
3119 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3120 int act_flags = 0;
3121
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003122 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003123
3124 /* If "the current_rule_list" match the executed rule list, we are in
3125 * resume condition. If a resume is needed it is always in the action
3126 * and never in the ACL or converters. In this case, we initialise the
3127 * current rule, and go to the action execution point.
3128 */
3129 if (s->current_rule) {
3130 rule = s->current_rule;
3131 s->current_rule = NULL;
3132 if (s->current_rule_list == rules)
3133 goto resume_execution;
3134 }
3135 s->current_rule_list = rules;
3136
3137 list_for_each_entry(rule, rules, list) {
3138 /* check optional condition */
3139 if (rule->cond) {
3140 int ret;
3141
3142 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3143 ret = acl_pass(ret);
3144
3145 if (rule->cond->pol == ACL_COND_UNLESS)
3146 ret = !ret;
3147
3148 if (!ret) /* condition not matched */
3149 continue;
3150 }
3151
3152 act_flags |= ACT_FLAG_FIRST;
3153resume_execution:
3154 switch (rule->action) {
3155 case ACT_ACTION_ALLOW:
3156 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3157 goto end;
3158
3159 case ACT_ACTION_DENY:
3160 txn->flags |= TX_SVDENY;
3161 rule_ret = HTTP_RULE_RES_STOP;
3162 goto end;
3163
3164 case ACT_HTTP_SET_NICE:
3165 s->task->nice = rule->arg.nice;
3166 break;
3167
3168 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003169 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003170 break;
3171
3172 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003173 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003174 break;
3175
3176 case ACT_HTTP_SET_LOGL:
3177 s->logs.level = rule->arg.loglevel;
3178 break;
3179
3180 case ACT_HTTP_REPLACE_HDR:
3181 case ACT_HTTP_REPLACE_VAL:
3182 if (htx_transform_header(s, &s->res, htx,
3183 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3184 &rule->arg.hdr_add.fmt,
3185 &rule->arg.hdr_add.re, rule->action)) {
3186 rule_ret = HTTP_RULE_RES_BADREQ;
3187 goto end;
3188 }
3189 break;
3190
3191 case ACT_HTTP_DEL_HDR:
3192 /* remove all occurrences of the header */
3193 ctx.blk = NULL;
3194 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3195 http_remove_header(htx, &ctx);
3196 break;
3197
3198 case ACT_HTTP_SET_HDR:
3199 case ACT_HTTP_ADD_HDR: {
3200 struct buffer *replace;
3201 struct ist n, v;
3202
3203 replace = alloc_trash_chunk();
3204 if (!replace) {
3205 rule_ret = HTTP_RULE_RES_BADREQ;
3206 goto end;
3207 }
3208
3209 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3210 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3211 v = ist2(replace->area, replace->data);
3212
3213 if (rule->action == ACT_HTTP_SET_HDR) {
3214 /* remove all occurrences of the header */
3215 ctx.blk = NULL;
3216 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3217 http_remove_header(htx, &ctx);
3218 }
3219
3220 if (!http_add_header(htx, n, v)) {
3221 static unsigned char rate_limit = 0;
3222
3223 if ((rate_limit++ & 255) == 0) {
3224 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);
3225 }
3226
Olivier Houcharda798bf52019-03-08 18:52:00 +01003227 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003228 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003229 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003230 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003231 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003232 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003233 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003234 }
3235 free_trash_chunk(replace);
3236 break;
3237 }
3238
3239 case ACT_HTTP_DEL_ACL:
3240 case ACT_HTTP_DEL_MAP: {
3241 struct pat_ref *ref;
3242 struct buffer *key;
3243
3244 /* collect reference */
3245 ref = pat_ref_lookup(rule->arg.map.ref);
3246 if (!ref)
3247 continue;
3248
3249 /* allocate key */
3250 key = alloc_trash_chunk();
3251 if (!key) {
3252 rule_ret = HTTP_RULE_RES_BADREQ;
3253 goto end;
3254 }
3255
3256 /* collect key */
3257 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3258 key->area[key->data] = '\0';
3259
3260 /* perform update */
3261 /* returned code: 1=ok, 0=ko */
3262 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3263 pat_ref_delete(ref, key->area);
3264 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3265
3266 free_trash_chunk(key);
3267 break;
3268 }
3269
3270 case ACT_HTTP_ADD_ACL: {
3271 struct pat_ref *ref;
3272 struct buffer *key;
3273
3274 /* collect reference */
3275 ref = pat_ref_lookup(rule->arg.map.ref);
3276 if (!ref)
3277 continue;
3278
3279 /* allocate key */
3280 key = alloc_trash_chunk();
3281 if (!key) {
3282 rule_ret = HTTP_RULE_RES_BADREQ;
3283 goto end;
3284 }
3285
3286 /* collect key */
3287 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3288 key->area[key->data] = '\0';
3289
3290 /* perform update */
3291 /* check if the entry already exists */
3292 if (pat_ref_find_elt(ref, key->area) == NULL)
3293 pat_ref_add(ref, key->area, NULL, NULL);
3294
3295 free_trash_chunk(key);
3296 break;
3297 }
3298
3299 case ACT_HTTP_SET_MAP: {
3300 struct pat_ref *ref;
3301 struct buffer *key, *value;
3302
3303 /* collect reference */
3304 ref = pat_ref_lookup(rule->arg.map.ref);
3305 if (!ref)
3306 continue;
3307
3308 /* allocate key */
3309 key = alloc_trash_chunk();
3310 if (!key) {
3311 rule_ret = HTTP_RULE_RES_BADREQ;
3312 goto end;
3313 }
3314
3315 /* allocate value */
3316 value = alloc_trash_chunk();
3317 if (!value) {
3318 free_trash_chunk(key);
3319 rule_ret = HTTP_RULE_RES_BADREQ;
3320 goto end;
3321 }
3322
3323 /* collect key */
3324 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3325 key->area[key->data] = '\0';
3326
3327 /* collect value */
3328 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3329 value->area[value->data] = '\0';
3330
3331 /* perform update */
3332 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3333 if (pat_ref_find_elt(ref, key->area) != NULL)
3334 /* update entry if it exists */
3335 pat_ref_set(ref, key->area, value->area, NULL);
3336 else
3337 /* insert a new entry */
3338 pat_ref_add(ref, key->area, value->area, NULL);
3339 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3340 free_trash_chunk(key);
3341 free_trash_chunk(value);
3342 break;
3343 }
3344
3345 case ACT_HTTP_REDIR:
3346 rule_ret = HTTP_RULE_RES_DONE;
3347 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3348 rule_ret = HTTP_RULE_RES_BADREQ;
3349 goto end;
3350
3351 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3352 /* Note: only the first valid tracking parameter of each
3353 * applies.
3354 */
3355 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3356 struct stktable *t;
3357 struct stksess *ts;
3358 struct stktable_key *key;
3359 void *ptr;
3360
3361 t = rule->arg.trk_ctr.table.t;
3362 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3363 rule->arg.trk_ctr.expr, NULL);
3364
3365 if (key && (ts = stktable_get_entry(t, key))) {
3366 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3367
3368 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3369
3370 /* let's count a new HTTP request as it's the first time we do it */
3371 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3372 if (ptr)
3373 stktable_data_cast(ptr, http_req_cnt)++;
3374
3375 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3376 if (ptr)
3377 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3378 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3379
3380 /* When the client triggers a 4xx from the server, it's most often due
3381 * to a missing object or permission. These events should be tracked
3382 * because if they happen often, it may indicate a brute force or a
3383 * vulnerability scan. Normally this is done when receiving the response
3384 * but here we're tracking after this ought to have been done so we have
3385 * to do it on purpose.
3386 */
3387 if ((unsigned)(txn->status - 400) < 100) {
3388 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3389 if (ptr)
3390 stktable_data_cast(ptr, http_err_cnt)++;
3391
3392 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3393 if (ptr)
3394 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3395 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3396 }
3397
3398 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3399
3400 /* If data was modified, we need to touch to re-schedule sync */
3401 stktable_touch_local(t, ts, 0);
3402
3403 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3404 if (sess->fe != s->be)
3405 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3406 }
3407 }
3408 break;
3409
3410 case ACT_CUSTOM:
3411 if ((s->req.flags & CF_READ_ERROR) ||
3412 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3413 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3414 (px->options & PR_O_ABRT_CLOSE)))
3415 act_flags |= ACT_FLAG_FINAL;
3416
3417 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3418 case ACT_RET_ERR:
3419 case ACT_RET_CONT:
3420 break;
3421 case ACT_RET_STOP:
3422 rule_ret = HTTP_RULE_RES_STOP;
3423 goto end;
3424 case ACT_RET_YIELD:
3425 s->current_rule = rule;
3426 rule_ret = HTTP_RULE_RES_YIELD;
3427 goto end;
3428 }
3429 break;
3430
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003431 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003432 default:
3433 break;
3434 }
3435 }
3436
3437 end:
3438 /* we reached the end of the rules, nothing to report */
3439 return rule_ret;
3440}
3441
Christopher Faulet33640082018-10-24 11:53:01 +02003442/* Iterate the same filter through all request headers.
3443 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3444 * Since it can manage the switch to another backend, it updates the per-proxy
3445 * DENY stats.
3446 */
3447static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3448{
3449 struct http_txn *txn = s->txn;
3450 struct htx *htx;
3451 struct buffer *hdr = get_trash_chunk();
3452 int32_t pos;
3453
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003454 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003455
3456 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3457 struct htx_blk *blk = htx_get_blk(htx, pos);
3458 enum htx_blk_type type;
3459 struct ist n, v;
3460
3461 next_hdr:
3462 type = htx_get_blk_type(blk);
3463 if (type == HTX_BLK_EOH)
3464 break;
3465 if (type != HTX_BLK_HDR)
3466 continue;
3467
3468 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3469 return 1;
3470 else if (unlikely(txn->flags & TX_CLALLOW) &&
3471 (exp->action == ACT_ALLOW ||
3472 exp->action == ACT_DENY ||
3473 exp->action == ACT_TARPIT))
3474 return 0;
3475
3476 n = htx_get_blk_name(htx, blk);
3477 v = htx_get_blk_value(htx, blk);
3478
Christopher Faulet02e771a2019-02-26 15:36:05 +01003479 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003480 hdr->area[hdr->data++] = ':';
3481 hdr->area[hdr->data++] = ' ';
3482 chunk_memcat(hdr, v.ptr, v.len);
3483
3484 /* Now we have one header in <hdr> */
3485
3486 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3487 struct http_hdr_ctx ctx;
3488 int len;
3489
3490 switch (exp->action) {
3491 case ACT_ALLOW:
3492 txn->flags |= TX_CLALLOW;
3493 goto end;
3494
3495 case ACT_DENY:
3496 txn->flags |= TX_CLDENY;
3497 goto end;
3498
3499 case ACT_TARPIT:
3500 txn->flags |= TX_CLTARPIT;
3501 goto end;
3502
3503 case ACT_REPLACE:
3504 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3505 if (len < 0)
3506 return -1;
3507
3508 http_parse_header(ist2(trash.area, len), &n, &v);
3509 ctx.blk = blk;
3510 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003511 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003512 if (!http_replace_header(htx, &ctx, n, v))
3513 return -1;
3514 if (!ctx.blk)
3515 goto end;
3516 pos = htx_get_blk_pos(htx, blk);
3517 break;
3518
3519 case ACT_REMOVE:
3520 ctx.blk = blk;
3521 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003522 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003523 if (!http_remove_header(htx, &ctx))
3524 return -1;
3525 if (!ctx.blk)
3526 goto end;
3527 pos = htx_get_blk_pos(htx, blk);
3528 goto next_hdr;
3529
3530 }
3531 }
3532 }
3533 end:
3534 return 0;
3535}
3536
3537/* Apply the filter to the request line.
3538 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3539 * or -1 if a replacement resulted in an invalid request line.
3540 * Since it can manage the switch to another backend, it updates the per-proxy
3541 * DENY stats.
3542 */
3543static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3544{
3545 struct http_txn *txn = s->txn;
3546 struct htx *htx;
3547 struct buffer *reqline = get_trash_chunk();
3548 int done;
3549
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003550 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003551
3552 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3553 return 1;
3554 else if (unlikely(txn->flags & TX_CLALLOW) &&
3555 (exp->action == ACT_ALLOW ||
3556 exp->action == ACT_DENY ||
3557 exp->action == ACT_TARPIT))
3558 return 0;
3559 else if (exp->action == ACT_REMOVE)
3560 return 0;
3561
3562 done = 0;
3563
3564 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3565
3566 /* Now we have the request line between cur_ptr and cur_end */
3567 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003568 struct htx_sl *sl = http_find_stline(htx);
3569 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003570 int len;
3571
3572 switch (exp->action) {
3573 case ACT_ALLOW:
3574 txn->flags |= TX_CLALLOW;
3575 done = 1;
3576 break;
3577
3578 case ACT_DENY:
3579 txn->flags |= TX_CLDENY;
3580 done = 1;
3581 break;
3582
3583 case ACT_TARPIT:
3584 txn->flags |= TX_CLTARPIT;
3585 done = 1;
3586 break;
3587
3588 case ACT_REPLACE:
3589 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3590 if (len < 0)
3591 return -1;
3592
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003593 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3594 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3595 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003596 return -1;
3597 done = 1;
3598 break;
3599 }
3600 }
3601 return done;
3602}
3603
3604/*
3605 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3606 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3607 * unparsable request. Since it can manage the switch to another backend, it
3608 * updates the per-proxy DENY stats.
3609 */
3610static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3611{
3612 struct session *sess = s->sess;
3613 struct http_txn *txn = s->txn;
3614 struct hdr_exp *exp;
3615
3616 for (exp = px->req_exp; exp; exp = exp->next) {
3617 int ret;
3618
3619 /*
3620 * The interleaving of transformations and verdicts
3621 * makes it difficult to decide to continue or stop
3622 * the evaluation.
3623 */
3624
3625 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3626 break;
3627
3628 if ((txn->flags & TX_CLALLOW) &&
3629 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3630 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3631 continue;
3632
3633 /* if this filter had a condition, evaluate it now and skip to
3634 * next filter if the condition does not match.
3635 */
3636 if (exp->cond) {
3637 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3638 ret = acl_pass(ret);
3639 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3640 ret = !ret;
3641
3642 if (!ret)
3643 continue;
3644 }
3645
3646 /* Apply the filter to the request line. */
3647 ret = htx_apply_filter_to_req_line(s, req, exp);
3648 if (unlikely(ret < 0))
3649 return -1;
3650
3651 if (likely(ret == 0)) {
3652 /* The filter did not match the request, it can be
3653 * iterated through all headers.
3654 */
3655 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3656 return -1;
3657 }
3658 }
3659 return 0;
3660}
3661
3662/* Iterate the same filter through all response headers contained in <res>.
3663 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3664 */
3665static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3666{
3667 struct http_txn *txn = s->txn;
3668 struct htx *htx;
3669 struct buffer *hdr = get_trash_chunk();
3670 int32_t pos;
3671
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003672 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003673
3674 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3675 struct htx_blk *blk = htx_get_blk(htx, pos);
3676 enum htx_blk_type type;
3677 struct ist n, v;
3678
3679 next_hdr:
3680 type = htx_get_blk_type(blk);
3681 if (type == HTX_BLK_EOH)
3682 break;
3683 if (type != HTX_BLK_HDR)
3684 continue;
3685
3686 if (unlikely(txn->flags & TX_SVDENY))
3687 return 1;
3688 else if (unlikely(txn->flags & TX_SVALLOW) &&
3689 (exp->action == ACT_ALLOW ||
3690 exp->action == ACT_DENY))
3691 return 0;
3692
3693 n = htx_get_blk_name(htx, blk);
3694 v = htx_get_blk_value(htx, blk);
3695
Christopher Faulet02e771a2019-02-26 15:36:05 +01003696 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003697 hdr->area[hdr->data++] = ':';
3698 hdr->area[hdr->data++] = ' ';
3699 chunk_memcat(hdr, v.ptr, v.len);
3700
3701 /* Now we have one header in <hdr> */
3702
3703 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3704 struct http_hdr_ctx ctx;
3705 int len;
3706
3707 switch (exp->action) {
3708 case ACT_ALLOW:
3709 txn->flags |= TX_SVALLOW;
3710 goto end;
3711 break;
3712
3713 case ACT_DENY:
3714 txn->flags |= TX_SVDENY;
3715 goto end;
3716 break;
3717
3718 case ACT_REPLACE:
3719 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3720 if (len < 0)
3721 return -1;
3722
3723 http_parse_header(ist2(trash.area, len), &n, &v);
3724 ctx.blk = blk;
3725 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003726 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003727 if (!http_replace_header(htx, &ctx, n, v))
3728 return -1;
3729 if (!ctx.blk)
3730 goto end;
3731 pos = htx_get_blk_pos(htx, blk);
3732 break;
3733
3734 case ACT_REMOVE:
3735 ctx.blk = blk;
3736 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003737 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003738 if (!http_remove_header(htx, &ctx))
3739 return -1;
3740 if (!ctx.blk)
3741 goto end;
3742 pos = htx_get_blk_pos(htx, blk);
3743 goto next_hdr;
3744 }
3745 }
3746
3747 }
3748 end:
3749 return 0;
3750}
3751
3752/* Apply the filter to the status line in the response buffer <res>.
3753 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3754 * or -1 if a replacement resulted in an invalid status line.
3755 */
3756static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3757{
3758 struct http_txn *txn = s->txn;
3759 struct htx *htx;
3760 struct buffer *resline = get_trash_chunk();
3761 int done;
3762
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003763 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003764
3765 if (unlikely(txn->flags & TX_SVDENY))
3766 return 1;
3767 else if (unlikely(txn->flags & TX_SVALLOW) &&
3768 (exp->action == ACT_ALLOW ||
3769 exp->action == ACT_DENY))
3770 return 0;
3771 else if (exp->action == ACT_REMOVE)
3772 return 0;
3773
3774 done = 0;
3775 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3776
3777 /* Now we have the status line between cur_ptr and cur_end */
3778 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003779 struct htx_sl *sl = http_find_stline(htx);
3780 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003781 int len;
3782
3783 switch (exp->action) {
3784 case ACT_ALLOW:
3785 txn->flags |= TX_SVALLOW;
3786 done = 1;
3787 break;
3788
3789 case ACT_DENY:
3790 txn->flags |= TX_SVDENY;
3791 done = 1;
3792 break;
3793
3794 case ACT_REPLACE:
3795 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3796 if (len < 0)
3797 return -1;
3798
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003799 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3800 sl->info.res.status = strl2ui(code.ptr, code.len);
3801 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003802 return -1;
3803
3804 done = 1;
3805 return 1;
3806 }
3807 }
3808 return done;
3809}
3810
3811/*
3812 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3813 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3814 * unparsable response.
3815 */
3816static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3817{
3818 struct session *sess = s->sess;
3819 struct http_txn *txn = s->txn;
3820 struct hdr_exp *exp;
3821
3822 for (exp = px->rsp_exp; exp; exp = exp->next) {
3823 int ret;
3824
3825 /*
3826 * The interleaving of transformations and verdicts
3827 * makes it difficult to decide to continue or stop
3828 * the evaluation.
3829 */
3830
3831 if (txn->flags & TX_SVDENY)
3832 break;
3833
3834 if ((txn->flags & TX_SVALLOW) &&
3835 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3836 exp->action == ACT_PASS)) {
3837 exp = exp->next;
3838 continue;
3839 }
3840
3841 /* if this filter had a condition, evaluate it now and skip to
3842 * next filter if the condition does not match.
3843 */
3844 if (exp->cond) {
3845 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3846 ret = acl_pass(ret);
3847 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3848 ret = !ret;
3849 if (!ret)
3850 continue;
3851 }
3852
3853 /* Apply the filter to the status line. */
3854 ret = htx_apply_filter_to_sts_line(s, res, exp);
3855 if (unlikely(ret < 0))
3856 return -1;
3857
3858 if (likely(ret == 0)) {
3859 /* The filter did not match the response, it can be
3860 * iterated through all headers.
3861 */
3862 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3863 return -1;
3864 }
3865 }
3866 return 0;
3867}
3868
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003869/*
3870 * Manage client-side cookie. It can impact performance by about 2% so it is
3871 * desirable to call it only when needed. This code is quite complex because
3872 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3873 * highly recommended not to touch this part without a good reason !
3874 */
3875static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3876{
3877 struct session *sess = s->sess;
3878 struct http_txn *txn = s->txn;
3879 struct htx *htx;
3880 struct http_hdr_ctx ctx;
3881 char *hdr_beg, *hdr_end, *del_from;
3882 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3883 int preserve_hdr;
3884
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003885 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003886 ctx.blk = NULL;
3887 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3888 del_from = NULL; /* nothing to be deleted */
3889 preserve_hdr = 0; /* assume we may kill the whole header */
3890
3891 /* Now look for cookies. Conforming to RFC2109, we have to support
3892 * attributes whose name begin with a '$', and associate them with
3893 * the right cookie, if we want to delete this cookie.
3894 * So there are 3 cases for each cookie read :
3895 * 1) it's a special attribute, beginning with a '$' : ignore it.
3896 * 2) it's a server id cookie that we *MAY* want to delete : save
3897 * some pointers on it (last semi-colon, beginning of cookie...)
3898 * 3) it's an application cookie : we *MAY* have to delete a previous
3899 * "special" cookie.
3900 * At the end of loop, if a "special" cookie remains, we may have to
3901 * remove it. If no application cookie persists in the header, we
3902 * *MUST* delete it.
3903 *
3904 * Note: RFC2965 is unclear about the processing of spaces around
3905 * the equal sign in the ATTR=VALUE form. A careful inspection of
3906 * the RFC explicitly allows spaces before it, and not within the
3907 * tokens (attrs or values). An inspection of RFC2109 allows that
3908 * too but section 10.1.3 lets one think that spaces may be allowed
3909 * after the equal sign too, resulting in some (rare) buggy
3910 * implementations trying to do that. So let's do what servers do.
3911 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3912 * allowed quoted strings in values, with any possible character
3913 * after a backslash, including control chars and delimitors, which
3914 * causes parsing to become ambiguous. Browsers also allow spaces
3915 * within values even without quotes.
3916 *
3917 * We have to keep multiple pointers in order to support cookie
3918 * removal at the beginning, middle or end of header without
3919 * corrupting the header. All of these headers are valid :
3920 *
3921 * hdr_beg hdr_end
3922 * | |
3923 * v |
3924 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3925 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3926 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3927 * | | | | | | |
3928 * | | | | | | |
3929 * | | | | | | +--> next
3930 * | | | | | +----> val_end
3931 * | | | | +-----------> val_beg
3932 * | | | +--------------> equal
3933 * | | +----------------> att_end
3934 * | +---------------------> att_beg
3935 * +--------------------------> prev
3936 *
3937 */
3938 hdr_beg = ctx.value.ptr;
3939 hdr_end = hdr_beg + ctx.value.len;
3940 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3941 /* Iterate through all cookies on this line */
3942
3943 /* find att_beg */
3944 att_beg = prev;
3945 if (prev > hdr_beg)
3946 att_beg++;
3947
3948 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3949 att_beg++;
3950
3951 /* find att_end : this is the first character after the last non
3952 * space before the equal. It may be equal to hdr_end.
3953 */
3954 equal = att_end = att_beg;
3955 while (equal < hdr_end) {
3956 if (*equal == '=' || *equal == ',' || *equal == ';')
3957 break;
3958 if (HTTP_IS_SPHT(*equal++))
3959 continue;
3960 att_end = equal;
3961 }
3962
3963 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3964 * is between <att_beg> and <equal>, both may be identical.
3965 */
3966 /* look for end of cookie if there is an equal sign */
3967 if (equal < hdr_end && *equal == '=') {
3968 /* look for the beginning of the value */
3969 val_beg = equal + 1;
3970 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3971 val_beg++;
3972
3973 /* find the end of the value, respecting quotes */
3974 next = http_find_cookie_value_end(val_beg, hdr_end);
3975
3976 /* make val_end point to the first white space or delimitor after the value */
3977 val_end = next;
3978 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3979 val_end--;
3980 }
3981 else
3982 val_beg = val_end = next = equal;
3983
3984 /* We have nothing to do with attributes beginning with
3985 * '$'. However, they will automatically be removed if a
3986 * header before them is removed, since they're supposed
3987 * to be linked together.
3988 */
3989 if (*att_beg == '$')
3990 continue;
3991
3992 /* Ignore cookies with no equal sign */
3993 if (equal == next) {
3994 /* This is not our cookie, so we must preserve it. But if we already
3995 * scheduled another cookie for removal, we cannot remove the
3996 * complete header, but we can remove the previous block itself.
3997 */
3998 preserve_hdr = 1;
3999 if (del_from != NULL) {
4000 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4001 val_end += delta;
4002 next += delta;
4003 hdr_end += delta;
4004 prev = del_from;
4005 del_from = NULL;
4006 }
4007 continue;
4008 }
4009
4010 /* if there are spaces around the equal sign, we need to
4011 * strip them otherwise we'll get trouble for cookie captures,
4012 * or even for rewrites. Since this happens extremely rarely,
4013 * it does not hurt performance.
4014 */
4015 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4016 int stripped_before = 0;
4017 int stripped_after = 0;
4018
4019 if (att_end != equal) {
4020 memmove(att_end, equal, hdr_end - equal);
4021 stripped_before = (att_end - equal);
4022 equal += stripped_before;
4023 val_beg += stripped_before;
4024 }
4025
4026 if (val_beg > equal + 1) {
4027 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4028 stripped_after = (equal + 1) - val_beg;
4029 val_beg += stripped_after;
4030 stripped_before += stripped_after;
4031 }
4032
4033 val_end += stripped_before;
4034 next += stripped_before;
4035 hdr_end += stripped_before;
4036 }
4037 /* now everything is as on the diagram above */
4038
4039 /* First, let's see if we want to capture this cookie. We check
4040 * that we don't already have a client side cookie, because we
4041 * can only capture one. Also as an optimisation, we ignore
4042 * cookies shorter than the declared name.
4043 */
4044 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4045 (val_end - att_beg >= sess->fe->capture_namelen) &&
4046 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4047 int log_len = val_end - att_beg;
4048
4049 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4050 ha_alert("HTTP logging : out of memory.\n");
4051 } else {
4052 if (log_len > sess->fe->capture_len)
4053 log_len = sess->fe->capture_len;
4054 memcpy(txn->cli_cookie, att_beg, log_len);
4055 txn->cli_cookie[log_len] = 0;
4056 }
4057 }
4058
4059 /* Persistence cookies in passive, rewrite or insert mode have the
4060 * following form :
4061 *
4062 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4063 *
4064 * For cookies in prefix mode, the form is :
4065 *
4066 * Cookie: NAME=SRV~VALUE
4067 */
4068 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4069 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4070 struct server *srv = s->be->srv;
4071 char *delim;
4072
4073 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4074 * have the server ID between val_beg and delim, and the original cookie between
4075 * delim+1 and val_end. Otherwise, delim==val_end :
4076 *
4077 * hdr_beg
4078 * |
4079 * v
4080 * NAME=SRV; # in all but prefix modes
4081 * NAME=SRV~OPAQUE ; # in prefix mode
4082 * || || | |+-> next
4083 * || || | +--> val_end
4084 * || || +---------> delim
4085 * || |+------------> val_beg
4086 * || +-------------> att_end = equal
4087 * |+-----------------> att_beg
4088 * +------------------> prev
4089 *
4090 */
4091 if (s->be->ck_opts & PR_CK_PFX) {
4092 for (delim = val_beg; delim < val_end; delim++)
4093 if (*delim == COOKIE_DELIM)
4094 break;
4095 }
4096 else {
4097 char *vbar1;
4098 delim = val_end;
4099 /* Now check if the cookie contains a date field, which would
4100 * appear after a vertical bar ('|') just after the server name
4101 * and before the delimiter.
4102 */
4103 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4104 if (vbar1) {
4105 /* OK, so left of the bar is the server's cookie and
4106 * right is the last seen date. It is a base64 encoded
4107 * 30-bit value representing the UNIX date since the
4108 * epoch in 4-second quantities.
4109 */
4110 int val;
4111 delim = vbar1++;
4112 if (val_end - vbar1 >= 5) {
4113 val = b64tos30(vbar1);
4114 if (val > 0)
4115 txn->cookie_last_date = val << 2;
4116 }
4117 /* look for a second vertical bar */
4118 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4119 if (vbar1 && (val_end - vbar1 > 5)) {
4120 val = b64tos30(vbar1 + 1);
4121 if (val > 0)
4122 txn->cookie_first_date = val << 2;
4123 }
4124 }
4125 }
4126
4127 /* if the cookie has an expiration date and the proxy wants to check
4128 * it, then we do that now. We first check if the cookie is too old,
4129 * then only if it has expired. We detect strict overflow because the
4130 * time resolution here is not great (4 seconds). Cookies with dates
4131 * in the future are ignored if their offset is beyond one day. This
4132 * allows an admin to fix timezone issues without expiring everyone
4133 * and at the same time avoids keeping unwanted side effects for too
4134 * long.
4135 */
4136 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4137 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4138 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4139 txn->flags &= ~TX_CK_MASK;
4140 txn->flags |= TX_CK_OLD;
4141 delim = val_beg; // let's pretend we have not found the cookie
4142 txn->cookie_first_date = 0;
4143 txn->cookie_last_date = 0;
4144 }
4145 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4146 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4147 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4148 txn->flags &= ~TX_CK_MASK;
4149 txn->flags |= TX_CK_EXPIRED;
4150 delim = val_beg; // let's pretend we have not found the cookie
4151 txn->cookie_first_date = 0;
4152 txn->cookie_last_date = 0;
4153 }
4154
4155 /* Here, we'll look for the first running server which supports the cookie.
4156 * This allows to share a same cookie between several servers, for example
4157 * to dedicate backup servers to specific servers only.
4158 * However, to prevent clients from sticking to cookie-less backup server
4159 * when they have incidentely learned an empty cookie, we simply ignore
4160 * empty cookies and mark them as invalid.
4161 * The same behaviour is applied when persistence must be ignored.
4162 */
4163 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4164 srv = NULL;
4165
4166 while (srv) {
4167 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4168 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4169 if ((srv->cur_state != SRV_ST_STOPPED) ||
4170 (s->be->options & PR_O_PERSIST) ||
4171 (s->flags & SF_FORCE_PRST)) {
4172 /* we found the server and we can use it */
4173 txn->flags &= ~TX_CK_MASK;
4174 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4175 s->flags |= SF_DIRECT | SF_ASSIGNED;
4176 s->target = &srv->obj_type;
4177 break;
4178 } else {
4179 /* we found a server, but it's down,
4180 * mark it as such and go on in case
4181 * another one is available.
4182 */
4183 txn->flags &= ~TX_CK_MASK;
4184 txn->flags |= TX_CK_DOWN;
4185 }
4186 }
4187 srv = srv->next;
4188 }
4189
4190 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4191 /* no server matched this cookie or we deliberately skipped it */
4192 txn->flags &= ~TX_CK_MASK;
4193 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4194 txn->flags |= TX_CK_UNUSED;
4195 else
4196 txn->flags |= TX_CK_INVALID;
4197 }
4198
4199 /* depending on the cookie mode, we may have to either :
4200 * - delete the complete cookie if we're in insert+indirect mode, so that
4201 * the server never sees it ;
4202 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004203 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004204 * if we're in cookie prefix mode
4205 */
4206 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4207 int delta; /* negative */
4208
4209 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4210 delta = val_beg - (delim + 1);
4211 val_end += delta;
4212 next += delta;
4213 hdr_end += delta;
4214 del_from = NULL;
4215 preserve_hdr = 1; /* we want to keep this cookie */
4216 }
4217 else if (del_from == NULL &&
4218 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4219 del_from = prev;
4220 }
4221 }
4222 else {
4223 /* This is not our cookie, so we must preserve it. But if we already
4224 * scheduled another cookie for removal, we cannot remove the
4225 * complete header, but we can remove the previous block itself.
4226 */
4227 preserve_hdr = 1;
4228
4229 if (del_from != NULL) {
4230 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4231 if (att_beg >= del_from)
4232 att_beg += delta;
4233 if (att_end >= del_from)
4234 att_end += delta;
4235 val_beg += delta;
4236 val_end += delta;
4237 next += delta;
4238 hdr_end += delta;
4239 prev = del_from;
4240 del_from = NULL;
4241 }
4242 }
4243
4244 /* continue with next cookie on this header line */
4245 att_beg = next;
4246 } /* for each cookie */
4247
4248
4249 /* There are no more cookies on this line.
4250 * We may still have one (or several) marked for deletion at the
4251 * end of the line. We must do this now in two ways :
4252 * - if some cookies must be preserved, we only delete from the
4253 * mark to the end of line ;
4254 * - if nothing needs to be preserved, simply delete the whole header
4255 */
4256 if (del_from) {
4257 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4258 }
4259 if ((hdr_end - hdr_beg) != ctx.value.len) {
4260 if (hdr_beg != hdr_end) {
4261 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004262 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004263 }
4264 else
4265 http_remove_header(htx, &ctx);
4266 }
4267 } /* for each "Cookie header */
4268}
4269
4270/*
4271 * Manage server-side cookies. It can impact performance by about 2% so it is
4272 * desirable to call it only when needed. This function is also used when we
4273 * just need to know if there is a cookie (eg: for check-cache).
4274 */
4275static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4276{
4277 struct session *sess = s->sess;
4278 struct http_txn *txn = s->txn;
4279 struct htx *htx;
4280 struct http_hdr_ctx ctx;
4281 struct server *srv;
4282 char *hdr_beg, *hdr_end;
4283 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4284 int is_cookie2;
4285
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004286 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004287
4288 ctx.blk = NULL;
4289 while (1) {
4290 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4291 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4292 break;
4293 is_cookie2 = 1;
4294 }
4295
4296 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4297 * <prev> points to the colon.
4298 */
4299 txn->flags |= TX_SCK_PRESENT;
4300
4301 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4302 * check-cache is enabled) and we are not interested in checking
4303 * them. Warning, the cookie capture is declared in the frontend.
4304 */
4305 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4306 break;
4307
4308 /* OK so now we know we have to process this response cookie.
4309 * The format of the Set-Cookie header is slightly different
4310 * from the format of the Cookie header in that it does not
4311 * support the comma as a cookie delimiter (thus the header
4312 * cannot be folded) because the Expires attribute described in
4313 * the original Netscape's spec may contain an unquoted date
4314 * with a comma inside. We have to live with this because
4315 * many browsers don't support Max-Age and some browsers don't
4316 * support quoted strings. However the Set-Cookie2 header is
4317 * clean.
4318 *
4319 * We have to keep multiple pointers in order to support cookie
4320 * removal at the beginning, middle or end of header without
4321 * corrupting the header (in case of set-cookie2). A special
4322 * pointer, <scav> points to the beginning of the set-cookie-av
4323 * fields after the first semi-colon. The <next> pointer points
4324 * either to the end of line (set-cookie) or next unquoted comma
4325 * (set-cookie2). All of these headers are valid :
4326 *
4327 * hdr_beg hdr_end
4328 * | |
4329 * v |
4330 * NAME1 = VALUE 1 ; Secure; Path="/" |
4331 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4332 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4333 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4334 * | | | | | | | |
4335 * | | | | | | | +-> next
4336 * | | | | | | +------------> scav
4337 * | | | | | +--------------> val_end
4338 * | | | | +--------------------> val_beg
4339 * | | | +----------------------> equal
4340 * | | +------------------------> att_end
4341 * | +----------------------------> att_beg
4342 * +------------------------------> prev
4343 * -------------------------------> hdr_beg
4344 */
4345 hdr_beg = ctx.value.ptr;
4346 hdr_end = hdr_beg + ctx.value.len;
4347 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4348
4349 /* Iterate through all cookies on this line */
4350
4351 /* find att_beg */
4352 att_beg = prev;
4353 if (prev > hdr_beg)
4354 att_beg++;
4355
4356 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4357 att_beg++;
4358
4359 /* find att_end : this is the first character after the last non
4360 * space before the equal. It may be equal to hdr_end.
4361 */
4362 equal = att_end = att_beg;
4363
4364 while (equal < hdr_end) {
4365 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4366 break;
4367 if (HTTP_IS_SPHT(*equal++))
4368 continue;
4369 att_end = equal;
4370 }
4371
4372 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4373 * is between <att_beg> and <equal>, both may be identical.
4374 */
4375
4376 /* look for end of cookie if there is an equal sign */
4377 if (equal < hdr_end && *equal == '=') {
4378 /* look for the beginning of the value */
4379 val_beg = equal + 1;
4380 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4381 val_beg++;
4382
4383 /* find the end of the value, respecting quotes */
4384 next = http_find_cookie_value_end(val_beg, hdr_end);
4385
4386 /* make val_end point to the first white space or delimitor after the value */
4387 val_end = next;
4388 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4389 val_end--;
4390 }
4391 else {
4392 /* <equal> points to next comma, semi-colon or EOL */
4393 val_beg = val_end = next = equal;
4394 }
4395
4396 if (next < hdr_end) {
4397 /* Set-Cookie2 supports multiple cookies, and <next> points to
4398 * a colon or semi-colon before the end. So skip all attr-value
4399 * pairs and look for the next comma. For Set-Cookie, since
4400 * commas are permitted in values, skip to the end.
4401 */
4402 if (is_cookie2)
4403 next = http_find_hdr_value_end(next, hdr_end);
4404 else
4405 next = hdr_end;
4406 }
4407
4408 /* Now everything is as on the diagram above */
4409
4410 /* Ignore cookies with no equal sign */
4411 if (equal == val_end)
4412 continue;
4413
4414 /* If there are spaces around the equal sign, we need to
4415 * strip them otherwise we'll get trouble for cookie captures,
4416 * or even for rewrites. Since this happens extremely rarely,
4417 * it does not hurt performance.
4418 */
4419 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4420 int stripped_before = 0;
4421 int stripped_after = 0;
4422
4423 if (att_end != equal) {
4424 memmove(att_end, equal, hdr_end - equal);
4425 stripped_before = (att_end - equal);
4426 equal += stripped_before;
4427 val_beg += stripped_before;
4428 }
4429
4430 if (val_beg > equal + 1) {
4431 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4432 stripped_after = (equal + 1) - val_beg;
4433 val_beg += stripped_after;
4434 stripped_before += stripped_after;
4435 }
4436
4437 val_end += stripped_before;
4438 next += stripped_before;
4439 hdr_end += stripped_before;
4440
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004441 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4442 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004443 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004444 }
4445
4446 /* First, let's see if we want to capture this cookie. We check
4447 * that we don't already have a server side cookie, because we
4448 * can only capture one. Also as an optimisation, we ignore
4449 * cookies shorter than the declared name.
4450 */
4451 if (sess->fe->capture_name != NULL &&
4452 txn->srv_cookie == NULL &&
4453 (val_end - att_beg >= sess->fe->capture_namelen) &&
4454 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4455 int log_len = val_end - att_beg;
4456 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4457 ha_alert("HTTP logging : out of memory.\n");
4458 }
4459 else {
4460 if (log_len > sess->fe->capture_len)
4461 log_len = sess->fe->capture_len;
4462 memcpy(txn->srv_cookie, att_beg, log_len);
4463 txn->srv_cookie[log_len] = 0;
4464 }
4465 }
4466
4467 srv = objt_server(s->target);
4468 /* now check if we need to process it for persistence */
4469 if (!(s->flags & SF_IGNORE_PRST) &&
4470 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4471 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4472 /* assume passive cookie by default */
4473 txn->flags &= ~TX_SCK_MASK;
4474 txn->flags |= TX_SCK_FOUND;
4475
4476 /* If the cookie is in insert mode on a known server, we'll delete
4477 * this occurrence because we'll insert another one later.
4478 * We'll delete it too if the "indirect" option is set and we're in
4479 * a direct access.
4480 */
4481 if (s->be->ck_opts & PR_CK_PSV) {
4482 /* The "preserve" flag was set, we don't want to touch the
4483 * server's cookie.
4484 */
4485 }
4486 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4487 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4488 /* this cookie must be deleted */
4489 if (prev == hdr_beg && next == hdr_end) {
4490 /* whole header */
4491 http_remove_header(htx, &ctx);
4492 /* note: while both invalid now, <next> and <hdr_end>
4493 * are still equal, so the for() will stop as expected.
4494 */
4495 } else {
4496 /* just remove the value */
4497 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4498 next = prev;
4499 hdr_end += delta;
4500 }
4501 txn->flags &= ~TX_SCK_MASK;
4502 txn->flags |= TX_SCK_DELETED;
4503 /* and go on with next cookie */
4504 }
4505 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4506 /* replace bytes val_beg->val_end with the cookie name associated
4507 * with this server since we know it.
4508 */
4509 int sliding, delta;
4510
4511 ctx.value = ist2(val_beg, val_end - val_beg);
4512 ctx.lws_before = ctx.lws_after = 0;
4513 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4514 delta = srv->cklen - (val_end - val_beg);
4515 sliding = (ctx.value.ptr - val_beg);
4516 hdr_beg += sliding;
4517 val_beg += sliding;
4518 next += sliding + delta;
4519 hdr_end += sliding + delta;
4520
4521 txn->flags &= ~TX_SCK_MASK;
4522 txn->flags |= TX_SCK_REPLACED;
4523 }
4524 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4525 /* insert the cookie name associated with this server
4526 * before existing cookie, and insert a delimiter between them..
4527 */
4528 int sliding, delta;
4529 ctx.value = ist2(val_beg, 0);
4530 ctx.lws_before = ctx.lws_after = 0;
4531 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4532 delta = srv->cklen + 1;
4533 sliding = (ctx.value.ptr - val_beg);
4534 hdr_beg += sliding;
4535 val_beg += sliding;
4536 next += sliding + delta;
4537 hdr_end += sliding + delta;
4538
4539 val_beg[srv->cklen] = COOKIE_DELIM;
4540 txn->flags &= ~TX_SCK_MASK;
4541 txn->flags |= TX_SCK_REPLACED;
4542 }
4543 }
4544 /* that's done for this cookie, check the next one on the same
4545 * line when next != hdr_end (only if is_cookie2).
4546 */
4547 }
4548 }
4549}
4550
Christopher Faulet25a02f62018-10-24 12:00:25 +02004551/*
4552 * Parses the Cache-Control and Pragma request header fields to determine if
4553 * the request may be served from the cache and/or if it is cacheable. Updates
4554 * s->txn->flags.
4555 */
4556void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4557{
4558 struct http_txn *txn = s->txn;
4559 struct htx *htx;
4560 int32_t pos;
4561 int pragma_found, cc_found, i;
4562
4563 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4564 return; /* nothing more to do here */
4565
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004566 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004567 pragma_found = cc_found = 0;
4568 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4569 struct htx_blk *blk = htx_get_blk(htx, pos);
4570 enum htx_blk_type type = htx_get_blk_type(blk);
4571 struct ist n, v;
4572
4573 if (type == HTX_BLK_EOH)
4574 break;
4575 if (type != HTX_BLK_HDR)
4576 continue;
4577
4578 n = htx_get_blk_name(htx, blk);
4579 v = htx_get_blk_value(htx, blk);
4580
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004581 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004582 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4583 pragma_found = 1;
4584 continue;
4585 }
4586 }
4587
4588 /* Don't use the cache and don't try to store if we found the
4589 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004590 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004591 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4592 txn->flags |= TX_CACHE_IGNORE;
4593 continue;
4594 }
4595
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004596 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004597 continue;
4598
4599 /* OK, right now we know we have a cache-control header */
4600 cc_found = 1;
4601 if (!v.len) /* no info */
4602 continue;
4603
4604 i = 0;
4605 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4606 !isspace((unsigned char)*(v.ptr+i)))
4607 i++;
4608
4609 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4610 * values after max-age, max-stale nor min-fresh, we simply don't
4611 * use the cache when they're specified.
4612 */
4613 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4614 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4615 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4616 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4617 txn->flags |= TX_CACHE_IGNORE;
4618 continue;
4619 }
4620
4621 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4622 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4623 continue;
4624 }
4625 }
4626
4627 /* RFC7234#5.4:
4628 * When the Cache-Control header field is also present and
4629 * understood in a request, Pragma is ignored.
4630 * When the Cache-Control header field is not present in a
4631 * request, caches MUST consider the no-cache request
4632 * pragma-directive as having the same effect as if
4633 * "Cache-Control: no-cache" were present.
4634 */
4635 if (!cc_found && pragma_found)
4636 txn->flags |= TX_CACHE_IGNORE;
4637}
4638
4639/*
4640 * Check if response is cacheable or not. Updates s->txn->flags.
4641 */
4642void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4643{
4644 struct http_txn *txn = s->txn;
4645 struct htx *htx;
4646 int32_t pos;
4647 int i;
4648
4649 if (txn->status < 200) {
4650 /* do not try to cache interim responses! */
4651 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4652 return;
4653 }
4654
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004655 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004656 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4657 struct htx_blk *blk = htx_get_blk(htx, pos);
4658 enum htx_blk_type type = htx_get_blk_type(blk);
4659 struct ist n, v;
4660
4661 if (type == HTX_BLK_EOH)
4662 break;
4663 if (type != HTX_BLK_HDR)
4664 continue;
4665
4666 n = htx_get_blk_name(htx, blk);
4667 v = htx_get_blk_value(htx, blk);
4668
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004669 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004670 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4671 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4672 return;
4673 }
4674 }
4675
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004676 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004677 continue;
4678
4679 /* OK, right now we know we have a cache-control header */
4680 if (!v.len) /* no info */
4681 continue;
4682
4683 i = 0;
4684 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4685 !isspace((unsigned char)*(v.ptr+i)))
4686 i++;
4687
4688 /* we have a complete value between v.ptr and (v.ptr+i) */
4689 if (i < v.len && *(v.ptr + i) == '=') {
4690 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4691 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4692 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4693 continue;
4694 }
4695
4696 /* we have something of the form no-cache="set-cookie" */
4697 if ((v.len >= 21) &&
4698 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4699 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4700 txn->flags &= ~TX_CACHE_COOK;
4701 continue;
4702 }
4703
4704 /* OK, so we know that either p2 points to the end of string or to a comma */
4705 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4706 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4707 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4708 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4709 return;
4710 }
4711
4712 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4713 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4714 continue;
4715 }
4716 }
4717}
4718
Christopher Faulet64159df2018-10-24 21:15:35 +02004719/* send a server's name with an outgoing request over an established connection.
4720 * Note: this function is designed to be called once the request has been
4721 * scheduled for being forwarded. This is the reason why the number of forwarded
4722 * bytes have to be adjusted.
4723 */
4724int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4725{
4726 struct htx *htx;
4727 struct http_hdr_ctx ctx;
4728 struct ist hdr;
4729 uint32_t data;
4730
4731 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004732 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004733 data = htx->data;
4734
4735 ctx.blk = NULL;
4736 while (http_find_header(htx, hdr, &ctx, 1))
4737 http_remove_header(htx, &ctx);
4738 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4739
4740 if (co_data(&s->req)) {
4741 if (data >= htx->data)
4742 c_rew(&s->req, data - htx->data);
4743 else
4744 c_adv(&s->req, htx->data - data);
4745 }
4746 return 0;
4747}
4748
Christopher Faulet377c5a52018-10-24 21:21:30 +02004749/*
4750 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4751 * for the current backend.
4752 *
4753 * It is assumed that the request is either a HEAD, GET, or POST and that the
4754 * uri_auth field is valid.
4755 *
4756 * Returns 1 if stats should be provided, otherwise 0.
4757 */
4758static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4759{
4760 struct uri_auth *uri_auth = backend->uri_auth;
4761 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004762 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004763 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004764
4765 if (!uri_auth)
4766 return 0;
4767
4768 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4769 return 0;
4770
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004771 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004772 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004773 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004774
4775 /* check URI size */
4776 if (uri_auth->uri_len > uri.len)
4777 return 0;
4778
4779 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4780 return 0;
4781
4782 return 1;
4783}
4784
4785/* This function prepares an applet to handle the stats. It can deal with the
4786 * "100-continue" expectation, check that admin rules are met for POST requests,
4787 * and program a response message if something was unexpected. It cannot fail
4788 * and always relies on the stats applet to complete the job. It does not touch
4789 * analysers nor counters, which are left to the caller. It does not touch
4790 * s->target which is supposed to already point to the stats applet. The caller
4791 * is expected to have already assigned an appctx to the stream.
4792 */
4793static int htx_handle_stats(struct stream *s, struct channel *req)
4794{
4795 struct stats_admin_rule *stats_admin_rule;
4796 struct stream_interface *si = &s->si[1];
4797 struct session *sess = s->sess;
4798 struct http_txn *txn = s->txn;
4799 struct http_msg *msg = &txn->req;
4800 struct uri_auth *uri_auth = s->be->uri_auth;
4801 const char *h, *lookup, *end;
4802 struct appctx *appctx;
4803 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004804 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004805
4806 appctx = si_appctx(si);
4807 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4808 appctx->st1 = appctx->st2 = 0;
4809 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4810 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4811 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4812 appctx->ctx.stats.flags |= STAT_CHUNKED;
4813
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004814 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004815 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004816 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4817 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004818
4819 for (h = lookup; h <= end - 3; h++) {
4820 if (memcmp(h, ";up", 3) == 0) {
4821 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4822 break;
4823 }
4824 }
4825
4826 if (uri_auth->refresh) {
4827 for (h = lookup; h <= end - 10; h++) {
4828 if (memcmp(h, ";norefresh", 10) == 0) {
4829 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4830 break;
4831 }
4832 }
4833 }
4834
4835 for (h = lookup; h <= end - 4; h++) {
4836 if (memcmp(h, ";csv", 4) == 0) {
4837 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4838 break;
4839 }
4840 }
4841
4842 for (h = lookup; h <= end - 6; h++) {
4843 if (memcmp(h, ";typed", 6) == 0) {
4844 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4845 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4846 break;
4847 }
4848 }
4849
4850 for (h = lookup; h <= end - 8; h++) {
4851 if (memcmp(h, ";st=", 4) == 0) {
4852 int i;
4853 h += 4;
4854 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4855 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4856 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4857 appctx->ctx.stats.st_code = i;
4858 break;
4859 }
4860 }
4861 break;
4862 }
4863 }
4864
4865 appctx->ctx.stats.scope_str = 0;
4866 appctx->ctx.stats.scope_len = 0;
4867 for (h = lookup; h <= end - 8; h++) {
4868 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4869 int itx = 0;
4870 const char *h2;
4871 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4872 const char *err;
4873
4874 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4875 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004876 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4877 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004878 if (*h == ';' || *h == '&' || *h == ' ')
4879 break;
4880 itx++;
4881 h++;
4882 }
4883
4884 if (itx > STAT_SCOPE_TXT_MAXLEN)
4885 itx = STAT_SCOPE_TXT_MAXLEN;
4886 appctx->ctx.stats.scope_len = itx;
4887
4888 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4889 memcpy(scope_txt, h2, itx);
4890 scope_txt[itx] = '\0';
4891 err = invalid_char(scope_txt);
4892 if (err) {
4893 /* bad char in search text => clear scope */
4894 appctx->ctx.stats.scope_str = 0;
4895 appctx->ctx.stats.scope_len = 0;
4896 }
4897 break;
4898 }
4899 }
4900
4901 /* now check whether we have some admin rules for this request */
4902 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4903 int ret = 1;
4904
4905 if (stats_admin_rule->cond) {
4906 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4907 ret = acl_pass(ret);
4908 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4909 ret = !ret;
4910 }
4911
4912 if (ret) {
4913 /* no rule, or the rule matches */
4914 appctx->ctx.stats.flags |= STAT_ADMIN;
4915 break;
4916 }
4917 }
4918
Christopher Faulet5d45e382019-02-27 15:15:23 +01004919 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4920 appctx->st0 = STAT_HTTP_HEAD;
4921 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004922 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004923 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004924 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004925 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004926 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4927 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4928 appctx->st0 = STAT_HTTP_LAST;
4929 }
4930 }
4931 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004932 /* Unsupported method */
4933 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4934 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4935 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004936 }
4937
4938 s->task->nice = -32; /* small boost for HTTP statistics */
4939 return 1;
4940}
4941
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004942void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4943{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004944 struct channel *req = &s->req;
4945 struct channel *res = &s->res;
4946 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004947 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004948 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004949 struct ist path, location;
4950 unsigned int flags;
4951 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004952
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004953 /*
4954 * Create the location
4955 */
4956 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004957
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004958 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004959 /* special prefix "/" means don't change URL */
4960 srv = __objt_server(s->target);
4961 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4962 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4963 return;
4964 }
4965
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004966 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004967 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004968 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004969 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004970 if (!path.ptr)
4971 return;
4972
4973 if (!chunk_memcat(&trash, path.ptr, path.len))
4974 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004975 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004976
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004977 /*
4978 * Create the 302 respone
4979 */
4980 htx = htx_from_buf(&res->buf);
4981 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4982 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4983 ist("HTTP/1.1"), ist("302"), ist("Found"));
4984 if (!sl)
4985 goto fail;
4986 sl->info.res.status = 302;
4987 s->txn->status = 302;
4988
4989 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4990 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4991 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4992 !htx_add_header(htx, ist("Location"), location))
4993 goto fail;
4994
4995 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4996 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004997
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004998 /*
4999 * Send the message
5000 */
5001 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005002 c_adv(res, data);
5003 res->total += data;
5004
5005 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005006 si_shutr(si);
5007 si_shutw(si);
5008 si->err_type = SI_ET_NONE;
5009 si->state = SI_ST_CLO;
5010
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005011 channel_auto_read(req);
5012 channel_abort(req);
5013 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005014 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005015 channel_auto_read(res);
5016 channel_auto_close(res);
5017
5018 if (!(s->flags & SF_ERR_MASK))
5019 s->flags |= SF_ERR_LOCAL;
5020 if (!(s->flags & SF_FINST_MASK))
5021 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022
5023 /* FIXME: we should increase a counter of redirects per server and per backend. */
5024 srv_inc_sess_ctr(srv);
5025 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005026 return;
5027
5028 fail:
5029 /* If an error occurred, remove the incomplete HTTP response from the
5030 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005031 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005032}
5033
Christopher Fauletf2824e62018-10-01 12:12:37 +02005034/* This function terminates the request because it was completly analyzed or
5035 * because an error was triggered during the body forwarding.
5036 */
5037static void htx_end_request(struct stream *s)
5038{
5039 struct channel *chn = &s->req;
5040 struct http_txn *txn = s->txn;
5041
5042 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5043 now_ms, __FUNCTION__, s,
5044 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5045 s->req.analysers, s->res.analysers);
5046
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005047 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5048 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005049 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005050 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005051 goto end;
5052 }
5053
5054 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5055 return;
5056
5057 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005058 /* No need to read anymore, the request was completely parsed.
5059 * We can shut the read side unless we want to abort_on_close,
5060 * or we have a POST request. The issue with POST requests is
5061 * that some browsers still send a CRLF after the request, and
5062 * this CRLF must be read so that it does not remain in the kernel
5063 * buffers, otherwise a close could cause an RST on some systems
5064 * (eg: Linux).
5065 */
5066 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5067 txn->meth != HTTP_METH_POST)
5068 channel_dont_read(chn);
5069
5070 /* if the server closes the connection, we want to immediately react
5071 * and close the socket to save packets and syscalls.
5072 */
5073 s->si[1].flags |= SI_FL_NOHALF;
5074
5075 /* In any case we've finished parsing the request so we must
5076 * disable Nagle when sending data because 1) we're not going
5077 * to shut this side, and 2) the server is waiting for us to
5078 * send pending data.
5079 */
5080 chn->flags |= CF_NEVER_WAIT;
5081
Christopher Fauletd01ce402019-01-02 17:44:13 +01005082 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5083 /* The server has not finished to respond, so we
5084 * don't want to move in order not to upset it.
5085 */
5086 return;
5087 }
5088
Christopher Fauletf2824e62018-10-01 12:12:37 +02005089 /* When we get here, it means that both the request and the
5090 * response have finished receiving. Depending on the connection
5091 * mode, we'll have to wait for the last bytes to leave in either
5092 * direction, and sometimes for a close to be effective.
5093 */
5094 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5095 /* Tunnel mode will not have any analyser so it needs to
5096 * poll for reads.
5097 */
5098 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005099 if (b_data(&chn->buf))
5100 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005101 txn->req.msg_state = HTTP_MSG_TUNNEL;
5102 }
5103 else {
5104 /* we're not expecting any new data to come for this
5105 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005106 *
5107 * However, there is an exception if the response
5108 * length is undefined. In this case, we need to wait
5109 * the close from the server. The response will be
5110 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005111 */
5112 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5113 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005114 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115
5116 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5117 channel_shutr_now(chn);
5118 channel_shutw_now(chn);
5119 }
5120 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 goto check_channel_flags;
5122 }
5123
5124 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5125 http_msg_closing:
5126 /* nothing else to forward, just waiting for the output buffer
5127 * to be empty and for the shutw_now to take effect.
5128 */
5129 if (channel_is_empty(chn)) {
5130 txn->req.msg_state = HTTP_MSG_CLOSED;
5131 goto http_msg_closed;
5132 }
5133 else if (chn->flags & CF_SHUTW) {
5134 txn->req.err_state = txn->req.msg_state;
5135 txn->req.msg_state = HTTP_MSG_ERROR;
5136 goto end;
5137 }
5138 return;
5139 }
5140
5141 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5142 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005143 /* if we don't know whether the server will close, we need to hard close */
5144 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5145 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005146 /* see above in MSG_DONE why we only do this in these states */
5147 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5148 channel_dont_read(chn);
5149 goto end;
5150 }
5151
5152 check_channel_flags:
5153 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5154 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5155 /* if we've just closed an output, let's switch */
5156 txn->req.msg_state = HTTP_MSG_CLOSING;
5157 goto http_msg_closing;
5158 }
5159
5160 end:
5161 chn->analysers &= AN_REQ_FLT_END;
5162 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5163 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5164 channel_auto_close(chn);
5165 channel_auto_read(chn);
5166}
5167
5168
5169/* This function terminates the response because it was completly analyzed or
5170 * because an error was triggered during the body forwarding.
5171 */
5172static void htx_end_response(struct stream *s)
5173{
5174 struct channel *chn = &s->res;
5175 struct http_txn *txn = s->txn;
5176
5177 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5178 now_ms, __FUNCTION__, s,
5179 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5180 s->req.analysers, s->res.analysers);
5181
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005182 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5183 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005184 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005185 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005186 goto end;
5187 }
5188
5189 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5190 return;
5191
5192 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5193 /* In theory, we don't need to read anymore, but we must
5194 * still monitor the server connection for a possible close
5195 * while the request is being uploaded, so we don't disable
5196 * reading.
5197 */
5198 /* channel_dont_read(chn); */
5199
5200 if (txn->req.msg_state < HTTP_MSG_DONE) {
5201 /* The client seems to still be sending data, probably
5202 * because we got an error response during an upload.
5203 * We have the choice of either breaking the connection
5204 * or letting it pass through. Let's do the later.
5205 */
5206 return;
5207 }
5208
5209 /* When we get here, it means that both the request and the
5210 * response have finished receiving. Depending on the connection
5211 * mode, we'll have to wait for the last bytes to leave in either
5212 * direction, and sometimes for a close to be effective.
5213 */
5214 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5215 channel_auto_read(chn);
5216 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005217 if (b_data(&chn->buf))
5218 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005219 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5220 }
5221 else {
5222 /* we're not expecting any new data to come for this
5223 * transaction, so we can close it.
5224 */
5225 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5226 channel_shutr_now(chn);
5227 channel_shutw_now(chn);
5228 }
5229 }
5230 goto check_channel_flags;
5231 }
5232
5233 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5234 http_msg_closing:
5235 /* nothing else to forward, just waiting for the output buffer
5236 * to be empty and for the shutw_now to take effect.
5237 */
5238 if (channel_is_empty(chn)) {
5239 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5240 goto http_msg_closed;
5241 }
5242 else if (chn->flags & CF_SHUTW) {
5243 txn->rsp.err_state = txn->rsp.msg_state;
5244 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005245 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005246 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005247 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005248 goto end;
5249 }
5250 return;
5251 }
5252
5253 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5254 http_msg_closed:
5255 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005256 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005257 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005258 goto end;
5259 }
5260
5261 check_channel_flags:
5262 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5263 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5264 /* if we've just closed an output, let's switch */
5265 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5266 goto http_msg_closing;
5267 }
5268
5269 end:
5270 chn->analysers &= AN_RES_FLT_END;
5271 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5272 chn->analysers |= AN_RES_FLT_XFER_DATA;
5273 channel_auto_close(chn);
5274 channel_auto_read(chn);
5275}
5276
Christopher Faulet0f226952018-10-22 09:29:56 +02005277void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5278 int finst, const struct buffer *msg)
5279{
5280 channel_auto_read(si_oc(si));
5281 channel_abort(si_oc(si));
5282 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005283 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005284 channel_auto_close(si_ic(si));
5285 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005286
5287 /* <msg> is an HTX structure. So we copy it in the response's
5288 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005289 if (msg) {
5290 struct channel *chn = si_ic(si);
5291 struct htx *htx;
5292
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005293 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005294 chn->buf.data = msg->data;
5295 memcpy(chn->buf.area, msg->area, msg->data);
5296 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005297 c_adv(chn, htx->data);
5298 chn->total += htx->data;
5299 }
5300 if (!(s->flags & SF_ERR_MASK))
5301 s->flags |= err;
5302 if (!(s->flags & SF_FINST_MASK))
5303 s->flags |= finst;
5304}
5305
5306void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5307{
5308 channel_auto_read(&s->req);
5309 channel_abort(&s->req);
5310 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005311 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5312 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005313
5314 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005315
5316 /* <msg> is an HTX structure. So we copy it in the response's
5317 * channel */
5318 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005319 if (msg) {
5320 struct channel *chn = &s->res;
5321 struct htx *htx;
5322
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005323 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005324 chn->buf.data = msg->data;
5325 memcpy(chn->buf.area, msg->area, msg->data);
5326 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005327 c_adv(chn, htx->data);
5328 chn->total += htx->data;
5329 }
5330
5331 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5332 channel_auto_read(&s->res);
5333 channel_auto_close(&s->res);
5334 channel_shutr_now(&s->res);
5335}
5336
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005337struct buffer *htx_error_message(struct stream *s)
5338{
5339 const int msgnum = http_get_status_idx(s->txn->status);
5340
5341 if (s->be->errmsg[msgnum].area)
5342 return &s->be->errmsg[msgnum];
5343 else if (strm_fe(s)->errmsg[msgnum].area)
5344 return &strm_fe(s)->errmsg[msgnum];
5345 else
5346 return &htx_err_chunks[msgnum];
5347}
5348
5349
Christopher Faulet4a28a532019-03-01 11:19:40 +01005350/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5351 * on success and -1 on error.
5352 */
5353static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5354{
5355 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5356 * then we must send an HTTP/1.1 100 Continue intermediate response.
5357 */
5358 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5359 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5360 struct ist hdr = { .ptr = "Expect", .len = 6 };
5361 struct http_hdr_ctx ctx;
5362
5363 ctx.blk = NULL;
5364 /* Expect is allowed in 1.1, look for it */
5365 if (http_find_header(htx, hdr, &ctx, 0) &&
5366 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5367 if (htx_reply_100_continue(s) == -1)
5368 return -1;
5369 http_remove_header(htx, &ctx);
5370 }
5371 }
5372 return 0;
5373}
5374
Christopher Faulet23a3c792018-11-28 10:01:23 +01005375/* Send a 100-Continue response to the client. It returns 0 on success and -1
5376 * on error. The response channel is updated accordingly.
5377 */
5378static int htx_reply_100_continue(struct stream *s)
5379{
5380 struct channel *res = &s->res;
5381 struct htx *htx = htx_from_buf(&res->buf);
5382 struct htx_sl *sl;
5383 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5384 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5385 size_t data;
5386
5387 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5388 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5389 if (!sl)
5390 goto fail;
5391 sl->info.res.status = 100;
5392
5393 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5394 goto fail;
5395
5396 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005397 c_adv(res, data);
5398 res->total += data;
5399 return 0;
5400
5401 fail:
5402 /* If an error occurred, remove the incomplete HTTP response from the
5403 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005404 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005405 return -1;
5406}
5407
Christopher Faulet12c51e22018-11-28 15:59:42 +01005408
5409/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5410 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5411 * error. The response channel is updated accordingly.
5412 */
5413static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5414{
5415 struct channel *res = &s->res;
5416 struct htx *htx = htx_from_buf(&res->buf);
5417 struct htx_sl *sl;
5418 struct ist code, body;
5419 int status;
5420 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5421 size_t data;
5422
5423 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5424 status = 401;
5425 code = ist("401");
5426 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5427 "You need a valid user and password to access this content.\n"
5428 "</body></html>\n");
5429 }
5430 else {
5431 status = 407;
5432 code = ist("407");
5433 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5434 "You need a valid user and password to access this content.\n"
5435 "</body></html>\n");
5436 }
5437
5438 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5439 ist("HTTP/1.1"), code, ist("Unauthorized"));
5440 if (!sl)
5441 goto fail;
5442 sl->info.res.status = status;
5443 s->txn->status = status;
5444
5445 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5446 goto fail;
5447
5448 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5449 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005450 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5451 goto fail;
5452 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5453 goto fail;
5454 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005455 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5457 goto fail;
5458
5459 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005460 c_adv(res, data);
5461 res->total += data;
5462
5463 channel_auto_read(&s->req);
5464 channel_abort(&s->req);
5465 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005466 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005467
5468 res->wex = tick_add_ifset(now_ms, res->wto);
5469 channel_auto_read(res);
5470 channel_auto_close(res);
5471 channel_shutr_now(res);
5472 return 0;
5473
5474 fail:
5475 /* If an error occurred, remove the incomplete HTTP response from the
5476 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005477 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005478 return -1;
5479}
5480
Christopher Faulet0f226952018-10-22 09:29:56 +02005481/*
5482 * Capture headers from message <htx> according to header list <cap_hdr>, and
5483 * fill the <cap> pointers appropriately.
5484 */
5485static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5486{
5487 struct cap_hdr *h;
5488 int32_t pos;
5489
5490 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5491 struct htx_blk *blk = htx_get_blk(htx, pos);
5492 enum htx_blk_type type = htx_get_blk_type(blk);
5493 struct ist n, v;
5494
5495 if (type == HTX_BLK_EOH)
5496 break;
5497 if (type != HTX_BLK_HDR)
5498 continue;
5499
5500 n = htx_get_blk_name(htx, blk);
5501
5502 for (h = cap_hdr; h; h = h->next) {
5503 if (h->namelen && (h->namelen == n.len) &&
5504 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5505 if (cap[h->index] == NULL)
5506 cap[h->index] =
5507 pool_alloc(h->pool);
5508
5509 if (cap[h->index] == NULL) {
5510 ha_alert("HTTP capture : out of memory.\n");
5511 break;
5512 }
5513
5514 v = htx_get_blk_value(htx, blk);
5515 if (v.len > h->len)
5516 v.len = h->len;
5517
5518 memcpy(cap[h->index], v.ptr, v.len);
5519 cap[h->index][v.len]=0;
5520 }
5521 }
5522 }
5523}
5524
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005525/* Delete a value in a header between delimiters <from> and <next>. The header
5526 * itself is delimited by <start> and <end> pointers. The number of characters
5527 * displaced is returned, and the pointer to the first delimiter is updated if
5528 * required. The function tries as much as possible to respect the following
5529 * principles :
5530 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5531 * in which case <next> is simply removed
5532 * - set exactly one space character after the new first delimiter, unless there
5533 * are not enough characters in the block being moved to do so.
5534 * - remove unneeded spaces before the previous delimiter and after the new
5535 * one.
5536 *
5537 * It is the caller's responsibility to ensure that :
5538 * - <from> points to a valid delimiter or <start> ;
5539 * - <next> points to a valid delimiter or <end> ;
5540 * - there are non-space chars before <from>.
5541 */
5542static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5543{
5544 char *prev = *from;
5545
5546 if (prev == start) {
5547 /* We're removing the first value. eat the semicolon, if <next>
5548 * is lower than <end> */
5549 if (next < end)
5550 next++;
5551
5552 while (next < end && HTTP_IS_SPHT(*next))
5553 next++;
5554 }
5555 else {
5556 /* Remove useless spaces before the old delimiter. */
5557 while (HTTP_IS_SPHT(*(prev-1)))
5558 prev--;
5559 *from = prev;
5560
5561 /* copy the delimiter and if possible a space if we're
5562 * not at the end of the line.
5563 */
5564 if (next < end) {
5565 *prev++ = *next++;
5566 if (prev + 1 < next)
5567 *prev++ = ' ';
5568 while (next < end && HTTP_IS_SPHT(*next))
5569 next++;
5570 }
5571 }
5572 memmove(prev, next, end - next);
5573 return (prev - next);
5574}
5575
Christopher Faulet0f226952018-10-22 09:29:56 +02005576
5577/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005578 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005579 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005580static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005581{
5582 struct ist dst = ist2(str, 0);
5583
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005584 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005585 goto end;
5586 if (dst.len + 1 > len)
5587 goto end;
5588 dst.ptr[dst.len++] = ' ';
5589
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005590 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005591 goto end;
5592 if (dst.len + 1 > len)
5593 goto end;
5594 dst.ptr[dst.len++] = ' ';
5595
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005596 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005597 end:
5598 return dst.len;
5599}
5600
Christopher Fauletf0523542018-10-24 11:06:58 +02005601/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005602 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005603 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005604static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005605{
5606 struct ist dst = ist2(str, 0);
5607
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005608 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005609 goto end;
5610 if (dst.len + 1 > len)
5611 goto end;
5612 dst.ptr[dst.len++] = ' ';
5613
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005614 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005615 goto end;
5616 if (dst.len + 1 > len)
5617 goto end;
5618 dst.ptr[dst.len++] = ' ';
5619
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005620 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005621 end:
5622 return dst.len;
5623}
5624
5625
Christopher Faulet0f226952018-10-22 09:29:56 +02005626/*
5627 * Print a debug line with a start line.
5628 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005629static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005630{
5631 struct session *sess = strm_sess(s);
5632 int max;
5633
5634 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5635 dir,
5636 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5637 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5638
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005639 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005640 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005641 chunk_memcat(&trash, HTX_SL_P1_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_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005645 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005646 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005647 trash.area[trash.data++] = ' ';
5648
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005649 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005650 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005651 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005652 trash.area[trash.data++] = '\n';
5653
5654 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5655}
5656
5657/*
5658 * Print a debug line with a header.
5659 */
5660static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5661{
5662 struct session *sess = strm_sess(s);
5663 int max;
5664
5665 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5666 dir,
5667 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5668 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5669
5670 max = n.len;
5671 UBOUND(max, trash.size - trash.data - 3);
5672 chunk_memcat(&trash, n.ptr, max);
5673 trash.area[trash.data++] = ':';
5674 trash.area[trash.data++] = ' ';
5675
5676 max = v.len;
5677 UBOUND(max, trash.size - trash.data - 1);
5678 chunk_memcat(&trash, v.ptr, max);
5679 trash.area[trash.data++] = '\n';
5680
5681 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5682}
5683
5684
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005685__attribute__((constructor))
5686static void __htx_protocol_init(void)
5687{
5688}
5689
5690
5691/*
5692 * Local variables:
5693 * c-indent-level: 8
5694 * c-basic-offset: 8
5695 * End:
5696 */