blob: 3837666b0f4004ae5632278b18b8002a4fcfb3bd [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100412 /* by default, close the stream at the end of the transaction. */
413 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
415 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200416 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417 req->analysers |= AN_REQ_HTTP_BODY;
418
419 /*
420 * RFC7234#4:
421 * A cache MUST write through requests with methods
422 * that are unsafe (Section 4.2.1 of [RFC7231]) to
423 * the origin server; i.e., a cache is not allowed
424 * to generate a reply to such a request before
425 * having forwarded the request and having received
426 * a corresponding response.
427 *
428 * RFC7231#4.2.1:
429 * Of the request methods defined by this
430 * specification, the GET, HEAD, OPTIONS, and TRACE
431 * methods are defined to be safe.
432 */
433 if (likely(txn->meth == HTTP_METH_GET ||
434 txn->meth == HTTP_METH_HEAD ||
435 txn->meth == HTTP_METH_OPTIONS ||
436 txn->meth == HTTP_METH_TRACE))
437 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
438
439 /* end of job, return OK */
440 req->analysers &= ~an_bit;
441 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200442
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 return 1;
444
445 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200446 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200447 txn->req.err_state = txn->req.msg_state;
448 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100449 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100450 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200451 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100452 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453
454 return_prx_cond:
455 if (!(s->flags & SF_ERR_MASK))
456 s->flags |= SF_ERR_PRXCOND;
457 if (!(s->flags & SF_FINST_MASK))
458 s->flags |= SF_FINST_R;
459
460 req->analysers &= AN_REQ_FLT_END;
461 req->analyse_exp = TICK_ETERNITY;
462 return 0;
463}
464
465
466/* This stream analyser runs all HTTP request processing which is common to
467 * frontends and backends, which means blocking ACLs, filters, connection-close,
468 * reqadd, stats and redirects. This is performed for the designated proxy.
469 * It returns 1 if the processing can continue on next analysers, or zero if it
470 * either needs more data or wants to immediately abort the request (eg: deny,
471 * error, ...).
472 */
473int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
474{
475 struct session *sess = s->sess;
476 struct http_txn *txn = s->txn;
477 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200478 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200479 struct redirect_rule *rule;
480 struct cond_wordlist *wl;
481 enum rule_result verdict;
482 int deny_status = HTTP_ERR_403;
483 struct connection *conn = objt_conn(sess->origin);
484
485 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
486 /* we need more data */
487 goto return_prx_yield;
488 }
489
490 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
491 now_ms, __FUNCTION__,
492 s,
493 req,
494 req->rex, req->wex,
495 req->flags,
496 ci_data(req),
497 req->analysers);
498
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100499 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501 /* just in case we have some per-backend tracking */
502 stream_inc_be_http_req_ctr(s);
503
504 /* evaluate http-request rules */
505 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200506 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200507
508 switch (verdict) {
509 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
510 goto return_prx_yield;
511
512 case HTTP_RULE_RES_CONT:
513 case HTTP_RULE_RES_STOP: /* nothing to do */
514 break;
515
516 case HTTP_RULE_RES_DENY: /* deny or tarpit */
517 if (txn->flags & TX_CLTARPIT)
518 goto tarpit;
519 goto deny;
520
521 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
522 goto return_prx_cond;
523
524 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
525 goto done;
526
527 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
528 goto return_bad_req;
529 }
530 }
531
532 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
533 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200534 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535
Christopher Fauletff2759f2018-10-24 11:13:16 +0200536 ctx.blk = NULL;
537 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
538 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200539 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200541 }
542
543 /* OK at this stage, we know that the request was accepted according to
544 * the http-request rules, we can check for the stats. Note that the
545 * URI is detected *before* the req* rules in order not to be affected
546 * by a possible reqrep, while they are processed *after* so that a
547 * reqdeny can still block them. This clearly needs to change in 1.6!
548 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200549 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100551 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200552 txn->status = 500;
553 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100554 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555
556 if (!(s->flags & SF_ERR_MASK))
557 s->flags |= SF_ERR_RESOURCE;
558 goto return_prx_cond;
559 }
560
561 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200562 htx_handle_stats(s, req);
563 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200564 /* not all actions implemented: deny, allow, auth */
565
566 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
567 goto deny;
568
569 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
570 goto return_prx_cond;
571 }
572
573 /* evaluate the req* rules except reqadd */
574 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200575 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200576 goto return_bad_req;
577
578 if (txn->flags & TX_CLDENY)
579 goto deny;
580
581 if (txn->flags & TX_CLTARPIT) {
582 deny_status = HTTP_ERR_500;
583 goto tarpit;
584 }
585 }
586
587 /* add request headers from the rule sets in the same order */
588 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200589 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200590 if (wl->cond) {
591 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
592 ret = acl_pass(ret);
593 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
594 ret = !ret;
595 if (!ret)
596 continue;
597 }
598
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
600 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601 goto return_bad_req;
602 }
603
Christopher Faulet2571bc62019-03-01 11:44:26 +0100604 /* Proceed with the applets now. */
605 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100607 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200608
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100609 if (htx_handle_expect_hdr(s, htx, msg) == -1)
610 goto return_bad_req;
611
Christopher Faulete0768eb2018-10-03 16:38:02 +0200612 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
613 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
614 if (!(s->flags & SF_FINST_MASK))
615 s->flags |= SF_FINST_R;
616
617 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
618 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
619 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
620 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100621
622 req->flags |= CF_SEND_DONTWAIT;
623 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200624 goto done;
625 }
626
627 /* check whether we have some ACLs set to redirect this request */
628 list_for_each_entry(rule, &px->redirect_rules, list) {
629 if (rule->cond) {
630 int ret;
631
632 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
633 ret = acl_pass(ret);
634 if (rule->cond->pol == ACL_COND_UNLESS)
635 ret = !ret;
636 if (!ret)
637 continue;
638 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200639 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200640 goto return_bad_req;
641 goto done;
642 }
643
644 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
645 * If this happens, then the data will not come immediately, so we must
646 * send all what we have without waiting. Note that due to the small gain
647 * in waiting for the body of the request, it's easier to simply put the
648 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
649 * itself once used.
650 */
651 req->flags |= CF_SEND_DONTWAIT;
652
653 done: /* done with this analyser, continue with next ones that the calling
654 * points will have set, if any.
655 */
656 req->analyse_exp = TICK_ETERNITY;
657 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
658 req->analysers &= ~an_bit;
659 return 1;
660
661 tarpit:
662 /* Allow cookie logging
663 */
664 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200665 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200666
667 /* When a connection is tarpitted, we use the tarpit timeout,
668 * which may be the same as the connect timeout if unspecified.
669 * If unset, then set it to zero because we really want it to
670 * eventually expire. We build the tarpit as an analyser.
671 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100672 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200673
674 /* wipe the request out so that we can drop the connection early
675 * if the client closes first.
676 */
677 channel_dont_connect(req);
678
679 txn->status = http_err_codes[deny_status];
680
681 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
682 req->analysers |= AN_REQ_HTTP_TARPIT;
683 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
684 if (!req->analyse_exp)
685 req->analyse_exp = tick_add(now_ms, 0);
686 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100687 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200688 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100689 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200690 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100691 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200692 goto done_without_exp;
693
694 deny: /* this request was blocked (denied) */
695
696 /* Allow cookie logging
697 */
698 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200699 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700
701 txn->flags |= TX_CLDENY;
702 txn->status = http_err_codes[deny_status];
703 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100704 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100706 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100708 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200709 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100710 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711 goto return_prx_cond;
712
713 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 txn->req.err_state = txn->req.msg_state;
715 txn->req.msg_state = HTTP_MSG_ERROR;
716 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100717 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200718
Olivier Houcharda798bf52019-03-08 18:52:00 +0100719 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100721 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200722
723 return_prx_cond:
724 if (!(s->flags & SF_ERR_MASK))
725 s->flags |= SF_ERR_PRXCOND;
726 if (!(s->flags & SF_FINST_MASK))
727 s->flags |= SF_FINST_R;
728
729 req->analysers &= AN_REQ_FLT_END;
730 req->analyse_exp = TICK_ETERNITY;
731 return 0;
732
733 return_prx_yield:
734 channel_dont_connect(req);
735 return 0;
736}
737
738/* This function performs all the processing enabled for the current request.
739 * It returns 1 if the processing can continue on next analysers, or zero if it
740 * needs more data, encounters an error, or wants to immediately abort the
741 * request. It relies on buffers flags, and updates s->req.analysers.
742 */
743int htx_process_request(struct stream *s, struct channel *req, int an_bit)
744{
745 struct session *sess = s->sess;
746 struct http_txn *txn = s->txn;
747 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200748 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200749 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
750
751 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
752 /* we need more data */
753 channel_dont_connect(req);
754 return 0;
755 }
756
757 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
758 now_ms, __FUNCTION__,
759 s,
760 req,
761 req->rex, req->wex,
762 req->flags,
763 ci_data(req),
764 req->analysers);
765
766 /*
767 * Right now, we know that we have processed the entire headers
768 * and that unwanted requests have been filtered out. We can do
769 * whatever we want with the remaining request. Also, now we
770 * may have separate values for ->fe, ->be.
771 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100772 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200773
774 /*
775 * If HTTP PROXY is set we simply get remote server address parsing
776 * incoming request. Note that this requires that a connection is
777 * allocated on the server side.
778 */
779 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
780 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100781 struct htx_sl *sl;
782 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200783
784 /* Note that for now we don't reuse existing proxy connections */
785 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
786 txn->req.err_state = txn->req.msg_state;
787 txn->req.msg_state = HTTP_MSG_ERROR;
788 txn->status = 500;
789 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100790 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200791
792 if (!(s->flags & SF_ERR_MASK))
793 s->flags |= SF_ERR_RESOURCE;
794 if (!(s->flags & SF_FINST_MASK))
795 s->flags |= SF_FINST_R;
796
797 return 0;
798 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100800 uri = htx_sl_req_uri(sl);
801 path = http_get_path(uri);
802 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200803 goto return_bad_req;
804
805 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200806 * uri.ptr and path.ptr (excluded). If it was not found, we need
807 * to replace from all the uri by a single "/".
808 *
809 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100810 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200811 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200812 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100813 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200814 }
815
816 /*
817 * 7: Now we can work with the cookies.
818 * Note that doing so might move headers in the request, but
819 * the fields will stay coherent and the URI will not move.
820 * This should only be performed in the backend.
821 */
822 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100823 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200824
825 /* add unique-id if "header-unique-id" is specified */
826
827 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
828 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
829 goto return_bad_req;
830 s->unique_id[0] = '\0';
831 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
832 }
833
834 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200835 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
836 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
837
838 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200839 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200840 }
841
842 /*
843 * 9: add X-Forwarded-For if either the frontend or the backend
844 * asks for it.
845 */
846 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 struct http_hdr_ctx ctx = { .blk = NULL };
848 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
849 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
850
Christopher Faulete0768eb2018-10-03 16:38:02 +0200851 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200852 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200853 /* The header is set to be added only if none is present
854 * and we found it, so don't do anything.
855 */
856 }
857 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
858 /* Add an X-Forwarded-For header unless the source IP is
859 * in the 'except' network range.
860 */
861 if ((!sess->fe->except_mask.s_addr ||
862 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
863 != sess->fe->except_net.s_addr) &&
864 (!s->be->except_mask.s_addr ||
865 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
866 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200867 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200868
869 /* Note: we rely on the backend to get the header name to be used for
870 * x-forwarded-for, because the header is really meant for the backends.
871 * However, if the backend did not specify any option, we have to rely
872 * on the frontend's header name.
873 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200874 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
875 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200876 goto return_bad_req;
877 }
878 }
879 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
880 /* FIXME: for the sake of completeness, we should also support
881 * 'except' here, although it is mostly useless in this case.
882 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200883 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200884
Christopher Faulete0768eb2018-10-03 16:38:02 +0200885 inet_ntop(AF_INET6,
886 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
887 pn, sizeof(pn));
888
889 /* Note: we rely on the backend to get the header name to be used for
890 * x-forwarded-for, because the header is really meant for the backends.
891 * However, if the backend did not specify any option, we have to rely
892 * on the frontend's header name.
893 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200894 chunk_printf(&trash, "%s", pn);
895 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200896 goto return_bad_req;
897 }
898 }
899
900 /*
901 * 10: add X-Original-To if either the frontend or the backend
902 * asks for it.
903 */
904 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
905
906 /* FIXME: don't know if IPv6 can handle that case too. */
907 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
908 /* Add an X-Original-To header unless the destination IP is
909 * in the 'except' network range.
910 */
911 conn_get_to_addr(cli_conn);
912
913 if (cli_conn->addr.to.ss_family == AF_INET &&
914 ((!sess->fe->except_mask_to.s_addr ||
915 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
916 != sess->fe->except_to.s_addr) &&
917 (!s->be->except_mask_to.s_addr ||
918 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
919 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200920 struct ist hdr;
921 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200922
923 /* Note: we rely on the backend to get the header name to be used for
924 * x-original-to, because the header is really meant for the backends.
925 * However, if the backend did not specify any option, we have to rely
926 * on the frontend's header name.
927 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 if (s->be->orgto_hdr_len)
929 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
930 else
931 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200933 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
934 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 goto return_bad_req;
936 }
937 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938 }
939
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 /* If we have no server assigned yet and we're balancing on url_param
941 * with a POST request, we may be interested in checking the body for
942 * that parameter. This will be done in another analyser.
943 */
944 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100945 s->txn->meth == HTTP_METH_POST &&
946 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200947 channel_dont_connect(req);
948 req->analysers |= AN_REQ_HTTP_BODY;
949 }
950
951 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
952 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100953
Christopher Faulete0768eb2018-10-03 16:38:02 +0200954 /* We expect some data from the client. Unless we know for sure
955 * we already have a full request, we have to re-enable quick-ack
956 * in case we previously disabled it, otherwise we might cause
957 * the client to delay further data.
958 */
959 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200960 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100961 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200962
963 /*************************************************************
964 * OK, that's finished for the headers. We have done what we *
965 * could. Let's switch to the DATA state. *
966 ************************************************************/
967 req->analyse_exp = TICK_ETERNITY;
968 req->analysers &= ~an_bit;
969
970 s->logs.tv_request = now;
971 /* OK let's go on with the BODY now */
972 return 1;
973
974 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975 txn->req.err_state = txn->req.msg_state;
976 txn->req.msg_state = HTTP_MSG_ERROR;
977 txn->status = 400;
978 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100979 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200980
Olivier Houcharda798bf52019-03-08 18:52:00 +0100981 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200982 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100983 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200984
985 if (!(s->flags & SF_ERR_MASK))
986 s->flags |= SF_ERR_PRXCOND;
987 if (!(s->flags & SF_FINST_MASK))
988 s->flags |= SF_FINST_R;
989 return 0;
990}
991
992/* This function is an analyser which processes the HTTP tarpit. It always
993 * returns zero, at the beginning because it prevents any other processing
994 * from occurring, and at the end because it terminates the request.
995 */
996int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
997{
998 struct http_txn *txn = s->txn;
999
1000 /* This connection is being tarpitted. The CLIENT side has
1001 * already set the connect expiration date to the right
1002 * timeout. We just have to check that the client is still
1003 * there and that the timeout has not expired.
1004 */
1005 channel_dont_connect(req);
1006 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1007 !tick_is_expired(req->analyse_exp, now_ms))
1008 return 0;
1009
1010 /* We will set the queue timer to the time spent, just for
1011 * logging purposes. We fake a 500 server error, so that the
1012 * attacker will not suspect his connection has been tarpitted.
1013 * It will not cause trouble to the logs because we can exclude
1014 * the tarpitted connections by filtering on the 'PT' status flags.
1015 */
1016 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1017
1018 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001019 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001020
1021 req->analysers &= AN_REQ_FLT_END;
1022 req->analyse_exp = TICK_ETERNITY;
1023
1024 if (!(s->flags & SF_ERR_MASK))
1025 s->flags |= SF_ERR_PRXCOND;
1026 if (!(s->flags & SF_FINST_MASK))
1027 s->flags |= SF_FINST_T;
1028 return 0;
1029}
1030
1031/* This function is an analyser which waits for the HTTP request body. It waits
1032 * for either the buffer to be full, or the full advertised contents to have
1033 * reached the buffer. It must only be called after the standard HTTP request
1034 * processing has occurred, because it expects the request to be parsed and will
1035 * look for the Expect header. It may send a 100-Continue interim response. It
1036 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1037 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1038 * needs to read more data, or 1 once it has completed its analysis.
1039 */
1040int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1041{
1042 struct session *sess = s->sess;
1043 struct http_txn *txn = s->txn;
1044 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001045 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001046
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001047
1048 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1049 now_ms, __FUNCTION__,
1050 s,
1051 req,
1052 req->rex, req->wex,
1053 req->flags,
1054 ci_data(req),
1055 req->analysers);
1056
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001057 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001058
Willy Tarreau4236f032019-03-05 10:43:32 +01001059 if (htx->flags & HTX_FL_PARSING_ERROR)
1060 goto return_bad_req;
1061
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001062 if (msg->msg_state < HTTP_MSG_BODY)
1063 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001064
Christopher Faulete0768eb2018-10-03 16:38:02 +02001065 /* We have to parse the HTTP request body to find any required data.
1066 * "balance url_param check_post" should have been the only way to get
1067 * into this. We were brought here after HTTP header analysis, so all
1068 * related structures are ready.
1069 */
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001072 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1073 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 }
1075
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001076 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001078 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1079 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001082 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083 goto http_end;
1084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1087 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001088 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089
1090 if (!(s->flags & SF_ERR_MASK))
1091 s->flags |= SF_ERR_CLITO;
1092 if (!(s->flags & SF_FINST_MASK))
1093 s->flags |= SF_FINST_D;
1094 goto return_err_msg;
1095 }
1096
1097 /* we get here if we need to wait for more data */
1098 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1099 /* Not enough data. We'll re-use the http-request
1100 * timeout here. Ideally, we should set the timeout
1101 * relative to the accept() date. We just set the
1102 * request timeout once at the beginning of the
1103 * request.
1104 */
1105 channel_dont_connect(req);
1106 if (!tick_isset(req->analyse_exp))
1107 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1108 return 0;
1109 }
1110
1111 http_end:
1112 /* The situation will not evolve, so let's give up on the analysis. */
1113 s->logs.tv_request = now; /* update the request timer to reflect full request */
1114 req->analysers &= ~an_bit;
1115 req->analyse_exp = TICK_ETERNITY;
1116 return 1;
1117
1118 return_bad_req: /* let's centralize all bad requests */
1119 txn->req.err_state = txn->req.msg_state;
1120 txn->req.msg_state = HTTP_MSG_ERROR;
1121 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001122 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001123
1124 if (!(s->flags & SF_ERR_MASK))
1125 s->flags |= SF_ERR_PRXCOND;
1126 if (!(s->flags & SF_FINST_MASK))
1127 s->flags |= SF_FINST_R;
1128
1129 return_err_msg:
1130 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001131 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001132 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001133 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001134 return 0;
1135}
1136
1137/* This function is an analyser which forwards request body (including chunk
1138 * sizes if any). It is called as soon as we must forward, even if we forward
1139 * zero byte. The only situation where it must not be called is when we're in
1140 * tunnel mode and we want to forward till the close. It's used both to forward
1141 * remaining data and to resync after end of body. It expects the msg_state to
1142 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1143 * read more data, or 1 once we can go on with next request or end the stream.
1144 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1145 * bytes of pending data + the headers if not already done.
1146 */
1147int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1148{
1149 struct session *sess = s->sess;
1150 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001151 struct http_msg *msg = &txn->req;
1152 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001153 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001154 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001155
1156 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1157 now_ms, __FUNCTION__,
1158 s,
1159 req,
1160 req->rex, req->wex,
1161 req->flags,
1162 ci_data(req),
1163 req->analysers);
1164
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001165 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001166
1167 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1168 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1169 /* Output closed while we were sending data. We must abort and
1170 * wake the other side up.
1171 */
1172 msg->err_state = msg->msg_state;
1173 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001174 htx_end_request(s);
1175 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 return 1;
1177 }
1178
1179 /* Note that we don't have to send 100-continue back because we don't
1180 * need the data to complete our job, and it's up to the server to
1181 * decide whether to return 100, 417 or anything else in return of
1182 * an "Expect: 100-continue" header.
1183 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001184 if (msg->msg_state == HTTP_MSG_BODY)
1185 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 /* Some post-connect processing might want us to refrain from starting to
1188 * forward data. Currently, the only reason for this is "balance url_param"
1189 * whichs need to parse/process the request after we've enabled forwarding.
1190 */
1191 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1192 if (!(s->res.flags & CF_READ_ATTACHED)) {
1193 channel_auto_connect(req);
1194 req->flags |= CF_WAKE_CONNECT;
1195 channel_dont_close(req); /* don't fail on early shutr */
1196 goto waiting;
1197 }
1198 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1199 }
1200
1201 /* in most states, we should abort in case of early close */
1202 channel_auto_close(req);
1203
1204 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001205 if (req->to_forward == CHN_INFINITE_FORWARD) {
1206 if (req->flags & (CF_SHUTR|CF_EOI)) {
1207 msg->msg_state = HTTP_MSG_DONE;
1208 req->to_forward = 0;
1209 goto done;
1210 }
1211 }
1212 else {
1213 /* We can't process the buffer's contents yet */
1214 req->flags |= CF_WAKE_WRITE;
1215 goto missing_data_or_waiting;
1216 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001217 }
1218
Christopher Faulet9768c262018-10-22 09:34:31 +02001219 if (msg->msg_state >= HTTP_MSG_DONE)
1220 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001221 /* Forward input data. We get it by removing all outgoing data not
1222 * forwarded yet from HTX data size. If there are some data filters, we
1223 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001224 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001225 if (HAS_REQ_DATA_FILTERS(s)) {
1226 ret = flt_http_payload(s, msg, htx->data);
1227 if (ret < 0)
1228 goto return_bad_req;
1229 c_adv(req, ret);
1230 if (htx->data != co_data(req) || htx->extra)
1231 goto missing_data_or_waiting;
1232 }
1233 else {
1234 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001235 if (msg->flags & HTTP_MSGF_XFER_LEN)
1236 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001237 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001238
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001239 if (txn->meth == HTTP_METH_CONNECT) {
1240 msg->msg_state = HTTP_MSG_TUNNEL;
1241 goto done;
1242 }
1243
Christopher Faulet9768c262018-10-22 09:34:31 +02001244 /* Check if the end-of-message is reached and if so, switch the message
1245 * in HTTP_MSG_DONE state.
1246 */
1247 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1248 goto missing_data_or_waiting;
1249
1250 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001251 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001252
1253 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001254 /* other states, DONE...TUNNEL */
1255 /* we don't want to forward closes on DONE except in tunnel mode. */
1256 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1257 channel_dont_close(req);
1258
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001259 if (HAS_REQ_DATA_FILTERS(s)) {
1260 ret = flt_http_end(s, msg);
1261 if (ret <= 0) {
1262 if (!ret)
1263 goto missing_data_or_waiting;
1264 goto return_bad_req;
1265 }
1266 }
1267
Christopher Fauletf2824e62018-10-01 12:12:37 +02001268 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001269 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001270 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1272 if (req->flags & CF_SHUTW) {
1273 /* request errors are most likely due to the
1274 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001275 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001277 goto return_bad_req;
1278 }
1279 return 1;
1280 }
1281
1282 /* If "option abortonclose" is set on the backend, we want to monitor
1283 * the client's connection and forward any shutdown notification to the
1284 * server, which will decide whether to close or to go on processing the
1285 * request. We only do that in tunnel mode, and not in other modes since
1286 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001287 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001288 channel_auto_read(req);
1289 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1290 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1291 s->si[1].flags |= SI_FL_NOLINGER;
1292 channel_auto_close(req);
1293 }
1294 else if (s->txn->meth == HTTP_METH_POST) {
1295 /* POST requests may require to read extra CRLF sent by broken
1296 * browsers and which could cause an RST to be sent upon close
1297 * on some systems (eg: Linux). */
1298 channel_auto_read(req);
1299 }
1300 return 0;
1301
1302 missing_data_or_waiting:
1303 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001304 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1305 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001306
1307 waiting:
1308 /* waiting for the last bits to leave the buffer */
1309 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001310 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001311
Christopher Faulet47365272018-10-31 17:40:50 +01001312 if (htx->flags & HTX_FL_PARSING_ERROR)
1313 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001314
Christopher Faulete0768eb2018-10-03 16:38:02 +02001315 /* When TE: chunked is used, we need to get there again to parse remaining
1316 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1317 * And when content-length is used, we never want to let the possible
1318 * shutdown be forwarded to the other side, as the state machine will
1319 * take care of it once the client responds. It's also important to
1320 * prevent TIME_WAITs from accumulating on the backend side, and for
1321 * HTTP/2 where the last frame comes with a shutdown.
1322 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001323 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001324 channel_dont_close(req);
1325
1326 /* We know that more data are expected, but we couldn't send more that
1327 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1328 * system knows it must not set a PUSH on this first part. Interactive
1329 * modes are already handled by the stream sock layer. We must not do
1330 * this in content-length mode because it could present the MSG_MORE
1331 * flag with the last block of forwarded data, which would cause an
1332 * additional delay to be observed by the receiver.
1333 */
1334 if (msg->flags & HTTP_MSGF_TE_CHNK)
1335 req->flags |= CF_EXPECT_MORE;
1336
1337 return 0;
1338
Christopher Faulet93e02d82019-03-08 14:18:50 +01001339 return_cli_abort:
1340 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1341 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1342 if (objt_server(s->target))
1343 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1344 if (!(s->flags & SF_ERR_MASK))
1345 s->flags |= SF_ERR_CLICL;
1346 status = 400;
1347 goto return_error;
1348
1349 return_srv_abort:
1350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1351 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1352 if (objt_server(s->target))
1353 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1354 if (!(s->flags & SF_ERR_MASK))
1355 s->flags |= SF_ERR_SRVCL;
1356 status = 502;
1357 goto return_error;
1358
1359 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001360 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001362 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001364 s->flags |= SF_ERR_CLICL;
1365 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366
Christopher Faulet93e02d82019-03-08 14:18:50 +01001367 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 txn->req.err_state = txn->req.msg_state;
1369 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001370 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001372 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001374 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001375 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 }
1377 req->analysers &= AN_REQ_FLT_END;
1378 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 +01001379 if (!(s->flags & SF_FINST_MASK))
1380 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 return 0;
1382}
1383
1384/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1385 * processing can continue on next analysers, or zero if it either needs more
1386 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1387 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1388 * when it has nothing left to do, and may remove any analyser when it wants to
1389 * abort.
1390 */
1391int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1392{
Christopher Faulet9768c262018-10-22 09:34:31 +02001393 /*
1394 * We will analyze a complete HTTP response to check the its syntax.
1395 *
1396 * Once the start line and all headers are received, we may perform a
1397 * capture of the error (if any), and we will set a few fields. We also
1398 * logging and finally headers capture.
1399 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001400 struct session *sess = s->sess;
1401 struct http_txn *txn = s->txn;
1402 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001403 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001404 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001405 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001406 int n;
1407
1408 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1409 now_ms, __FUNCTION__,
1410 s,
1411 rep,
1412 rep->rex, rep->wex,
1413 rep->flags,
1414 ci_data(rep),
1415 rep->analysers);
1416
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001417 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001418
Willy Tarreau4236f032019-03-05 10:43:32 +01001419 /* Parsing errors are caught here */
1420 if (htx->flags & HTX_FL_PARSING_ERROR)
1421 goto return_bad_res;
1422
Christopher Faulete0768eb2018-10-03 16:38:02 +02001423 /*
1424 * Now we quickly check if we have found a full valid response.
1425 * If not so, we check the FD and buffer states before leaving.
1426 * A full response is indicated by the fact that we have seen
1427 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1428 * responses are checked first.
1429 *
1430 * Depending on whether the client is still there or not, we
1431 * may send an error response back or not. Note that normally
1432 * we should only check for HTTP status there, and check I/O
1433 * errors somewhere else.
1434 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001435 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001436 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001437 * First catch invalid response because of a parsing error or
1438 * because only part of headers have been transfered.
1439 * Multiplexers have the responsibility to emit all headers at
1440 * once. We must be sure to have forwarded all outgoing data
1441 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001442 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001443 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001444 goto return_bad_res;
1445
Christopher Faulet9768c262018-10-22 09:34:31 +02001446 /* 1: have we encountered a read error ? */
1447 if (rep->flags & CF_READ_ERROR) {
1448 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001449 goto abort_keep_alive;
1450
Olivier Houcharda798bf52019-03-08 18:52:00 +01001451 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001453 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001454 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001455 }
1456
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 rep->analysers &= AN_RES_FLT_END;
1458 txn->status = 502;
1459
1460 /* Check to see if the server refused the early data.
1461 * If so, just send a 425
1462 */
1463 if (objt_cs(s->si[1].end)) {
1464 struct connection *conn = objt_cs(s->si[1].end)->conn;
1465
1466 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1467 txn->status = 425;
1468 }
1469
1470 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001471 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472
1473 if (!(s->flags & SF_ERR_MASK))
1474 s->flags |= SF_ERR_SRVCL;
1475 if (!(s->flags & SF_FINST_MASK))
1476 s->flags |= SF_FINST_H;
1477 return 0;
1478 }
1479
Christopher Faulet9768c262018-10-22 09:34:31 +02001480 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001481 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001482 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001484 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001485 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001486 }
1487
Christopher Faulete0768eb2018-10-03 16:38:02 +02001488 rep->analysers &= AN_RES_FLT_END;
1489 txn->status = 504;
1490 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001491 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001492
1493 if (!(s->flags & SF_ERR_MASK))
1494 s->flags |= SF_ERR_SRVTO;
1495 if (!(s->flags & SF_FINST_MASK))
1496 s->flags |= SF_FINST_H;
1497 return 0;
1498 }
1499
Christopher Faulet9768c262018-10-22 09:34:31 +02001500 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001502 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1503 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001504 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001505 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506
1507 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001509 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510
1511 if (!(s->flags & SF_ERR_MASK))
1512 s->flags |= SF_ERR_CLICL;
1513 if (!(s->flags & SF_FINST_MASK))
1514 s->flags |= SF_FINST_H;
1515
1516 /* process_stream() will take care of the error */
1517 return 0;
1518 }
1519
Christopher Faulet9768c262018-10-22 09:34:31 +02001520 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001522 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 goto abort_keep_alive;
1524
Olivier Houcharda798bf52019-03-08 18:52:00 +01001525 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001527 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001528 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 }
1530
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 rep->analysers &= AN_RES_FLT_END;
1532 txn->status = 502;
1533 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001534 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535
1536 if (!(s->flags & SF_ERR_MASK))
1537 s->flags |= SF_ERR_SRVCL;
1538 if (!(s->flags & SF_FINST_MASK))
1539 s->flags |= SF_FINST_H;
1540 return 0;
1541 }
1542
Christopher Faulet9768c262018-10-22 09:34:31 +02001543 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001545 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001546 goto abort_keep_alive;
1547
Olivier Houcharda798bf52019-03-08 18:52:00 +01001548 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550
1551 if (!(s->flags & SF_ERR_MASK))
1552 s->flags |= SF_ERR_CLICL;
1553 if (!(s->flags & SF_FINST_MASK))
1554 s->flags |= SF_FINST_H;
1555
1556 /* process_stream() will take care of the error */
1557 return 0;
1558 }
1559
1560 channel_dont_close(rep);
1561 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1562 return 0;
1563 }
1564
1565 /* More interesting part now : we know that we have a complete
1566 * response which at least looks like HTTP. We have an indicator
1567 * of each header's length, so we can parse them quickly.
1568 */
1569
Christopher Faulet9768c262018-10-22 09:34:31 +02001570 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001571 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 /* 0: we might have to print this header in debug mode */
1574 if (unlikely((global.mode & MODE_DEBUG) &&
1575 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1576 int32_t pos;
1577
Christopher Faulet03599112018-11-27 11:21:21 +01001578 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001579
1580 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1581 struct htx_blk *blk = htx_get_blk(htx, pos);
1582 enum htx_blk_type type = htx_get_blk_type(blk);
1583
1584 if (type == HTX_BLK_EOH)
1585 break;
1586 if (type != HTX_BLK_HDR)
1587 continue;
1588
1589 htx_debug_hdr("srvhdr", s,
1590 htx_get_blk_name(htx, blk),
1591 htx_get_blk_value(htx, blk));
1592 }
1593 }
1594
Christopher Faulet03599112018-11-27 11:21:21 +01001595 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001596 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001597 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001598 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001599 if (sl->flags & HTX_SL_F_XFER_LEN) {
1600 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001601 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001602 if (sl->flags & HTX_SL_F_BODYLESS)
1603 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001604 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001605
1606 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 if (n < 1 || n > 5)
1608 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001609
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610 /* when the client triggers a 4xx from the server, it's most often due
1611 * to a missing object or permission. These events should be tracked
1612 * because if they happen often, it may indicate a brute force or a
1613 * vulnerability scan.
1614 */
1615 if (n == 4)
1616 stream_inc_http_err_ctr(s);
1617
1618 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001619 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621 /* Adjust server's health based on status code. Note: status codes 501
1622 * and 505 are triggered on demand by client request, so we must not
1623 * count them as server failures.
1624 */
1625 if (objt_server(s->target)) {
1626 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001627 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001628 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001629 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001630 }
1631
1632 /*
1633 * We may be facing a 100-continue response, or any other informational
1634 * 1xx response which is non-final, in which case this is not the right
1635 * response, and we're waiting for the next one. Let's allow this response
1636 * to go to the client and wait for the next one. There's an exception for
1637 * 101 which is used later in the code to switch protocols.
1638 */
1639 if (txn->status < 200 &&
1640 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001641 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001642 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001643 msg->msg_state = HTTP_MSG_RPBEFORE;
1644 txn->status = 0;
1645 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001646 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647 }
1648
1649 /*
1650 * 2: check for cacheability.
1651 */
1652
1653 switch (txn->status) {
1654 case 200:
1655 case 203:
1656 case 204:
1657 case 206:
1658 case 300:
1659 case 301:
1660 case 404:
1661 case 405:
1662 case 410:
1663 case 414:
1664 case 501:
1665 break;
1666 default:
1667 /* RFC7231#6.1:
1668 * Responses with status codes that are defined as
1669 * cacheable by default (e.g., 200, 203, 204, 206,
1670 * 300, 301, 404, 405, 410, 414, and 501 in this
1671 * specification) can be reused by a cache with
1672 * heuristic expiration unless otherwise indicated
1673 * by the method definition or explicit cache
1674 * controls [RFC7234]; all other status codes are
1675 * not cacheable by default.
1676 */
1677 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1678 break;
1679 }
1680
1681 /*
1682 * 3: we may need to capture headers
1683 */
1684 s->logs.logwait &= ~LW_RESP;
1685 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001686 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687
Christopher Faulet9768c262018-10-22 09:34:31 +02001688 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001689 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1690 txn->status == 101)) {
1691 /* Either we've established an explicit tunnel, or we're
1692 * switching the protocol. In both cases, we're very unlikely
1693 * to understand the next protocols. We have to switch to tunnel
1694 * mode, so that we transfer the request and responses then let
1695 * this protocol pass unmodified. When we later implement specific
1696 * parsers for such protocols, we'll want to check the Upgrade
1697 * header which contains information about that protocol for
1698 * responses with status 101 (eg: see RFC2817 about TLS).
1699 */
1700 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001701 }
1702
Christopher Faulet61608322018-11-23 16:23:45 +01001703 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1704 * 407 (Proxy-Authenticate) responses and set the connection to private
1705 */
1706 srv_conn = cs_conn(objt_cs(s->si[1].end));
1707 if (srv_conn) {
1708 struct ist hdr;
1709 struct http_hdr_ctx ctx;
1710
1711 if (txn->status == 401)
1712 hdr = ist("WWW-Authenticate");
1713 else if (txn->status == 407)
1714 hdr = ist("Proxy-Authenticate");
1715 else
1716 goto end;
1717
1718 ctx.blk = NULL;
1719 while (http_find_header(htx, hdr, &ctx, 0)) {
1720 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1721 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1722 srv_conn->flags |= CO_FL_PRIVATE;
1723 }
1724 }
1725
1726 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001727 /* we want to have the response time before we start processing it */
1728 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1729
1730 /* end of job, return OK */
1731 rep->analysers &= ~an_bit;
1732 rep->analyse_exp = TICK_ETERNITY;
1733 channel_auto_close(rep);
1734 return 1;
1735
Christopher Faulet47365272018-10-31 17:40:50 +01001736 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001737 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001738 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001739 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001740 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001741 }
1742 txn->status = 502;
1743 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001744 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001745 rep->analysers &= AN_RES_FLT_END;
1746
1747 if (!(s->flags & SF_ERR_MASK))
1748 s->flags |= SF_ERR_PRXCOND;
1749 if (!(s->flags & SF_FINST_MASK))
1750 s->flags |= SF_FINST_H;
1751 return 0;
1752
Christopher Faulete0768eb2018-10-03 16:38:02 +02001753 abort_keep_alive:
1754 /* A keep-alive request to the server failed on a network error.
1755 * The client is required to retry. We need to close without returning
1756 * any other information so that the client retries.
1757 */
1758 txn->status = 0;
1759 rep->analysers &= AN_RES_FLT_END;
1760 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001761 s->logs.logwait = 0;
1762 s->logs.level = 0;
1763 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001764 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001765 return 0;
1766}
1767
1768/* This function performs all the processing enabled for the current response.
1769 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1770 * and updates s->res.analysers. It might make sense to explode it into several
1771 * other functions. It works like process_request (see indications above).
1772 */
1773int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1774{
1775 struct session *sess = s->sess;
1776 struct http_txn *txn = s->txn;
1777 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001778 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 struct proxy *cur_proxy;
1780 struct cond_wordlist *wl;
1781 enum rule_result ret = HTTP_RULE_RES_CONT;
1782
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001783 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1784 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001785
Christopher Faulete0768eb2018-10-03 16:38:02 +02001786 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1787 now_ms, __FUNCTION__,
1788 s,
1789 rep,
1790 rep->rex, rep->wex,
1791 rep->flags,
1792 ci_data(rep),
1793 rep->analysers);
1794
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001795 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001796
1797 /* The stats applet needs to adjust the Connection header but we don't
1798 * apply any filter there.
1799 */
1800 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1801 rep->analysers &= ~an_bit;
1802 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001803 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 }
1805
1806 /*
1807 * We will have to evaluate the filters.
1808 * As opposed to version 1.2, now they will be evaluated in the
1809 * filters order and not in the header order. This means that
1810 * each filter has to be validated among all headers.
1811 *
1812 * Filters are tried with ->be first, then with ->fe if it is
1813 * different from ->be.
1814 *
1815 * Maybe we are in resume condiion. In this case I choose the
1816 * "struct proxy" which contains the rule list matching the resume
1817 * pointer. If none of theses "struct proxy" match, I initialise
1818 * the process with the first one.
1819 *
1820 * In fact, I check only correspondance betwwen the current list
1821 * pointer and the ->fe rule list. If it doesn't match, I initialize
1822 * the loop with the ->be.
1823 */
1824 if (s->current_rule_list == &sess->fe->http_res_rules)
1825 cur_proxy = sess->fe;
1826 else
1827 cur_proxy = s->be;
1828 while (1) {
1829 struct proxy *rule_set = cur_proxy;
1830
1831 /* evaluate http-response rules */
1832 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001833 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001834
1835 if (ret == HTTP_RULE_RES_BADREQ)
1836 goto return_srv_prx_502;
1837
1838 if (ret == HTTP_RULE_RES_DONE) {
1839 rep->analysers &= ~an_bit;
1840 rep->analyse_exp = TICK_ETERNITY;
1841 return 1;
1842 }
1843 }
1844
1845 /* we need to be called again. */
1846 if (ret == HTTP_RULE_RES_YIELD) {
1847 channel_dont_close(rep);
1848 return 0;
1849 }
1850
1851 /* try headers filters */
1852 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001853 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1854 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001855 }
1856
1857 /* has the response been denied ? */
1858 if (txn->flags & TX_SVDENY) {
1859 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001860 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861
Olivier Houcharda798bf52019-03-08 18:52:00 +01001862 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1863 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001864 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001865 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866 goto return_srv_prx_502;
1867 }
1868
1869 /* add response headers from the rule sets in the same order */
1870 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001871 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001872 if (txn->status < 200 && txn->status != 101)
1873 break;
1874 if (wl->cond) {
1875 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1876 ret = acl_pass(ret);
1877 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1878 ret = !ret;
1879 if (!ret)
1880 continue;
1881 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001882
1883 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1884 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001885 goto return_bad_resp;
1886 }
1887
1888 /* check whether we're already working on the frontend */
1889 if (cur_proxy == sess->fe)
1890 break;
1891 cur_proxy = sess->fe;
1892 }
1893
1894 /* After this point, this anayzer can't return yield, so we can
1895 * remove the bit corresponding to this analyzer from the list.
1896 *
1897 * Note that the intermediate returns and goto found previously
1898 * reset the analyzers.
1899 */
1900 rep->analysers &= ~an_bit;
1901 rep->analyse_exp = TICK_ETERNITY;
1902
1903 /* OK that's all we can do for 1xx responses */
1904 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001905 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001906
1907 /*
1908 * Now check for a server cookie.
1909 */
1910 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001911 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001912
1913 /*
1914 * Check for cache-control or pragma headers if required.
1915 */
1916 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1917 check_response_for_cacheability(s, rep);
1918
1919 /*
1920 * Add server cookie in the response if needed
1921 */
1922 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1923 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1924 (!(s->flags & SF_DIRECT) ||
1925 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1926 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1927 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1928 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1929 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1930 !(s->flags & SF_IGNORE_PRST)) {
1931 /* the server is known, it's not the one the client requested, or the
1932 * cookie's last seen date needs to be refreshed. We have to
1933 * insert a set-cookie here, except if we want to insert only on POST
1934 * requests and this one isn't. Note that servers which don't have cookies
1935 * (eg: some backup servers) will return a full cookie removal request.
1936 */
1937 if (!objt_server(s->target)->cookie) {
1938 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001939 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001940 s->be->cookie_name);
1941 }
1942 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944
1945 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1946 /* emit last_date, which is mandatory */
1947 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1948 s30tob64((date.tv_sec+3) >> 2,
1949 trash.area + trash.data);
1950 trash.data += 5;
1951
1952 if (s->be->cookie_maxlife) {
1953 /* emit first_date, which is either the original one or
1954 * the current date.
1955 */
1956 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1957 s30tob64(txn->cookie_first_date ?
1958 txn->cookie_first_date >> 2 :
1959 (date.tv_sec+3) >> 2,
1960 trash.area + trash.data);
1961 trash.data += 5;
1962 }
1963 }
1964 chunk_appendf(&trash, "; path=/");
1965 }
1966
1967 if (s->be->cookie_domain)
1968 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1969
1970 if (s->be->ck_opts & PR_CK_HTTPONLY)
1971 chunk_appendf(&trash, "; HttpOnly");
1972
1973 if (s->be->ck_opts & PR_CK_SECURE)
1974 chunk_appendf(&trash, "; Secure");
1975
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001976 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001977 goto return_bad_resp;
1978
1979 txn->flags &= ~TX_SCK_MASK;
1980 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1981 /* the server did not change, only the date was updated */
1982 txn->flags |= TX_SCK_UPDATED;
1983 else
1984 txn->flags |= TX_SCK_INSERTED;
1985
1986 /* Here, we will tell an eventual cache on the client side that we don't
1987 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1988 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1989 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1990 */
1991 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1992
1993 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1994
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001995 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001996 goto return_bad_resp;
1997 }
1998 }
1999
2000 /*
2001 * Check if result will be cacheable with a cookie.
2002 * We'll block the response if security checks have caught
2003 * nasty things such as a cacheable cookie.
2004 */
2005 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2006 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2007 (s->be->options & PR_O_CHK_CACHE)) {
2008 /* we're in presence of a cacheable response containing
2009 * a set-cookie header. We'll block it as requested by
2010 * the 'checkcache' option, and send an alert.
2011 */
2012 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002013 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002014
Olivier Houcharda798bf52019-03-08 18:52:00 +01002015 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2016 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002017 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002018 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019
2020 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2021 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2022 send_log(s->be, LOG_ALERT,
2023 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2024 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2025 goto return_srv_prx_502;
2026 }
2027
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002028 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002029 /* Always enter in the body analyzer */
2030 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2031 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2032
2033 /* if the user wants to log as soon as possible, without counting
2034 * bytes from the server, then this is the right moment. We have
2035 * to temporarily assign bytes_out to log what we currently have.
2036 */
2037 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2038 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002039 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002040 s->do_log(s);
2041 s->logs.bytes_out = 0;
2042 }
2043 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002044
2045 return_bad_resp:
2046 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002047 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002048 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002050 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002051
2052 return_srv_prx_502:
2053 rep->analysers &= AN_RES_FLT_END;
2054 txn->status = 502;
2055 s->logs.t_data = -1; /* was not a valid response */
2056 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002057 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002058 if (!(s->flags & SF_ERR_MASK))
2059 s->flags |= SF_ERR_PRXCOND;
2060 if (!(s->flags & SF_FINST_MASK))
2061 s->flags |= SF_FINST_H;
2062 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002063}
2064
2065/* This function is an analyser which forwards response body (including chunk
2066 * sizes if any). It is called as soon as we must forward, even if we forward
2067 * zero byte. The only situation where it must not be called is when we're in
2068 * tunnel mode and we want to forward till the close. It's used both to forward
2069 * remaining data and to resync after end of body. It expects the msg_state to
2070 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2071 * read more data, or 1 once we can go on with next request or end the stream.
2072 *
2073 * It is capable of compressing response data both in content-length mode and
2074 * in chunked mode. The state machines follows different flows depending on
2075 * whether content-length and chunked modes are used, since there are no
2076 * trailers in content-length :
2077 *
2078 * chk-mode cl-mode
2079 * ,----- BODY -----.
2080 * / \
2081 * V size > 0 V chk-mode
2082 * .--> SIZE -------------> DATA -------------> CRLF
2083 * | | size == 0 | last byte |
2084 * | v final crlf v inspected |
2085 * | TRAILERS -----------> DONE |
2086 * | |
2087 * `----------------------------------------------'
2088 *
2089 * Compression only happens in the DATA state, and must be flushed in final
2090 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2091 * is performed at once on final states for all bytes parsed, or when leaving
2092 * on missing data.
2093 */
2094int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2095{
2096 struct session *sess = s->sess;
2097 struct http_txn *txn = s->txn;
2098 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002099 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002100 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101
2102 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2103 now_ms, __FUNCTION__,
2104 s,
2105 res,
2106 res->rex, res->wex,
2107 res->flags,
2108 ci_data(res),
2109 res->analysers);
2110
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002111 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002112
2113 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002114 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002115 /* Output closed while we were sending data. We must abort and
2116 * wake the other side up.
2117 */
2118 msg->err_state = msg->msg_state;
2119 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002120 htx_end_response(s);
2121 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002122 return 1;
2123 }
2124
Christopher Faulet9768c262018-10-22 09:34:31 +02002125 if (msg->msg_state == HTTP_MSG_BODY)
2126 msg->msg_state = HTTP_MSG_DATA;
2127
Christopher Faulete0768eb2018-10-03 16:38:02 +02002128 /* in most states, we should abort in case of early close */
2129 channel_auto_close(res);
2130
Christopher Faulete0768eb2018-10-03 16:38:02 +02002131 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002132 if (res->to_forward == CHN_INFINITE_FORWARD) {
2133 if (res->flags & (CF_SHUTR|CF_EOI)) {
2134 msg->msg_state = HTTP_MSG_DONE;
2135 res->to_forward = 0;
2136 goto done;
2137 }
2138 }
2139 else {
2140 /* We can't process the buffer's contents yet */
2141 res->flags |= CF_WAKE_WRITE;
2142 goto missing_data_or_waiting;
2143 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002144 }
2145
Christopher Faulet9768c262018-10-22 09:34:31 +02002146 if (msg->msg_state >= HTTP_MSG_DONE)
2147 goto done;
2148
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002149 /* Forward input data. We get it by removing all outgoing data not
2150 * forwarded yet from HTX data size. If there are some data filters, we
2151 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002152 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002153 if (HAS_RSP_DATA_FILTERS(s)) {
2154 ret = flt_http_payload(s, msg, htx->data);
2155 if (ret < 0)
2156 goto return_bad_res;
2157 c_adv(res, ret);
2158 if (htx->data != co_data(res) || htx->extra)
2159 goto missing_data_or_waiting;
2160 }
2161 else {
2162 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002163 if (msg->flags & HTTP_MSGF_XFER_LEN)
2164 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002165 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002166
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002167 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2168 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2169 msg->msg_state = HTTP_MSG_TUNNEL;
2170 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002171 }
2172
Christopher Faulet9768c262018-10-22 09:34:31 +02002173 /* Check if the end-of-message is reached and if so, switch the message
2174 * in HTTP_MSG_DONE state.
2175 */
2176 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2177 goto missing_data_or_waiting;
2178
2179 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002180 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002181
2182 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002184 channel_dont_close(res);
2185
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002186 if (HAS_RSP_DATA_FILTERS(s)) {
2187 ret = flt_http_end(s, msg);
2188 if (ret <= 0) {
2189 if (!ret)
2190 goto missing_data_or_waiting;
2191 goto return_bad_res;
2192 }
2193 }
2194
Christopher Fauletf2824e62018-10-01 12:12:37 +02002195 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002197 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002198 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2199 if (res->flags & CF_SHUTW) {
2200 /* response errors are most likely due to the
2201 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002202 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 goto return_bad_res;
2205 }
2206 return 1;
2207 }
2208 return 0;
2209
2210 missing_data_or_waiting:
2211 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002212 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213
Christopher Faulet47365272018-10-31 17:40:50 +01002214 if (htx->flags & HTX_FL_PARSING_ERROR)
2215 goto return_bad_res;
2216
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217 /* stop waiting for data if the input is closed before the end. If the
2218 * client side was already closed, it means that the client has aborted,
2219 * so we don't want to count this as a server abort. Otherwise it's a
2220 * server abort.
2221 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002222 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002223 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002224 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002226 if (htx_is_empty(htx))
2227 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228 }
2229
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 /* When TE: chunked is used, we need to get there again to parse
2231 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002232 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2233 * are filters registered on the stream, we don't want to forward a
2234 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002235 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002236 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 channel_dont_close(res);
2238
2239 /* We know that more data are expected, but we couldn't send more that
2240 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2241 * system knows it must not set a PUSH on this first part. Interactive
2242 * modes are already handled by the stream sock layer. We must not do
2243 * this in content-length mode because it could present the MSG_MORE
2244 * flag with the last block of forwarded data, which would cause an
2245 * additional delay to be observed by the receiver.
2246 */
2247 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2248 res->flags |= CF_EXPECT_MORE;
2249
2250 /* the stream handler will take care of timeouts and errors */
2251 return 0;
2252
Christopher Faulet93e02d82019-03-08 14:18:50 +01002253 return_srv_abort:
2254 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2255 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002257 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2258 if (!(s->flags & SF_ERR_MASK))
2259 s->flags |= SF_ERR_SRVCL;
2260 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261
Christopher Faulet93e02d82019-03-08 14:18:50 +01002262 return_cli_abort:
2263 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2264 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002266 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2267 if (!(s->flags & SF_ERR_MASK))
2268 s->flags |= SF_ERR_CLICL;
2269 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002270
Christopher Faulet93e02d82019-03-08 14:18:50 +01002271 return_bad_res:
2272 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2273 if (objt_server(s->target)) {
2274 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2275 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2276 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002277 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002278 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002279
Christopher Faulet93e02d82019-03-08 14:18:50 +01002280 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002281 txn->rsp.err_state = txn->rsp.msg_state;
2282 txn->rsp.msg_state = HTTP_MSG_ERROR;
2283 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002284 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 res->analysers &= AN_RES_FLT_END;
2286 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 +02002287 if (!(s->flags & SF_FINST_MASK))
2288 s->flags |= SF_FINST_D;
2289 return 0;
2290}
2291
Christopher Fauletf2824e62018-10-01 12:12:37 +02002292/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002293 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002294 * as too large a request to build a valid response.
2295 */
2296int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2297{
Christopher Faulet99daf282018-11-28 22:58:13 +01002298 struct channel *req = &s->req;
2299 struct channel *res = &s->res;
2300 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002301 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002302 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002303 struct ist status, reason, location;
2304 unsigned int flags;
2305 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002306
2307 chunk = alloc_trash_chunk();
2308 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002309 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002310
Christopher Faulet99daf282018-11-28 22:58:13 +01002311 /*
2312 * Create the location
2313 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002314 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002315 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002316 case REDIRECT_TYPE_SCHEME: {
2317 struct http_hdr_ctx ctx;
2318 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002319
Christopher Faulet99daf282018-11-28 22:58:13 +01002320 host = ist("");
2321 ctx.blk = NULL;
2322 if (http_find_header(htx, ist("Host"), &ctx, 0))
2323 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002324
Christopher Faulet99daf282018-11-28 22:58:13 +01002325 sl = http_find_stline(htx);
2326 path = http_get_path(htx_sl_req_uri(sl));
2327 /* build message using path */
2328 if (path.ptr) {
2329 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2330 int qs = 0;
2331 while (qs < path.len) {
2332 if (*(path.ptr + qs) == '?') {
2333 path.len = qs;
2334 break;
2335 }
2336 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002337 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338 }
2339 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 else
2341 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002342
Christopher Faulet99daf282018-11-28 22:58:13 +01002343 if (rule->rdr_str) { /* this is an old "redirect" rule */
2344 /* add scheme */
2345 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2346 goto fail;
2347 }
2348 else {
2349 /* add scheme with executing log format */
2350 chunk->data += build_logline(s, chunk->area + chunk->data,
2351 chunk->size - chunk->data,
2352 &rule->rdr_fmt);
2353 }
2354 /* add "://" + host + path */
2355 if (!chunk_memcat(chunk, "://", 3) ||
2356 !chunk_memcat(chunk, host.ptr, host.len) ||
2357 !chunk_memcat(chunk, path.ptr, path.len))
2358 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359
Christopher Faulet99daf282018-11-28 22:58:13 +01002360 /* append a slash at the end of the location if needed and missing */
2361 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2362 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2363 if (chunk->data + 1 >= chunk->size)
2364 goto fail;
2365 chunk->area[chunk->data++] = '/';
2366 }
2367 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 case REDIRECT_TYPE_PREFIX: {
2371 struct ist path;
2372
2373 sl = http_find_stline(htx);
2374 path = http_get_path(htx_sl_req_uri(sl));
2375 /* build message using path */
2376 if (path.ptr) {
2377 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2378 int qs = 0;
2379 while (qs < path.len) {
2380 if (*(path.ptr + qs) == '?') {
2381 path.len = qs;
2382 break;
2383 }
2384 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386 }
2387 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 else
2389 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 if (rule->rdr_str) { /* this is an old "redirect" rule */
2392 /* add prefix. Note that if prefix == "/", we don't want to
2393 * add anything, otherwise it makes it hard for the user to
2394 * configure a self-redirection.
2395 */
2396 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2397 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2398 goto fail;
2399 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002401 else {
2402 /* add prefix with executing log format */
2403 chunk->data += build_logline(s, chunk->area + chunk->data,
2404 chunk->size - chunk->data,
2405 &rule->rdr_fmt);
2406 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407
Christopher Faulet99daf282018-11-28 22:58:13 +01002408 /* add path */
2409 if (!chunk_memcat(chunk, path.ptr, path.len))
2410 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 /* append a slash at the end of the location if needed and missing */
2413 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2414 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2415 if (chunk->data + 1 >= chunk->size)
2416 goto fail;
2417 chunk->area[chunk->data++] = '/';
2418 }
2419 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002421 case REDIRECT_TYPE_LOCATION:
2422 default:
2423 if (rule->rdr_str) { /* this is an old "redirect" rule */
2424 /* add location */
2425 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2426 goto fail;
2427 }
2428 else {
2429 /* add location with executing log format */
2430 chunk->data += build_logline(s, chunk->area + chunk->data,
2431 chunk->size - chunk->data,
2432 &rule->rdr_fmt);
2433 }
2434 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 location = ist2(chunk->area, chunk->data);
2437
2438 /*
2439 * Create the 30x response
2440 */
2441 switch (rule->code) {
2442 case 308:
2443 status = ist("308");
2444 reason = ist("Permanent Redirect");
2445 break;
2446 case 307:
2447 status = ist("307");
2448 reason = ist("Temporary Redirect");
2449 break;
2450 case 303:
2451 status = ist("303");
2452 reason = ist("See Other");
2453 break;
2454 case 301:
2455 status = ist("301");
2456 reason = ist("Moved Permanently");
2457 break;
2458 case 302:
2459 default:
2460 status = ist("302");
2461 reason = ist("Found");
2462 break;
2463 }
2464
2465 htx = htx_from_buf(&res->buf);
2466 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2467 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2468 if (!sl)
2469 goto fail;
2470 sl->info.res.status = rule->code;
2471 s->txn->status = rule->code;
2472
2473 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2474 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2475 !htx_add_header(htx, ist("Location"), location))
2476 goto fail;
2477
2478 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2479 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2480 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002481 }
2482
2483 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002484 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2485 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002486 }
2487
Christopher Faulet99daf282018-11-28 22:58:13 +01002488 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2489 goto fail;
2490
Christopher Fauletf2824e62018-10-01 12:12:37 +02002491 /* let's log the request time */
2492 s->logs.tv_request = now;
2493
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002495 c_adv(res, data);
2496 res->total += data;
2497
2498 channel_auto_read(req);
2499 channel_abort(req);
2500 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002501 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002502
2503 res->wex = tick_add_ifset(now_ms, res->wto);
2504 channel_auto_read(res);
2505 channel_auto_close(res);
2506 channel_shutr_now(res);
2507
2508 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002509
2510 if (!(s->flags & SF_ERR_MASK))
2511 s->flags |= SF_ERR_LOCAL;
2512 if (!(s->flags & SF_FINST_MASK))
2513 s->flags |= SF_FINST_R;
2514
Christopher Faulet99daf282018-11-28 22:58:13 +01002515 free_trash_chunk(chunk);
2516 return 1;
2517
2518 fail:
2519 /* If an error occurred, remove the incomplete HTTP response from the
2520 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002521 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002522 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002523 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002524}
2525
Christopher Faulet72333522018-10-24 11:25:02 +02002526int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2527 struct ist name, const char *str, struct my_regex *re, int action)
2528{
2529 struct http_hdr_ctx ctx;
2530 struct buffer *output = get_trash_chunk();
2531
2532 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2533 ctx.blk = NULL;
2534 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2535 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2536 continue;
2537
2538 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2539 if (output->data == -1)
2540 return -1;
2541 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2542 return -1;
2543 }
2544 return 0;
2545}
2546
2547static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2548 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2549{
2550 struct buffer *replace;
2551 int ret = -1;
2552
2553 replace = alloc_trash_chunk();
2554 if (!replace)
2555 goto leave;
2556
2557 replace->data = build_logline(s, replace->area, replace->size, fmt);
2558 if (replace->data >= replace->size - 1)
2559 goto leave;
2560
2561 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2562
2563 leave:
2564 free_trash_chunk(replace);
2565 return ret;
2566}
2567
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002568
2569/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2570 * on success and -1 on error. The response channel is updated accordingly.
2571 */
2572static int htx_reply_103_early_hints(struct channel *res)
2573{
2574 struct htx *htx = htx_from_buf(&res->buf);
2575 size_t data;
2576
2577 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2578 /* If an error occurred during an Early-hint rule,
2579 * remove the incomplete HTTP 103 response from the
2580 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002581 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002582 return -1;
2583 }
2584
2585 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002586 c_adv(res, data);
2587 res->total += data;
2588 return 0;
2589}
2590
Christopher Faulet6eb92892018-11-15 16:39:29 +01002591/*
2592 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2593 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002594 * If <early_hints> is 0, it is starts a new response by adding the start
2595 * line. If an error occurred -1 is returned. On success 0 is returned. The
2596 * channel is not updated here. It must be done calling the function
2597 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002598 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002599static 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 +01002600{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002601 struct channel *res = &s->res;
2602 struct htx *htx = htx_from_buf(&res->buf);
2603 struct buffer *value = alloc_trash_chunk();
2604
Christopher Faulet6eb92892018-11-15 16:39:29 +01002605 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002606 struct htx_sl *sl;
2607 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2608 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2609
2610 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2611 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2612 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002613 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002614 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002615 }
2616
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002617 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2618 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002619 goto fail;
2620
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002621 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002623
2624 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002625 /* If an error occurred during an Early-hint rule, remove the incomplete
2626 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002627 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002628 free_trash_chunk(value);
2629 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002630}
2631
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002632/* This function executes one of the set-{method,path,query,uri} actions. It
2633 * takes the string from the variable 'replace' with length 'len', then modifies
2634 * the relevant part of the request line accordingly. Then it updates various
2635 * pointers to the next elements which were moved, and the total buffer length.
2636 * It finds the action to be performed in p[2], previously filled by function
2637 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2638 * error, though this can be revisited when this code is finally exploited.
2639 *
2640 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2641 * query string and 3 to replace uri.
2642 *
2643 * In query string case, the mark question '?' must be set at the start of the
2644 * string by the caller, event if the replacement query string is empty.
2645 */
2646int htx_req_replace_stline(int action, const char *replace, int len,
2647 struct proxy *px, struct stream *s)
2648{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002649 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002650
2651 switch (action) {
2652 case 0: // method
2653 if (!http_replace_req_meth(htx, ist2(replace, len)))
2654 return -1;
2655 break;
2656
2657 case 1: // path
2658 if (!http_replace_req_path(htx, ist2(replace, len)))
2659 return -1;
2660 break;
2661
2662 case 2: // query
2663 if (!http_replace_req_query(htx, ist2(replace, len)))
2664 return -1;
2665 break;
2666
2667 case 3: // uri
2668 if (!http_replace_req_uri(htx, ist2(replace, len)))
2669 return -1;
2670 break;
2671
2672 default:
2673 return -1;
2674 }
2675 return 0;
2676}
2677
2678/* This function replace the HTTP status code and the associated message. The
2679 * variable <status> contains the new status code. This function never fails.
2680 */
2681void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2682{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002683 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002684 char *res;
2685
2686 chunk_reset(&trash);
2687 res = ultoa_o(status, trash.area, trash.size);
2688 trash.data = res - trash.area;
2689
2690 /* Do we have a custom reason format string? */
2691 if (reason == NULL)
2692 reason = http_get_reason(status);
2693
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002694 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002695 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2696}
2697
Christopher Faulet3e964192018-10-24 11:39:23 +02002698/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2699 * transaction <txn>. Returns the verdict of the first rule that prevents
2700 * further processing of the request (auth, deny, ...), and defaults to
2701 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2702 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2703 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2704 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2705 * status.
2706 */
2707static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2708 struct stream *s, int *deny_status)
2709{
2710 struct session *sess = strm_sess(s);
2711 struct http_txn *txn = s->txn;
2712 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002713 struct act_rule *rule;
2714 struct http_hdr_ctx ctx;
2715 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002716 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2717 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002718 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002719
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002720 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002721
2722 /* If "the current_rule_list" match the executed rule list, we are in
2723 * resume condition. If a resume is needed it is always in the action
2724 * and never in the ACL or converters. In this case, we initialise the
2725 * current rule, and go to the action execution point.
2726 */
2727 if (s->current_rule) {
2728 rule = s->current_rule;
2729 s->current_rule = NULL;
2730 if (s->current_rule_list == rules)
2731 goto resume_execution;
2732 }
2733 s->current_rule_list = rules;
2734
2735 list_for_each_entry(rule, rules, list) {
2736 /* check optional condition */
2737 if (rule->cond) {
2738 int ret;
2739
2740 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2741 ret = acl_pass(ret);
2742
2743 if (rule->cond->pol == ACL_COND_UNLESS)
2744 ret = !ret;
2745
2746 if (!ret) /* condition not matched */
2747 continue;
2748 }
2749
2750 act_flags |= ACT_FLAG_FIRST;
2751 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002752 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2753 early_hints = 0;
2754 if (htx_reply_103_early_hints(&s->res) == -1) {
2755 rule_ret = HTTP_RULE_RES_BADREQ;
2756 goto end;
2757 }
2758 }
2759
Christopher Faulet3e964192018-10-24 11:39:23 +02002760 switch (rule->action) {
2761 case ACT_ACTION_ALLOW:
2762 rule_ret = HTTP_RULE_RES_STOP;
2763 goto end;
2764
2765 case ACT_ACTION_DENY:
2766 if (deny_status)
2767 *deny_status = rule->deny_status;
2768 rule_ret = HTTP_RULE_RES_DENY;
2769 goto end;
2770
2771 case ACT_HTTP_REQ_TARPIT:
2772 txn->flags |= TX_CLTARPIT;
2773 if (deny_status)
2774 *deny_status = rule->deny_status;
2775 rule_ret = HTTP_RULE_RES_DENY;
2776 goto end;
2777
2778 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002779 /* Auth might be performed on regular http-req rules as well as on stats */
2780 auth_realm = rule->arg.auth.realm;
2781 if (!auth_realm) {
2782 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2783 auth_realm = STATS_DEFAULT_REALM;
2784 else
2785 auth_realm = px->id;
2786 }
2787 /* send 401/407 depending on whether we use a proxy or not. We still
2788 * count one error, because normal browsing won't significantly
2789 * increase the counter but brute force attempts will.
2790 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002791 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002792 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2793 rule_ret = HTTP_RULE_RES_BADREQ;
2794 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002795 goto end;
2796
2797 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002798 rule_ret = HTTP_RULE_RES_DONE;
2799 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2800 rule_ret = HTTP_RULE_RES_BADREQ;
2801 goto end;
2802
2803 case ACT_HTTP_SET_NICE:
2804 s->task->nice = rule->arg.nice;
2805 break;
2806
2807 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002808 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002809 break;
2810
2811 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002812 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002813 break;
2814
2815 case ACT_HTTP_SET_LOGL:
2816 s->logs.level = rule->arg.loglevel;
2817 break;
2818
2819 case ACT_HTTP_REPLACE_HDR:
2820 case ACT_HTTP_REPLACE_VAL:
2821 if (htx_transform_header(s, &s->req, htx,
2822 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2823 &rule->arg.hdr_add.fmt,
2824 &rule->arg.hdr_add.re, rule->action)) {
2825 rule_ret = HTTP_RULE_RES_BADREQ;
2826 goto end;
2827 }
2828 break;
2829
2830 case ACT_HTTP_DEL_HDR:
2831 /* remove all occurrences of the header */
2832 ctx.blk = NULL;
2833 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2834 http_remove_header(htx, &ctx);
2835 break;
2836
2837 case ACT_HTTP_SET_HDR:
2838 case ACT_HTTP_ADD_HDR: {
2839 /* The scope of the trash buffer must be limited to this function. The
2840 * build_logline() function can execute a lot of other function which
2841 * can use the trash buffer. So for limiting the scope of this global
2842 * buffer, we build first the header value using build_logline, and
2843 * after we store the header name.
2844 */
2845 struct buffer *replace;
2846 struct ist n, v;
2847
2848 replace = alloc_trash_chunk();
2849 if (!replace) {
2850 rule_ret = HTTP_RULE_RES_BADREQ;
2851 goto end;
2852 }
2853
2854 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2855 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2856 v = ist2(replace->area, replace->data);
2857
2858 if (rule->action == ACT_HTTP_SET_HDR) {
2859 /* remove all occurrences of the header */
2860 ctx.blk = NULL;
2861 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2862 http_remove_header(htx, &ctx);
2863 }
2864
2865 if (!http_add_header(htx, n, v)) {
2866 static unsigned char rate_limit = 0;
2867
2868 if ((rate_limit++ & 255) == 0) {
2869 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);
2870 }
2871
Olivier Houcharda798bf52019-03-08 18:52:00 +01002872 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002873 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002874 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002875 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002876 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002877 }
2878 free_trash_chunk(replace);
2879 break;
2880 }
2881
2882 case ACT_HTTP_DEL_ACL:
2883 case ACT_HTTP_DEL_MAP: {
2884 struct pat_ref *ref;
2885 struct buffer *key;
2886
2887 /* collect reference */
2888 ref = pat_ref_lookup(rule->arg.map.ref);
2889 if (!ref)
2890 continue;
2891
2892 /* allocate key */
2893 key = alloc_trash_chunk();
2894 if (!key) {
2895 rule_ret = HTTP_RULE_RES_BADREQ;
2896 goto end;
2897 }
2898
2899 /* collect key */
2900 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2901 key->area[key->data] = '\0';
2902
2903 /* perform update */
2904 /* returned code: 1=ok, 0=ko */
2905 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2906 pat_ref_delete(ref, key->area);
2907 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2908
2909 free_trash_chunk(key);
2910 break;
2911 }
2912
2913 case ACT_HTTP_ADD_ACL: {
2914 struct pat_ref *ref;
2915 struct buffer *key;
2916
2917 /* collect reference */
2918 ref = pat_ref_lookup(rule->arg.map.ref);
2919 if (!ref)
2920 continue;
2921
2922 /* allocate key */
2923 key = alloc_trash_chunk();
2924 if (!key) {
2925 rule_ret = HTTP_RULE_RES_BADREQ;
2926 goto end;
2927 }
2928
2929 /* collect key */
2930 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2931 key->area[key->data] = '\0';
2932
2933 /* perform update */
2934 /* add entry only if it does not already exist */
2935 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2936 if (pat_ref_find_elt(ref, key->area) == NULL)
2937 pat_ref_add(ref, key->area, NULL, NULL);
2938 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2939
2940 free_trash_chunk(key);
2941 break;
2942 }
2943
2944 case ACT_HTTP_SET_MAP: {
2945 struct pat_ref *ref;
2946 struct buffer *key, *value;
2947
2948 /* collect reference */
2949 ref = pat_ref_lookup(rule->arg.map.ref);
2950 if (!ref)
2951 continue;
2952
2953 /* allocate key */
2954 key = alloc_trash_chunk();
2955 if (!key) {
2956 rule_ret = HTTP_RULE_RES_BADREQ;
2957 goto end;
2958 }
2959
2960 /* allocate value */
2961 value = alloc_trash_chunk();
2962 if (!value) {
2963 free_trash_chunk(key);
2964 rule_ret = HTTP_RULE_RES_BADREQ;
2965 goto end;
2966 }
2967
2968 /* collect key */
2969 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2970 key->area[key->data] = '\0';
2971
2972 /* collect value */
2973 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2974 value->area[value->data] = '\0';
2975
2976 /* perform update */
2977 if (pat_ref_find_elt(ref, key->area) != NULL)
2978 /* update entry if it exists */
2979 pat_ref_set(ref, key->area, value->area, NULL);
2980 else
2981 /* insert a new entry */
2982 pat_ref_add(ref, key->area, value->area, NULL);
2983
2984 free_trash_chunk(key);
2985 free_trash_chunk(value);
2986 break;
2987 }
2988
2989 case ACT_HTTP_EARLY_HINT:
2990 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2991 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002992 early_hints = htx_add_early_hint_header(s, early_hints,
2993 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02002994 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002995 if (early_hints == -1) {
2996 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02002997 goto end;
2998 }
2999 break;
3000
3001 case ACT_CUSTOM:
3002 if ((s->req.flags & CF_READ_ERROR) ||
3003 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003004 (px->options & PR_O_ABRT_CLOSE)))
3005 act_flags |= ACT_FLAG_FINAL;
3006
3007 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3008 case ACT_RET_ERR:
3009 case ACT_RET_CONT:
3010 break;
3011 case ACT_RET_STOP:
3012 rule_ret = HTTP_RULE_RES_DONE;
3013 goto end;
3014 case ACT_RET_YIELD:
3015 s->current_rule = rule;
3016 rule_ret = HTTP_RULE_RES_YIELD;
3017 goto end;
3018 }
3019 break;
3020
3021 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3022 /* Note: only the first valid tracking parameter of each
3023 * applies.
3024 */
3025
3026 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3027 struct stktable *t;
3028 struct stksess *ts;
3029 struct stktable_key *key;
3030 void *ptr1, *ptr2;
3031
3032 t = rule->arg.trk_ctr.table.t;
3033 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3034 rule->arg.trk_ctr.expr, NULL);
3035
3036 if (key && (ts = stktable_get_entry(t, key))) {
3037 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3038
3039 /* let's count a new HTTP request as it's the first time we do it */
3040 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3041 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3042 if (ptr1 || ptr2) {
3043 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3044
3045 if (ptr1)
3046 stktable_data_cast(ptr1, http_req_cnt)++;
3047
3048 if (ptr2)
3049 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3050 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3051
3052 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3053
3054 /* If data was modified, we need to touch to re-schedule sync */
3055 stktable_touch_local(t, ts, 0);
3056 }
3057
3058 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3059 if (sess->fe != s->be)
3060 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3061 }
3062 }
3063 break;
3064
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003065 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003066 default:
3067 break;
3068 }
3069 }
3070
3071 end:
3072 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003073 if (htx_reply_103_early_hints(&s->res) == -1)
3074 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003075 }
3076
3077 /* we reached the end of the rules, nothing to report */
3078 return rule_ret;
3079}
3080
3081/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3082 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3083 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3084 * is returned, the process can continue the evaluation of next rule list. If
3085 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3086 * is returned, it means the operation could not be processed and a server error
3087 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3088 * deny rule. If *YIELD is returned, the caller must call again the function
3089 * with the same context.
3090 */
3091static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3092 struct stream *s)
3093{
3094 struct session *sess = strm_sess(s);
3095 struct http_txn *txn = s->txn;
3096 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003097 struct act_rule *rule;
3098 struct http_hdr_ctx ctx;
3099 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3100 int act_flags = 0;
3101
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003102 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003103
3104 /* If "the current_rule_list" match the executed rule list, we are in
3105 * resume condition. If a resume is needed it is always in the action
3106 * and never in the ACL or converters. In this case, we initialise the
3107 * current rule, and go to the action execution point.
3108 */
3109 if (s->current_rule) {
3110 rule = s->current_rule;
3111 s->current_rule = NULL;
3112 if (s->current_rule_list == rules)
3113 goto resume_execution;
3114 }
3115 s->current_rule_list = rules;
3116
3117 list_for_each_entry(rule, rules, list) {
3118 /* check optional condition */
3119 if (rule->cond) {
3120 int ret;
3121
3122 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3123 ret = acl_pass(ret);
3124
3125 if (rule->cond->pol == ACL_COND_UNLESS)
3126 ret = !ret;
3127
3128 if (!ret) /* condition not matched */
3129 continue;
3130 }
3131
3132 act_flags |= ACT_FLAG_FIRST;
3133resume_execution:
3134 switch (rule->action) {
3135 case ACT_ACTION_ALLOW:
3136 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3137 goto end;
3138
3139 case ACT_ACTION_DENY:
3140 txn->flags |= TX_SVDENY;
3141 rule_ret = HTTP_RULE_RES_STOP;
3142 goto end;
3143
3144 case ACT_HTTP_SET_NICE:
3145 s->task->nice = rule->arg.nice;
3146 break;
3147
3148 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003149 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003150 break;
3151
3152 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003153 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003154 break;
3155
3156 case ACT_HTTP_SET_LOGL:
3157 s->logs.level = rule->arg.loglevel;
3158 break;
3159
3160 case ACT_HTTP_REPLACE_HDR:
3161 case ACT_HTTP_REPLACE_VAL:
3162 if (htx_transform_header(s, &s->res, htx,
3163 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3164 &rule->arg.hdr_add.fmt,
3165 &rule->arg.hdr_add.re, rule->action)) {
3166 rule_ret = HTTP_RULE_RES_BADREQ;
3167 goto end;
3168 }
3169 break;
3170
3171 case ACT_HTTP_DEL_HDR:
3172 /* remove all occurrences of the header */
3173 ctx.blk = NULL;
3174 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3175 http_remove_header(htx, &ctx);
3176 break;
3177
3178 case ACT_HTTP_SET_HDR:
3179 case ACT_HTTP_ADD_HDR: {
3180 struct buffer *replace;
3181 struct ist n, v;
3182
3183 replace = alloc_trash_chunk();
3184 if (!replace) {
3185 rule_ret = HTTP_RULE_RES_BADREQ;
3186 goto end;
3187 }
3188
3189 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3190 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3191 v = ist2(replace->area, replace->data);
3192
3193 if (rule->action == ACT_HTTP_SET_HDR) {
3194 /* remove all occurrences of the header */
3195 ctx.blk = NULL;
3196 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3197 http_remove_header(htx, &ctx);
3198 }
3199
3200 if (!http_add_header(htx, n, v)) {
3201 static unsigned char rate_limit = 0;
3202
3203 if ((rate_limit++ & 255) == 0) {
3204 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);
3205 }
3206
Olivier Houcharda798bf52019-03-08 18:52:00 +01003207 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003208 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003209 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003210 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003211 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003212 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003213 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003214 }
3215 free_trash_chunk(replace);
3216 break;
3217 }
3218
3219 case ACT_HTTP_DEL_ACL:
3220 case ACT_HTTP_DEL_MAP: {
3221 struct pat_ref *ref;
3222 struct buffer *key;
3223
3224 /* collect reference */
3225 ref = pat_ref_lookup(rule->arg.map.ref);
3226 if (!ref)
3227 continue;
3228
3229 /* allocate key */
3230 key = alloc_trash_chunk();
3231 if (!key) {
3232 rule_ret = HTTP_RULE_RES_BADREQ;
3233 goto end;
3234 }
3235
3236 /* collect key */
3237 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3238 key->area[key->data] = '\0';
3239
3240 /* perform update */
3241 /* returned code: 1=ok, 0=ko */
3242 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3243 pat_ref_delete(ref, key->area);
3244 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3245
3246 free_trash_chunk(key);
3247 break;
3248 }
3249
3250 case ACT_HTTP_ADD_ACL: {
3251 struct pat_ref *ref;
3252 struct buffer *key;
3253
3254 /* collect reference */
3255 ref = pat_ref_lookup(rule->arg.map.ref);
3256 if (!ref)
3257 continue;
3258
3259 /* allocate key */
3260 key = alloc_trash_chunk();
3261 if (!key) {
3262 rule_ret = HTTP_RULE_RES_BADREQ;
3263 goto end;
3264 }
3265
3266 /* collect key */
3267 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3268 key->area[key->data] = '\0';
3269
3270 /* perform update */
3271 /* check if the entry already exists */
3272 if (pat_ref_find_elt(ref, key->area) == NULL)
3273 pat_ref_add(ref, key->area, NULL, NULL);
3274
3275 free_trash_chunk(key);
3276 break;
3277 }
3278
3279 case ACT_HTTP_SET_MAP: {
3280 struct pat_ref *ref;
3281 struct buffer *key, *value;
3282
3283 /* collect reference */
3284 ref = pat_ref_lookup(rule->arg.map.ref);
3285 if (!ref)
3286 continue;
3287
3288 /* allocate key */
3289 key = alloc_trash_chunk();
3290 if (!key) {
3291 rule_ret = HTTP_RULE_RES_BADREQ;
3292 goto end;
3293 }
3294
3295 /* allocate value */
3296 value = alloc_trash_chunk();
3297 if (!value) {
3298 free_trash_chunk(key);
3299 rule_ret = HTTP_RULE_RES_BADREQ;
3300 goto end;
3301 }
3302
3303 /* collect key */
3304 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3305 key->area[key->data] = '\0';
3306
3307 /* collect value */
3308 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3309 value->area[value->data] = '\0';
3310
3311 /* perform update */
3312 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3313 if (pat_ref_find_elt(ref, key->area) != NULL)
3314 /* update entry if it exists */
3315 pat_ref_set(ref, key->area, value->area, NULL);
3316 else
3317 /* insert a new entry */
3318 pat_ref_add(ref, key->area, value->area, NULL);
3319 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3320 free_trash_chunk(key);
3321 free_trash_chunk(value);
3322 break;
3323 }
3324
3325 case ACT_HTTP_REDIR:
3326 rule_ret = HTTP_RULE_RES_DONE;
3327 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3328 rule_ret = HTTP_RULE_RES_BADREQ;
3329 goto end;
3330
3331 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3332 /* Note: only the first valid tracking parameter of each
3333 * applies.
3334 */
3335 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3336 struct stktable *t;
3337 struct stksess *ts;
3338 struct stktable_key *key;
3339 void *ptr;
3340
3341 t = rule->arg.trk_ctr.table.t;
3342 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3343 rule->arg.trk_ctr.expr, NULL);
3344
3345 if (key && (ts = stktable_get_entry(t, key))) {
3346 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3347
3348 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3349
3350 /* let's count a new HTTP request as it's the first time we do it */
3351 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3352 if (ptr)
3353 stktable_data_cast(ptr, http_req_cnt)++;
3354
3355 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3356 if (ptr)
3357 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3358 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3359
3360 /* When the client triggers a 4xx from the server, it's most often due
3361 * to a missing object or permission. These events should be tracked
3362 * because if they happen often, it may indicate a brute force or a
3363 * vulnerability scan. Normally this is done when receiving the response
3364 * but here we're tracking after this ought to have been done so we have
3365 * to do it on purpose.
3366 */
3367 if ((unsigned)(txn->status - 400) < 100) {
3368 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3369 if (ptr)
3370 stktable_data_cast(ptr, http_err_cnt)++;
3371
3372 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3373 if (ptr)
3374 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3375 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3376 }
3377
3378 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3379
3380 /* If data was modified, we need to touch to re-schedule sync */
3381 stktable_touch_local(t, ts, 0);
3382
3383 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3384 if (sess->fe != s->be)
3385 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3386 }
3387 }
3388 break;
3389
3390 case ACT_CUSTOM:
3391 if ((s->req.flags & CF_READ_ERROR) ||
3392 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003393 (px->options & PR_O_ABRT_CLOSE)))
3394 act_flags |= ACT_FLAG_FINAL;
3395
3396 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3397 case ACT_RET_ERR:
3398 case ACT_RET_CONT:
3399 break;
3400 case ACT_RET_STOP:
3401 rule_ret = HTTP_RULE_RES_STOP;
3402 goto end;
3403 case ACT_RET_YIELD:
3404 s->current_rule = rule;
3405 rule_ret = HTTP_RULE_RES_YIELD;
3406 goto end;
3407 }
3408 break;
3409
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003410 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003411 default:
3412 break;
3413 }
3414 }
3415
3416 end:
3417 /* we reached the end of the rules, nothing to report */
3418 return rule_ret;
3419}
3420
Christopher Faulet33640082018-10-24 11:53:01 +02003421/* Iterate the same filter through all request headers.
3422 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3423 * Since it can manage the switch to another backend, it updates the per-proxy
3424 * DENY stats.
3425 */
3426static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3427{
3428 struct http_txn *txn = s->txn;
3429 struct htx *htx;
3430 struct buffer *hdr = get_trash_chunk();
3431 int32_t pos;
3432
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003433 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003434
3435 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3436 struct htx_blk *blk = htx_get_blk(htx, pos);
3437 enum htx_blk_type type;
3438 struct ist n, v;
3439
3440 next_hdr:
3441 type = htx_get_blk_type(blk);
3442 if (type == HTX_BLK_EOH)
3443 break;
3444 if (type != HTX_BLK_HDR)
3445 continue;
3446
3447 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3448 return 1;
3449 else if (unlikely(txn->flags & TX_CLALLOW) &&
3450 (exp->action == ACT_ALLOW ||
3451 exp->action == ACT_DENY ||
3452 exp->action == ACT_TARPIT))
3453 return 0;
3454
3455 n = htx_get_blk_name(htx, blk);
3456 v = htx_get_blk_value(htx, blk);
3457
Christopher Faulet02e771a2019-02-26 15:36:05 +01003458 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003459 hdr->area[hdr->data++] = ':';
3460 hdr->area[hdr->data++] = ' ';
3461 chunk_memcat(hdr, v.ptr, v.len);
3462
3463 /* Now we have one header in <hdr> */
3464
3465 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3466 struct http_hdr_ctx ctx;
3467 int len;
3468
3469 switch (exp->action) {
3470 case ACT_ALLOW:
3471 txn->flags |= TX_CLALLOW;
3472 goto end;
3473
3474 case ACT_DENY:
3475 txn->flags |= TX_CLDENY;
3476 goto end;
3477
3478 case ACT_TARPIT:
3479 txn->flags |= TX_CLTARPIT;
3480 goto end;
3481
3482 case ACT_REPLACE:
3483 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3484 if (len < 0)
3485 return -1;
3486
3487 http_parse_header(ist2(trash.area, len), &n, &v);
3488 ctx.blk = blk;
3489 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003490 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003491 if (!http_replace_header(htx, &ctx, n, v))
3492 return -1;
3493 if (!ctx.blk)
3494 goto end;
3495 pos = htx_get_blk_pos(htx, blk);
3496 break;
3497
3498 case ACT_REMOVE:
3499 ctx.blk = blk;
3500 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003501 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003502 if (!http_remove_header(htx, &ctx))
3503 return -1;
3504 if (!ctx.blk)
3505 goto end;
3506 pos = htx_get_blk_pos(htx, blk);
3507 goto next_hdr;
3508
3509 }
3510 }
3511 }
3512 end:
3513 return 0;
3514}
3515
3516/* Apply the filter to the request line.
3517 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3518 * or -1 if a replacement resulted in an invalid request line.
3519 * Since it can manage the switch to another backend, it updates the per-proxy
3520 * DENY stats.
3521 */
3522static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3523{
3524 struct http_txn *txn = s->txn;
3525 struct htx *htx;
3526 struct buffer *reqline = get_trash_chunk();
3527 int done;
3528
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003529 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003530
3531 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3532 return 1;
3533 else if (unlikely(txn->flags & TX_CLALLOW) &&
3534 (exp->action == ACT_ALLOW ||
3535 exp->action == ACT_DENY ||
3536 exp->action == ACT_TARPIT))
3537 return 0;
3538 else if (exp->action == ACT_REMOVE)
3539 return 0;
3540
3541 done = 0;
3542
3543 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3544
3545 /* Now we have the request line between cur_ptr and cur_end */
3546 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003547 struct htx_sl *sl = http_find_stline(htx);
3548 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003549 int len;
3550
3551 switch (exp->action) {
3552 case ACT_ALLOW:
3553 txn->flags |= TX_CLALLOW;
3554 done = 1;
3555 break;
3556
3557 case ACT_DENY:
3558 txn->flags |= TX_CLDENY;
3559 done = 1;
3560 break;
3561
3562 case ACT_TARPIT:
3563 txn->flags |= TX_CLTARPIT;
3564 done = 1;
3565 break;
3566
3567 case ACT_REPLACE:
3568 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3569 if (len < 0)
3570 return -1;
3571
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003572 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3573 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3574 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003575 return -1;
3576 done = 1;
3577 break;
3578 }
3579 }
3580 return done;
3581}
3582
3583/*
3584 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3585 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3586 * unparsable request. Since it can manage the switch to another backend, it
3587 * updates the per-proxy DENY stats.
3588 */
3589static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3590{
3591 struct session *sess = s->sess;
3592 struct http_txn *txn = s->txn;
3593 struct hdr_exp *exp;
3594
3595 for (exp = px->req_exp; exp; exp = exp->next) {
3596 int ret;
3597
3598 /*
3599 * The interleaving of transformations and verdicts
3600 * makes it difficult to decide to continue or stop
3601 * the evaluation.
3602 */
3603
3604 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3605 break;
3606
3607 if ((txn->flags & TX_CLALLOW) &&
3608 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3609 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3610 continue;
3611
3612 /* if this filter had a condition, evaluate it now and skip to
3613 * next filter if the condition does not match.
3614 */
3615 if (exp->cond) {
3616 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3617 ret = acl_pass(ret);
3618 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3619 ret = !ret;
3620
3621 if (!ret)
3622 continue;
3623 }
3624
3625 /* Apply the filter to the request line. */
3626 ret = htx_apply_filter_to_req_line(s, req, exp);
3627 if (unlikely(ret < 0))
3628 return -1;
3629
3630 if (likely(ret == 0)) {
3631 /* The filter did not match the request, it can be
3632 * iterated through all headers.
3633 */
3634 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3635 return -1;
3636 }
3637 }
3638 return 0;
3639}
3640
3641/* Iterate the same filter through all response headers contained in <res>.
3642 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3643 */
3644static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3645{
3646 struct http_txn *txn = s->txn;
3647 struct htx *htx;
3648 struct buffer *hdr = get_trash_chunk();
3649 int32_t pos;
3650
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003651 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003652
3653 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3654 struct htx_blk *blk = htx_get_blk(htx, pos);
3655 enum htx_blk_type type;
3656 struct ist n, v;
3657
3658 next_hdr:
3659 type = htx_get_blk_type(blk);
3660 if (type == HTX_BLK_EOH)
3661 break;
3662 if (type != HTX_BLK_HDR)
3663 continue;
3664
3665 if (unlikely(txn->flags & TX_SVDENY))
3666 return 1;
3667 else if (unlikely(txn->flags & TX_SVALLOW) &&
3668 (exp->action == ACT_ALLOW ||
3669 exp->action == ACT_DENY))
3670 return 0;
3671
3672 n = htx_get_blk_name(htx, blk);
3673 v = htx_get_blk_value(htx, blk);
3674
Christopher Faulet02e771a2019-02-26 15:36:05 +01003675 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003676 hdr->area[hdr->data++] = ':';
3677 hdr->area[hdr->data++] = ' ';
3678 chunk_memcat(hdr, v.ptr, v.len);
3679
3680 /* Now we have one header in <hdr> */
3681
3682 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3683 struct http_hdr_ctx ctx;
3684 int len;
3685
3686 switch (exp->action) {
3687 case ACT_ALLOW:
3688 txn->flags |= TX_SVALLOW;
3689 goto end;
3690 break;
3691
3692 case ACT_DENY:
3693 txn->flags |= TX_SVDENY;
3694 goto end;
3695 break;
3696
3697 case ACT_REPLACE:
3698 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3699 if (len < 0)
3700 return -1;
3701
3702 http_parse_header(ist2(trash.area, len), &n, &v);
3703 ctx.blk = blk;
3704 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003705 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003706 if (!http_replace_header(htx, &ctx, n, v))
3707 return -1;
3708 if (!ctx.blk)
3709 goto end;
3710 pos = htx_get_blk_pos(htx, blk);
3711 break;
3712
3713 case ACT_REMOVE:
3714 ctx.blk = blk;
3715 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003716 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003717 if (!http_remove_header(htx, &ctx))
3718 return -1;
3719 if (!ctx.blk)
3720 goto end;
3721 pos = htx_get_blk_pos(htx, blk);
3722 goto next_hdr;
3723 }
3724 }
3725
3726 }
3727 end:
3728 return 0;
3729}
3730
3731/* Apply the filter to the status line in the response buffer <res>.
3732 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3733 * or -1 if a replacement resulted in an invalid status line.
3734 */
3735static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3736{
3737 struct http_txn *txn = s->txn;
3738 struct htx *htx;
3739 struct buffer *resline = get_trash_chunk();
3740 int done;
3741
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003742 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003743
3744 if (unlikely(txn->flags & TX_SVDENY))
3745 return 1;
3746 else if (unlikely(txn->flags & TX_SVALLOW) &&
3747 (exp->action == ACT_ALLOW ||
3748 exp->action == ACT_DENY))
3749 return 0;
3750 else if (exp->action == ACT_REMOVE)
3751 return 0;
3752
3753 done = 0;
3754 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3755
3756 /* Now we have the status line between cur_ptr and cur_end */
3757 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003758 struct htx_sl *sl = http_find_stline(htx);
3759 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003760 int len;
3761
3762 switch (exp->action) {
3763 case ACT_ALLOW:
3764 txn->flags |= TX_SVALLOW;
3765 done = 1;
3766 break;
3767
3768 case ACT_DENY:
3769 txn->flags |= TX_SVDENY;
3770 done = 1;
3771 break;
3772
3773 case ACT_REPLACE:
3774 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3775 if (len < 0)
3776 return -1;
3777
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003778 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3779 sl->info.res.status = strl2ui(code.ptr, code.len);
3780 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003781 return -1;
3782
3783 done = 1;
3784 return 1;
3785 }
3786 }
3787 return done;
3788}
3789
3790/*
3791 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3792 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3793 * unparsable response.
3794 */
3795static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3796{
3797 struct session *sess = s->sess;
3798 struct http_txn *txn = s->txn;
3799 struct hdr_exp *exp;
3800
3801 for (exp = px->rsp_exp; exp; exp = exp->next) {
3802 int ret;
3803
3804 /*
3805 * The interleaving of transformations and verdicts
3806 * makes it difficult to decide to continue or stop
3807 * the evaluation.
3808 */
3809
3810 if (txn->flags & TX_SVDENY)
3811 break;
3812
3813 if ((txn->flags & TX_SVALLOW) &&
3814 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3815 exp->action == ACT_PASS)) {
3816 exp = exp->next;
3817 continue;
3818 }
3819
3820 /* if this filter had a condition, evaluate it now and skip to
3821 * next filter if the condition does not match.
3822 */
3823 if (exp->cond) {
3824 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3825 ret = acl_pass(ret);
3826 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3827 ret = !ret;
3828 if (!ret)
3829 continue;
3830 }
3831
3832 /* Apply the filter to the status line. */
3833 ret = htx_apply_filter_to_sts_line(s, res, exp);
3834 if (unlikely(ret < 0))
3835 return -1;
3836
3837 if (likely(ret == 0)) {
3838 /* The filter did not match the response, it can be
3839 * iterated through all headers.
3840 */
3841 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3842 return -1;
3843 }
3844 }
3845 return 0;
3846}
3847
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003848/*
3849 * Manage client-side cookie. It can impact performance by about 2% so it is
3850 * desirable to call it only when needed. This code is quite complex because
3851 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3852 * highly recommended not to touch this part without a good reason !
3853 */
3854static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3855{
3856 struct session *sess = s->sess;
3857 struct http_txn *txn = s->txn;
3858 struct htx *htx;
3859 struct http_hdr_ctx ctx;
3860 char *hdr_beg, *hdr_end, *del_from;
3861 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3862 int preserve_hdr;
3863
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003864 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003865 ctx.blk = NULL;
3866 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3867 del_from = NULL; /* nothing to be deleted */
3868 preserve_hdr = 0; /* assume we may kill the whole header */
3869
3870 /* Now look for cookies. Conforming to RFC2109, we have to support
3871 * attributes whose name begin with a '$', and associate them with
3872 * the right cookie, if we want to delete this cookie.
3873 * So there are 3 cases for each cookie read :
3874 * 1) it's a special attribute, beginning with a '$' : ignore it.
3875 * 2) it's a server id cookie that we *MAY* want to delete : save
3876 * some pointers on it (last semi-colon, beginning of cookie...)
3877 * 3) it's an application cookie : we *MAY* have to delete a previous
3878 * "special" cookie.
3879 * At the end of loop, if a "special" cookie remains, we may have to
3880 * remove it. If no application cookie persists in the header, we
3881 * *MUST* delete it.
3882 *
3883 * Note: RFC2965 is unclear about the processing of spaces around
3884 * the equal sign in the ATTR=VALUE form. A careful inspection of
3885 * the RFC explicitly allows spaces before it, and not within the
3886 * tokens (attrs or values). An inspection of RFC2109 allows that
3887 * too but section 10.1.3 lets one think that spaces may be allowed
3888 * after the equal sign too, resulting in some (rare) buggy
3889 * implementations trying to do that. So let's do what servers do.
3890 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3891 * allowed quoted strings in values, with any possible character
3892 * after a backslash, including control chars and delimitors, which
3893 * causes parsing to become ambiguous. Browsers also allow spaces
3894 * within values even without quotes.
3895 *
3896 * We have to keep multiple pointers in order to support cookie
3897 * removal at the beginning, middle or end of header without
3898 * corrupting the header. All of these headers are valid :
3899 *
3900 * hdr_beg hdr_end
3901 * | |
3902 * v |
3903 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3904 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3905 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3906 * | | | | | | |
3907 * | | | | | | |
3908 * | | | | | | +--> next
3909 * | | | | | +----> val_end
3910 * | | | | +-----------> val_beg
3911 * | | | +--------------> equal
3912 * | | +----------------> att_end
3913 * | +---------------------> att_beg
3914 * +--------------------------> prev
3915 *
3916 */
3917 hdr_beg = ctx.value.ptr;
3918 hdr_end = hdr_beg + ctx.value.len;
3919 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3920 /* Iterate through all cookies on this line */
3921
3922 /* find att_beg */
3923 att_beg = prev;
3924 if (prev > hdr_beg)
3925 att_beg++;
3926
3927 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3928 att_beg++;
3929
3930 /* find att_end : this is the first character after the last non
3931 * space before the equal. It may be equal to hdr_end.
3932 */
3933 equal = att_end = att_beg;
3934 while (equal < hdr_end) {
3935 if (*equal == '=' || *equal == ',' || *equal == ';')
3936 break;
3937 if (HTTP_IS_SPHT(*equal++))
3938 continue;
3939 att_end = equal;
3940 }
3941
3942 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3943 * is between <att_beg> and <equal>, both may be identical.
3944 */
3945 /* look for end of cookie if there is an equal sign */
3946 if (equal < hdr_end && *equal == '=') {
3947 /* look for the beginning of the value */
3948 val_beg = equal + 1;
3949 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3950 val_beg++;
3951
3952 /* find the end of the value, respecting quotes */
3953 next = http_find_cookie_value_end(val_beg, hdr_end);
3954
3955 /* make val_end point to the first white space or delimitor after the value */
3956 val_end = next;
3957 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3958 val_end--;
3959 }
3960 else
3961 val_beg = val_end = next = equal;
3962
3963 /* We have nothing to do with attributes beginning with
3964 * '$'. However, they will automatically be removed if a
3965 * header before them is removed, since they're supposed
3966 * to be linked together.
3967 */
3968 if (*att_beg == '$')
3969 continue;
3970
3971 /* Ignore cookies with no equal sign */
3972 if (equal == next) {
3973 /* This is not our cookie, so we must preserve it. But if we already
3974 * scheduled another cookie for removal, we cannot remove the
3975 * complete header, but we can remove the previous block itself.
3976 */
3977 preserve_hdr = 1;
3978 if (del_from != NULL) {
3979 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3980 val_end += delta;
3981 next += delta;
3982 hdr_end += delta;
3983 prev = del_from;
3984 del_from = NULL;
3985 }
3986 continue;
3987 }
3988
3989 /* if there are spaces around the equal sign, we need to
3990 * strip them otherwise we'll get trouble for cookie captures,
3991 * or even for rewrites. Since this happens extremely rarely,
3992 * it does not hurt performance.
3993 */
3994 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3995 int stripped_before = 0;
3996 int stripped_after = 0;
3997
3998 if (att_end != equal) {
3999 memmove(att_end, equal, hdr_end - equal);
4000 stripped_before = (att_end - equal);
4001 equal += stripped_before;
4002 val_beg += stripped_before;
4003 }
4004
4005 if (val_beg > equal + 1) {
4006 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4007 stripped_after = (equal + 1) - val_beg;
4008 val_beg += stripped_after;
4009 stripped_before += stripped_after;
4010 }
4011
4012 val_end += stripped_before;
4013 next += stripped_before;
4014 hdr_end += stripped_before;
4015 }
4016 /* now everything is as on the diagram above */
4017
4018 /* First, let's see if we want to capture this cookie. We check
4019 * that we don't already have a client side cookie, because we
4020 * can only capture one. Also as an optimisation, we ignore
4021 * cookies shorter than the declared name.
4022 */
4023 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4024 (val_end - att_beg >= sess->fe->capture_namelen) &&
4025 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4026 int log_len = val_end - att_beg;
4027
4028 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4029 ha_alert("HTTP logging : out of memory.\n");
4030 } else {
4031 if (log_len > sess->fe->capture_len)
4032 log_len = sess->fe->capture_len;
4033 memcpy(txn->cli_cookie, att_beg, log_len);
4034 txn->cli_cookie[log_len] = 0;
4035 }
4036 }
4037
4038 /* Persistence cookies in passive, rewrite or insert mode have the
4039 * following form :
4040 *
4041 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4042 *
4043 * For cookies in prefix mode, the form is :
4044 *
4045 * Cookie: NAME=SRV~VALUE
4046 */
4047 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4048 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4049 struct server *srv = s->be->srv;
4050 char *delim;
4051
4052 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4053 * have the server ID between val_beg and delim, and the original cookie between
4054 * delim+1 and val_end. Otherwise, delim==val_end :
4055 *
4056 * hdr_beg
4057 * |
4058 * v
4059 * NAME=SRV; # in all but prefix modes
4060 * NAME=SRV~OPAQUE ; # in prefix mode
4061 * || || | |+-> next
4062 * || || | +--> val_end
4063 * || || +---------> delim
4064 * || |+------------> val_beg
4065 * || +-------------> att_end = equal
4066 * |+-----------------> att_beg
4067 * +------------------> prev
4068 *
4069 */
4070 if (s->be->ck_opts & PR_CK_PFX) {
4071 for (delim = val_beg; delim < val_end; delim++)
4072 if (*delim == COOKIE_DELIM)
4073 break;
4074 }
4075 else {
4076 char *vbar1;
4077 delim = val_end;
4078 /* Now check if the cookie contains a date field, which would
4079 * appear after a vertical bar ('|') just after the server name
4080 * and before the delimiter.
4081 */
4082 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4083 if (vbar1) {
4084 /* OK, so left of the bar is the server's cookie and
4085 * right is the last seen date. It is a base64 encoded
4086 * 30-bit value representing the UNIX date since the
4087 * epoch in 4-second quantities.
4088 */
4089 int val;
4090 delim = vbar1++;
4091 if (val_end - vbar1 >= 5) {
4092 val = b64tos30(vbar1);
4093 if (val > 0)
4094 txn->cookie_last_date = val << 2;
4095 }
4096 /* look for a second vertical bar */
4097 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4098 if (vbar1 && (val_end - vbar1 > 5)) {
4099 val = b64tos30(vbar1 + 1);
4100 if (val > 0)
4101 txn->cookie_first_date = val << 2;
4102 }
4103 }
4104 }
4105
4106 /* if the cookie has an expiration date and the proxy wants to check
4107 * it, then we do that now. We first check if the cookie is too old,
4108 * then only if it has expired. We detect strict overflow because the
4109 * time resolution here is not great (4 seconds). Cookies with dates
4110 * in the future are ignored if their offset is beyond one day. This
4111 * allows an admin to fix timezone issues without expiring everyone
4112 * and at the same time avoids keeping unwanted side effects for too
4113 * long.
4114 */
4115 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4116 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4117 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4118 txn->flags &= ~TX_CK_MASK;
4119 txn->flags |= TX_CK_OLD;
4120 delim = val_beg; // let's pretend we have not found the cookie
4121 txn->cookie_first_date = 0;
4122 txn->cookie_last_date = 0;
4123 }
4124 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4125 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4126 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4127 txn->flags &= ~TX_CK_MASK;
4128 txn->flags |= TX_CK_EXPIRED;
4129 delim = val_beg; // let's pretend we have not found the cookie
4130 txn->cookie_first_date = 0;
4131 txn->cookie_last_date = 0;
4132 }
4133
4134 /* Here, we'll look for the first running server which supports the cookie.
4135 * This allows to share a same cookie between several servers, for example
4136 * to dedicate backup servers to specific servers only.
4137 * However, to prevent clients from sticking to cookie-less backup server
4138 * when they have incidentely learned an empty cookie, we simply ignore
4139 * empty cookies and mark them as invalid.
4140 * The same behaviour is applied when persistence must be ignored.
4141 */
4142 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4143 srv = NULL;
4144
4145 while (srv) {
4146 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4147 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4148 if ((srv->cur_state != SRV_ST_STOPPED) ||
4149 (s->be->options & PR_O_PERSIST) ||
4150 (s->flags & SF_FORCE_PRST)) {
4151 /* we found the server and we can use it */
4152 txn->flags &= ~TX_CK_MASK;
4153 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4154 s->flags |= SF_DIRECT | SF_ASSIGNED;
4155 s->target = &srv->obj_type;
4156 break;
4157 } else {
4158 /* we found a server, but it's down,
4159 * mark it as such and go on in case
4160 * another one is available.
4161 */
4162 txn->flags &= ~TX_CK_MASK;
4163 txn->flags |= TX_CK_DOWN;
4164 }
4165 }
4166 srv = srv->next;
4167 }
4168
4169 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4170 /* no server matched this cookie or we deliberately skipped it */
4171 txn->flags &= ~TX_CK_MASK;
4172 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4173 txn->flags |= TX_CK_UNUSED;
4174 else
4175 txn->flags |= TX_CK_INVALID;
4176 }
4177
4178 /* depending on the cookie mode, we may have to either :
4179 * - delete the complete cookie if we're in insert+indirect mode, so that
4180 * the server never sees it ;
4181 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004182 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004183 * if we're in cookie prefix mode
4184 */
4185 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4186 int delta; /* negative */
4187
4188 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4189 delta = val_beg - (delim + 1);
4190 val_end += delta;
4191 next += delta;
4192 hdr_end += delta;
4193 del_from = NULL;
4194 preserve_hdr = 1; /* we want to keep this cookie */
4195 }
4196 else if (del_from == NULL &&
4197 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4198 del_from = prev;
4199 }
4200 }
4201 else {
4202 /* This is not our cookie, so we must preserve it. But if we already
4203 * scheduled another cookie for removal, we cannot remove the
4204 * complete header, but we can remove the previous block itself.
4205 */
4206 preserve_hdr = 1;
4207
4208 if (del_from != NULL) {
4209 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4210 if (att_beg >= del_from)
4211 att_beg += delta;
4212 if (att_end >= del_from)
4213 att_end += delta;
4214 val_beg += delta;
4215 val_end += delta;
4216 next += delta;
4217 hdr_end += delta;
4218 prev = del_from;
4219 del_from = NULL;
4220 }
4221 }
4222
4223 /* continue with next cookie on this header line */
4224 att_beg = next;
4225 } /* for each cookie */
4226
4227
4228 /* There are no more cookies on this line.
4229 * We may still have one (or several) marked for deletion at the
4230 * end of the line. We must do this now in two ways :
4231 * - if some cookies must be preserved, we only delete from the
4232 * mark to the end of line ;
4233 * - if nothing needs to be preserved, simply delete the whole header
4234 */
4235 if (del_from) {
4236 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4237 }
4238 if ((hdr_end - hdr_beg) != ctx.value.len) {
4239 if (hdr_beg != hdr_end) {
4240 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004241 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004242 }
4243 else
4244 http_remove_header(htx, &ctx);
4245 }
4246 } /* for each "Cookie header */
4247}
4248
4249/*
4250 * Manage server-side cookies. It can impact performance by about 2% so it is
4251 * desirable to call it only when needed. This function is also used when we
4252 * just need to know if there is a cookie (eg: for check-cache).
4253 */
4254static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4255{
4256 struct session *sess = s->sess;
4257 struct http_txn *txn = s->txn;
4258 struct htx *htx;
4259 struct http_hdr_ctx ctx;
4260 struct server *srv;
4261 char *hdr_beg, *hdr_end;
4262 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4263 int is_cookie2;
4264
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004265 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004266
4267 ctx.blk = NULL;
4268 while (1) {
4269 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4270 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4271 break;
4272 is_cookie2 = 1;
4273 }
4274
4275 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4276 * <prev> points to the colon.
4277 */
4278 txn->flags |= TX_SCK_PRESENT;
4279
4280 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4281 * check-cache is enabled) and we are not interested in checking
4282 * them. Warning, the cookie capture is declared in the frontend.
4283 */
4284 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4285 break;
4286
4287 /* OK so now we know we have to process this response cookie.
4288 * The format of the Set-Cookie header is slightly different
4289 * from the format of the Cookie header in that it does not
4290 * support the comma as a cookie delimiter (thus the header
4291 * cannot be folded) because the Expires attribute described in
4292 * the original Netscape's spec may contain an unquoted date
4293 * with a comma inside. We have to live with this because
4294 * many browsers don't support Max-Age and some browsers don't
4295 * support quoted strings. However the Set-Cookie2 header is
4296 * clean.
4297 *
4298 * We have to keep multiple pointers in order to support cookie
4299 * removal at the beginning, middle or end of header without
4300 * corrupting the header (in case of set-cookie2). A special
4301 * pointer, <scav> points to the beginning of the set-cookie-av
4302 * fields after the first semi-colon. The <next> pointer points
4303 * either to the end of line (set-cookie) or next unquoted comma
4304 * (set-cookie2). All of these headers are valid :
4305 *
4306 * hdr_beg hdr_end
4307 * | |
4308 * v |
4309 * NAME1 = VALUE 1 ; Secure; Path="/" |
4310 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4311 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4312 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4313 * | | | | | | | |
4314 * | | | | | | | +-> next
4315 * | | | | | | +------------> scav
4316 * | | | | | +--------------> val_end
4317 * | | | | +--------------------> val_beg
4318 * | | | +----------------------> equal
4319 * | | +------------------------> att_end
4320 * | +----------------------------> att_beg
4321 * +------------------------------> prev
4322 * -------------------------------> hdr_beg
4323 */
4324 hdr_beg = ctx.value.ptr;
4325 hdr_end = hdr_beg + ctx.value.len;
4326 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4327
4328 /* Iterate through all cookies on this line */
4329
4330 /* find att_beg */
4331 att_beg = prev;
4332 if (prev > hdr_beg)
4333 att_beg++;
4334
4335 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4336 att_beg++;
4337
4338 /* find att_end : this is the first character after the last non
4339 * space before the equal. It may be equal to hdr_end.
4340 */
4341 equal = att_end = att_beg;
4342
4343 while (equal < hdr_end) {
4344 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4345 break;
4346 if (HTTP_IS_SPHT(*equal++))
4347 continue;
4348 att_end = equal;
4349 }
4350
4351 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4352 * is between <att_beg> and <equal>, both may be identical.
4353 */
4354
4355 /* look for end of cookie if there is an equal sign */
4356 if (equal < hdr_end && *equal == '=') {
4357 /* look for the beginning of the value */
4358 val_beg = equal + 1;
4359 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4360 val_beg++;
4361
4362 /* find the end of the value, respecting quotes */
4363 next = http_find_cookie_value_end(val_beg, hdr_end);
4364
4365 /* make val_end point to the first white space or delimitor after the value */
4366 val_end = next;
4367 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4368 val_end--;
4369 }
4370 else {
4371 /* <equal> points to next comma, semi-colon or EOL */
4372 val_beg = val_end = next = equal;
4373 }
4374
4375 if (next < hdr_end) {
4376 /* Set-Cookie2 supports multiple cookies, and <next> points to
4377 * a colon or semi-colon before the end. So skip all attr-value
4378 * pairs and look for the next comma. For Set-Cookie, since
4379 * commas are permitted in values, skip to the end.
4380 */
4381 if (is_cookie2)
4382 next = http_find_hdr_value_end(next, hdr_end);
4383 else
4384 next = hdr_end;
4385 }
4386
4387 /* Now everything is as on the diagram above */
4388
4389 /* Ignore cookies with no equal sign */
4390 if (equal == val_end)
4391 continue;
4392
4393 /* If there are spaces around the equal sign, we need to
4394 * strip them otherwise we'll get trouble for cookie captures,
4395 * or even for rewrites. Since this happens extremely rarely,
4396 * it does not hurt performance.
4397 */
4398 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4399 int stripped_before = 0;
4400 int stripped_after = 0;
4401
4402 if (att_end != equal) {
4403 memmove(att_end, equal, hdr_end - equal);
4404 stripped_before = (att_end - equal);
4405 equal += stripped_before;
4406 val_beg += stripped_before;
4407 }
4408
4409 if (val_beg > equal + 1) {
4410 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4411 stripped_after = (equal + 1) - val_beg;
4412 val_beg += stripped_after;
4413 stripped_before += stripped_after;
4414 }
4415
4416 val_end += stripped_before;
4417 next += stripped_before;
4418 hdr_end += stripped_before;
4419
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004420 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4421 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004422 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004423 }
4424
4425 /* First, let's see if we want to capture this cookie. We check
4426 * that we don't already have a server side cookie, because we
4427 * can only capture one. Also as an optimisation, we ignore
4428 * cookies shorter than the declared name.
4429 */
4430 if (sess->fe->capture_name != NULL &&
4431 txn->srv_cookie == NULL &&
4432 (val_end - att_beg >= sess->fe->capture_namelen) &&
4433 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4434 int log_len = val_end - att_beg;
4435 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4436 ha_alert("HTTP logging : out of memory.\n");
4437 }
4438 else {
4439 if (log_len > sess->fe->capture_len)
4440 log_len = sess->fe->capture_len;
4441 memcpy(txn->srv_cookie, att_beg, log_len);
4442 txn->srv_cookie[log_len] = 0;
4443 }
4444 }
4445
4446 srv = objt_server(s->target);
4447 /* now check if we need to process it for persistence */
4448 if (!(s->flags & SF_IGNORE_PRST) &&
4449 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4450 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4451 /* assume passive cookie by default */
4452 txn->flags &= ~TX_SCK_MASK;
4453 txn->flags |= TX_SCK_FOUND;
4454
4455 /* If the cookie is in insert mode on a known server, we'll delete
4456 * this occurrence because we'll insert another one later.
4457 * We'll delete it too if the "indirect" option is set and we're in
4458 * a direct access.
4459 */
4460 if (s->be->ck_opts & PR_CK_PSV) {
4461 /* The "preserve" flag was set, we don't want to touch the
4462 * server's cookie.
4463 */
4464 }
4465 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4466 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4467 /* this cookie must be deleted */
4468 if (prev == hdr_beg && next == hdr_end) {
4469 /* whole header */
4470 http_remove_header(htx, &ctx);
4471 /* note: while both invalid now, <next> and <hdr_end>
4472 * are still equal, so the for() will stop as expected.
4473 */
4474 } else {
4475 /* just remove the value */
4476 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4477 next = prev;
4478 hdr_end += delta;
4479 }
4480 txn->flags &= ~TX_SCK_MASK;
4481 txn->flags |= TX_SCK_DELETED;
4482 /* and go on with next cookie */
4483 }
4484 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4485 /* replace bytes val_beg->val_end with the cookie name associated
4486 * with this server since we know it.
4487 */
4488 int sliding, delta;
4489
4490 ctx.value = ist2(val_beg, val_end - val_beg);
4491 ctx.lws_before = ctx.lws_after = 0;
4492 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4493 delta = srv->cklen - (val_end - val_beg);
4494 sliding = (ctx.value.ptr - val_beg);
4495 hdr_beg += sliding;
4496 val_beg += sliding;
4497 next += sliding + delta;
4498 hdr_end += sliding + delta;
4499
4500 txn->flags &= ~TX_SCK_MASK;
4501 txn->flags |= TX_SCK_REPLACED;
4502 }
4503 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4504 /* insert the cookie name associated with this server
4505 * before existing cookie, and insert a delimiter between them..
4506 */
4507 int sliding, delta;
4508 ctx.value = ist2(val_beg, 0);
4509 ctx.lws_before = ctx.lws_after = 0;
4510 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4511 delta = srv->cklen + 1;
4512 sliding = (ctx.value.ptr - val_beg);
4513 hdr_beg += sliding;
4514 val_beg += sliding;
4515 next += sliding + delta;
4516 hdr_end += sliding + delta;
4517
4518 val_beg[srv->cklen] = COOKIE_DELIM;
4519 txn->flags &= ~TX_SCK_MASK;
4520 txn->flags |= TX_SCK_REPLACED;
4521 }
4522 }
4523 /* that's done for this cookie, check the next one on the same
4524 * line when next != hdr_end (only if is_cookie2).
4525 */
4526 }
4527 }
4528}
4529
Christopher Faulet25a02f62018-10-24 12:00:25 +02004530/*
4531 * Parses the Cache-Control and Pragma request header fields to determine if
4532 * the request may be served from the cache and/or if it is cacheable. Updates
4533 * s->txn->flags.
4534 */
4535void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4536{
4537 struct http_txn *txn = s->txn;
4538 struct htx *htx;
4539 int32_t pos;
4540 int pragma_found, cc_found, i;
4541
4542 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4543 return; /* nothing more to do here */
4544
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004545 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004546 pragma_found = cc_found = 0;
4547 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4548 struct htx_blk *blk = htx_get_blk(htx, pos);
4549 enum htx_blk_type type = htx_get_blk_type(blk);
4550 struct ist n, v;
4551
4552 if (type == HTX_BLK_EOH)
4553 break;
4554 if (type != HTX_BLK_HDR)
4555 continue;
4556
4557 n = htx_get_blk_name(htx, blk);
4558 v = htx_get_blk_value(htx, blk);
4559
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004560 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004561 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4562 pragma_found = 1;
4563 continue;
4564 }
4565 }
4566
4567 /* Don't use the cache and don't try to store if we found the
4568 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004569 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004570 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4571 txn->flags |= TX_CACHE_IGNORE;
4572 continue;
4573 }
4574
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004575 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004576 continue;
4577
4578 /* OK, right now we know we have a cache-control header */
4579 cc_found = 1;
4580 if (!v.len) /* no info */
4581 continue;
4582
4583 i = 0;
4584 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4585 !isspace((unsigned char)*(v.ptr+i)))
4586 i++;
4587
4588 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4589 * values after max-age, max-stale nor min-fresh, we simply don't
4590 * use the cache when they're specified.
4591 */
4592 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4593 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4594 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4595 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4596 txn->flags |= TX_CACHE_IGNORE;
4597 continue;
4598 }
4599
4600 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4601 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4602 continue;
4603 }
4604 }
4605
4606 /* RFC7234#5.4:
4607 * When the Cache-Control header field is also present and
4608 * understood in a request, Pragma is ignored.
4609 * When the Cache-Control header field is not present in a
4610 * request, caches MUST consider the no-cache request
4611 * pragma-directive as having the same effect as if
4612 * "Cache-Control: no-cache" were present.
4613 */
4614 if (!cc_found && pragma_found)
4615 txn->flags |= TX_CACHE_IGNORE;
4616}
4617
4618/*
4619 * Check if response is cacheable or not. Updates s->txn->flags.
4620 */
4621void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4622{
4623 struct http_txn *txn = s->txn;
4624 struct htx *htx;
4625 int32_t pos;
4626 int i;
4627
4628 if (txn->status < 200) {
4629 /* do not try to cache interim responses! */
4630 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4631 return;
4632 }
4633
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004634 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004635 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4636 struct htx_blk *blk = htx_get_blk(htx, pos);
4637 enum htx_blk_type type = htx_get_blk_type(blk);
4638 struct ist n, v;
4639
4640 if (type == HTX_BLK_EOH)
4641 break;
4642 if (type != HTX_BLK_HDR)
4643 continue;
4644
4645 n = htx_get_blk_name(htx, blk);
4646 v = htx_get_blk_value(htx, blk);
4647
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004648 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004649 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4650 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4651 return;
4652 }
4653 }
4654
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004655 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004656 continue;
4657
4658 /* OK, right now we know we have a cache-control header */
4659 if (!v.len) /* no info */
4660 continue;
4661
4662 i = 0;
4663 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4664 !isspace((unsigned char)*(v.ptr+i)))
4665 i++;
4666
4667 /* we have a complete value between v.ptr and (v.ptr+i) */
4668 if (i < v.len && *(v.ptr + i) == '=') {
4669 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4670 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4671 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4672 continue;
4673 }
4674
4675 /* we have something of the form no-cache="set-cookie" */
4676 if ((v.len >= 21) &&
4677 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4678 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4679 txn->flags &= ~TX_CACHE_COOK;
4680 continue;
4681 }
4682
4683 /* OK, so we know that either p2 points to the end of string or to a comma */
4684 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4685 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4686 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4687 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4688 return;
4689 }
4690
4691 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4692 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4693 continue;
4694 }
4695 }
4696}
4697
Christopher Faulet64159df2018-10-24 21:15:35 +02004698/* send a server's name with an outgoing request over an established connection.
4699 * Note: this function is designed to be called once the request has been
4700 * scheduled for being forwarded. This is the reason why the number of forwarded
4701 * bytes have to be adjusted.
4702 */
4703int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4704{
4705 struct htx *htx;
4706 struct http_hdr_ctx ctx;
4707 struct ist hdr;
4708 uint32_t data;
4709
4710 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004711 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004712 data = htx->data;
4713
4714 ctx.blk = NULL;
4715 while (http_find_header(htx, hdr, &ctx, 1))
4716 http_remove_header(htx, &ctx);
4717 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4718
4719 if (co_data(&s->req)) {
4720 if (data >= htx->data)
4721 c_rew(&s->req, data - htx->data);
4722 else
4723 c_adv(&s->req, htx->data - data);
4724 }
4725 return 0;
4726}
4727
Christopher Faulet377c5a52018-10-24 21:21:30 +02004728/*
4729 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4730 * for the current backend.
4731 *
4732 * It is assumed that the request is either a HEAD, GET, or POST and that the
4733 * uri_auth field is valid.
4734 *
4735 * Returns 1 if stats should be provided, otherwise 0.
4736 */
4737static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4738{
4739 struct uri_auth *uri_auth = backend->uri_auth;
4740 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004741 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004742 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004743
4744 if (!uri_auth)
4745 return 0;
4746
4747 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4748 return 0;
4749
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004750 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004751 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004752 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004753
4754 /* check URI size */
4755 if (uri_auth->uri_len > uri.len)
4756 return 0;
4757
4758 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4759 return 0;
4760
4761 return 1;
4762}
4763
4764/* This function prepares an applet to handle the stats. It can deal with the
4765 * "100-continue" expectation, check that admin rules are met for POST requests,
4766 * and program a response message if something was unexpected. It cannot fail
4767 * and always relies on the stats applet to complete the job. It does not touch
4768 * analysers nor counters, which are left to the caller. It does not touch
4769 * s->target which is supposed to already point to the stats applet. The caller
4770 * is expected to have already assigned an appctx to the stream.
4771 */
4772static int htx_handle_stats(struct stream *s, struct channel *req)
4773{
4774 struct stats_admin_rule *stats_admin_rule;
4775 struct stream_interface *si = &s->si[1];
4776 struct session *sess = s->sess;
4777 struct http_txn *txn = s->txn;
4778 struct http_msg *msg = &txn->req;
4779 struct uri_auth *uri_auth = s->be->uri_auth;
4780 const char *h, *lookup, *end;
4781 struct appctx *appctx;
4782 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004783 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004784
4785 appctx = si_appctx(si);
4786 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4787 appctx->st1 = appctx->st2 = 0;
4788 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4789 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4790 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4791 appctx->ctx.stats.flags |= STAT_CHUNKED;
4792
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004793 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004794 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004795 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4796 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797
4798 for (h = lookup; h <= end - 3; h++) {
4799 if (memcmp(h, ";up", 3) == 0) {
4800 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4801 break;
4802 }
4803 }
4804
4805 if (uri_auth->refresh) {
4806 for (h = lookup; h <= end - 10; h++) {
4807 if (memcmp(h, ";norefresh", 10) == 0) {
4808 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4809 break;
4810 }
4811 }
4812 }
4813
4814 for (h = lookup; h <= end - 4; h++) {
4815 if (memcmp(h, ";csv", 4) == 0) {
4816 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4817 break;
4818 }
4819 }
4820
4821 for (h = lookup; h <= end - 6; h++) {
4822 if (memcmp(h, ";typed", 6) == 0) {
4823 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4824 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4825 break;
4826 }
4827 }
4828
4829 for (h = lookup; h <= end - 8; h++) {
4830 if (memcmp(h, ";st=", 4) == 0) {
4831 int i;
4832 h += 4;
4833 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4834 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4835 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4836 appctx->ctx.stats.st_code = i;
4837 break;
4838 }
4839 }
4840 break;
4841 }
4842 }
4843
4844 appctx->ctx.stats.scope_str = 0;
4845 appctx->ctx.stats.scope_len = 0;
4846 for (h = lookup; h <= end - 8; h++) {
4847 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4848 int itx = 0;
4849 const char *h2;
4850 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4851 const char *err;
4852
4853 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4854 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004855 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4856 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004857 if (*h == ';' || *h == '&' || *h == ' ')
4858 break;
4859 itx++;
4860 h++;
4861 }
4862
4863 if (itx > STAT_SCOPE_TXT_MAXLEN)
4864 itx = STAT_SCOPE_TXT_MAXLEN;
4865 appctx->ctx.stats.scope_len = itx;
4866
4867 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4868 memcpy(scope_txt, h2, itx);
4869 scope_txt[itx] = '\0';
4870 err = invalid_char(scope_txt);
4871 if (err) {
4872 /* bad char in search text => clear scope */
4873 appctx->ctx.stats.scope_str = 0;
4874 appctx->ctx.stats.scope_len = 0;
4875 }
4876 break;
4877 }
4878 }
4879
4880 /* now check whether we have some admin rules for this request */
4881 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4882 int ret = 1;
4883
4884 if (stats_admin_rule->cond) {
4885 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4886 ret = acl_pass(ret);
4887 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4888 ret = !ret;
4889 }
4890
4891 if (ret) {
4892 /* no rule, or the rule matches */
4893 appctx->ctx.stats.flags |= STAT_ADMIN;
4894 break;
4895 }
4896 }
4897
Christopher Faulet5d45e382019-02-27 15:15:23 +01004898 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4899 appctx->st0 = STAT_HTTP_HEAD;
4900 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004901 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004902 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004903 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004904 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004905 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4906 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4907 appctx->st0 = STAT_HTTP_LAST;
4908 }
4909 }
4910 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004911 /* Unsupported method */
4912 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4913 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4914 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004915 }
4916
4917 s->task->nice = -32; /* small boost for HTTP statistics */
4918 return 1;
4919}
4920
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004921void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4922{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004923 struct channel *req = &s->req;
4924 struct channel *res = &s->res;
4925 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004926 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004927 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004928 struct ist path, location;
4929 unsigned int flags;
4930 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004931
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004932 /*
4933 * Create the location
4934 */
4935 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004936
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004937 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004938 /* special prefix "/" means don't change URL */
4939 srv = __objt_server(s->target);
4940 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4941 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4942 return;
4943 }
4944
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004945 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004946 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004947 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004948 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004949 if (!path.ptr)
4950 return;
4951
4952 if (!chunk_memcat(&trash, path.ptr, path.len))
4953 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004954 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004955
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004956 /*
4957 * Create the 302 respone
4958 */
4959 htx = htx_from_buf(&res->buf);
4960 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4961 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4962 ist("HTTP/1.1"), ist("302"), ist("Found"));
4963 if (!sl)
4964 goto fail;
4965 sl->info.res.status = 302;
4966 s->txn->status = 302;
4967
4968 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4969 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4970 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4971 !htx_add_header(htx, ist("Location"), location))
4972 goto fail;
4973
4974 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4975 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004976
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004977 /*
4978 * Send the message
4979 */
4980 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004981 c_adv(res, data);
4982 res->total += data;
4983
4984 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004985 si_shutr(si);
4986 si_shutw(si);
4987 si->err_type = SI_ET_NONE;
4988 si->state = SI_ST_CLO;
4989
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004990 channel_auto_read(req);
4991 channel_abort(req);
4992 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01004993 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004994 channel_auto_read(res);
4995 channel_auto_close(res);
4996
4997 if (!(s->flags & SF_ERR_MASK))
4998 s->flags |= SF_ERR_LOCAL;
4999 if (!(s->flags & SF_FINST_MASK))
5000 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005001
5002 /* FIXME: we should increase a counter of redirects per server and per backend. */
5003 srv_inc_sess_ctr(srv);
5004 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005005 return;
5006
5007 fail:
5008 /* If an error occurred, remove the incomplete HTTP response from the
5009 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005010 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011}
5012
Christopher Fauletf2824e62018-10-01 12:12:37 +02005013/* This function terminates the request because it was completly analyzed or
5014 * because an error was triggered during the body forwarding.
5015 */
5016static void htx_end_request(struct stream *s)
5017{
5018 struct channel *chn = &s->req;
5019 struct http_txn *txn = s->txn;
5020
5021 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5022 now_ms, __FUNCTION__, s,
5023 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5024 s->req.analysers, s->res.analysers);
5025
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005026 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5027 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005028 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005029 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005030 goto end;
5031 }
5032
5033 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5034 return;
5035
5036 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005037 /* No need to read anymore, the request was completely parsed.
5038 * We can shut the read side unless we want to abort_on_close,
5039 * or we have a POST request. The issue with POST requests is
5040 * that some browsers still send a CRLF after the request, and
5041 * this CRLF must be read so that it does not remain in the kernel
5042 * buffers, otherwise a close could cause an RST on some systems
5043 * (eg: Linux).
5044 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005045 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005046 channel_dont_read(chn);
5047
5048 /* if the server closes the connection, we want to immediately react
5049 * and close the socket to save packets and syscalls.
5050 */
5051 s->si[1].flags |= SI_FL_NOHALF;
5052
5053 /* In any case we've finished parsing the request so we must
5054 * disable Nagle when sending data because 1) we're not going
5055 * to shut this side, and 2) the server is waiting for us to
5056 * send pending data.
5057 */
5058 chn->flags |= CF_NEVER_WAIT;
5059
Christopher Fauletd01ce402019-01-02 17:44:13 +01005060 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5061 /* The server has not finished to respond, so we
5062 * don't want to move in order not to upset it.
5063 */
5064 return;
5065 }
5066
Christopher Fauletf2824e62018-10-01 12:12:37 +02005067 /* When we get here, it means that both the request and the
5068 * response have finished receiving. Depending on the connection
5069 * mode, we'll have to wait for the last bytes to leave in either
5070 * direction, and sometimes for a close to be effective.
5071 */
5072 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5073 /* Tunnel mode will not have any analyser so it needs to
5074 * poll for reads.
5075 */
5076 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005077 if (b_data(&chn->buf))
5078 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005079 txn->req.msg_state = HTTP_MSG_TUNNEL;
5080 }
5081 else {
5082 /* we're not expecting any new data to come for this
5083 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005084 *
5085 * However, there is an exception if the response
5086 * length is undefined. In this case, we need to wait
5087 * the close from the server. The response will be
5088 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005089 */
5090 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5091 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005092 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005093
5094 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5095 channel_shutr_now(chn);
5096 channel_shutw_now(chn);
5097 }
5098 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 goto check_channel_flags;
5100 }
5101
5102 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5103 http_msg_closing:
5104 /* nothing else to forward, just waiting for the output buffer
5105 * to be empty and for the shutw_now to take effect.
5106 */
5107 if (channel_is_empty(chn)) {
5108 txn->req.msg_state = HTTP_MSG_CLOSED;
5109 goto http_msg_closed;
5110 }
5111 else if (chn->flags & CF_SHUTW) {
5112 txn->req.err_state = txn->req.msg_state;
5113 txn->req.msg_state = HTTP_MSG_ERROR;
5114 goto end;
5115 }
5116 return;
5117 }
5118
5119 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5120 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 /* if we don't know whether the server will close, we need to hard close */
5122 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5123 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005124 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005125 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005126 channel_dont_read(chn);
5127 goto end;
5128 }
5129
5130 check_channel_flags:
5131 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5132 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5133 /* if we've just closed an output, let's switch */
5134 txn->req.msg_state = HTTP_MSG_CLOSING;
5135 goto http_msg_closing;
5136 }
5137
5138 end:
5139 chn->analysers &= AN_REQ_FLT_END;
5140 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5141 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5142 channel_auto_close(chn);
5143 channel_auto_read(chn);
5144}
5145
5146
5147/* This function terminates the response because it was completly analyzed or
5148 * because an error was triggered during the body forwarding.
5149 */
5150static void htx_end_response(struct stream *s)
5151{
5152 struct channel *chn = &s->res;
5153 struct http_txn *txn = s->txn;
5154
5155 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5156 now_ms, __FUNCTION__, s,
5157 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5158 s->req.analysers, s->res.analysers);
5159
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005160 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5161 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005162 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005163 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005164 goto end;
5165 }
5166
5167 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5168 return;
5169
5170 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5171 /* In theory, we don't need to read anymore, but we must
5172 * still monitor the server connection for a possible close
5173 * while the request is being uploaded, so we don't disable
5174 * reading.
5175 */
5176 /* channel_dont_read(chn); */
5177
5178 if (txn->req.msg_state < HTTP_MSG_DONE) {
5179 /* The client seems to still be sending data, probably
5180 * because we got an error response during an upload.
5181 * We have the choice of either breaking the connection
5182 * or letting it pass through. Let's do the later.
5183 */
5184 return;
5185 }
5186
5187 /* When we get here, it means that both the request and the
5188 * response have finished receiving. Depending on the connection
5189 * mode, we'll have to wait for the last bytes to leave in either
5190 * direction, and sometimes for a close to be effective.
5191 */
5192 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5193 channel_auto_read(chn);
5194 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005195 if (b_data(&chn->buf))
5196 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5198 }
5199 else {
5200 /* we're not expecting any new data to come for this
5201 * transaction, so we can close it.
5202 */
5203 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5204 channel_shutr_now(chn);
5205 channel_shutw_now(chn);
5206 }
5207 }
5208 goto check_channel_flags;
5209 }
5210
5211 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5212 http_msg_closing:
5213 /* nothing else to forward, just waiting for the output buffer
5214 * to be empty and for the shutw_now to take effect.
5215 */
5216 if (channel_is_empty(chn)) {
5217 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5218 goto http_msg_closed;
5219 }
5220 else if (chn->flags & CF_SHUTW) {
5221 txn->rsp.err_state = txn->rsp.msg_state;
5222 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005223 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005224 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005225 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005226 goto end;
5227 }
5228 return;
5229 }
5230
5231 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5232 http_msg_closed:
5233 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005234 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005235 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005236 goto end;
5237 }
5238
5239 check_channel_flags:
5240 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5241 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5242 /* if we've just closed an output, let's switch */
5243 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5244 goto http_msg_closing;
5245 }
5246
5247 end:
5248 chn->analysers &= AN_RES_FLT_END;
5249 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5250 chn->analysers |= AN_RES_FLT_XFER_DATA;
5251 channel_auto_close(chn);
5252 channel_auto_read(chn);
5253}
5254
Christopher Faulet0f226952018-10-22 09:29:56 +02005255void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5256 int finst, const struct buffer *msg)
5257{
5258 channel_auto_read(si_oc(si));
5259 channel_abort(si_oc(si));
5260 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005261 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005262 channel_auto_close(si_ic(si));
5263 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005264
5265 /* <msg> is an HTX structure. So we copy it in the response's
5266 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005267 if (msg) {
5268 struct channel *chn = si_ic(si);
5269 struct htx *htx;
5270
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005271 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005272 chn->buf.data = msg->data;
5273 memcpy(chn->buf.area, msg->area, msg->data);
5274 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005275 c_adv(chn, htx->data);
5276 chn->total += htx->data;
5277 }
5278 if (!(s->flags & SF_ERR_MASK))
5279 s->flags |= err;
5280 if (!(s->flags & SF_FINST_MASK))
5281 s->flags |= finst;
5282}
5283
5284void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5285{
5286 channel_auto_read(&s->req);
5287 channel_abort(&s->req);
5288 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005289 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5290 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005291
5292 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005293
5294 /* <msg> is an HTX structure. So we copy it in the response's
5295 * channel */
5296 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005297 if (msg) {
5298 struct channel *chn = &s->res;
5299 struct htx *htx;
5300
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005301 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005302 chn->buf.data = msg->data;
5303 memcpy(chn->buf.area, msg->area, msg->data);
5304 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005305 c_adv(chn, htx->data);
5306 chn->total += htx->data;
5307 }
5308
5309 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5310 channel_auto_read(&s->res);
5311 channel_auto_close(&s->res);
5312 channel_shutr_now(&s->res);
5313}
5314
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005315struct buffer *htx_error_message(struct stream *s)
5316{
5317 const int msgnum = http_get_status_idx(s->txn->status);
5318
5319 if (s->be->errmsg[msgnum].area)
5320 return &s->be->errmsg[msgnum];
5321 else if (strm_fe(s)->errmsg[msgnum].area)
5322 return &strm_fe(s)->errmsg[msgnum];
5323 else
5324 return &htx_err_chunks[msgnum];
5325}
5326
5327
Christopher Faulet4a28a532019-03-01 11:19:40 +01005328/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5329 * on success and -1 on error.
5330 */
5331static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5332{
5333 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5334 * then we must send an HTTP/1.1 100 Continue intermediate response.
5335 */
5336 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5337 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5338 struct ist hdr = { .ptr = "Expect", .len = 6 };
5339 struct http_hdr_ctx ctx;
5340
5341 ctx.blk = NULL;
5342 /* Expect is allowed in 1.1, look for it */
5343 if (http_find_header(htx, hdr, &ctx, 0) &&
5344 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5345 if (htx_reply_100_continue(s) == -1)
5346 return -1;
5347 http_remove_header(htx, &ctx);
5348 }
5349 }
5350 return 0;
5351}
5352
Christopher Faulet23a3c792018-11-28 10:01:23 +01005353/* Send a 100-Continue response to the client. It returns 0 on success and -1
5354 * on error. The response channel is updated accordingly.
5355 */
5356static int htx_reply_100_continue(struct stream *s)
5357{
5358 struct channel *res = &s->res;
5359 struct htx *htx = htx_from_buf(&res->buf);
5360 struct htx_sl *sl;
5361 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5362 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5363 size_t data;
5364
5365 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5366 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5367 if (!sl)
5368 goto fail;
5369 sl->info.res.status = 100;
5370
5371 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5372 goto fail;
5373
5374 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005375 c_adv(res, data);
5376 res->total += data;
5377 return 0;
5378
5379 fail:
5380 /* If an error occurred, remove the incomplete HTTP response from the
5381 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005382 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005383 return -1;
5384}
5385
Christopher Faulet12c51e22018-11-28 15:59:42 +01005386
5387/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5388 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5389 * error. The response channel is updated accordingly.
5390 */
5391static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5392{
5393 struct channel *res = &s->res;
5394 struct htx *htx = htx_from_buf(&res->buf);
5395 struct htx_sl *sl;
5396 struct ist code, body;
5397 int status;
5398 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5399 size_t data;
5400
5401 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5402 status = 401;
5403 code = ist("401");
5404 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5405 "You need a valid user and password to access this content.\n"
5406 "</body></html>\n");
5407 }
5408 else {
5409 status = 407;
5410 code = ist("407");
5411 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5412 "You need a valid user and password to access this content.\n"
5413 "</body></html>\n");
5414 }
5415
5416 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5417 ist("HTTP/1.1"), code, ist("Unauthorized"));
5418 if (!sl)
5419 goto fail;
5420 sl->info.res.status = status;
5421 s->txn->status = status;
5422
5423 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5424 goto fail;
5425
5426 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5427 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005428 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5429 goto fail;
5430 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5431 goto fail;
5432 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005433 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005434 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5435 goto fail;
5436
5437 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005438 c_adv(res, data);
5439 res->total += data;
5440
5441 channel_auto_read(&s->req);
5442 channel_abort(&s->req);
5443 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005444 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005445
5446 res->wex = tick_add_ifset(now_ms, res->wto);
5447 channel_auto_read(res);
5448 channel_auto_close(res);
5449 channel_shutr_now(res);
5450 return 0;
5451
5452 fail:
5453 /* If an error occurred, remove the incomplete HTTP response from the
5454 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005455 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456 return -1;
5457}
5458
Christopher Faulet0f226952018-10-22 09:29:56 +02005459/*
5460 * Capture headers from message <htx> according to header list <cap_hdr>, and
5461 * fill the <cap> pointers appropriately.
5462 */
5463static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5464{
5465 struct cap_hdr *h;
5466 int32_t pos;
5467
5468 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5469 struct htx_blk *blk = htx_get_blk(htx, pos);
5470 enum htx_blk_type type = htx_get_blk_type(blk);
5471 struct ist n, v;
5472
5473 if (type == HTX_BLK_EOH)
5474 break;
5475 if (type != HTX_BLK_HDR)
5476 continue;
5477
5478 n = htx_get_blk_name(htx, blk);
5479
5480 for (h = cap_hdr; h; h = h->next) {
5481 if (h->namelen && (h->namelen == n.len) &&
5482 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5483 if (cap[h->index] == NULL)
5484 cap[h->index] =
5485 pool_alloc(h->pool);
5486
5487 if (cap[h->index] == NULL) {
5488 ha_alert("HTTP capture : out of memory.\n");
5489 break;
5490 }
5491
5492 v = htx_get_blk_value(htx, blk);
5493 if (v.len > h->len)
5494 v.len = h->len;
5495
5496 memcpy(cap[h->index], v.ptr, v.len);
5497 cap[h->index][v.len]=0;
5498 }
5499 }
5500 }
5501}
5502
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005503/* Delete a value in a header between delimiters <from> and <next>. The header
5504 * itself is delimited by <start> and <end> pointers. The number of characters
5505 * displaced is returned, and the pointer to the first delimiter is updated if
5506 * required. The function tries as much as possible to respect the following
5507 * principles :
5508 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5509 * in which case <next> is simply removed
5510 * - set exactly one space character after the new first delimiter, unless there
5511 * are not enough characters in the block being moved to do so.
5512 * - remove unneeded spaces before the previous delimiter and after the new
5513 * one.
5514 *
5515 * It is the caller's responsibility to ensure that :
5516 * - <from> points to a valid delimiter or <start> ;
5517 * - <next> points to a valid delimiter or <end> ;
5518 * - there are non-space chars before <from>.
5519 */
5520static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5521{
5522 char *prev = *from;
5523
5524 if (prev == start) {
5525 /* We're removing the first value. eat the semicolon, if <next>
5526 * is lower than <end> */
5527 if (next < end)
5528 next++;
5529
5530 while (next < end && HTTP_IS_SPHT(*next))
5531 next++;
5532 }
5533 else {
5534 /* Remove useless spaces before the old delimiter. */
5535 while (HTTP_IS_SPHT(*(prev-1)))
5536 prev--;
5537 *from = prev;
5538
5539 /* copy the delimiter and if possible a space if we're
5540 * not at the end of the line.
5541 */
5542 if (next < end) {
5543 *prev++ = *next++;
5544 if (prev + 1 < next)
5545 *prev++ = ' ';
5546 while (next < end && HTTP_IS_SPHT(*next))
5547 next++;
5548 }
5549 }
5550 memmove(prev, next, end - next);
5551 return (prev - next);
5552}
5553
Christopher Faulet0f226952018-10-22 09:29:56 +02005554
5555/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005556 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005557 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005558static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005559{
5560 struct ist dst = ist2(str, 0);
5561
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005562 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005563 goto end;
5564 if (dst.len + 1 > len)
5565 goto end;
5566 dst.ptr[dst.len++] = ' ';
5567
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005568 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005569 goto end;
5570 if (dst.len + 1 > len)
5571 goto end;
5572 dst.ptr[dst.len++] = ' ';
5573
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005574 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005575 end:
5576 return dst.len;
5577}
5578
Christopher Fauletf0523542018-10-24 11:06:58 +02005579/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005580 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005581 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005582static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005583{
5584 struct ist dst = ist2(str, 0);
5585
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005586 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005587 goto end;
5588 if (dst.len + 1 > len)
5589 goto end;
5590 dst.ptr[dst.len++] = ' ';
5591
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005592 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005593 goto end;
5594 if (dst.len + 1 > len)
5595 goto end;
5596 dst.ptr[dst.len++] = ' ';
5597
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005598 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005599 end:
5600 return dst.len;
5601}
5602
5603
Christopher Faulet0f226952018-10-22 09:29:56 +02005604/*
5605 * Print a debug line with a start line.
5606 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005607static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005608{
5609 struct session *sess = strm_sess(s);
5610 int max;
5611
5612 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5613 dir,
5614 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5615 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5616
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005617 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005618 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005619 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005620 trash.area[trash.data++] = ' ';
5621
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005622 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005623 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005624 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005625 trash.area[trash.data++] = ' ';
5626
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005628 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005629 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005630 trash.area[trash.data++] = '\n';
5631
5632 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5633}
5634
5635/*
5636 * Print a debug line with a header.
5637 */
5638static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5639{
5640 struct session *sess = strm_sess(s);
5641 int max;
5642
5643 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5644 dir,
5645 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5646 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5647
5648 max = n.len;
5649 UBOUND(max, trash.size - trash.data - 3);
5650 chunk_memcat(&trash, n.ptr, max);
5651 trash.area[trash.data++] = ':';
5652 trash.area[trash.data++] = ' ';
5653
5654 max = v.len;
5655 UBOUND(max, trash.size - trash.data - 1);
5656 chunk_memcat(&trash, v.ptr, max);
5657 trash.area[trash.data++] = '\n';
5658
5659 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5660}
5661
5662
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005663__attribute__((constructor))
5664static void __htx_protocol_init(void)
5665{
5666}
5667
5668
5669/*
5670 * Local variables:
5671 * c-indent-level: 8
5672 * c-basic-offset: 8
5673 * End:
5674 */