blob: e7341c1ae1261ca46ff030b3f5450d2ddf834972 [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 Faulet0ef372a2019-04-08 10:57:20 +0200148 if (htx->flags & HTX_FL_UPGRADE)
149 goto failed_keep_alive;
150
Christopher Faulet9768c262018-10-22 09:34:31 +0200151 /* 1: have we encountered a read error ? */
152 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200153 if (!(s->flags & SF_ERR_MASK))
154 s->flags |= SF_ERR_CLICL;
155
156 if (txn->flags & TX_WAIT_NEXT_RQ)
157 goto failed_keep_alive;
158
159 if (sess->fe->options & PR_O_IGNORE_PRB)
160 goto failed_keep_alive;
161
Christopher Faulet9768c262018-10-22 09:34:31 +0200162 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 stream_inc_http_req_ctr(s);
164 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100165 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200166 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100167 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168
Christopher Faulet9768c262018-10-22 09:34:31 +0200169 txn->status = 400;
170 msg->err_state = msg->msg_state;
171 msg->msg_state = HTTP_MSG_ERROR;
172 htx_reply_and_close(s, txn->status, NULL);
173 req->analysers &= AN_REQ_FLT_END;
174
Christopher Faulete0768eb2018-10-03 16:38:02 +0200175 if (!(s->flags & SF_FINST_MASK))
176 s->flags |= SF_FINST_R;
177 return 0;
178 }
179
Christopher Faulet9768c262018-10-22 09:34:31 +0200180 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200181 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
182 if (!(s->flags & SF_ERR_MASK))
183 s->flags |= SF_ERR_CLITO;
184
185 if (txn->flags & TX_WAIT_NEXT_RQ)
186 goto failed_keep_alive;
187
188 if (sess->fe->options & PR_O_IGNORE_PRB)
189 goto failed_keep_alive;
190
Christopher Faulet9768c262018-10-22 09:34:31 +0200191 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 stream_inc_http_req_ctr(s);
193 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100194 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200195 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100196 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197
Christopher Faulet9768c262018-10-22 09:34:31 +0200198 txn->status = 408;
199 msg->err_state = msg->msg_state;
200 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100201 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200202 req->analysers &= AN_REQ_FLT_END;
203
Christopher Faulete0768eb2018-10-03 16:38:02 +0200204 if (!(s->flags & SF_FINST_MASK))
205 s->flags |= SF_FINST_R;
206 return 0;
207 }
208
Christopher Faulet9768c262018-10-22 09:34:31 +0200209 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200210 else if (req->flags & CF_SHUTR) {
211 if (!(s->flags & SF_ERR_MASK))
212 s->flags |= SF_ERR_CLICL;
213
214 if (txn->flags & TX_WAIT_NEXT_RQ)
215 goto failed_keep_alive;
216
217 if (sess->fe->options & PR_O_IGNORE_PRB)
218 goto failed_keep_alive;
219
Christopher Faulete0768eb2018-10-03 16:38:02 +0200220 stream_inc_http_err_ctr(s);
221 stream_inc_http_req_ctr(s);
222 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100223 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200224 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100225 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200226
Christopher Faulet9768c262018-10-22 09:34:31 +0200227 txn->status = 400;
228 msg->err_state = msg->msg_state;
229 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100230 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200231 req->analysers &= AN_REQ_FLT_END;
232
Christopher Faulete0768eb2018-10-03 16:38:02 +0200233 if (!(s->flags & SF_FINST_MASK))
234 s->flags |= SF_FINST_R;
235 return 0;
236 }
237
238 channel_dont_connect(req);
239 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
240 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100241
Christopher Faulet9768c262018-10-22 09:34:31 +0200242 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200243 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
244 /* We need more data, we have to re-enable quick-ack in case we
245 * previously disabled it, otherwise we might cause the client
246 * to delay next data.
247 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100248 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100250
Christopher Faulet47365272018-10-31 17:40:50 +0100251 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200252 /* If the client starts to talk, let's fall back to
253 * request timeout processing.
254 */
255 txn->flags &= ~TX_WAIT_NEXT_RQ;
256 req->analyse_exp = TICK_ETERNITY;
257 }
258
259 /* just set the request timeout once at the beginning of the request */
260 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100261 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200262 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
263 else
264 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
265 }
266
267 /* we're not ready yet */
268 return 0;
269
270 failed_keep_alive:
271 /* Here we process low-level errors for keep-alive requests. In
272 * short, if the request is not the first one and it experiences
273 * a timeout, read error or shutdown, we just silently close so
274 * that the client can try again.
275 */
276 txn->status = 0;
277 msg->msg_state = HTTP_MSG_RQBEFORE;
278 req->analysers &= AN_REQ_FLT_END;
279 s->logs.logwait = 0;
280 s->logs.level = 0;
281 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200282 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200283 return 0;
284 }
285
Christopher Faulet9768c262018-10-22 09:34:31 +0200286 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200287 stream_inc_http_req_ctr(s);
288 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
289
Christopher Faulet9768c262018-10-22 09:34:31 +0200290 /* kill the pending keep-alive timeout */
291 txn->flags &= ~TX_WAIT_NEXT_RQ;
292 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200293
Christopher Faulet03599112018-11-27 11:21:21 +0100294 sl = http_find_stline(htx);
295
Christopher Faulet9768c262018-10-22 09:34:31 +0200296 /* 0: we might have to print this header in debug mode */
297 if (unlikely((global.mode & MODE_DEBUG) &&
298 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
299 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200300
Christopher Faulet03599112018-11-27 11:21:21 +0100301 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200302
303 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
304 struct htx_blk *blk = htx_get_blk(htx, pos);
305 enum htx_blk_type type = htx_get_blk_type(blk);
306
307 if (type == HTX_BLK_EOH)
308 break;
309 if (type != HTX_BLK_HDR)
310 continue;
311
312 htx_debug_hdr("clihdr", s,
313 htx_get_blk_name(htx, blk),
314 htx_get_blk_value(htx, blk));
315 }
316 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100319 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100322 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200323 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100324 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100325 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100326 if (sl->flags & HTX_SL_F_BODYLESS)
327 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200328
329 /* we can make use of server redirect on GET and HEAD */
330 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
331 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100332 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200334 goto return_bad_req;
335 }
336
337 /*
338 * 2: check if the URI matches the monitor_uri.
339 * We have to do this for every request which gets in, because
340 * the monitor-uri is defined by the frontend.
341 */
342 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100343 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200344 /*
345 * We have found the monitor URI
346 */
347 struct acl_cond *cond;
348
349 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200351
352 /* Check if we want to fail this monitor request or not */
353 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
354 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
355
356 ret = acl_pass(ret);
357 if (cond->pol == ACL_COND_UNLESS)
358 ret = !ret;
359
360 if (ret) {
361 /* we fail this request, let's return 503 service unavail */
362 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100363 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200364 if (!(s->flags & SF_ERR_MASK))
365 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
366 goto return_prx_cond;
367 }
368 }
369
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800370 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200371 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100372 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200373 if (!(s->flags & SF_ERR_MASK))
374 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
375 goto return_prx_cond;
376 }
377
378 /*
379 * 3: Maybe we have to copy the original REQURI for the logs ?
380 * Note: we cannot log anymore if the request has been
381 * classified as invalid.
382 */
383 if (unlikely(s->logs.logwait & LW_REQ)) {
384 /* we have a complete HTTP request that we must log */
385 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200386 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
Christopher Faulet9768c262018-10-22 09:34:31 +0200388 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
389 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200390
391 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
392 s->do_log(s);
393 } else {
394 ha_alert("HTTP logging : out of memory.\n");
395 }
396 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200397
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 /* if the frontend has "option http-use-proxy-header", we'll check if
399 * we have what looks like a proxied connection instead of a connection,
400 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
401 * Note that this is *not* RFC-compliant, however browsers and proxies
402 * happen to do that despite being non-standard :-(
403 * We consider that a request not beginning with either '/' or '*' is
404 * a proxied connection, which covers both "scheme://location" and
405 * CONNECT ip:port.
406 */
407 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100408 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 txn->flags |= TX_USE_PX_CONN;
410
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411 /* 5: we may need to capture headers */
412 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200413 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100415 /* by default, close the stream at the end of the transaction. */
416 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417
418 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200419 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200420 req->analysers |= AN_REQ_HTTP_BODY;
421
422 /*
423 * RFC7234#4:
424 * A cache MUST write through requests with methods
425 * that are unsafe (Section 4.2.1 of [RFC7231]) to
426 * the origin server; i.e., a cache is not allowed
427 * to generate a reply to such a request before
428 * having forwarded the request and having received
429 * a corresponding response.
430 *
431 * RFC7231#4.2.1:
432 * Of the request methods defined by this
433 * specification, the GET, HEAD, OPTIONS, and TRACE
434 * methods are defined to be safe.
435 */
436 if (likely(txn->meth == HTTP_METH_GET ||
437 txn->meth == HTTP_METH_HEAD ||
438 txn->meth == HTTP_METH_OPTIONS ||
439 txn->meth == HTTP_METH_TRACE))
440 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
441
442 /* end of job, return OK */
443 req->analysers &= ~an_bit;
444 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200445
Christopher Faulete0768eb2018-10-03 16:38:02 +0200446 return 1;
447
448 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200449 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200450 txn->req.err_state = txn->req.msg_state;
451 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100452 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100453 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200454 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100455 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200456
457 return_prx_cond:
458 if (!(s->flags & SF_ERR_MASK))
459 s->flags |= SF_ERR_PRXCOND;
460 if (!(s->flags & SF_FINST_MASK))
461 s->flags |= SF_FINST_R;
462
463 req->analysers &= AN_REQ_FLT_END;
464 req->analyse_exp = TICK_ETERNITY;
465 return 0;
466}
467
468
469/* This stream analyser runs all HTTP request processing which is common to
470 * frontends and backends, which means blocking ACLs, filters, connection-close,
471 * reqadd, stats and redirects. This is performed for the designated proxy.
472 * It returns 1 if the processing can continue on next analysers, or zero if it
473 * either needs more data or wants to immediately abort the request (eg: deny,
474 * error, ...).
475 */
476int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
477{
478 struct session *sess = s->sess;
479 struct http_txn *txn = s->txn;
480 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200481 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200482 struct redirect_rule *rule;
483 struct cond_wordlist *wl;
484 enum rule_result verdict;
485 int deny_status = HTTP_ERR_403;
486 struct connection *conn = objt_conn(sess->origin);
487
488 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
489 /* we need more data */
490 goto return_prx_yield;
491 }
492
493 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
494 now_ms, __FUNCTION__,
495 s,
496 req,
497 req->rex, req->wex,
498 req->flags,
499 ci_data(req),
500 req->analysers);
501
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100502 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200503
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200504 /* just in case we have some per-backend tracking. Only called the first
505 * execution of the analyser. */
506 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
507 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200508
509 /* evaluate http-request rules */
510 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200511 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200512
513 switch (verdict) {
514 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
515 goto return_prx_yield;
516
517 case HTTP_RULE_RES_CONT:
518 case HTTP_RULE_RES_STOP: /* nothing to do */
519 break;
520
521 case HTTP_RULE_RES_DENY: /* deny or tarpit */
522 if (txn->flags & TX_CLTARPIT)
523 goto tarpit;
524 goto deny;
525
526 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
527 goto return_prx_cond;
528
529 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
530 goto done;
531
532 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
533 goto return_bad_req;
534 }
535 }
536
537 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
538 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200539 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540
Christopher Fauletff2759f2018-10-24 11:13:16 +0200541 ctx.blk = NULL;
542 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
543 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 }
547
548 /* OK at this stage, we know that the request was accepted according to
549 * the http-request rules, we can check for the stats. Note that the
550 * URI is detected *before* the req* rules in order not to be affected
551 * by a possible reqrep, while they are processed *after* so that a
552 * reqdeny can still block them. This clearly needs to change in 1.6!
553 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200554 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100556 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200557 txn->status = 500;
558 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100559 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560
561 if (!(s->flags & SF_ERR_MASK))
562 s->flags |= SF_ERR_RESOURCE;
563 goto return_prx_cond;
564 }
565
566 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200567 htx_handle_stats(s, req);
568 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200569 /* not all actions implemented: deny, allow, auth */
570
571 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
572 goto deny;
573
574 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
575 goto return_prx_cond;
576 }
577
578 /* evaluate the req* rules except reqadd */
579 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200580 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200581 goto return_bad_req;
582
583 if (txn->flags & TX_CLDENY)
584 goto deny;
585
586 if (txn->flags & TX_CLTARPIT) {
587 deny_status = HTTP_ERR_500;
588 goto tarpit;
589 }
590 }
591
592 /* add request headers from the rule sets in the same order */
593 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200594 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 if (wl->cond) {
596 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
597 ret = acl_pass(ret);
598 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
599 ret = !ret;
600 if (!ret)
601 continue;
602 }
603
Christopher Fauletff2759f2018-10-24 11:13:16 +0200604 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
605 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 goto return_bad_req;
607 }
608
Christopher Faulet2571bc62019-03-01 11:44:26 +0100609 /* Proceed with the applets now. */
610 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100612 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200613
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100614 if (htx_handle_expect_hdr(s, htx, msg) == -1)
615 goto return_bad_req;
616
Christopher Faulete0768eb2018-10-03 16:38:02 +0200617 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
618 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
619 if (!(s->flags & SF_FINST_MASK))
620 s->flags |= SF_FINST_R;
621
622 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
623 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
624 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
625 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100626
627 req->flags |= CF_SEND_DONTWAIT;
628 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200629 goto done;
630 }
631
632 /* check whether we have some ACLs set to redirect this request */
633 list_for_each_entry(rule, &px->redirect_rules, list) {
634 if (rule->cond) {
635 int ret;
636
637 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
638 ret = acl_pass(ret);
639 if (rule->cond->pol == ACL_COND_UNLESS)
640 ret = !ret;
641 if (!ret)
642 continue;
643 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200644 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200645 goto return_bad_req;
646 goto done;
647 }
648
649 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
650 * If this happens, then the data will not come immediately, so we must
651 * send all what we have without waiting. Note that due to the small gain
652 * in waiting for the body of the request, it's easier to simply put the
653 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
654 * itself once used.
655 */
656 req->flags |= CF_SEND_DONTWAIT;
657
658 done: /* done with this analyser, continue with next ones that the calling
659 * points will have set, if any.
660 */
661 req->analyse_exp = TICK_ETERNITY;
662 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
663 req->analysers &= ~an_bit;
664 return 1;
665
666 tarpit:
667 /* Allow cookie logging
668 */
669 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200670 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200671
672 /* When a connection is tarpitted, we use the tarpit timeout,
673 * which may be the same as the connect timeout if unspecified.
674 * If unset, then set it to zero because we really want it to
675 * eventually expire. We build the tarpit as an analyser.
676 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100677 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200678
679 /* wipe the request out so that we can drop the connection early
680 * if the client closes first.
681 */
682 channel_dont_connect(req);
683
684 txn->status = http_err_codes[deny_status];
685
686 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
687 req->analysers |= AN_REQ_HTTP_TARPIT;
688 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
689 if (!req->analyse_exp)
690 req->analyse_exp = tick_add(now_ms, 0);
691 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100692 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200693 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100694 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200695 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100696 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200697 goto done_without_exp;
698
699 deny: /* this request was blocked (denied) */
700
701 /* Allow cookie logging
702 */
703 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200704 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705
706 txn->flags |= TX_CLDENY;
707 txn->status = http_err_codes[deny_status];
708 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100709 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100711 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716 goto return_prx_cond;
717
718 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200719 txn->req.err_state = txn->req.msg_state;
720 txn->req.msg_state = HTTP_MSG_ERROR;
721 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100722 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200723
Olivier Houcharda798bf52019-03-08 18:52:00 +0100724 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200725 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100726 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200727
728 return_prx_cond:
729 if (!(s->flags & SF_ERR_MASK))
730 s->flags |= SF_ERR_PRXCOND;
731 if (!(s->flags & SF_FINST_MASK))
732 s->flags |= SF_FINST_R;
733
734 req->analysers &= AN_REQ_FLT_END;
735 req->analyse_exp = TICK_ETERNITY;
736 return 0;
737
738 return_prx_yield:
739 channel_dont_connect(req);
740 return 0;
741}
742
743/* This function performs all the processing enabled for the current request.
744 * It returns 1 if the processing can continue on next analysers, or zero if it
745 * needs more data, encounters an error, or wants to immediately abort the
746 * request. It relies on buffers flags, and updates s->req.analysers.
747 */
748int htx_process_request(struct stream *s, struct channel *req, int an_bit)
749{
750 struct session *sess = s->sess;
751 struct http_txn *txn = s->txn;
752 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200753 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200754 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
755
756 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
757 /* we need more data */
758 channel_dont_connect(req);
759 return 0;
760 }
761
762 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
763 now_ms, __FUNCTION__,
764 s,
765 req,
766 req->rex, req->wex,
767 req->flags,
768 ci_data(req),
769 req->analysers);
770
771 /*
772 * Right now, we know that we have processed the entire headers
773 * and that unwanted requests have been filtered out. We can do
774 * whatever we want with the remaining request. Also, now we
775 * may have separate values for ->fe, ->be.
776 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100777 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200778
779 /*
780 * If HTTP PROXY is set we simply get remote server address parsing
781 * incoming request. Note that this requires that a connection is
782 * allocated on the server side.
783 */
784 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
785 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100786 struct htx_sl *sl;
787 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200788
789 /* Note that for now we don't reuse existing proxy connections */
790 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
791 txn->req.err_state = txn->req.msg_state;
792 txn->req.msg_state = HTTP_MSG_ERROR;
793 txn->status = 500;
794 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100795 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200796
797 if (!(s->flags & SF_ERR_MASK))
798 s->flags |= SF_ERR_RESOURCE;
799 if (!(s->flags & SF_FINST_MASK))
800 s->flags |= SF_FINST_R;
801
802 return 0;
803 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200804 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100805 uri = htx_sl_req_uri(sl);
806 path = http_get_path(uri);
807 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200808 goto return_bad_req;
809
810 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200811 * uri.ptr and path.ptr (excluded). If it was not found, we need
812 * to replace from all the uri by a single "/".
813 *
814 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100815 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200816 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200817 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100818 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819 }
820
821 /*
822 * 7: Now we can work with the cookies.
823 * Note that doing so might move headers in the request, but
824 * the fields will stay coherent and the URI will not move.
825 * This should only be performed in the backend.
826 */
827 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100828 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200829
830 /* add unique-id if "header-unique-id" is specified */
831
832 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
833 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
834 goto return_bad_req;
835 s->unique_id[0] = '\0';
836 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
837 }
838
839 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200840 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
841 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
842
843 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200844 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 }
846
847 /*
848 * 9: add X-Forwarded-For if either the frontend or the backend
849 * asks for it.
850 */
851 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200852 struct http_hdr_ctx ctx = { .blk = NULL };
853 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
854 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
855
Christopher Faulete0768eb2018-10-03 16:38:02 +0200856 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200857 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200858 /* The header is set to be added only if none is present
859 * and we found it, so don't do anything.
860 */
861 }
862 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
863 /* Add an X-Forwarded-For header unless the source IP is
864 * in the 'except' network range.
865 */
866 if ((!sess->fe->except_mask.s_addr ||
867 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
868 != sess->fe->except_net.s_addr) &&
869 (!s->be->except_mask.s_addr ||
870 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
871 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200872 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200873
874 /* Note: we rely on the backend to get the header name to be used for
875 * x-forwarded-for, because the header is really meant for the backends.
876 * However, if the backend did not specify any option, we have to rely
877 * on the frontend's header name.
878 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200879 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
880 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200881 goto return_bad_req;
882 }
883 }
884 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
885 /* FIXME: for the sake of completeness, we should also support
886 * 'except' here, although it is mostly useless in this case.
887 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200888 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200889
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890 inet_ntop(AF_INET6,
891 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
892 pn, sizeof(pn));
893
894 /* Note: we rely on the backend to get the header name to be used for
895 * x-forwarded-for, because the header is really meant for the backends.
896 * However, if the backend did not specify any option, we have to rely
897 * on the frontend's header name.
898 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200899 chunk_printf(&trash, "%s", pn);
900 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200901 goto return_bad_req;
902 }
903 }
904
905 /*
906 * 10: add X-Original-To if either the frontend or the backend
907 * asks for it.
908 */
909 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
910
911 /* FIXME: don't know if IPv6 can handle that case too. */
912 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
913 /* Add an X-Original-To header unless the destination IP is
914 * in the 'except' network range.
915 */
916 conn_get_to_addr(cli_conn);
917
918 if (cli_conn->addr.to.ss_family == AF_INET &&
919 ((!sess->fe->except_mask_to.s_addr ||
920 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
921 != sess->fe->except_to.s_addr) &&
922 (!s->be->except_mask_to.s_addr ||
923 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
924 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200925 struct ist hdr;
926 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200927
928 /* Note: we rely on the backend to get the header name to be used for
929 * x-original-to, because the header is really meant for the backends.
930 * However, if the backend did not specify any option, we have to rely
931 * on the frontend's header name.
932 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200933 if (s->be->orgto_hdr_len)
934 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
935 else
936 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200937
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200938 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
939 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 goto return_bad_req;
941 }
942 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200943 }
944
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 /* If we have no server assigned yet and we're balancing on url_param
946 * with a POST request, we may be interested in checking the body for
947 * that parameter. This will be done in another analyser.
948 */
949 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100950 s->txn->meth == HTTP_METH_POST &&
951 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200952 channel_dont_connect(req);
953 req->analysers |= AN_REQ_HTTP_BODY;
954 }
955
956 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
957 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100958
Christopher Faulete0768eb2018-10-03 16:38:02 +0200959 /* We expect some data from the client. Unless we know for sure
960 * we already have a full request, we have to re-enable quick-ack
961 * in case we previously disabled it, otherwise we might cause
962 * the client to delay further data.
963 */
964 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200965 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100966 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200967
968 /*************************************************************
969 * OK, that's finished for the headers. We have done what we *
970 * could. Let's switch to the DATA state. *
971 ************************************************************/
972 req->analyse_exp = TICK_ETERNITY;
973 req->analysers &= ~an_bit;
974
975 s->logs.tv_request = now;
976 /* OK let's go on with the BODY now */
977 return 1;
978
979 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200980 txn->req.err_state = txn->req.msg_state;
981 txn->req.msg_state = HTTP_MSG_ERROR;
982 txn->status = 400;
983 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100984 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200985
Olivier Houcharda798bf52019-03-08 18:52:00 +0100986 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200987 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100988 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200989
990 if (!(s->flags & SF_ERR_MASK))
991 s->flags |= SF_ERR_PRXCOND;
992 if (!(s->flags & SF_FINST_MASK))
993 s->flags |= SF_FINST_R;
994 return 0;
995}
996
997/* This function is an analyser which processes the HTTP tarpit. It always
998 * returns zero, at the beginning because it prevents any other processing
999 * from occurring, and at the end because it terminates the request.
1000 */
1001int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1002{
1003 struct http_txn *txn = s->txn;
1004
1005 /* This connection is being tarpitted. The CLIENT side has
1006 * already set the connect expiration date to the right
1007 * timeout. We just have to check that the client is still
1008 * there and that the timeout has not expired.
1009 */
1010 channel_dont_connect(req);
1011 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1012 !tick_is_expired(req->analyse_exp, now_ms))
1013 return 0;
1014
1015 /* We will set the queue timer to the time spent, just for
1016 * logging purposes. We fake a 500 server error, so that the
1017 * attacker will not suspect his connection has been tarpitted.
1018 * It will not cause trouble to the logs because we can exclude
1019 * the tarpitted connections by filtering on the 'PT' status flags.
1020 */
1021 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1022
1023 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001024 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001025
1026 req->analysers &= AN_REQ_FLT_END;
1027 req->analyse_exp = TICK_ETERNITY;
1028
1029 if (!(s->flags & SF_ERR_MASK))
1030 s->flags |= SF_ERR_PRXCOND;
1031 if (!(s->flags & SF_FINST_MASK))
1032 s->flags |= SF_FINST_T;
1033 return 0;
1034}
1035
1036/* This function is an analyser which waits for the HTTP request body. It waits
1037 * for either the buffer to be full, or the full advertised contents to have
1038 * reached the buffer. It must only be called after the standard HTTP request
1039 * processing has occurred, because it expects the request to be parsed and will
1040 * look for the Expect header. It may send a 100-Continue interim response. It
1041 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1042 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1043 * needs to read more data, or 1 once it has completed its analysis.
1044 */
1045int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1046{
1047 struct session *sess = s->sess;
1048 struct http_txn *txn = s->txn;
1049 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001050 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001051
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
1053 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1054 now_ms, __FUNCTION__,
1055 s,
1056 req,
1057 req->rex, req->wex,
1058 req->flags,
1059 ci_data(req),
1060 req->analysers);
1061
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001062 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001063
Willy Tarreau4236f032019-03-05 10:43:32 +01001064 if (htx->flags & HTX_FL_PARSING_ERROR)
1065 goto return_bad_req;
1066
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001067 if (msg->msg_state < HTTP_MSG_BODY)
1068 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001069
Christopher Faulete0768eb2018-10-03 16:38:02 +02001070 /* We have to parse the HTTP request body to find any required data.
1071 * "balance url_param check_post" should have been the only way to get
1072 * into this. We were brought here after HTTP header analysis, so all
1073 * related structures are ready.
1074 */
1075
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001076 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001077 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1078 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079 }
1080
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001082
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001083 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1084 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001085 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001086 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001087 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001088 goto http_end;
1089
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001090 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001091 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1092 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001093 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001094
1095 if (!(s->flags & SF_ERR_MASK))
1096 s->flags |= SF_ERR_CLITO;
1097 if (!(s->flags & SF_FINST_MASK))
1098 s->flags |= SF_FINST_D;
1099 goto return_err_msg;
1100 }
1101
1102 /* we get here if we need to wait for more data */
1103 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1104 /* Not enough data. We'll re-use the http-request
1105 * timeout here. Ideally, we should set the timeout
1106 * relative to the accept() date. We just set the
1107 * request timeout once at the beginning of the
1108 * request.
1109 */
1110 channel_dont_connect(req);
1111 if (!tick_isset(req->analyse_exp))
1112 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1113 return 0;
1114 }
1115
1116 http_end:
1117 /* The situation will not evolve, so let's give up on the analysis. */
1118 s->logs.tv_request = now; /* update the request timer to reflect full request */
1119 req->analysers &= ~an_bit;
1120 req->analyse_exp = TICK_ETERNITY;
1121 return 1;
1122
1123 return_bad_req: /* let's centralize all bad requests */
1124 txn->req.err_state = txn->req.msg_state;
1125 txn->req.msg_state = HTTP_MSG_ERROR;
1126 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001127 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128
1129 if (!(s->flags & SF_ERR_MASK))
1130 s->flags |= SF_ERR_PRXCOND;
1131 if (!(s->flags & SF_FINST_MASK))
1132 s->flags |= SF_FINST_R;
1133
1134 return_err_msg:
1135 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001136 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001137 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001138 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001139 return 0;
1140}
1141
1142/* This function is an analyser which forwards request body (including chunk
1143 * sizes if any). It is called as soon as we must forward, even if we forward
1144 * zero byte. The only situation where it must not be called is when we're in
1145 * tunnel mode and we want to forward till the close. It's used both to forward
1146 * remaining data and to resync after end of body. It expects the msg_state to
1147 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1148 * read more data, or 1 once we can go on with next request or end the stream.
1149 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1150 * bytes of pending data + the headers if not already done.
1151 */
1152int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1153{
1154 struct session *sess = s->sess;
1155 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001156 struct http_msg *msg = &txn->req;
1157 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001158 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001159 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1162 now_ms, __FUNCTION__,
1163 s,
1164 req,
1165 req->rex, req->wex,
1166 req->flags,
1167 ci_data(req),
1168 req->analysers);
1169
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001170 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001171
1172 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1173 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1174 /* Output closed while we were sending data. We must abort and
1175 * wake the other side up.
1176 */
1177 msg->err_state = msg->msg_state;
1178 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001179 htx_end_request(s);
1180 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001181 return 1;
1182 }
1183
1184 /* Note that we don't have to send 100-continue back because we don't
1185 * need the data to complete our job, and it's up to the server to
1186 * decide whether to return 100, 417 or anything else in return of
1187 * an "Expect: 100-continue" header.
1188 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001189 if (msg->msg_state == HTTP_MSG_BODY)
1190 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001191
1192 /* Some post-connect processing might want us to refrain from starting to
1193 * forward data. Currently, the only reason for this is "balance url_param"
1194 * whichs need to parse/process the request after we've enabled forwarding.
1195 */
1196 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1197 if (!(s->res.flags & CF_READ_ATTACHED)) {
1198 channel_auto_connect(req);
1199 req->flags |= CF_WAKE_CONNECT;
1200 channel_dont_close(req); /* don't fail on early shutr */
1201 goto waiting;
1202 }
1203 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1204 }
1205
1206 /* in most states, we should abort in case of early close */
1207 channel_auto_close(req);
1208
1209 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001210 if (req->to_forward == CHN_INFINITE_FORWARD) {
1211 if (req->flags & (CF_SHUTR|CF_EOI)) {
1212 msg->msg_state = HTTP_MSG_DONE;
1213 req->to_forward = 0;
1214 goto done;
1215 }
1216 }
1217 else {
1218 /* We can't process the buffer's contents yet */
1219 req->flags |= CF_WAKE_WRITE;
1220 goto missing_data_or_waiting;
1221 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001222 }
1223
Christopher Faulet9768c262018-10-22 09:34:31 +02001224 if (msg->msg_state >= HTTP_MSG_DONE)
1225 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001226 /* Forward input data. We get it by removing all outgoing data not
1227 * forwarded yet from HTX data size. If there are some data filters, we
1228 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001230 if (HAS_REQ_DATA_FILTERS(s)) {
1231 ret = flt_http_payload(s, msg, htx->data);
1232 if (ret < 0)
1233 goto return_bad_req;
1234 c_adv(req, ret);
1235 if (htx->data != co_data(req) || htx->extra)
1236 goto missing_data_or_waiting;
1237 }
1238 else {
1239 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001240 if (msg->flags & HTTP_MSGF_XFER_LEN)
1241 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001242 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001244 if (txn->meth == HTTP_METH_CONNECT) {
1245 msg->msg_state = HTTP_MSG_TUNNEL;
1246 goto done;
1247 }
1248
Christopher Faulet9768c262018-10-22 09:34:31 +02001249 /* Check if the end-of-message is reached and if so, switch the message
1250 * in HTTP_MSG_DONE state.
1251 */
1252 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1253 goto missing_data_or_waiting;
1254
1255 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001256 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001257
1258 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001259 /* other states, DONE...TUNNEL */
1260 /* we don't want to forward closes on DONE except in tunnel mode. */
1261 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1262 channel_dont_close(req);
1263
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001264 if (HAS_REQ_DATA_FILTERS(s)) {
1265 ret = flt_http_end(s, msg);
1266 if (ret <= 0) {
1267 if (!ret)
1268 goto missing_data_or_waiting;
1269 goto return_bad_req;
1270 }
1271 }
1272
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001275 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1277 if (req->flags & CF_SHUTW) {
1278 /* request errors are most likely due to the
1279 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001280 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 goto return_bad_req;
1283 }
1284 return 1;
1285 }
1286
1287 /* If "option abortonclose" is set on the backend, we want to monitor
1288 * the client's connection and forward any shutdown notification to the
1289 * server, which will decide whether to close or to go on processing the
1290 * request. We only do that in tunnel mode, and not in other modes since
1291 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001292 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001293 channel_auto_read(req);
1294 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1295 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1296 s->si[1].flags |= SI_FL_NOLINGER;
1297 channel_auto_close(req);
1298 }
1299 else if (s->txn->meth == HTTP_METH_POST) {
1300 /* POST requests may require to read extra CRLF sent by broken
1301 * browsers and which could cause an RST to be sent upon close
1302 * on some systems (eg: Linux). */
1303 channel_auto_read(req);
1304 }
1305 return 0;
1306
1307 missing_data_or_waiting:
1308 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001309 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1310 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001311
1312 waiting:
1313 /* waiting for the last bits to leave the buffer */
1314 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316
Christopher Faulet47365272018-10-31 17:40:50 +01001317 if (htx->flags & HTX_FL_PARSING_ERROR)
1318 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001319
Christopher Faulete0768eb2018-10-03 16:38:02 +02001320 /* When TE: chunked is used, we need to get there again to parse remaining
1321 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1322 * And when content-length is used, we never want to let the possible
1323 * shutdown be forwarded to the other side, as the state machine will
1324 * take care of it once the client responds. It's also important to
1325 * prevent TIME_WAITs from accumulating on the backend side, and for
1326 * HTTP/2 where the last frame comes with a shutdown.
1327 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001328 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 channel_dont_close(req);
1330
1331 /* We know that more data are expected, but we couldn't send more that
1332 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1333 * system knows it must not set a PUSH on this first part. Interactive
1334 * modes are already handled by the stream sock layer. We must not do
1335 * this in content-length mode because it could present the MSG_MORE
1336 * flag with the last block of forwarded data, which would cause an
1337 * additional delay to be observed by the receiver.
1338 */
1339 if (msg->flags & HTTP_MSGF_TE_CHNK)
1340 req->flags |= CF_EXPECT_MORE;
1341
1342 return 0;
1343
Christopher Faulet93e02d82019-03-08 14:18:50 +01001344 return_cli_abort:
1345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1346 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1347 if (objt_server(s->target))
1348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1349 if (!(s->flags & SF_ERR_MASK))
1350 s->flags |= SF_ERR_CLICL;
1351 status = 400;
1352 goto return_error;
1353
1354 return_srv_abort:
1355 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1356 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1357 if (objt_server(s->target))
1358 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1359 if (!(s->flags & SF_ERR_MASK))
1360 s->flags |= SF_ERR_SRVCL;
1361 status = 502;
1362 goto return_error;
1363
1364 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001365 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001367 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001369 s->flags |= SF_ERR_CLICL;
1370 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371
Christopher Faulet93e02d82019-03-08 14:18:50 +01001372 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 txn->req.err_state = txn->req.msg_state;
1374 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001375 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001377 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001379 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001380 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 }
1382 req->analysers &= AN_REQ_FLT_END;
1383 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001384 if (!(s->flags & SF_FINST_MASK))
1385 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 return 0;
1387}
1388
Olivier Houcharda254a372019-04-05 15:30:12 +02001389/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1390/* Returns 0 if we can attempt to retry, -1 otherwise */
1391static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1392{
1393 struct channel *req, *res;
1394 int co_data;
1395
1396 si->conn_retries--;
1397 if (si->conn_retries < 0)
1398 return -1;
1399
Willy Tarreau223995e2019-05-04 10:38:31 +02001400 if (objt_server(s->target))
1401 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1402 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1403
Olivier Houcharda254a372019-04-05 15:30:12 +02001404 req = &s->req;
1405 res = &s->res;
1406 /* Remove any write error from the request, and read error from the response */
1407 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1408 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1409 res->analysers = 0;
1410 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1411 si->state = SI_ST_REQ;
1412 si->exp = TICK_ETERNITY;
1413 res->rex = TICK_ETERNITY;
1414 res->to_forward = 0;
1415 res->analyse_exp = TICK_ETERNITY;
1416 res->total = 0;
1417 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1418 si_release_endpoint(&s->si[1]);
1419 b_free(&req->buf);
1420 /* Swap the L7 buffer with the channel buffer */
1421 /* We know we stored the co_data as b_data, so get it there */
1422 co_data = b_data(&si->l7_buffer);
1423 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1424 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1425
1426 co_set_data(req, co_data);
1427 b_reset(&res->buf);
1428 co_set_data(res, 0);
1429 return 0;
1430}
1431
Christopher Faulete0768eb2018-10-03 16:38:02 +02001432/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1433 * processing can continue on next analysers, or zero if it either needs more
1434 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1435 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1436 * when it has nothing left to do, and may remove any analyser when it wants to
1437 * abort.
1438 */
1439int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1440{
Christopher Faulet9768c262018-10-22 09:34:31 +02001441 /*
1442 * We will analyze a complete HTTP response to check the its syntax.
1443 *
1444 * Once the start line and all headers are received, we may perform a
1445 * capture of the error (if any), and we will set a few fields. We also
1446 * logging and finally headers capture.
1447 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001448 struct session *sess = s->sess;
1449 struct http_txn *txn = s->txn;
1450 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001451 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001452 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001453 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001454 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001455 int n;
1456
1457 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1458 now_ms, __FUNCTION__,
1459 s,
1460 rep,
1461 rep->rex, rep->wex,
1462 rep->flags,
1463 ci_data(rep),
1464 rep->analysers);
1465
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001466 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001467
Willy Tarreau4236f032019-03-05 10:43:32 +01001468 /* Parsing errors are caught here */
1469 if (htx->flags & HTX_FL_PARSING_ERROR)
1470 goto return_bad_res;
1471
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472 /*
1473 * Now we quickly check if we have found a full valid response.
1474 * If not so, we check the FD and buffer states before leaving.
1475 * A full response is indicated by the fact that we have seen
1476 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1477 * responses are checked first.
1478 *
1479 * Depending on whether the client is still there or not, we
1480 * may send an error response back or not. Note that normally
1481 * we should only check for HTTP status there, and check I/O
1482 * errors somewhere else.
1483 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001484 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001485 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001486 * First catch invalid response because of a parsing error or
1487 * because only part of headers have been transfered.
1488 * Multiplexers have the responsibility to emit all headers at
1489 * once. We must be sure to have forwarded all outgoing data
1490 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001491 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001492 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001493 goto return_bad_res;
1494
Christopher Faulet9768c262018-10-22 09:34:31 +02001495 /* 1: have we encountered a read error ? */
1496 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001497 struct connection *conn = NULL;
1498
Christopher Faulet9768c262018-10-22 09:34:31 +02001499 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500 goto abort_keep_alive;
1501
Olivier Houchard865d8392019-05-03 22:46:27 +02001502 if (objt_cs(s->si[1].end))
1503 conn = objt_cs(s->si[1].end)->conn;
1504
1505 if (si_b->flags & SI_FL_L7_RETRY &&
1506 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001507 /* If we arrive here, then CF_READ_ERROR was
1508 * set by si_cs_recv() because we matched a
1509 * status, overwise it would have removed
1510 * the SI_FL_L7_RETRY flag, so it's ok not
1511 * to check s->be->retry_type.
1512 */
1513 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1514 return 0;
1515 }
1516
Olivier Houcharda798bf52019-03-08 18:52:00 +01001517 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001519 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001520 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521 }
1522
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 rep->analysers &= AN_RES_FLT_END;
1524 txn->status = 502;
1525
1526 /* Check to see if the server refused the early data.
1527 * If so, just send a 425
1528 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001529 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1530 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001531 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001532 do_l7_retry(s, si_b) == 0)
1533 return 0;
1534 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 }
1536
1537 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001538 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539
1540 if (!(s->flags & SF_ERR_MASK))
1541 s->flags |= SF_ERR_SRVCL;
1542 if (!(s->flags & SF_FINST_MASK))
1543 s->flags |= SF_FINST_H;
1544 return 0;
1545 }
1546
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001549 if ((si_b->flags & SI_FL_L7_RETRY) &&
1550 (s->be->retry_type & PR_RE_TIMEOUT)) {
1551 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1552 return 0;
1553 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001554 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001556 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001557 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558 }
1559
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560 rep->analysers &= AN_RES_FLT_END;
1561 txn->status = 504;
1562 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001563 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564
1565 if (!(s->flags & SF_ERR_MASK))
1566 s->flags |= SF_ERR_SRVTO;
1567 if (!(s->flags & SF_FINST_MASK))
1568 s->flags |= SF_FINST_H;
1569 return 0;
1570 }
1571
Christopher Faulet9768c262018-10-22 09:34:31 +02001572 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001574 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1575 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001577 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578
1579 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001580 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001581 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001582
1583 if (!(s->flags & SF_ERR_MASK))
1584 s->flags |= SF_ERR_CLICL;
1585 if (!(s->flags & SF_FINST_MASK))
1586 s->flags |= SF_FINST_H;
1587
1588 /* process_stream() will take care of the error */
1589 return 0;
1590 }
1591
Christopher Faulet9768c262018-10-22 09:34:31 +02001592 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001594 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001595 goto abort_keep_alive;
1596
Olivier Houcharda254a372019-04-05 15:30:12 +02001597 if ((si_b->flags & SI_FL_L7_RETRY) &&
1598 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1599 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1600 return 0;
1601 }
1602
Olivier Houcharda798bf52019-03-08 18:52:00 +01001603 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001605 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001606 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 }
1608
Christopher Faulete0768eb2018-10-03 16:38:02 +02001609 rep->analysers &= AN_RES_FLT_END;
1610 txn->status = 502;
1611 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001612 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001613
1614 if (!(s->flags & SF_ERR_MASK))
1615 s->flags |= SF_ERR_SRVCL;
1616 if (!(s->flags & SF_FINST_MASK))
1617 s->flags |= SF_FINST_H;
1618 return 0;
1619 }
1620
Christopher Faulet9768c262018-10-22 09:34:31 +02001621 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001623 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624 goto abort_keep_alive;
1625
Olivier Houcharda798bf52019-03-08 18:52:00 +01001626 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001628
1629 if (!(s->flags & SF_ERR_MASK))
1630 s->flags |= SF_ERR_CLICL;
1631 if (!(s->flags & SF_FINST_MASK))
1632 s->flags |= SF_FINST_H;
1633
1634 /* process_stream() will take care of the error */
1635 return 0;
1636 }
1637
1638 channel_dont_close(rep);
1639 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1640 return 0;
1641 }
1642
1643 /* More interesting part now : we know that we have a complete
1644 * response which at least looks like HTTP. We have an indicator
1645 * of each header's length, so we can parse them quickly.
1646 */
1647
Christopher Faulet9768c262018-10-22 09:34:31 +02001648 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001649 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001650
Christopher Faulet9768c262018-10-22 09:34:31 +02001651 /* 0: we might have to print this header in debug mode */
1652 if (unlikely((global.mode & MODE_DEBUG) &&
1653 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1654 int32_t pos;
1655
Christopher Faulet03599112018-11-27 11:21:21 +01001656 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001657
1658 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1659 struct htx_blk *blk = htx_get_blk(htx, pos);
1660 enum htx_blk_type type = htx_get_blk_type(blk);
1661
1662 if (type == HTX_BLK_EOH)
1663 break;
1664 if (type != HTX_BLK_HDR)
1665 continue;
1666
1667 htx_debug_hdr("srvhdr", s,
1668 htx_get_blk_name(htx, blk),
1669 htx_get_blk_value(htx, blk));
1670 }
1671 }
1672
Christopher Faulet03599112018-11-27 11:21:21 +01001673 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001674 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001675 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001676 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001677 if (sl->flags & HTX_SL_F_XFER_LEN) {
1678 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001679 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001680 if (sl->flags & HTX_SL_F_BODYLESS)
1681 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001682 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001683
1684 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001685 if (n < 1 || n > 5)
1686 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001687
Christopher Faulete0768eb2018-10-03 16:38:02 +02001688 /* when the client triggers a 4xx from the server, it's most often due
1689 * to a missing object or permission. These events should be tracked
1690 * because if they happen often, it may indicate a brute force or a
1691 * vulnerability scan.
1692 */
1693 if (n == 4)
1694 stream_inc_http_err_ctr(s);
1695
1696 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001697 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001698
Christopher Faulete0768eb2018-10-03 16:38:02 +02001699 /* Adjust server's health based on status code. Note: status codes 501
1700 * and 505 are triggered on demand by client request, so we must not
1701 * count them as server failures.
1702 */
1703 if (objt_server(s->target)) {
1704 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001705 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001707 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001708 }
1709
1710 /*
1711 * We may be facing a 100-continue response, or any other informational
1712 * 1xx response which is non-final, in which case this is not the right
1713 * response, and we're waiting for the next one. Let's allow this response
1714 * to go to the client and wait for the next one. There's an exception for
1715 * 101 which is used later in the code to switch protocols.
1716 */
1717 if (txn->status < 200 &&
1718 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001719 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001720 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001721 msg->msg_state = HTTP_MSG_RPBEFORE;
1722 txn->status = 0;
1723 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001724 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001725 }
1726
1727 /*
1728 * 2: check for cacheability.
1729 */
1730
1731 switch (txn->status) {
1732 case 200:
1733 case 203:
1734 case 204:
1735 case 206:
1736 case 300:
1737 case 301:
1738 case 404:
1739 case 405:
1740 case 410:
1741 case 414:
1742 case 501:
1743 break;
1744 default:
1745 /* RFC7231#6.1:
1746 * Responses with status codes that are defined as
1747 * cacheable by default (e.g., 200, 203, 204, 206,
1748 * 300, 301, 404, 405, 410, 414, and 501 in this
1749 * specification) can be reused by a cache with
1750 * heuristic expiration unless otherwise indicated
1751 * by the method definition or explicit cache
1752 * controls [RFC7234]; all other status codes are
1753 * not cacheable by default.
1754 */
1755 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1756 break;
1757 }
1758
1759 /*
1760 * 3: we may need to capture headers
1761 */
1762 s->logs.logwait &= ~LW_RESP;
1763 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001764 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001765
Christopher Faulet9768c262018-10-22 09:34:31 +02001766 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001767 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1768 txn->status == 101)) {
1769 /* Either we've established an explicit tunnel, or we're
1770 * switching the protocol. In both cases, we're very unlikely
1771 * to understand the next protocols. We have to switch to tunnel
1772 * mode, so that we transfer the request and responses then let
1773 * this protocol pass unmodified. When we later implement specific
1774 * parsers for such protocols, we'll want to check the Upgrade
1775 * header which contains information about that protocol for
1776 * responses with status 101 (eg: see RFC2817 about TLS).
1777 */
1778 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 }
1780
Christopher Faulet61608322018-11-23 16:23:45 +01001781 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1782 * 407 (Proxy-Authenticate) responses and set the connection to private
1783 */
1784 srv_conn = cs_conn(objt_cs(s->si[1].end));
1785 if (srv_conn) {
1786 struct ist hdr;
1787 struct http_hdr_ctx ctx;
1788
1789 if (txn->status == 401)
1790 hdr = ist("WWW-Authenticate");
1791 else if (txn->status == 407)
1792 hdr = ist("Proxy-Authenticate");
1793 else
1794 goto end;
1795
1796 ctx.blk = NULL;
1797 while (http_find_header(htx, hdr, &ctx, 0)) {
1798 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1799 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1800 srv_conn->flags |= CO_FL_PRIVATE;
1801 }
1802 }
1803
1804 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 /* we want to have the response time before we start processing it */
1806 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1807
1808 /* end of job, return OK */
1809 rep->analysers &= ~an_bit;
1810 rep->analyse_exp = TICK_ETERNITY;
1811 channel_auto_close(rep);
1812 return 1;
1813
Christopher Faulet47365272018-10-31 17:40:50 +01001814 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001815 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001816 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001817 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001818 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001819 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001820 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001821 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001822 do_l7_retry(s, si_b) == 0)
1823 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001824 txn->status = 502;
1825 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001826 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001827 rep->analysers &= AN_RES_FLT_END;
1828
1829 if (!(s->flags & SF_ERR_MASK))
1830 s->flags |= SF_ERR_PRXCOND;
1831 if (!(s->flags & SF_FINST_MASK))
1832 s->flags |= SF_FINST_H;
1833 return 0;
1834
Christopher Faulete0768eb2018-10-03 16:38:02 +02001835 abort_keep_alive:
1836 /* A keep-alive request to the server failed on a network error.
1837 * The client is required to retry. We need to close without returning
1838 * any other information so that the client retries.
1839 */
1840 txn->status = 0;
1841 rep->analysers &= AN_RES_FLT_END;
1842 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001843 s->logs.logwait = 0;
1844 s->logs.level = 0;
1845 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001846 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 return 0;
1848}
1849
1850/* This function performs all the processing enabled for the current response.
1851 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1852 * and updates s->res.analysers. It might make sense to explode it into several
1853 * other functions. It works like process_request (see indications above).
1854 */
1855int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1856{
1857 struct session *sess = s->sess;
1858 struct http_txn *txn = s->txn;
1859 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001860 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861 struct proxy *cur_proxy;
1862 struct cond_wordlist *wl;
1863 enum rule_result ret = HTTP_RULE_RES_CONT;
1864
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001865 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1866 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001867
Christopher Faulete0768eb2018-10-03 16:38:02 +02001868 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1869 now_ms, __FUNCTION__,
1870 s,
1871 rep,
1872 rep->rex, rep->wex,
1873 rep->flags,
1874 ci_data(rep),
1875 rep->analysers);
1876
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001877 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001878
1879 /* The stats applet needs to adjust the Connection header but we don't
1880 * apply any filter there.
1881 */
1882 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1883 rep->analysers &= ~an_bit;
1884 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001885 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001886 }
1887
1888 /*
1889 * We will have to evaluate the filters.
1890 * As opposed to version 1.2, now they will be evaluated in the
1891 * filters order and not in the header order. This means that
1892 * each filter has to be validated among all headers.
1893 *
1894 * Filters are tried with ->be first, then with ->fe if it is
1895 * different from ->be.
1896 *
1897 * Maybe we are in resume condiion. In this case I choose the
1898 * "struct proxy" which contains the rule list matching the resume
1899 * pointer. If none of theses "struct proxy" match, I initialise
1900 * the process with the first one.
1901 *
1902 * In fact, I check only correspondance betwwen the current list
1903 * pointer and the ->fe rule list. If it doesn't match, I initialize
1904 * the loop with the ->be.
1905 */
1906 if (s->current_rule_list == &sess->fe->http_res_rules)
1907 cur_proxy = sess->fe;
1908 else
1909 cur_proxy = s->be;
1910 while (1) {
1911 struct proxy *rule_set = cur_proxy;
1912
1913 /* evaluate http-response rules */
1914 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001915 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001916
1917 if (ret == HTTP_RULE_RES_BADREQ)
1918 goto return_srv_prx_502;
1919
1920 if (ret == HTTP_RULE_RES_DONE) {
1921 rep->analysers &= ~an_bit;
1922 rep->analyse_exp = TICK_ETERNITY;
1923 return 1;
1924 }
1925 }
1926
1927 /* we need to be called again. */
1928 if (ret == HTTP_RULE_RES_YIELD) {
1929 channel_dont_close(rep);
1930 return 0;
1931 }
1932
1933 /* try headers filters */
1934 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001935 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1936 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001937 }
1938
1939 /* has the response been denied ? */
1940 if (txn->flags & TX_SVDENY) {
1941 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001942 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001943
Olivier Houcharda798bf52019-03-08 18:52:00 +01001944 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1945 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001947 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001948 goto return_srv_prx_502;
1949 }
1950
1951 /* add response headers from the rule sets in the same order */
1952 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001953 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001954 if (txn->status < 200 && txn->status != 101)
1955 break;
1956 if (wl->cond) {
1957 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1958 ret = acl_pass(ret);
1959 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1960 ret = !ret;
1961 if (!ret)
1962 continue;
1963 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001964
1965 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1966 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967 goto return_bad_resp;
1968 }
1969
1970 /* check whether we're already working on the frontend */
1971 if (cur_proxy == sess->fe)
1972 break;
1973 cur_proxy = sess->fe;
1974 }
1975
1976 /* After this point, this anayzer can't return yield, so we can
1977 * remove the bit corresponding to this analyzer from the list.
1978 *
1979 * Note that the intermediate returns and goto found previously
1980 * reset the analyzers.
1981 */
1982 rep->analysers &= ~an_bit;
1983 rep->analyse_exp = TICK_ETERNITY;
1984
1985 /* OK that's all we can do for 1xx responses */
1986 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001987 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001988
1989 /*
1990 * Now check for a server cookie.
1991 */
1992 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001993 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001994
1995 /*
1996 * Check for cache-control or pragma headers if required.
1997 */
1998 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1999 check_response_for_cacheability(s, rep);
2000
2001 /*
2002 * Add server cookie in the response if needed
2003 */
2004 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2005 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2006 (!(s->flags & SF_DIRECT) ||
2007 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2008 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2009 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2010 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2011 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2012 !(s->flags & SF_IGNORE_PRST)) {
2013 /* the server is known, it's not the one the client requested, or the
2014 * cookie's last seen date needs to be refreshed. We have to
2015 * insert a set-cookie here, except if we want to insert only on POST
2016 * requests and this one isn't. Note that servers which don't have cookies
2017 * (eg: some backup servers) will return a full cookie removal request.
2018 */
2019 if (!objt_server(s->target)->cookie) {
2020 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002021 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022 s->be->cookie_name);
2023 }
2024 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002025 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002026
2027 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2028 /* emit last_date, which is mandatory */
2029 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2030 s30tob64((date.tv_sec+3) >> 2,
2031 trash.area + trash.data);
2032 trash.data += 5;
2033
2034 if (s->be->cookie_maxlife) {
2035 /* emit first_date, which is either the original one or
2036 * the current date.
2037 */
2038 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2039 s30tob64(txn->cookie_first_date ?
2040 txn->cookie_first_date >> 2 :
2041 (date.tv_sec+3) >> 2,
2042 trash.area + trash.data);
2043 trash.data += 5;
2044 }
2045 }
2046 chunk_appendf(&trash, "; path=/");
2047 }
2048
2049 if (s->be->cookie_domain)
2050 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2051
2052 if (s->be->ck_opts & PR_CK_HTTPONLY)
2053 chunk_appendf(&trash, "; HttpOnly");
2054
2055 if (s->be->ck_opts & PR_CK_SECURE)
2056 chunk_appendf(&trash, "; Secure");
2057
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002058 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002059 goto return_bad_resp;
2060
2061 txn->flags &= ~TX_SCK_MASK;
2062 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2063 /* the server did not change, only the date was updated */
2064 txn->flags |= TX_SCK_UPDATED;
2065 else
2066 txn->flags |= TX_SCK_INSERTED;
2067
2068 /* Here, we will tell an eventual cache on the client side that we don't
2069 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2070 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2071 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2072 */
2073 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2074
2075 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2076
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002077 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002078 goto return_bad_resp;
2079 }
2080 }
2081
2082 /*
2083 * Check if result will be cacheable with a cookie.
2084 * We'll block the response if security checks have caught
2085 * nasty things such as a cacheable cookie.
2086 */
2087 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2088 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2089 (s->be->options & PR_O_CHK_CACHE)) {
2090 /* we're in presence of a cacheable response containing
2091 * a set-cookie header. We'll block it as requested by
2092 * the 'checkcache' option, and send an alert.
2093 */
2094 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002095 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002096
Olivier Houcharda798bf52019-03-08 18:52:00 +01002097 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2098 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002099 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002100 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101
2102 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2103 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2104 send_log(s->be, LOG_ALERT,
2105 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2106 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2107 goto return_srv_prx_502;
2108 }
2109
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002110 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002111 /* Always enter in the body analyzer */
2112 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2113 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2114
2115 /* if the user wants to log as soon as possible, without counting
2116 * bytes from the server, then this is the right moment. We have
2117 * to temporarily assign bytes_out to log what we currently have.
2118 */
2119 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2120 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002121 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002122 s->do_log(s);
2123 s->logs.bytes_out = 0;
2124 }
2125 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002126
2127 return_bad_resp:
2128 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002129 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002130 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002131 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002132 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002133
2134 return_srv_prx_502:
2135 rep->analysers &= AN_RES_FLT_END;
2136 txn->status = 502;
2137 s->logs.t_data = -1; /* was not a valid response */
2138 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002139 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002140 if (!(s->flags & SF_ERR_MASK))
2141 s->flags |= SF_ERR_PRXCOND;
2142 if (!(s->flags & SF_FINST_MASK))
2143 s->flags |= SF_FINST_H;
2144 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002145}
2146
2147/* This function is an analyser which forwards response body (including chunk
2148 * sizes if any). It is called as soon as we must forward, even if we forward
2149 * zero byte. The only situation where it must not be called is when we're in
2150 * tunnel mode and we want to forward till the close. It's used both to forward
2151 * remaining data and to resync after end of body. It expects the msg_state to
2152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2153 * read more data, or 1 once we can go on with next request or end the stream.
2154 *
2155 * It is capable of compressing response data both in content-length mode and
2156 * in chunked mode. The state machines follows different flows depending on
2157 * whether content-length and chunked modes are used, since there are no
2158 * trailers in content-length :
2159 *
2160 * chk-mode cl-mode
2161 * ,----- BODY -----.
2162 * / \
2163 * V size > 0 V chk-mode
2164 * .--> SIZE -------------> DATA -------------> CRLF
2165 * | | size == 0 | last byte |
2166 * | v final crlf v inspected |
2167 * | TRAILERS -----------> DONE |
2168 * | |
2169 * `----------------------------------------------'
2170 *
2171 * Compression only happens in the DATA state, and must be flushed in final
2172 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2173 * is performed at once on final states for all bytes parsed, or when leaving
2174 * on missing data.
2175 */
2176int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2177{
2178 struct session *sess = s->sess;
2179 struct http_txn *txn = s->txn;
2180 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002181 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002182 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183
2184 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2185 now_ms, __FUNCTION__,
2186 s,
2187 res,
2188 res->rex, res->wex,
2189 res->flags,
2190 ci_data(res),
2191 res->analysers);
2192
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002193 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002194
2195 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002196 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197 /* Output closed while we were sending data. We must abort and
2198 * wake the other side up.
2199 */
2200 msg->err_state = msg->msg_state;
2201 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002202 htx_end_response(s);
2203 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 return 1;
2205 }
2206
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 if (msg->msg_state == HTTP_MSG_BODY)
2208 msg->msg_state = HTTP_MSG_DATA;
2209
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210 /* in most states, we should abort in case of early close */
2211 channel_auto_close(res);
2212
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002214 if (res->to_forward == CHN_INFINITE_FORWARD) {
2215 if (res->flags & (CF_SHUTR|CF_EOI)) {
2216 msg->msg_state = HTTP_MSG_DONE;
2217 res->to_forward = 0;
2218 goto done;
2219 }
2220 }
2221 else {
2222 /* We can't process the buffer's contents yet */
2223 res->flags |= CF_WAKE_WRITE;
2224 goto missing_data_or_waiting;
2225 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 }
2227
Christopher Faulet9768c262018-10-22 09:34:31 +02002228 if (msg->msg_state >= HTTP_MSG_DONE)
2229 goto done;
2230
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002231 /* Forward input data. We get it by removing all outgoing data not
2232 * forwarded yet from HTX data size. If there are some data filters, we
2233 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002234 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002235 if (HAS_RSP_DATA_FILTERS(s)) {
2236 ret = flt_http_payload(s, msg, htx->data);
2237 if (ret < 0)
2238 goto return_bad_res;
2239 c_adv(res, ret);
2240 if (htx->data != co_data(res) || htx->extra)
2241 goto missing_data_or_waiting;
2242 }
2243 else {
2244 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002245 if (msg->flags & HTTP_MSGF_XFER_LEN)
2246 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002247 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002248
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002249 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2250 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2251 msg->msg_state = HTTP_MSG_TUNNEL;
2252 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253 }
2254
Christopher Faulet9768c262018-10-22 09:34:31 +02002255 /* Check if the end-of-message is reached and if so, switch the message
2256 * in HTTP_MSG_DONE state.
2257 */
2258 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2259 goto missing_data_or_waiting;
2260
2261 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002262 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002263
2264 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002266 channel_dont_close(res);
2267
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002268 if (HAS_RSP_DATA_FILTERS(s)) {
2269 ret = flt_http_end(s, msg);
2270 if (ret <= 0) {
2271 if (!ret)
2272 goto missing_data_or_waiting;
2273 goto return_bad_res;
2274 }
2275 }
2276
Christopher Fauletf2824e62018-10-01 12:12:37 +02002277 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002279 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2281 if (res->flags & CF_SHUTW) {
2282 /* response errors are most likely due to the
2283 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002284 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 goto return_bad_res;
2287 }
2288 return 1;
2289 }
2290 return 0;
2291
2292 missing_data_or_waiting:
2293 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002294 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295
Christopher Faulet47365272018-10-31 17:40:50 +01002296 if (htx->flags & HTX_FL_PARSING_ERROR)
2297 goto return_bad_res;
2298
Christopher Faulete0768eb2018-10-03 16:38:02 +02002299 /* stop waiting for data if the input is closed before the end. If the
2300 * client side was already closed, it means that the client has aborted,
2301 * so we don't want to count this as a server abort. Otherwise it's a
2302 * server abort.
2303 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002304 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002306 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002308 if (htx_is_empty(htx))
2309 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002310 }
2311
Christopher Faulete0768eb2018-10-03 16:38:02 +02002312 /* When TE: chunked is used, we need to get there again to parse
2313 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002314 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2315 * are filters registered on the stream, we don't want to forward a
2316 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002317 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002318 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002319 channel_dont_close(res);
2320
2321 /* We know that more data are expected, but we couldn't send more that
2322 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2323 * system knows it must not set a PUSH on this first part. Interactive
2324 * modes are already handled by the stream sock layer. We must not do
2325 * this in content-length mode because it could present the MSG_MORE
2326 * flag with the last block of forwarded data, which would cause an
2327 * additional delay to be observed by the receiver.
2328 */
2329 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2330 res->flags |= CF_EXPECT_MORE;
2331
2332 /* the stream handler will take care of timeouts and errors */
2333 return 0;
2334
Christopher Faulet93e02d82019-03-08 14:18:50 +01002335 return_srv_abort:
2336 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2337 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002339 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2340 if (!(s->flags & SF_ERR_MASK))
2341 s->flags |= SF_ERR_SRVCL;
2342 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343
Christopher Faulet93e02d82019-03-08 14:18:50 +01002344 return_cli_abort:
2345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2346 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2349 if (!(s->flags & SF_ERR_MASK))
2350 s->flags |= SF_ERR_CLICL;
2351 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002352
Christopher Faulet93e02d82019-03-08 14:18:50 +01002353 return_bad_res:
2354 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2355 if (objt_server(s->target)) {
2356 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2357 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2358 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002359 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002360 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002361
Christopher Faulet93e02d82019-03-08 14:18:50 +01002362 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363 txn->rsp.err_state = txn->rsp.msg_state;
2364 txn->rsp.msg_state = HTTP_MSG_ERROR;
2365 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002366 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002367 res->analysers &= AN_RES_FLT_END;
2368 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 +02002369 if (!(s->flags & SF_FINST_MASK))
2370 s->flags |= SF_FINST_D;
2371 return 0;
2372}
2373
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002376 * as too large a request to build a valid response.
2377 */
2378int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2379{
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 struct channel *req = &s->req;
2381 struct channel *res = &s->res;
2382 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002383 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002384 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 struct ist status, reason, location;
2386 unsigned int flags;
2387 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
2389 chunk = alloc_trash_chunk();
2390 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002392
Christopher Faulet99daf282018-11-28 22:58:13 +01002393 /*
2394 * Create the location
2395 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002396 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002398 case REDIRECT_TYPE_SCHEME: {
2399 struct http_hdr_ctx ctx;
2400 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401
Christopher Faulet99daf282018-11-28 22:58:13 +01002402 host = ist("");
2403 ctx.blk = NULL;
2404 if (http_find_header(htx, ist("Host"), &ctx, 0))
2405 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 sl = http_find_stline(htx);
2408 path = http_get_path(htx_sl_req_uri(sl));
2409 /* build message using path */
2410 if (path.ptr) {
2411 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2412 int qs = 0;
2413 while (qs < path.len) {
2414 if (*(path.ptr + qs) == '?') {
2415 path.len = qs;
2416 break;
2417 }
2418 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002419 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420 }
2421 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002422 else
2423 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002424
Christopher Faulet99daf282018-11-28 22:58:13 +01002425 if (rule->rdr_str) { /* this is an old "redirect" rule */
2426 /* add scheme */
2427 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2428 goto fail;
2429 }
2430 else {
2431 /* add scheme with executing log format */
2432 chunk->data += build_logline(s, chunk->area + chunk->data,
2433 chunk->size - chunk->data,
2434 &rule->rdr_fmt);
2435 }
2436 /* add "://" + host + path */
2437 if (!chunk_memcat(chunk, "://", 3) ||
2438 !chunk_memcat(chunk, host.ptr, host.len) ||
2439 !chunk_memcat(chunk, path.ptr, path.len))
2440 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441
Christopher Faulet99daf282018-11-28 22:58:13 +01002442 /* append a slash at the end of the location if needed and missing */
2443 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2444 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2445 if (chunk->data + 1 >= chunk->size)
2446 goto fail;
2447 chunk->area[chunk->data++] = '/';
2448 }
2449 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 case REDIRECT_TYPE_PREFIX: {
2453 struct ist path;
2454
2455 sl = http_find_stline(htx);
2456 path = http_get_path(htx_sl_req_uri(sl));
2457 /* build message using path */
2458 if (path.ptr) {
2459 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2460 int qs = 0;
2461 while (qs < path.len) {
2462 if (*(path.ptr + qs) == '?') {
2463 path.len = qs;
2464 break;
2465 }
2466 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002467 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468 }
2469 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002470 else
2471 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472
Christopher Faulet99daf282018-11-28 22:58:13 +01002473 if (rule->rdr_str) { /* this is an old "redirect" rule */
2474 /* add prefix. Note that if prefix == "/", we don't want to
2475 * add anything, otherwise it makes it hard for the user to
2476 * configure a self-redirection.
2477 */
2478 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2479 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2480 goto fail;
2481 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002482 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002483 else {
2484 /* add prefix with executing log format */
2485 chunk->data += build_logline(s, chunk->area + chunk->data,
2486 chunk->size - chunk->data,
2487 &rule->rdr_fmt);
2488 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489
Christopher Faulet99daf282018-11-28 22:58:13 +01002490 /* add path */
2491 if (!chunk_memcat(chunk, path.ptr, path.len))
2492 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 /* append a slash at the end of the location if needed and missing */
2495 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2496 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2497 if (chunk->data + 1 >= chunk->size)
2498 goto fail;
2499 chunk->area[chunk->data++] = '/';
2500 }
2501 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002503 case REDIRECT_TYPE_LOCATION:
2504 default:
2505 if (rule->rdr_str) { /* this is an old "redirect" rule */
2506 /* add location */
2507 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2508 goto fail;
2509 }
2510 else {
2511 /* add location with executing log format */
2512 chunk->data += build_logline(s, chunk->area + chunk->data,
2513 chunk->size - chunk->data,
2514 &rule->rdr_fmt);
2515 }
2516 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002517 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002518 location = ist2(chunk->area, chunk->data);
2519
2520 /*
2521 * Create the 30x response
2522 */
2523 switch (rule->code) {
2524 case 308:
2525 status = ist("308");
2526 reason = ist("Permanent Redirect");
2527 break;
2528 case 307:
2529 status = ist("307");
2530 reason = ist("Temporary Redirect");
2531 break;
2532 case 303:
2533 status = ist("303");
2534 reason = ist("See Other");
2535 break;
2536 case 301:
2537 status = ist("301");
2538 reason = ist("Moved Permanently");
2539 break;
2540 case 302:
2541 default:
2542 status = ist("302");
2543 reason = ist("Found");
2544 break;
2545 }
2546
2547 htx = htx_from_buf(&res->buf);
2548 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2549 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2550 if (!sl)
2551 goto fail;
2552 sl->info.res.status = rule->code;
2553 s->txn->status = rule->code;
2554
2555 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2556 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2557 !htx_add_header(htx, ist("Location"), location))
2558 goto fail;
2559
2560 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2561 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2562 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002563 }
2564
2565 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002566 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2567 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002568 }
2569
Christopher Faulet99daf282018-11-28 22:58:13 +01002570 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2571 goto fail;
2572
Christopher Fauletf2824e62018-10-01 12:12:37 +02002573 /* let's log the request time */
2574 s->logs.tv_request = now;
2575
Christopher Faulet99daf282018-11-28 22:58:13 +01002576 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002577 c_adv(res, data);
2578 res->total += data;
2579
2580 channel_auto_read(req);
2581 channel_abort(req);
2582 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002583 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002584
2585 res->wex = tick_add_ifset(now_ms, res->wto);
2586 channel_auto_read(res);
2587 channel_auto_close(res);
2588 channel_shutr_now(res);
2589
2590 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591
2592 if (!(s->flags & SF_ERR_MASK))
2593 s->flags |= SF_ERR_LOCAL;
2594 if (!(s->flags & SF_FINST_MASK))
2595 s->flags |= SF_FINST_R;
2596
Christopher Faulet99daf282018-11-28 22:58:13 +01002597 free_trash_chunk(chunk);
2598 return 1;
2599
2600 fail:
2601 /* If an error occurred, remove the incomplete HTTP response from the
2602 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002603 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002604 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002605 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002606}
2607
Christopher Faulet72333522018-10-24 11:25:02 +02002608int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2609 struct ist name, const char *str, struct my_regex *re, int action)
2610{
2611 struct http_hdr_ctx ctx;
2612 struct buffer *output = get_trash_chunk();
2613
2614 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2615 ctx.blk = NULL;
2616 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2617 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2618 continue;
2619
2620 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2621 if (output->data == -1)
2622 return -1;
2623 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2624 return -1;
2625 }
2626 return 0;
2627}
2628
2629static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2630 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2631{
2632 struct buffer *replace;
2633 int ret = -1;
2634
2635 replace = alloc_trash_chunk();
2636 if (!replace)
2637 goto leave;
2638
2639 replace->data = build_logline(s, replace->area, replace->size, fmt);
2640 if (replace->data >= replace->size - 1)
2641 goto leave;
2642
2643 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2644
2645 leave:
2646 free_trash_chunk(replace);
2647 return ret;
2648}
2649
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650
2651/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2652 * on success and -1 on error. The response channel is updated accordingly.
2653 */
2654static int htx_reply_103_early_hints(struct channel *res)
2655{
2656 struct htx *htx = htx_from_buf(&res->buf);
2657 size_t data;
2658
2659 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2660 /* If an error occurred during an Early-hint rule,
2661 * remove the incomplete HTTP 103 response from the
2662 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002663 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002664 return -1;
2665 }
2666
2667 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002668 c_adv(res, data);
2669 res->total += data;
2670 return 0;
2671}
2672
Christopher Faulet6eb92892018-11-15 16:39:29 +01002673/*
2674 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2675 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002676 * If <early_hints> is 0, it is starts a new response by adding the start
2677 * line. If an error occurred -1 is returned. On success 0 is returned. The
2678 * channel is not updated here. It must be done calling the function
2679 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002680 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681static 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 +01002682{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002683 struct channel *res = &s->res;
2684 struct htx *htx = htx_from_buf(&res->buf);
2685 struct buffer *value = alloc_trash_chunk();
2686
Christopher Faulet6eb92892018-11-15 16:39:29 +01002687 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002688 struct htx_sl *sl;
2689 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2690 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2691
2692 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2693 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2694 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002695 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002696 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002697 }
2698
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2700 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002701 goto fail;
2702
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002703 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002704 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002705
2706 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002707 /* If an error occurred during an Early-hint rule, remove the incomplete
2708 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002709 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002710 free_trash_chunk(value);
2711 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002712}
2713
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002714/* This function executes one of the set-{method,path,query,uri} actions. It
2715 * takes the string from the variable 'replace' with length 'len', then modifies
2716 * the relevant part of the request line accordingly. Then it updates various
2717 * pointers to the next elements which were moved, and the total buffer length.
2718 * It finds the action to be performed in p[2], previously filled by function
2719 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2720 * error, though this can be revisited when this code is finally exploited.
2721 *
2722 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2723 * query string and 3 to replace uri.
2724 *
2725 * In query string case, the mark question '?' must be set at the start of the
2726 * string by the caller, event if the replacement query string is empty.
2727 */
2728int htx_req_replace_stline(int action, const char *replace, int len,
2729 struct proxy *px, struct stream *s)
2730{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002731 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002732
2733 switch (action) {
2734 case 0: // method
2735 if (!http_replace_req_meth(htx, ist2(replace, len)))
2736 return -1;
2737 break;
2738
2739 case 1: // path
2740 if (!http_replace_req_path(htx, ist2(replace, len)))
2741 return -1;
2742 break;
2743
2744 case 2: // query
2745 if (!http_replace_req_query(htx, ist2(replace, len)))
2746 return -1;
2747 break;
2748
2749 case 3: // uri
2750 if (!http_replace_req_uri(htx, ist2(replace, len)))
2751 return -1;
2752 break;
2753
2754 default:
2755 return -1;
2756 }
2757 return 0;
2758}
2759
2760/* This function replace the HTTP status code and the associated message. The
2761 * variable <status> contains the new status code. This function never fails.
2762 */
2763void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2764{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002765 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002766 char *res;
2767
2768 chunk_reset(&trash);
2769 res = ultoa_o(status, trash.area, trash.size);
2770 trash.data = res - trash.area;
2771
2772 /* Do we have a custom reason format string? */
2773 if (reason == NULL)
2774 reason = http_get_reason(status);
2775
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002776 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002777 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2778}
2779
Christopher Faulet3e964192018-10-24 11:39:23 +02002780/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2781 * transaction <txn>. Returns the verdict of the first rule that prevents
2782 * further processing of the request (auth, deny, ...), and defaults to
2783 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2784 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2785 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2786 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2787 * status.
2788 */
2789static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2790 struct stream *s, int *deny_status)
2791{
2792 struct session *sess = strm_sess(s);
2793 struct http_txn *txn = s->txn;
2794 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002795 struct act_rule *rule;
2796 struct http_hdr_ctx ctx;
2797 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002798 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2799 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002800 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002801
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002802 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002803
2804 /* If "the current_rule_list" match the executed rule list, we are in
2805 * resume condition. If a resume is needed it is always in the action
2806 * and never in the ACL or converters. In this case, we initialise the
2807 * current rule, and go to the action execution point.
2808 */
2809 if (s->current_rule) {
2810 rule = s->current_rule;
2811 s->current_rule = NULL;
2812 if (s->current_rule_list == rules)
2813 goto resume_execution;
2814 }
2815 s->current_rule_list = rules;
2816
2817 list_for_each_entry(rule, rules, list) {
2818 /* check optional condition */
2819 if (rule->cond) {
2820 int ret;
2821
2822 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2823 ret = acl_pass(ret);
2824
2825 if (rule->cond->pol == ACL_COND_UNLESS)
2826 ret = !ret;
2827
2828 if (!ret) /* condition not matched */
2829 continue;
2830 }
2831
2832 act_flags |= ACT_FLAG_FIRST;
2833 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002834 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2835 early_hints = 0;
2836 if (htx_reply_103_early_hints(&s->res) == -1) {
2837 rule_ret = HTTP_RULE_RES_BADREQ;
2838 goto end;
2839 }
2840 }
2841
Christopher Faulet3e964192018-10-24 11:39:23 +02002842 switch (rule->action) {
2843 case ACT_ACTION_ALLOW:
2844 rule_ret = HTTP_RULE_RES_STOP;
2845 goto end;
2846
2847 case ACT_ACTION_DENY:
2848 if (deny_status)
2849 *deny_status = rule->deny_status;
2850 rule_ret = HTTP_RULE_RES_DENY;
2851 goto end;
2852
2853 case ACT_HTTP_REQ_TARPIT:
2854 txn->flags |= TX_CLTARPIT;
2855 if (deny_status)
2856 *deny_status = rule->deny_status;
2857 rule_ret = HTTP_RULE_RES_DENY;
2858 goto end;
2859
2860 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002861 /* Auth might be performed on regular http-req rules as well as on stats */
2862 auth_realm = rule->arg.auth.realm;
2863 if (!auth_realm) {
2864 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2865 auth_realm = STATS_DEFAULT_REALM;
2866 else
2867 auth_realm = px->id;
2868 }
2869 /* send 401/407 depending on whether we use a proxy or not. We still
2870 * count one error, because normal browsing won't significantly
2871 * increase the counter but brute force attempts will.
2872 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002873 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002874 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2875 rule_ret = HTTP_RULE_RES_BADREQ;
2876 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002877 goto end;
2878
2879 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002880 rule_ret = HTTP_RULE_RES_DONE;
2881 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2882 rule_ret = HTTP_RULE_RES_BADREQ;
2883 goto end;
2884
2885 case ACT_HTTP_SET_NICE:
2886 s->task->nice = rule->arg.nice;
2887 break;
2888
2889 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002890 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002891 break;
2892
2893 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002894 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002895 break;
2896
2897 case ACT_HTTP_SET_LOGL:
2898 s->logs.level = rule->arg.loglevel;
2899 break;
2900
2901 case ACT_HTTP_REPLACE_HDR:
2902 case ACT_HTTP_REPLACE_VAL:
2903 if (htx_transform_header(s, &s->req, htx,
2904 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2905 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002906 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002907 rule_ret = HTTP_RULE_RES_BADREQ;
2908 goto end;
2909 }
2910 break;
2911
2912 case ACT_HTTP_DEL_HDR:
2913 /* remove all occurrences of the header */
2914 ctx.blk = NULL;
2915 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2916 http_remove_header(htx, &ctx);
2917 break;
2918
2919 case ACT_HTTP_SET_HDR:
2920 case ACT_HTTP_ADD_HDR: {
2921 /* The scope of the trash buffer must be limited to this function. The
2922 * build_logline() function can execute a lot of other function which
2923 * can use the trash buffer. So for limiting the scope of this global
2924 * buffer, we build first the header value using build_logline, and
2925 * after we store the header name.
2926 */
2927 struct buffer *replace;
2928 struct ist n, v;
2929
2930 replace = alloc_trash_chunk();
2931 if (!replace) {
2932 rule_ret = HTTP_RULE_RES_BADREQ;
2933 goto end;
2934 }
2935
2936 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2937 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2938 v = ist2(replace->area, replace->data);
2939
2940 if (rule->action == ACT_HTTP_SET_HDR) {
2941 /* remove all occurrences of the header */
2942 ctx.blk = NULL;
2943 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2944 http_remove_header(htx, &ctx);
2945 }
2946
2947 if (!http_add_header(htx, n, v)) {
2948 static unsigned char rate_limit = 0;
2949
2950 if ((rate_limit++ & 255) == 0) {
2951 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);
2952 }
2953
Olivier Houcharda798bf52019-03-08 18:52:00 +01002954 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002955 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002956 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002957 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002958 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002959 }
2960 free_trash_chunk(replace);
2961 break;
2962 }
2963
2964 case ACT_HTTP_DEL_ACL:
2965 case ACT_HTTP_DEL_MAP: {
2966 struct pat_ref *ref;
2967 struct buffer *key;
2968
2969 /* collect reference */
2970 ref = pat_ref_lookup(rule->arg.map.ref);
2971 if (!ref)
2972 continue;
2973
2974 /* allocate key */
2975 key = alloc_trash_chunk();
2976 if (!key) {
2977 rule_ret = HTTP_RULE_RES_BADREQ;
2978 goto end;
2979 }
2980
2981 /* collect key */
2982 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2983 key->area[key->data] = '\0';
2984
2985 /* perform update */
2986 /* returned code: 1=ok, 0=ko */
2987 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2988 pat_ref_delete(ref, key->area);
2989 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2990
2991 free_trash_chunk(key);
2992 break;
2993 }
2994
2995 case ACT_HTTP_ADD_ACL: {
2996 struct pat_ref *ref;
2997 struct buffer *key;
2998
2999 /* collect reference */
3000 ref = pat_ref_lookup(rule->arg.map.ref);
3001 if (!ref)
3002 continue;
3003
3004 /* allocate key */
3005 key = alloc_trash_chunk();
3006 if (!key) {
3007 rule_ret = HTTP_RULE_RES_BADREQ;
3008 goto end;
3009 }
3010
3011 /* collect key */
3012 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3013 key->area[key->data] = '\0';
3014
3015 /* perform update */
3016 /* add entry only if it does not already exist */
3017 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3018 if (pat_ref_find_elt(ref, key->area) == NULL)
3019 pat_ref_add(ref, key->area, NULL, NULL);
3020 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3021
3022 free_trash_chunk(key);
3023 break;
3024 }
3025
3026 case ACT_HTTP_SET_MAP: {
3027 struct pat_ref *ref;
3028 struct buffer *key, *value;
3029
3030 /* collect reference */
3031 ref = pat_ref_lookup(rule->arg.map.ref);
3032 if (!ref)
3033 continue;
3034
3035 /* allocate key */
3036 key = alloc_trash_chunk();
3037 if (!key) {
3038 rule_ret = HTTP_RULE_RES_BADREQ;
3039 goto end;
3040 }
3041
3042 /* allocate value */
3043 value = alloc_trash_chunk();
3044 if (!value) {
3045 free_trash_chunk(key);
3046 rule_ret = HTTP_RULE_RES_BADREQ;
3047 goto end;
3048 }
3049
3050 /* collect key */
3051 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3052 key->area[key->data] = '\0';
3053
3054 /* collect value */
3055 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3056 value->area[value->data] = '\0';
3057
3058 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003059 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003060 if (pat_ref_find_elt(ref, key->area) != NULL)
3061 /* update entry if it exists */
3062 pat_ref_set(ref, key->area, value->area, NULL);
3063 else
3064 /* insert a new entry */
3065 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003066 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003067 free_trash_chunk(key);
3068 free_trash_chunk(value);
3069 break;
3070 }
3071
3072 case ACT_HTTP_EARLY_HINT:
3073 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3074 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003075 early_hints = htx_add_early_hint_header(s, early_hints,
3076 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003077 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003078 if (early_hints == -1) {
3079 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003080 goto end;
3081 }
3082 break;
3083
3084 case ACT_CUSTOM:
3085 if ((s->req.flags & CF_READ_ERROR) ||
3086 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003087 (px->options & PR_O_ABRT_CLOSE)))
3088 act_flags |= ACT_FLAG_FINAL;
3089
3090 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3091 case ACT_RET_ERR:
3092 case ACT_RET_CONT:
3093 break;
3094 case ACT_RET_STOP:
3095 rule_ret = HTTP_RULE_RES_DONE;
3096 goto end;
3097 case ACT_RET_YIELD:
3098 s->current_rule = rule;
3099 rule_ret = HTTP_RULE_RES_YIELD;
3100 goto end;
3101 }
3102 break;
3103
3104 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3105 /* Note: only the first valid tracking parameter of each
3106 * applies.
3107 */
3108
3109 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3110 struct stktable *t;
3111 struct stksess *ts;
3112 struct stktable_key *key;
3113 void *ptr1, *ptr2;
3114
3115 t = rule->arg.trk_ctr.table.t;
3116 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3117 rule->arg.trk_ctr.expr, NULL);
3118
3119 if (key && (ts = stktable_get_entry(t, key))) {
3120 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3121
3122 /* let's count a new HTTP request as it's the first time we do it */
3123 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3124 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3125 if (ptr1 || ptr2) {
3126 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3127
3128 if (ptr1)
3129 stktable_data_cast(ptr1, http_req_cnt)++;
3130
3131 if (ptr2)
3132 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3133 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3134
3135 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3136
3137 /* If data was modified, we need to touch to re-schedule sync */
3138 stktable_touch_local(t, ts, 0);
3139 }
3140
3141 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3142 if (sess->fe != s->be)
3143 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3144 }
3145 }
3146 break;
3147
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003148 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003149 default:
3150 break;
3151 }
3152 }
3153
3154 end:
3155 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003156 if (htx_reply_103_early_hints(&s->res) == -1)
3157 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003158 }
3159
3160 /* we reached the end of the rules, nothing to report */
3161 return rule_ret;
3162}
3163
3164/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3165 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3166 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3167 * is returned, the process can continue the evaluation of next rule list. If
3168 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3169 * is returned, it means the operation could not be processed and a server error
3170 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3171 * deny rule. If *YIELD is returned, the caller must call again the function
3172 * with the same context.
3173 */
3174static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3175 struct stream *s)
3176{
3177 struct session *sess = strm_sess(s);
3178 struct http_txn *txn = s->txn;
3179 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003180 struct act_rule *rule;
3181 struct http_hdr_ctx ctx;
3182 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3183 int act_flags = 0;
3184
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003185 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003186
3187 /* If "the current_rule_list" match the executed rule list, we are in
3188 * resume condition. If a resume is needed it is always in the action
3189 * and never in the ACL or converters. In this case, we initialise the
3190 * current rule, and go to the action execution point.
3191 */
3192 if (s->current_rule) {
3193 rule = s->current_rule;
3194 s->current_rule = NULL;
3195 if (s->current_rule_list == rules)
3196 goto resume_execution;
3197 }
3198 s->current_rule_list = rules;
3199
3200 list_for_each_entry(rule, rules, list) {
3201 /* check optional condition */
3202 if (rule->cond) {
3203 int ret;
3204
3205 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3206 ret = acl_pass(ret);
3207
3208 if (rule->cond->pol == ACL_COND_UNLESS)
3209 ret = !ret;
3210
3211 if (!ret) /* condition not matched */
3212 continue;
3213 }
3214
3215 act_flags |= ACT_FLAG_FIRST;
3216resume_execution:
3217 switch (rule->action) {
3218 case ACT_ACTION_ALLOW:
3219 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3220 goto end;
3221
3222 case ACT_ACTION_DENY:
3223 txn->flags |= TX_SVDENY;
3224 rule_ret = HTTP_RULE_RES_STOP;
3225 goto end;
3226
3227 case ACT_HTTP_SET_NICE:
3228 s->task->nice = rule->arg.nice;
3229 break;
3230
3231 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003232 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003233 break;
3234
3235 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003236 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003237 break;
3238
3239 case ACT_HTTP_SET_LOGL:
3240 s->logs.level = rule->arg.loglevel;
3241 break;
3242
3243 case ACT_HTTP_REPLACE_HDR:
3244 case ACT_HTTP_REPLACE_VAL:
3245 if (htx_transform_header(s, &s->res, htx,
3246 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3247 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003248 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003249 rule_ret = HTTP_RULE_RES_BADREQ;
3250 goto end;
3251 }
3252 break;
3253
3254 case ACT_HTTP_DEL_HDR:
3255 /* remove all occurrences of the header */
3256 ctx.blk = NULL;
3257 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3258 http_remove_header(htx, &ctx);
3259 break;
3260
3261 case ACT_HTTP_SET_HDR:
3262 case ACT_HTTP_ADD_HDR: {
3263 struct buffer *replace;
3264 struct ist n, v;
3265
3266 replace = alloc_trash_chunk();
3267 if (!replace) {
3268 rule_ret = HTTP_RULE_RES_BADREQ;
3269 goto end;
3270 }
3271
3272 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3273 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3274 v = ist2(replace->area, replace->data);
3275
3276 if (rule->action == ACT_HTTP_SET_HDR) {
3277 /* remove all occurrences of the header */
3278 ctx.blk = NULL;
3279 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3280 http_remove_header(htx, &ctx);
3281 }
3282
3283 if (!http_add_header(htx, n, v)) {
3284 static unsigned char rate_limit = 0;
3285
3286 if ((rate_limit++ & 255) == 0) {
3287 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);
3288 }
3289
Olivier Houcharda798bf52019-03-08 18:52:00 +01003290 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003291 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003292 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003293 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003294 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003295 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003296 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003297 }
3298 free_trash_chunk(replace);
3299 break;
3300 }
3301
3302 case ACT_HTTP_DEL_ACL:
3303 case ACT_HTTP_DEL_MAP: {
3304 struct pat_ref *ref;
3305 struct buffer *key;
3306
3307 /* collect reference */
3308 ref = pat_ref_lookup(rule->arg.map.ref);
3309 if (!ref)
3310 continue;
3311
3312 /* allocate key */
3313 key = alloc_trash_chunk();
3314 if (!key) {
3315 rule_ret = HTTP_RULE_RES_BADREQ;
3316 goto end;
3317 }
3318
3319 /* collect key */
3320 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3321 key->area[key->data] = '\0';
3322
3323 /* perform update */
3324 /* returned code: 1=ok, 0=ko */
3325 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3326 pat_ref_delete(ref, key->area);
3327 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3328
3329 free_trash_chunk(key);
3330 break;
3331 }
3332
3333 case ACT_HTTP_ADD_ACL: {
3334 struct pat_ref *ref;
3335 struct buffer *key;
3336
3337 /* collect reference */
3338 ref = pat_ref_lookup(rule->arg.map.ref);
3339 if (!ref)
3340 continue;
3341
3342 /* allocate key */
3343 key = alloc_trash_chunk();
3344 if (!key) {
3345 rule_ret = HTTP_RULE_RES_BADREQ;
3346 goto end;
3347 }
3348
3349 /* collect key */
3350 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3351 key->area[key->data] = '\0';
3352
3353 /* perform update */
3354 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003355 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003356 if (pat_ref_find_elt(ref, key->area) == NULL)
3357 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003358 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003359 free_trash_chunk(key);
3360 break;
3361 }
3362
3363 case ACT_HTTP_SET_MAP: {
3364 struct pat_ref *ref;
3365 struct buffer *key, *value;
3366
3367 /* collect reference */
3368 ref = pat_ref_lookup(rule->arg.map.ref);
3369 if (!ref)
3370 continue;
3371
3372 /* allocate key */
3373 key = alloc_trash_chunk();
3374 if (!key) {
3375 rule_ret = HTTP_RULE_RES_BADREQ;
3376 goto end;
3377 }
3378
3379 /* allocate value */
3380 value = alloc_trash_chunk();
3381 if (!value) {
3382 free_trash_chunk(key);
3383 rule_ret = HTTP_RULE_RES_BADREQ;
3384 goto end;
3385 }
3386
3387 /* collect key */
3388 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3389 key->area[key->data] = '\0';
3390
3391 /* collect value */
3392 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3393 value->area[value->data] = '\0';
3394
3395 /* perform update */
3396 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3397 if (pat_ref_find_elt(ref, key->area) != NULL)
3398 /* update entry if it exists */
3399 pat_ref_set(ref, key->area, value->area, NULL);
3400 else
3401 /* insert a new entry */
3402 pat_ref_add(ref, key->area, value->area, NULL);
3403 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3404 free_trash_chunk(key);
3405 free_trash_chunk(value);
3406 break;
3407 }
3408
3409 case ACT_HTTP_REDIR:
3410 rule_ret = HTTP_RULE_RES_DONE;
3411 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3412 rule_ret = HTTP_RULE_RES_BADREQ;
3413 goto end;
3414
3415 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3416 /* Note: only the first valid tracking parameter of each
3417 * applies.
3418 */
3419 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3420 struct stktable *t;
3421 struct stksess *ts;
3422 struct stktable_key *key;
3423 void *ptr;
3424
3425 t = rule->arg.trk_ctr.table.t;
3426 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3427 rule->arg.trk_ctr.expr, NULL);
3428
3429 if (key && (ts = stktable_get_entry(t, key))) {
3430 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3431
3432 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3433
3434 /* let's count a new HTTP request as it's the first time we do it */
3435 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3436 if (ptr)
3437 stktable_data_cast(ptr, http_req_cnt)++;
3438
3439 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3440 if (ptr)
3441 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3442 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3443
3444 /* When the client triggers a 4xx from the server, it's most often due
3445 * to a missing object or permission. These events should be tracked
3446 * because if they happen often, it may indicate a brute force or a
3447 * vulnerability scan. Normally this is done when receiving the response
3448 * but here we're tracking after this ought to have been done so we have
3449 * to do it on purpose.
3450 */
3451 if ((unsigned)(txn->status - 400) < 100) {
3452 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3453 if (ptr)
3454 stktable_data_cast(ptr, http_err_cnt)++;
3455
3456 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3457 if (ptr)
3458 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3459 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3460 }
3461
3462 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3463
3464 /* If data was modified, we need to touch to re-schedule sync */
3465 stktable_touch_local(t, ts, 0);
3466
3467 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3468 if (sess->fe != s->be)
3469 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3470 }
3471 }
3472 break;
3473
3474 case ACT_CUSTOM:
3475 if ((s->req.flags & CF_READ_ERROR) ||
3476 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003477 (px->options & PR_O_ABRT_CLOSE)))
3478 act_flags |= ACT_FLAG_FINAL;
3479
3480 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3481 case ACT_RET_ERR:
3482 case ACT_RET_CONT:
3483 break;
3484 case ACT_RET_STOP:
3485 rule_ret = HTTP_RULE_RES_STOP;
3486 goto end;
3487 case ACT_RET_YIELD:
3488 s->current_rule = rule;
3489 rule_ret = HTTP_RULE_RES_YIELD;
3490 goto end;
3491 }
3492 break;
3493
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003494 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003495 default:
3496 break;
3497 }
3498 }
3499
3500 end:
3501 /* we reached the end of the rules, nothing to report */
3502 return rule_ret;
3503}
3504
Christopher Faulet33640082018-10-24 11:53:01 +02003505/* Iterate the same filter through all request headers.
3506 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3507 * Since it can manage the switch to another backend, it updates the per-proxy
3508 * DENY stats.
3509 */
3510static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3511{
3512 struct http_txn *txn = s->txn;
3513 struct htx *htx;
3514 struct buffer *hdr = get_trash_chunk();
3515 int32_t pos;
3516
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003517 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003518
3519 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3520 struct htx_blk *blk = htx_get_blk(htx, pos);
3521 enum htx_blk_type type;
3522 struct ist n, v;
3523
3524 next_hdr:
3525 type = htx_get_blk_type(blk);
3526 if (type == HTX_BLK_EOH)
3527 break;
3528 if (type != HTX_BLK_HDR)
3529 continue;
3530
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
3539 n = htx_get_blk_name(htx, blk);
3540 v = htx_get_blk_value(htx, blk);
3541
Christopher Faulet02e771a2019-02-26 15:36:05 +01003542 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003543 hdr->area[hdr->data++] = ':';
3544 hdr->area[hdr->data++] = ' ';
3545 chunk_memcat(hdr, v.ptr, v.len);
3546
3547 /* Now we have one header in <hdr> */
3548
3549 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3550 struct http_hdr_ctx ctx;
3551 int len;
3552
3553 switch (exp->action) {
3554 case ACT_ALLOW:
3555 txn->flags |= TX_CLALLOW;
3556 goto end;
3557
3558 case ACT_DENY:
3559 txn->flags |= TX_CLDENY;
3560 goto end;
3561
3562 case ACT_TARPIT:
3563 txn->flags |= TX_CLTARPIT;
3564 goto end;
3565
3566 case ACT_REPLACE:
3567 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3568 if (len < 0)
3569 return -1;
3570
3571 http_parse_header(ist2(trash.area, len), &n, &v);
3572 ctx.blk = blk;
3573 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003574 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003575 if (!http_replace_header(htx, &ctx, n, v))
3576 return -1;
3577 if (!ctx.blk)
3578 goto end;
3579 pos = htx_get_blk_pos(htx, blk);
3580 break;
3581
3582 case ACT_REMOVE:
3583 ctx.blk = blk;
3584 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003585 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003586 if (!http_remove_header(htx, &ctx))
3587 return -1;
3588 if (!ctx.blk)
3589 goto end;
3590 pos = htx_get_blk_pos(htx, blk);
3591 goto next_hdr;
3592
3593 }
3594 }
3595 }
3596 end:
3597 return 0;
3598}
3599
3600/* Apply the filter to the request line.
3601 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3602 * or -1 if a replacement resulted in an invalid request line.
3603 * Since it can manage the switch to another backend, it updates the per-proxy
3604 * DENY stats.
3605 */
3606static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3607{
3608 struct http_txn *txn = s->txn;
3609 struct htx *htx;
3610 struct buffer *reqline = get_trash_chunk();
3611 int done;
3612
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003613 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003614
3615 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3616 return 1;
3617 else if (unlikely(txn->flags & TX_CLALLOW) &&
3618 (exp->action == ACT_ALLOW ||
3619 exp->action == ACT_DENY ||
3620 exp->action == ACT_TARPIT))
3621 return 0;
3622 else if (exp->action == ACT_REMOVE)
3623 return 0;
3624
3625 done = 0;
3626
3627 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3628
3629 /* Now we have the request line between cur_ptr and cur_end */
3630 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003631 struct htx_sl *sl = http_find_stline(htx);
3632 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003633 int len;
3634
3635 switch (exp->action) {
3636 case ACT_ALLOW:
3637 txn->flags |= TX_CLALLOW;
3638 done = 1;
3639 break;
3640
3641 case ACT_DENY:
3642 txn->flags |= TX_CLDENY;
3643 done = 1;
3644 break;
3645
3646 case ACT_TARPIT:
3647 txn->flags |= TX_CLTARPIT;
3648 done = 1;
3649 break;
3650
3651 case ACT_REPLACE:
3652 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3653 if (len < 0)
3654 return -1;
3655
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003656 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3657 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3658 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003659 return -1;
3660 done = 1;
3661 break;
3662 }
3663 }
3664 return done;
3665}
3666
3667/*
3668 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3669 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3670 * unparsable request. Since it can manage the switch to another backend, it
3671 * updates the per-proxy DENY stats.
3672 */
3673static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3674{
3675 struct session *sess = s->sess;
3676 struct http_txn *txn = s->txn;
3677 struct hdr_exp *exp;
3678
3679 for (exp = px->req_exp; exp; exp = exp->next) {
3680 int ret;
3681
3682 /*
3683 * The interleaving of transformations and verdicts
3684 * makes it difficult to decide to continue or stop
3685 * the evaluation.
3686 */
3687
3688 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3689 break;
3690
3691 if ((txn->flags & TX_CLALLOW) &&
3692 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3693 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3694 continue;
3695
3696 /* if this filter had a condition, evaluate it now and skip to
3697 * next filter if the condition does not match.
3698 */
3699 if (exp->cond) {
3700 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3701 ret = acl_pass(ret);
3702 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3703 ret = !ret;
3704
3705 if (!ret)
3706 continue;
3707 }
3708
3709 /* Apply the filter to the request line. */
3710 ret = htx_apply_filter_to_req_line(s, req, exp);
3711 if (unlikely(ret < 0))
3712 return -1;
3713
3714 if (likely(ret == 0)) {
3715 /* The filter did not match the request, it can be
3716 * iterated through all headers.
3717 */
3718 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3719 return -1;
3720 }
3721 }
3722 return 0;
3723}
3724
3725/* Iterate the same filter through all response headers contained in <res>.
3726 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3727 */
3728static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3729{
3730 struct http_txn *txn = s->txn;
3731 struct htx *htx;
3732 struct buffer *hdr = get_trash_chunk();
3733 int32_t pos;
3734
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003735 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003736
3737 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3738 struct htx_blk *blk = htx_get_blk(htx, pos);
3739 enum htx_blk_type type;
3740 struct ist n, v;
3741
3742 next_hdr:
3743 type = htx_get_blk_type(blk);
3744 if (type == HTX_BLK_EOH)
3745 break;
3746 if (type != HTX_BLK_HDR)
3747 continue;
3748
3749 if (unlikely(txn->flags & TX_SVDENY))
3750 return 1;
3751 else if (unlikely(txn->flags & TX_SVALLOW) &&
3752 (exp->action == ACT_ALLOW ||
3753 exp->action == ACT_DENY))
3754 return 0;
3755
3756 n = htx_get_blk_name(htx, blk);
3757 v = htx_get_blk_value(htx, blk);
3758
Christopher Faulet02e771a2019-02-26 15:36:05 +01003759 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003760 hdr->area[hdr->data++] = ':';
3761 hdr->area[hdr->data++] = ' ';
3762 chunk_memcat(hdr, v.ptr, v.len);
3763
3764 /* Now we have one header in <hdr> */
3765
3766 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3767 struct http_hdr_ctx ctx;
3768 int len;
3769
3770 switch (exp->action) {
3771 case ACT_ALLOW:
3772 txn->flags |= TX_SVALLOW;
3773 goto end;
3774 break;
3775
3776 case ACT_DENY:
3777 txn->flags |= TX_SVDENY;
3778 goto end;
3779 break;
3780
3781 case ACT_REPLACE:
3782 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3783 if (len < 0)
3784 return -1;
3785
3786 http_parse_header(ist2(trash.area, len), &n, &v);
3787 ctx.blk = blk;
3788 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003789 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003790 if (!http_replace_header(htx, &ctx, n, v))
3791 return -1;
3792 if (!ctx.blk)
3793 goto end;
3794 pos = htx_get_blk_pos(htx, blk);
3795 break;
3796
3797 case ACT_REMOVE:
3798 ctx.blk = blk;
3799 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003800 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003801 if (!http_remove_header(htx, &ctx))
3802 return -1;
3803 if (!ctx.blk)
3804 goto end;
3805 pos = htx_get_blk_pos(htx, blk);
3806 goto next_hdr;
3807 }
3808 }
3809
3810 }
3811 end:
3812 return 0;
3813}
3814
3815/* Apply the filter to the status line in the response buffer <res>.
3816 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3817 * or -1 if a replacement resulted in an invalid status line.
3818 */
3819static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3820{
3821 struct http_txn *txn = s->txn;
3822 struct htx *htx;
3823 struct buffer *resline = get_trash_chunk();
3824 int done;
3825
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003826 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003827
3828 if (unlikely(txn->flags & TX_SVDENY))
3829 return 1;
3830 else if (unlikely(txn->flags & TX_SVALLOW) &&
3831 (exp->action == ACT_ALLOW ||
3832 exp->action == ACT_DENY))
3833 return 0;
3834 else if (exp->action == ACT_REMOVE)
3835 return 0;
3836
3837 done = 0;
3838 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3839
3840 /* Now we have the status line between cur_ptr and cur_end */
3841 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003842 struct htx_sl *sl = http_find_stline(htx);
3843 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003844 int len;
3845
3846 switch (exp->action) {
3847 case ACT_ALLOW:
3848 txn->flags |= TX_SVALLOW;
3849 done = 1;
3850 break;
3851
3852 case ACT_DENY:
3853 txn->flags |= TX_SVDENY;
3854 done = 1;
3855 break;
3856
3857 case ACT_REPLACE:
3858 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3859 if (len < 0)
3860 return -1;
3861
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003862 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3863 sl->info.res.status = strl2ui(code.ptr, code.len);
3864 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003865 return -1;
3866
3867 done = 1;
3868 return 1;
3869 }
3870 }
3871 return done;
3872}
3873
3874/*
3875 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3876 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3877 * unparsable response.
3878 */
3879static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3880{
3881 struct session *sess = s->sess;
3882 struct http_txn *txn = s->txn;
3883 struct hdr_exp *exp;
3884
3885 for (exp = px->rsp_exp; exp; exp = exp->next) {
3886 int ret;
3887
3888 /*
3889 * The interleaving of transformations and verdicts
3890 * makes it difficult to decide to continue or stop
3891 * the evaluation.
3892 */
3893
3894 if (txn->flags & TX_SVDENY)
3895 break;
3896
3897 if ((txn->flags & TX_SVALLOW) &&
3898 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3899 exp->action == ACT_PASS)) {
3900 exp = exp->next;
3901 continue;
3902 }
3903
3904 /* if this filter had a condition, evaluate it now and skip to
3905 * next filter if the condition does not match.
3906 */
3907 if (exp->cond) {
3908 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3909 ret = acl_pass(ret);
3910 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3911 ret = !ret;
3912 if (!ret)
3913 continue;
3914 }
3915
3916 /* Apply the filter to the status line. */
3917 ret = htx_apply_filter_to_sts_line(s, res, exp);
3918 if (unlikely(ret < 0))
3919 return -1;
3920
3921 if (likely(ret == 0)) {
3922 /* The filter did not match the response, it can be
3923 * iterated through all headers.
3924 */
3925 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3926 return -1;
3927 }
3928 }
3929 return 0;
3930}
3931
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003932/*
3933 * Manage client-side cookie. It can impact performance by about 2% so it is
3934 * desirable to call it only when needed. This code is quite complex because
3935 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3936 * highly recommended not to touch this part without a good reason !
3937 */
3938static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3939{
3940 struct session *sess = s->sess;
3941 struct http_txn *txn = s->txn;
3942 struct htx *htx;
3943 struct http_hdr_ctx ctx;
3944 char *hdr_beg, *hdr_end, *del_from;
3945 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3946 int preserve_hdr;
3947
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003948 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003949 ctx.blk = NULL;
3950 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3951 del_from = NULL; /* nothing to be deleted */
3952 preserve_hdr = 0; /* assume we may kill the whole header */
3953
3954 /* Now look for cookies. Conforming to RFC2109, we have to support
3955 * attributes whose name begin with a '$', and associate them with
3956 * the right cookie, if we want to delete this cookie.
3957 * So there are 3 cases for each cookie read :
3958 * 1) it's a special attribute, beginning with a '$' : ignore it.
3959 * 2) it's a server id cookie that we *MAY* want to delete : save
3960 * some pointers on it (last semi-colon, beginning of cookie...)
3961 * 3) it's an application cookie : we *MAY* have to delete a previous
3962 * "special" cookie.
3963 * At the end of loop, if a "special" cookie remains, we may have to
3964 * remove it. If no application cookie persists in the header, we
3965 * *MUST* delete it.
3966 *
3967 * Note: RFC2965 is unclear about the processing of spaces around
3968 * the equal sign in the ATTR=VALUE form. A careful inspection of
3969 * the RFC explicitly allows spaces before it, and not within the
3970 * tokens (attrs or values). An inspection of RFC2109 allows that
3971 * too but section 10.1.3 lets one think that spaces may be allowed
3972 * after the equal sign too, resulting in some (rare) buggy
3973 * implementations trying to do that. So let's do what servers do.
3974 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3975 * allowed quoted strings in values, with any possible character
3976 * after a backslash, including control chars and delimitors, which
3977 * causes parsing to become ambiguous. Browsers also allow spaces
3978 * within values even without quotes.
3979 *
3980 * We have to keep multiple pointers in order to support cookie
3981 * removal at the beginning, middle or end of header without
3982 * corrupting the header. All of these headers are valid :
3983 *
3984 * hdr_beg hdr_end
3985 * | |
3986 * v |
3987 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3988 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3989 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3990 * | | | | | | |
3991 * | | | | | | |
3992 * | | | | | | +--> next
3993 * | | | | | +----> val_end
3994 * | | | | +-----------> val_beg
3995 * | | | +--------------> equal
3996 * | | +----------------> att_end
3997 * | +---------------------> att_beg
3998 * +--------------------------> prev
3999 *
4000 */
4001 hdr_beg = ctx.value.ptr;
4002 hdr_end = hdr_beg + ctx.value.len;
4003 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4004 /* Iterate through all cookies on this line */
4005
4006 /* find att_beg */
4007 att_beg = prev;
4008 if (prev > hdr_beg)
4009 att_beg++;
4010
4011 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4012 att_beg++;
4013
4014 /* find att_end : this is the first character after the last non
4015 * space before the equal. It may be equal to hdr_end.
4016 */
4017 equal = att_end = att_beg;
4018 while (equal < hdr_end) {
4019 if (*equal == '=' || *equal == ',' || *equal == ';')
4020 break;
4021 if (HTTP_IS_SPHT(*equal++))
4022 continue;
4023 att_end = equal;
4024 }
4025
4026 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4027 * is between <att_beg> and <equal>, both may be identical.
4028 */
4029 /* look for end of cookie if there is an equal sign */
4030 if (equal < hdr_end && *equal == '=') {
4031 /* look for the beginning of the value */
4032 val_beg = equal + 1;
4033 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4034 val_beg++;
4035
4036 /* find the end of the value, respecting quotes */
4037 next = http_find_cookie_value_end(val_beg, hdr_end);
4038
4039 /* make val_end point to the first white space or delimitor after the value */
4040 val_end = next;
4041 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4042 val_end--;
4043 }
4044 else
4045 val_beg = val_end = next = equal;
4046
4047 /* We have nothing to do with attributes beginning with
4048 * '$'. However, they will automatically be removed if a
4049 * header before them is removed, since they're supposed
4050 * to be linked together.
4051 */
4052 if (*att_beg == '$')
4053 continue;
4054
4055 /* Ignore cookies with no equal sign */
4056 if (equal == next) {
4057 /* This is not our cookie, so we must preserve it. But if we already
4058 * scheduled another cookie for removal, we cannot remove the
4059 * complete header, but we can remove the previous block itself.
4060 */
4061 preserve_hdr = 1;
4062 if (del_from != NULL) {
4063 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4064 val_end += delta;
4065 next += delta;
4066 hdr_end += delta;
4067 prev = del_from;
4068 del_from = NULL;
4069 }
4070 continue;
4071 }
4072
4073 /* if there are spaces around the equal sign, we need to
4074 * strip them otherwise we'll get trouble for cookie captures,
4075 * or even for rewrites. Since this happens extremely rarely,
4076 * it does not hurt performance.
4077 */
4078 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4079 int stripped_before = 0;
4080 int stripped_after = 0;
4081
4082 if (att_end != equal) {
4083 memmove(att_end, equal, hdr_end - equal);
4084 stripped_before = (att_end - equal);
4085 equal += stripped_before;
4086 val_beg += stripped_before;
4087 }
4088
4089 if (val_beg > equal + 1) {
4090 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4091 stripped_after = (equal + 1) - val_beg;
4092 val_beg += stripped_after;
4093 stripped_before += stripped_after;
4094 }
4095
4096 val_end += stripped_before;
4097 next += stripped_before;
4098 hdr_end += stripped_before;
4099 }
4100 /* now everything is as on the diagram above */
4101
4102 /* First, let's see if we want to capture this cookie. We check
4103 * that we don't already have a client side cookie, because we
4104 * can only capture one. Also as an optimisation, we ignore
4105 * cookies shorter than the declared name.
4106 */
4107 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4108 (val_end - att_beg >= sess->fe->capture_namelen) &&
4109 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4110 int log_len = val_end - att_beg;
4111
4112 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4113 ha_alert("HTTP logging : out of memory.\n");
4114 } else {
4115 if (log_len > sess->fe->capture_len)
4116 log_len = sess->fe->capture_len;
4117 memcpy(txn->cli_cookie, att_beg, log_len);
4118 txn->cli_cookie[log_len] = 0;
4119 }
4120 }
4121
4122 /* Persistence cookies in passive, rewrite or insert mode have the
4123 * following form :
4124 *
4125 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4126 *
4127 * For cookies in prefix mode, the form is :
4128 *
4129 * Cookie: NAME=SRV~VALUE
4130 */
4131 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4132 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4133 struct server *srv = s->be->srv;
4134 char *delim;
4135
4136 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4137 * have the server ID between val_beg and delim, and the original cookie between
4138 * delim+1 and val_end. Otherwise, delim==val_end :
4139 *
4140 * hdr_beg
4141 * |
4142 * v
4143 * NAME=SRV; # in all but prefix modes
4144 * NAME=SRV~OPAQUE ; # in prefix mode
4145 * || || | |+-> next
4146 * || || | +--> val_end
4147 * || || +---------> delim
4148 * || |+------------> val_beg
4149 * || +-------------> att_end = equal
4150 * |+-----------------> att_beg
4151 * +------------------> prev
4152 *
4153 */
4154 if (s->be->ck_opts & PR_CK_PFX) {
4155 for (delim = val_beg; delim < val_end; delim++)
4156 if (*delim == COOKIE_DELIM)
4157 break;
4158 }
4159 else {
4160 char *vbar1;
4161 delim = val_end;
4162 /* Now check if the cookie contains a date field, which would
4163 * appear after a vertical bar ('|') just after the server name
4164 * and before the delimiter.
4165 */
4166 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4167 if (vbar1) {
4168 /* OK, so left of the bar is the server's cookie and
4169 * right is the last seen date. It is a base64 encoded
4170 * 30-bit value representing the UNIX date since the
4171 * epoch in 4-second quantities.
4172 */
4173 int val;
4174 delim = vbar1++;
4175 if (val_end - vbar1 >= 5) {
4176 val = b64tos30(vbar1);
4177 if (val > 0)
4178 txn->cookie_last_date = val << 2;
4179 }
4180 /* look for a second vertical bar */
4181 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4182 if (vbar1 && (val_end - vbar1 > 5)) {
4183 val = b64tos30(vbar1 + 1);
4184 if (val > 0)
4185 txn->cookie_first_date = val << 2;
4186 }
4187 }
4188 }
4189
4190 /* if the cookie has an expiration date and the proxy wants to check
4191 * it, then we do that now. We first check if the cookie is too old,
4192 * then only if it has expired. We detect strict overflow because the
4193 * time resolution here is not great (4 seconds). Cookies with dates
4194 * in the future are ignored if their offset is beyond one day. This
4195 * allows an admin to fix timezone issues without expiring everyone
4196 * and at the same time avoids keeping unwanted side effects for too
4197 * long.
4198 */
4199 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4200 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4201 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4202 txn->flags &= ~TX_CK_MASK;
4203 txn->flags |= TX_CK_OLD;
4204 delim = val_beg; // let's pretend we have not found the cookie
4205 txn->cookie_first_date = 0;
4206 txn->cookie_last_date = 0;
4207 }
4208 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4209 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4210 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4211 txn->flags &= ~TX_CK_MASK;
4212 txn->flags |= TX_CK_EXPIRED;
4213 delim = val_beg; // let's pretend we have not found the cookie
4214 txn->cookie_first_date = 0;
4215 txn->cookie_last_date = 0;
4216 }
4217
4218 /* Here, we'll look for the first running server which supports the cookie.
4219 * This allows to share a same cookie between several servers, for example
4220 * to dedicate backup servers to specific servers only.
4221 * However, to prevent clients from sticking to cookie-less backup server
4222 * when they have incidentely learned an empty cookie, we simply ignore
4223 * empty cookies and mark them as invalid.
4224 * The same behaviour is applied when persistence must be ignored.
4225 */
4226 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4227 srv = NULL;
4228
4229 while (srv) {
4230 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4231 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4232 if ((srv->cur_state != SRV_ST_STOPPED) ||
4233 (s->be->options & PR_O_PERSIST) ||
4234 (s->flags & SF_FORCE_PRST)) {
4235 /* we found the server and we can use it */
4236 txn->flags &= ~TX_CK_MASK;
4237 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4238 s->flags |= SF_DIRECT | SF_ASSIGNED;
4239 s->target = &srv->obj_type;
4240 break;
4241 } else {
4242 /* we found a server, but it's down,
4243 * mark it as such and go on in case
4244 * another one is available.
4245 */
4246 txn->flags &= ~TX_CK_MASK;
4247 txn->flags |= TX_CK_DOWN;
4248 }
4249 }
4250 srv = srv->next;
4251 }
4252
4253 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4254 /* no server matched this cookie or we deliberately skipped it */
4255 txn->flags &= ~TX_CK_MASK;
4256 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4257 txn->flags |= TX_CK_UNUSED;
4258 else
4259 txn->flags |= TX_CK_INVALID;
4260 }
4261
4262 /* depending on the cookie mode, we may have to either :
4263 * - delete the complete cookie if we're in insert+indirect mode, so that
4264 * the server never sees it ;
4265 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004266 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004267 * if we're in cookie prefix mode
4268 */
4269 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4270 int delta; /* negative */
4271
4272 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4273 delta = val_beg - (delim + 1);
4274 val_end += delta;
4275 next += delta;
4276 hdr_end += delta;
4277 del_from = NULL;
4278 preserve_hdr = 1; /* we want to keep this cookie */
4279 }
4280 else if (del_from == NULL &&
4281 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4282 del_from = prev;
4283 }
4284 }
4285 else {
4286 /* This is not our cookie, so we must preserve it. But if we already
4287 * scheduled another cookie for removal, we cannot remove the
4288 * complete header, but we can remove the previous block itself.
4289 */
4290 preserve_hdr = 1;
4291
4292 if (del_from != NULL) {
4293 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4294 if (att_beg >= del_from)
4295 att_beg += delta;
4296 if (att_end >= del_from)
4297 att_end += delta;
4298 val_beg += delta;
4299 val_end += delta;
4300 next += delta;
4301 hdr_end += delta;
4302 prev = del_from;
4303 del_from = NULL;
4304 }
4305 }
4306
4307 /* continue with next cookie on this header line */
4308 att_beg = next;
4309 } /* for each cookie */
4310
4311
4312 /* There are no more cookies on this line.
4313 * We may still have one (or several) marked for deletion at the
4314 * end of the line. We must do this now in two ways :
4315 * - if some cookies must be preserved, we only delete from the
4316 * mark to the end of line ;
4317 * - if nothing needs to be preserved, simply delete the whole header
4318 */
4319 if (del_from) {
4320 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4321 }
4322 if ((hdr_end - hdr_beg) != ctx.value.len) {
4323 if (hdr_beg != hdr_end) {
4324 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004325 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004326 }
4327 else
4328 http_remove_header(htx, &ctx);
4329 }
4330 } /* for each "Cookie header */
4331}
4332
4333/*
4334 * Manage server-side cookies. It can impact performance by about 2% so it is
4335 * desirable to call it only when needed. This function is also used when we
4336 * just need to know if there is a cookie (eg: for check-cache).
4337 */
4338static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4339{
4340 struct session *sess = s->sess;
4341 struct http_txn *txn = s->txn;
4342 struct htx *htx;
4343 struct http_hdr_ctx ctx;
4344 struct server *srv;
4345 char *hdr_beg, *hdr_end;
4346 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004347 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004348
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004349 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004350
4351 ctx.blk = NULL;
4352 while (1) {
4353 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4354 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4355 break;
4356 is_cookie2 = 1;
4357 }
4358
4359 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4360 * <prev> points to the colon.
4361 */
4362 txn->flags |= TX_SCK_PRESENT;
4363
4364 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4365 * check-cache is enabled) and we are not interested in checking
4366 * them. Warning, the cookie capture is declared in the frontend.
4367 */
4368 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4369 break;
4370
4371 /* OK so now we know we have to process this response cookie.
4372 * The format of the Set-Cookie header is slightly different
4373 * from the format of the Cookie header in that it does not
4374 * support the comma as a cookie delimiter (thus the header
4375 * cannot be folded) because the Expires attribute described in
4376 * the original Netscape's spec may contain an unquoted date
4377 * with a comma inside. We have to live with this because
4378 * many browsers don't support Max-Age and some browsers don't
4379 * support quoted strings. However the Set-Cookie2 header is
4380 * clean.
4381 *
4382 * We have to keep multiple pointers in order to support cookie
4383 * removal at the beginning, middle or end of header without
4384 * corrupting the header (in case of set-cookie2). A special
4385 * pointer, <scav> points to the beginning of the set-cookie-av
4386 * fields after the first semi-colon. The <next> pointer points
4387 * either to the end of line (set-cookie) or next unquoted comma
4388 * (set-cookie2). All of these headers are valid :
4389 *
4390 * hdr_beg hdr_end
4391 * | |
4392 * v |
4393 * NAME1 = VALUE 1 ; Secure; Path="/" |
4394 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4395 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4396 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4397 * | | | | | | | |
4398 * | | | | | | | +-> next
4399 * | | | | | | +------------> scav
4400 * | | | | | +--------------> val_end
4401 * | | | | +--------------------> val_beg
4402 * | | | +----------------------> equal
4403 * | | +------------------------> att_end
4404 * | +----------------------------> att_beg
4405 * +------------------------------> prev
4406 * -------------------------------> hdr_beg
4407 */
4408 hdr_beg = ctx.value.ptr;
4409 hdr_end = hdr_beg + ctx.value.len;
4410 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4411
4412 /* Iterate through all cookies on this line */
4413
4414 /* find att_beg */
4415 att_beg = prev;
4416 if (prev > hdr_beg)
4417 att_beg++;
4418
4419 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4420 att_beg++;
4421
4422 /* find att_end : this is the first character after the last non
4423 * space before the equal. It may be equal to hdr_end.
4424 */
4425 equal = att_end = att_beg;
4426
4427 while (equal < hdr_end) {
4428 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4429 break;
4430 if (HTTP_IS_SPHT(*equal++))
4431 continue;
4432 att_end = equal;
4433 }
4434
4435 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4436 * is between <att_beg> and <equal>, both may be identical.
4437 */
4438
4439 /* look for end of cookie if there is an equal sign */
4440 if (equal < hdr_end && *equal == '=') {
4441 /* look for the beginning of the value */
4442 val_beg = equal + 1;
4443 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4444 val_beg++;
4445
4446 /* find the end of the value, respecting quotes */
4447 next = http_find_cookie_value_end(val_beg, hdr_end);
4448
4449 /* make val_end point to the first white space or delimitor after the value */
4450 val_end = next;
4451 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4452 val_end--;
4453 }
4454 else {
4455 /* <equal> points to next comma, semi-colon or EOL */
4456 val_beg = val_end = next = equal;
4457 }
4458
4459 if (next < hdr_end) {
4460 /* Set-Cookie2 supports multiple cookies, and <next> points to
4461 * a colon or semi-colon before the end. So skip all attr-value
4462 * pairs and look for the next comma. For Set-Cookie, since
4463 * commas are permitted in values, skip to the end.
4464 */
4465 if (is_cookie2)
4466 next = http_find_hdr_value_end(next, hdr_end);
4467 else
4468 next = hdr_end;
4469 }
4470
4471 /* Now everything is as on the diagram above */
4472
4473 /* Ignore cookies with no equal sign */
4474 if (equal == val_end)
4475 continue;
4476
4477 /* If there are spaces around the equal sign, we need to
4478 * strip them otherwise we'll get trouble for cookie captures,
4479 * or even for rewrites. Since this happens extremely rarely,
4480 * it does not hurt performance.
4481 */
4482 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4483 int stripped_before = 0;
4484 int stripped_after = 0;
4485
4486 if (att_end != equal) {
4487 memmove(att_end, equal, hdr_end - equal);
4488 stripped_before = (att_end - equal);
4489 equal += stripped_before;
4490 val_beg += stripped_before;
4491 }
4492
4493 if (val_beg > equal + 1) {
4494 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4495 stripped_after = (equal + 1) - val_beg;
4496 val_beg += stripped_after;
4497 stripped_before += stripped_after;
4498 }
4499
4500 val_end += stripped_before;
4501 next += stripped_before;
4502 hdr_end += stripped_before;
4503
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004504 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4505 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004506 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004507 }
4508
4509 /* First, let's see if we want to capture this cookie. We check
4510 * that we don't already have a server side cookie, because we
4511 * can only capture one. Also as an optimisation, we ignore
4512 * cookies shorter than the declared name.
4513 */
4514 if (sess->fe->capture_name != NULL &&
4515 txn->srv_cookie == NULL &&
4516 (val_end - att_beg >= sess->fe->capture_namelen) &&
4517 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4518 int log_len = val_end - att_beg;
4519 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4520 ha_alert("HTTP logging : out of memory.\n");
4521 }
4522 else {
4523 if (log_len > sess->fe->capture_len)
4524 log_len = sess->fe->capture_len;
4525 memcpy(txn->srv_cookie, att_beg, log_len);
4526 txn->srv_cookie[log_len] = 0;
4527 }
4528 }
4529
4530 srv = objt_server(s->target);
4531 /* now check if we need to process it for persistence */
4532 if (!(s->flags & SF_IGNORE_PRST) &&
4533 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4534 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4535 /* assume passive cookie by default */
4536 txn->flags &= ~TX_SCK_MASK;
4537 txn->flags |= TX_SCK_FOUND;
4538
4539 /* If the cookie is in insert mode on a known server, we'll delete
4540 * this occurrence because we'll insert another one later.
4541 * We'll delete it too if the "indirect" option is set and we're in
4542 * a direct access.
4543 */
4544 if (s->be->ck_opts & PR_CK_PSV) {
4545 /* The "preserve" flag was set, we don't want to touch the
4546 * server's cookie.
4547 */
4548 }
4549 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4550 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4551 /* this cookie must be deleted */
4552 if (prev == hdr_beg && next == hdr_end) {
4553 /* whole header */
4554 http_remove_header(htx, &ctx);
4555 /* note: while both invalid now, <next> and <hdr_end>
4556 * are still equal, so the for() will stop as expected.
4557 */
4558 } else {
4559 /* just remove the value */
4560 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4561 next = prev;
4562 hdr_end += delta;
4563 }
4564 txn->flags &= ~TX_SCK_MASK;
4565 txn->flags |= TX_SCK_DELETED;
4566 /* and go on with next cookie */
4567 }
4568 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4569 /* replace bytes val_beg->val_end with the cookie name associated
4570 * with this server since we know it.
4571 */
4572 int sliding, delta;
4573
4574 ctx.value = ist2(val_beg, val_end - val_beg);
4575 ctx.lws_before = ctx.lws_after = 0;
4576 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4577 delta = srv->cklen - (val_end - val_beg);
4578 sliding = (ctx.value.ptr - val_beg);
4579 hdr_beg += sliding;
4580 val_beg += sliding;
4581 next += sliding + delta;
4582 hdr_end += sliding + delta;
4583
4584 txn->flags &= ~TX_SCK_MASK;
4585 txn->flags |= TX_SCK_REPLACED;
4586 }
4587 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4588 /* insert the cookie name associated with this server
4589 * before existing cookie, and insert a delimiter between them..
4590 */
4591 int sliding, delta;
4592 ctx.value = ist2(val_beg, 0);
4593 ctx.lws_before = ctx.lws_after = 0;
4594 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4595 delta = srv->cklen + 1;
4596 sliding = (ctx.value.ptr - val_beg);
4597 hdr_beg += sliding;
4598 val_beg += sliding;
4599 next += sliding + delta;
4600 hdr_end += sliding + delta;
4601
4602 val_beg[srv->cklen] = COOKIE_DELIM;
4603 txn->flags &= ~TX_SCK_MASK;
4604 txn->flags |= TX_SCK_REPLACED;
4605 }
4606 }
4607 /* that's done for this cookie, check the next one on the same
4608 * line when next != hdr_end (only if is_cookie2).
4609 */
4610 }
4611 }
4612}
4613
Christopher Faulet25a02f62018-10-24 12:00:25 +02004614/*
4615 * Parses the Cache-Control and Pragma request header fields to determine if
4616 * the request may be served from the cache and/or if it is cacheable. Updates
4617 * s->txn->flags.
4618 */
4619void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4620{
4621 struct http_txn *txn = s->txn;
4622 struct htx *htx;
4623 int32_t pos;
4624 int pragma_found, cc_found, i;
4625
4626 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4627 return; /* nothing more to do here */
4628
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004629 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004630 pragma_found = cc_found = 0;
4631 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4632 struct htx_blk *blk = htx_get_blk(htx, pos);
4633 enum htx_blk_type type = htx_get_blk_type(blk);
4634 struct ist n, v;
4635
4636 if (type == HTX_BLK_EOH)
4637 break;
4638 if (type != HTX_BLK_HDR)
4639 continue;
4640
4641 n = htx_get_blk_name(htx, blk);
4642 v = htx_get_blk_value(htx, blk);
4643
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4646 pragma_found = 1;
4647 continue;
4648 }
4649 }
4650
4651 /* Don't use the cache and don't try to store if we found the
4652 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004653 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004654 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4655 txn->flags |= TX_CACHE_IGNORE;
4656 continue;
4657 }
4658
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004659 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004660 continue;
4661
4662 /* OK, right now we know we have a cache-control header */
4663 cc_found = 1;
4664 if (!v.len) /* no info */
4665 continue;
4666
4667 i = 0;
4668 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4669 !isspace((unsigned char)*(v.ptr+i)))
4670 i++;
4671
4672 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4673 * values after max-age, max-stale nor min-fresh, we simply don't
4674 * use the cache when they're specified.
4675 */
4676 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4677 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4678 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4679 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4680 txn->flags |= TX_CACHE_IGNORE;
4681 continue;
4682 }
4683
4684 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4685 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4686 continue;
4687 }
4688 }
4689
4690 /* RFC7234#5.4:
4691 * When the Cache-Control header field is also present and
4692 * understood in a request, Pragma is ignored.
4693 * When the Cache-Control header field is not present in a
4694 * request, caches MUST consider the no-cache request
4695 * pragma-directive as having the same effect as if
4696 * "Cache-Control: no-cache" were present.
4697 */
4698 if (!cc_found && pragma_found)
4699 txn->flags |= TX_CACHE_IGNORE;
4700}
4701
4702/*
4703 * Check if response is cacheable or not. Updates s->txn->flags.
4704 */
4705void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4706{
4707 struct http_txn *txn = s->txn;
4708 struct htx *htx;
4709 int32_t pos;
4710 int i;
4711
4712 if (txn->status < 200) {
4713 /* do not try to cache interim responses! */
4714 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4715 return;
4716 }
4717
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004718 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004719 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4720 struct htx_blk *blk = htx_get_blk(htx, pos);
4721 enum htx_blk_type type = htx_get_blk_type(blk);
4722 struct ist n, v;
4723
4724 if (type == HTX_BLK_EOH)
4725 break;
4726 if (type != HTX_BLK_HDR)
4727 continue;
4728
4729 n = htx_get_blk_name(htx, blk);
4730 v = htx_get_blk_value(htx, blk);
4731
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004732 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004733 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4734 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4735 return;
4736 }
4737 }
4738
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004739 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004740 continue;
4741
4742 /* OK, right now we know we have a cache-control header */
4743 if (!v.len) /* no info */
4744 continue;
4745
4746 i = 0;
4747 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4748 !isspace((unsigned char)*(v.ptr+i)))
4749 i++;
4750
4751 /* we have a complete value between v.ptr and (v.ptr+i) */
4752 if (i < v.len && *(v.ptr + i) == '=') {
4753 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4754 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4755 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4756 continue;
4757 }
4758
4759 /* we have something of the form no-cache="set-cookie" */
4760 if ((v.len >= 21) &&
4761 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4762 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4763 txn->flags &= ~TX_CACHE_COOK;
4764 continue;
4765 }
4766
4767 /* OK, so we know that either p2 points to the end of string or to a comma */
4768 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4769 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4770 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4771 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4772 return;
4773 }
4774
4775 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4776 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4777 continue;
4778 }
4779 }
4780}
4781
Christopher Faulet64159df2018-10-24 21:15:35 +02004782/* send a server's name with an outgoing request over an established connection.
4783 * Note: this function is designed to be called once the request has been
4784 * scheduled for being forwarded. This is the reason why the number of forwarded
4785 * bytes have to be adjusted.
4786 */
4787int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4788{
4789 struct htx *htx;
4790 struct http_hdr_ctx ctx;
4791 struct ist hdr;
4792 uint32_t data;
4793
4794 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004795 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004796 data = htx->data;
4797
4798 ctx.blk = NULL;
4799 while (http_find_header(htx, hdr, &ctx, 1))
4800 http_remove_header(htx, &ctx);
4801 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4802
4803 if (co_data(&s->req)) {
4804 if (data >= htx->data)
4805 c_rew(&s->req, data - htx->data);
4806 else
4807 c_adv(&s->req, htx->data - data);
4808 }
4809 return 0;
4810}
4811
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812/*
4813 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4814 * for the current backend.
4815 *
4816 * It is assumed that the request is either a HEAD, GET, or POST and that the
4817 * uri_auth field is valid.
4818 *
4819 * Returns 1 if stats should be provided, otherwise 0.
4820 */
4821static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4822{
4823 struct uri_auth *uri_auth = backend->uri_auth;
4824 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004825 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004826 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004827
4828 if (!uri_auth)
4829 return 0;
4830
4831 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4832 return 0;
4833
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004834 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004835 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004836 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004837
4838 /* check URI size */
4839 if (uri_auth->uri_len > uri.len)
4840 return 0;
4841
4842 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4843 return 0;
4844
4845 return 1;
4846}
4847
4848/* This function prepares an applet to handle the stats. It can deal with the
4849 * "100-continue" expectation, check that admin rules are met for POST requests,
4850 * and program a response message if something was unexpected. It cannot fail
4851 * and always relies on the stats applet to complete the job. It does not touch
4852 * analysers nor counters, which are left to the caller. It does not touch
4853 * s->target which is supposed to already point to the stats applet. The caller
4854 * is expected to have already assigned an appctx to the stream.
4855 */
4856static int htx_handle_stats(struct stream *s, struct channel *req)
4857{
4858 struct stats_admin_rule *stats_admin_rule;
4859 struct stream_interface *si = &s->si[1];
4860 struct session *sess = s->sess;
4861 struct http_txn *txn = s->txn;
4862 struct http_msg *msg = &txn->req;
4863 struct uri_auth *uri_auth = s->be->uri_auth;
4864 const char *h, *lookup, *end;
4865 struct appctx *appctx;
4866 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004867 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004868
4869 appctx = si_appctx(si);
4870 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4871 appctx->st1 = appctx->st2 = 0;
4872 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4873 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4874 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4875 appctx->ctx.stats.flags |= STAT_CHUNKED;
4876
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004877 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004878 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004879 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4880 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004881
4882 for (h = lookup; h <= end - 3; h++) {
4883 if (memcmp(h, ";up", 3) == 0) {
4884 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4885 break;
4886 }
4887 }
4888
4889 if (uri_auth->refresh) {
4890 for (h = lookup; h <= end - 10; h++) {
4891 if (memcmp(h, ";norefresh", 10) == 0) {
4892 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4893 break;
4894 }
4895 }
4896 }
4897
4898 for (h = lookup; h <= end - 4; h++) {
4899 if (memcmp(h, ";csv", 4) == 0) {
4900 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4901 break;
4902 }
4903 }
4904
4905 for (h = lookup; h <= end - 6; h++) {
4906 if (memcmp(h, ";typed", 6) == 0) {
4907 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4908 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4909 break;
4910 }
4911 }
4912
4913 for (h = lookup; h <= end - 8; h++) {
4914 if (memcmp(h, ";st=", 4) == 0) {
4915 int i;
4916 h += 4;
4917 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4918 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4919 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4920 appctx->ctx.stats.st_code = i;
4921 break;
4922 }
4923 }
4924 break;
4925 }
4926 }
4927
4928 appctx->ctx.stats.scope_str = 0;
4929 appctx->ctx.stats.scope_len = 0;
4930 for (h = lookup; h <= end - 8; h++) {
4931 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4932 int itx = 0;
4933 const char *h2;
4934 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4935 const char *err;
4936
4937 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4938 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004939 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4940 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004941 if (*h == ';' || *h == '&' || *h == ' ')
4942 break;
4943 itx++;
4944 h++;
4945 }
4946
4947 if (itx > STAT_SCOPE_TXT_MAXLEN)
4948 itx = STAT_SCOPE_TXT_MAXLEN;
4949 appctx->ctx.stats.scope_len = itx;
4950
4951 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4952 memcpy(scope_txt, h2, itx);
4953 scope_txt[itx] = '\0';
4954 err = invalid_char(scope_txt);
4955 if (err) {
4956 /* bad char in search text => clear scope */
4957 appctx->ctx.stats.scope_str = 0;
4958 appctx->ctx.stats.scope_len = 0;
4959 }
4960 break;
4961 }
4962 }
4963
4964 /* now check whether we have some admin rules for this request */
4965 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4966 int ret = 1;
4967
4968 if (stats_admin_rule->cond) {
4969 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4970 ret = acl_pass(ret);
4971 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4972 ret = !ret;
4973 }
4974
4975 if (ret) {
4976 /* no rule, or the rule matches */
4977 appctx->ctx.stats.flags |= STAT_ADMIN;
4978 break;
4979 }
4980 }
4981
Christopher Faulet5d45e382019-02-27 15:15:23 +01004982 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4983 appctx->st0 = STAT_HTTP_HEAD;
4984 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004985 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004986 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004987 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004988 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004989 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4990 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4991 appctx->st0 = STAT_HTTP_LAST;
4992 }
4993 }
4994 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004995 /* Unsupported method */
4996 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4997 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4998 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004999 }
5000
5001 s->task->nice = -32; /* small boost for HTTP statistics */
5002 return 1;
5003}
5004
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5006{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005007 struct channel *req = &s->req;
5008 struct channel *res = &s->res;
5009 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005010 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005011 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 struct ist path, location;
5013 unsigned int flags;
5014 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005015
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005016 /*
5017 * Create the location
5018 */
5019 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005020
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005021 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022 /* special prefix "/" means don't change URL */
5023 srv = __objt_server(s->target);
5024 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5025 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5026 return;
5027 }
5028
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005030 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005031 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005032 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005033 if (!path.ptr)
5034 return;
5035
5036 if (!chunk_memcat(&trash, path.ptr, path.len))
5037 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005038 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005039
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005040 /*
5041 * Create the 302 respone
5042 */
5043 htx = htx_from_buf(&res->buf);
5044 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5045 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5046 ist("HTTP/1.1"), ist("302"), ist("Found"));
5047 if (!sl)
5048 goto fail;
5049 sl->info.res.status = 302;
5050 s->txn->status = 302;
5051
5052 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5053 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5054 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5055 !htx_add_header(htx, ist("Location"), location))
5056 goto fail;
5057
5058 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5059 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005060
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005061 /*
5062 * Send the message
5063 */
5064 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005065 c_adv(res, data);
5066 res->total += data;
5067
5068 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005069 si_shutr(si);
5070 si_shutw(si);
5071 si->err_type = SI_ET_NONE;
5072 si->state = SI_ST_CLO;
5073
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005074 channel_auto_read(req);
5075 channel_abort(req);
5076 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005077 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005078 channel_auto_read(res);
5079 channel_auto_close(res);
5080
5081 if (!(s->flags & SF_ERR_MASK))
5082 s->flags |= SF_ERR_LOCAL;
5083 if (!(s->flags & SF_FINST_MASK))
5084 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005085
5086 /* FIXME: we should increase a counter of redirects per server and per backend. */
5087 srv_inc_sess_ctr(srv);
5088 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005089 return;
5090
5091 fail:
5092 /* If an error occurred, remove the incomplete HTTP response from the
5093 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005094 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005095}
5096
Christopher Fauletf2824e62018-10-01 12:12:37 +02005097/* This function terminates the request because it was completly analyzed or
5098 * because an error was triggered during the body forwarding.
5099 */
5100static void htx_end_request(struct stream *s)
5101{
5102 struct channel *chn = &s->req;
5103 struct http_txn *txn = s->txn;
5104
5105 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5106 now_ms, __FUNCTION__, s,
5107 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5108 s->req.analysers, s->res.analysers);
5109
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005110 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5111 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005112 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005113 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005114 goto end;
5115 }
5116
5117 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5118 return;
5119
5120 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 /* No need to read anymore, the request was completely parsed.
5122 * We can shut the read side unless we want to abort_on_close,
5123 * or we have a POST request. The issue with POST requests is
5124 * that some browsers still send a CRLF after the request, and
5125 * this CRLF must be read so that it does not remain in the kernel
5126 * buffers, otherwise a close could cause an RST on some systems
5127 * (eg: Linux).
5128 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005129 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005130 channel_dont_read(chn);
5131
5132 /* if the server closes the connection, we want to immediately react
5133 * and close the socket to save packets and syscalls.
5134 */
5135 s->si[1].flags |= SI_FL_NOHALF;
5136
5137 /* In any case we've finished parsing the request so we must
5138 * disable Nagle when sending data because 1) we're not going
5139 * to shut this side, and 2) the server is waiting for us to
5140 * send pending data.
5141 */
5142 chn->flags |= CF_NEVER_WAIT;
5143
Christopher Fauletd01ce402019-01-02 17:44:13 +01005144 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5145 /* The server has not finished to respond, so we
5146 * don't want to move in order not to upset it.
5147 */
5148 return;
5149 }
5150
Christopher Fauletf2824e62018-10-01 12:12:37 +02005151 /* When we get here, it means that both the request and the
5152 * response have finished receiving. Depending on the connection
5153 * mode, we'll have to wait for the last bytes to leave in either
5154 * direction, and sometimes for a close to be effective.
5155 */
5156 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5157 /* Tunnel mode will not have any analyser so it needs to
5158 * poll for reads.
5159 */
5160 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005161 if (b_data(&chn->buf))
5162 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005163 txn->req.msg_state = HTTP_MSG_TUNNEL;
5164 }
5165 else {
5166 /* we're not expecting any new data to come for this
5167 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005168 *
5169 * However, there is an exception if the response
5170 * length is undefined. In this case, we need to wait
5171 * the close from the server. The response will be
5172 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005173 */
5174 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5175 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005176 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005177
5178 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5179 channel_shutr_now(chn);
5180 channel_shutw_now(chn);
5181 }
5182 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005183 goto check_channel_flags;
5184 }
5185
5186 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5187 http_msg_closing:
5188 /* nothing else to forward, just waiting for the output buffer
5189 * to be empty and for the shutw_now to take effect.
5190 */
5191 if (channel_is_empty(chn)) {
5192 txn->req.msg_state = HTTP_MSG_CLOSED;
5193 goto http_msg_closed;
5194 }
5195 else if (chn->flags & CF_SHUTW) {
5196 txn->req.err_state = txn->req.msg_state;
5197 txn->req.msg_state = HTTP_MSG_ERROR;
5198 goto end;
5199 }
5200 return;
5201 }
5202
5203 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5204 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005205 /* if we don't know whether the server will close, we need to hard close */
5206 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5207 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005208 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005209 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005210 channel_dont_read(chn);
5211 goto end;
5212 }
5213
5214 check_channel_flags:
5215 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5216 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5217 /* if we've just closed an output, let's switch */
5218 txn->req.msg_state = HTTP_MSG_CLOSING;
5219 goto http_msg_closing;
5220 }
5221
5222 end:
5223 chn->analysers &= AN_REQ_FLT_END;
5224 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5225 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5226 channel_auto_close(chn);
5227 channel_auto_read(chn);
5228}
5229
5230
5231/* This function terminates the response because it was completly analyzed or
5232 * because an error was triggered during the body forwarding.
5233 */
5234static void htx_end_response(struct stream *s)
5235{
5236 struct channel *chn = &s->res;
5237 struct http_txn *txn = s->txn;
5238
5239 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5240 now_ms, __FUNCTION__, s,
5241 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5242 s->req.analysers, s->res.analysers);
5243
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005244 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5245 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005246 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005247 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005248 goto end;
5249 }
5250
5251 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5252 return;
5253
5254 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5255 /* In theory, we don't need to read anymore, but we must
5256 * still monitor the server connection for a possible close
5257 * while the request is being uploaded, so we don't disable
5258 * reading.
5259 */
5260 /* channel_dont_read(chn); */
5261
5262 if (txn->req.msg_state < HTTP_MSG_DONE) {
5263 /* The client seems to still be sending data, probably
5264 * because we got an error response during an upload.
5265 * We have the choice of either breaking the connection
5266 * or letting it pass through. Let's do the later.
5267 */
5268 return;
5269 }
5270
5271 /* When we get here, it means that both the request and the
5272 * response have finished receiving. Depending on the connection
5273 * mode, we'll have to wait for the last bytes to leave in either
5274 * direction, and sometimes for a close to be effective.
5275 */
5276 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5277 channel_auto_read(chn);
5278 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005279 if (b_data(&chn->buf))
5280 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005281 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5282 }
5283 else {
5284 /* we're not expecting any new data to come for this
5285 * transaction, so we can close it.
5286 */
5287 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5288 channel_shutr_now(chn);
5289 channel_shutw_now(chn);
5290 }
5291 }
5292 goto check_channel_flags;
5293 }
5294
5295 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5296 http_msg_closing:
5297 /* nothing else to forward, just waiting for the output buffer
5298 * to be empty and for the shutw_now to take effect.
5299 */
5300 if (channel_is_empty(chn)) {
5301 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5302 goto http_msg_closed;
5303 }
5304 else if (chn->flags & CF_SHUTW) {
5305 txn->rsp.err_state = txn->rsp.msg_state;
5306 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005307 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005308 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005309 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005310 goto end;
5311 }
5312 return;
5313 }
5314
5315 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5316 http_msg_closed:
5317 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005318 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005319 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005320 goto end;
5321 }
5322
5323 check_channel_flags:
5324 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5325 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5326 /* if we've just closed an output, let's switch */
5327 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5328 goto http_msg_closing;
5329 }
5330
5331 end:
5332 chn->analysers &= AN_RES_FLT_END;
5333 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5334 chn->analysers |= AN_RES_FLT_XFER_DATA;
5335 channel_auto_close(chn);
5336 channel_auto_read(chn);
5337}
5338
Christopher Faulet0f226952018-10-22 09:29:56 +02005339void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5340 int finst, const struct buffer *msg)
5341{
5342 channel_auto_read(si_oc(si));
5343 channel_abort(si_oc(si));
5344 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005345 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005346 channel_auto_close(si_ic(si));
5347 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005348
5349 /* <msg> is an HTX structure. So we copy it in the response's
5350 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005351 if (msg) {
5352 struct channel *chn = si_ic(si);
5353 struct htx *htx;
5354
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005355 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005356 chn->buf.data = msg->data;
5357 memcpy(chn->buf.area, msg->area, msg->data);
5358 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005359 c_adv(chn, htx->data);
5360 chn->total += htx->data;
5361 }
5362 if (!(s->flags & SF_ERR_MASK))
5363 s->flags |= err;
5364 if (!(s->flags & SF_FINST_MASK))
5365 s->flags |= finst;
5366}
5367
5368void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5369{
5370 channel_auto_read(&s->req);
5371 channel_abort(&s->req);
5372 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005373 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5374 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005375
5376 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005377
5378 /* <msg> is an HTX structure. So we copy it in the response's
5379 * channel */
5380 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005381 if (msg) {
5382 struct channel *chn = &s->res;
5383 struct htx *htx;
5384
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005385 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005386 chn->buf.data = msg->data;
5387 memcpy(chn->buf.area, msg->area, msg->data);
5388 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005389 c_adv(chn, htx->data);
5390 chn->total += htx->data;
5391 }
5392
5393 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5394 channel_auto_read(&s->res);
5395 channel_auto_close(&s->res);
5396 channel_shutr_now(&s->res);
5397}
5398
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005399struct buffer *htx_error_message(struct stream *s)
5400{
5401 const int msgnum = http_get_status_idx(s->txn->status);
5402
5403 if (s->be->errmsg[msgnum].area)
5404 return &s->be->errmsg[msgnum];
5405 else if (strm_fe(s)->errmsg[msgnum].area)
5406 return &strm_fe(s)->errmsg[msgnum];
5407 else
5408 return &htx_err_chunks[msgnum];
5409}
5410
5411
Christopher Faulet4a28a532019-03-01 11:19:40 +01005412/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5413 * on success and -1 on error.
5414 */
5415static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5416{
5417 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5418 * then we must send an HTTP/1.1 100 Continue intermediate response.
5419 */
5420 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5421 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5422 struct ist hdr = { .ptr = "Expect", .len = 6 };
5423 struct http_hdr_ctx ctx;
5424
5425 ctx.blk = NULL;
5426 /* Expect is allowed in 1.1, look for it */
5427 if (http_find_header(htx, hdr, &ctx, 0) &&
5428 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5429 if (htx_reply_100_continue(s) == -1)
5430 return -1;
5431 http_remove_header(htx, &ctx);
5432 }
5433 }
5434 return 0;
5435}
5436
Christopher Faulet23a3c792018-11-28 10:01:23 +01005437/* Send a 100-Continue response to the client. It returns 0 on success and -1
5438 * on error. The response channel is updated accordingly.
5439 */
5440static int htx_reply_100_continue(struct stream *s)
5441{
5442 struct channel *res = &s->res;
5443 struct htx *htx = htx_from_buf(&res->buf);
5444 struct htx_sl *sl;
5445 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5446 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5447 size_t data;
5448
5449 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5450 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5451 if (!sl)
5452 goto fail;
5453 sl->info.res.status = 100;
5454
5455 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5456 goto fail;
5457
5458 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005459 c_adv(res, data);
5460 res->total += data;
5461 return 0;
5462
5463 fail:
5464 /* If an error occurred, remove the incomplete HTTP response from the
5465 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005466 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005467 return -1;
5468}
5469
Christopher Faulet12c51e22018-11-28 15:59:42 +01005470
5471/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5472 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5473 * error. The response channel is updated accordingly.
5474 */
5475static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5476{
5477 struct channel *res = &s->res;
5478 struct htx *htx = htx_from_buf(&res->buf);
5479 struct htx_sl *sl;
5480 struct ist code, body;
5481 int status;
5482 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5483 size_t data;
5484
5485 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5486 status = 401;
5487 code = ist("401");
5488 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5489 "You need a valid user and password to access this content.\n"
5490 "</body></html>\n");
5491 }
5492 else {
5493 status = 407;
5494 code = ist("407");
5495 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5496 "You need a valid user and password to access this content.\n"
5497 "</body></html>\n");
5498 }
5499
5500 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5501 ist("HTTP/1.1"), code, ist("Unauthorized"));
5502 if (!sl)
5503 goto fail;
5504 sl->info.res.status = status;
5505 s->txn->status = status;
5506
5507 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5508 goto fail;
5509
5510 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5511 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005512 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5513 goto fail;
5514 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5515 goto fail;
5516 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005517 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005518 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5519 goto fail;
5520
5521 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005522 c_adv(res, data);
5523 res->total += data;
5524
5525 channel_auto_read(&s->req);
5526 channel_abort(&s->req);
5527 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005528 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005529
5530 res->wex = tick_add_ifset(now_ms, res->wto);
5531 channel_auto_read(res);
5532 channel_auto_close(res);
5533 channel_shutr_now(res);
5534 return 0;
5535
5536 fail:
5537 /* If an error occurred, remove the incomplete HTTP response from the
5538 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005539 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005540 return -1;
5541}
5542
Christopher Faulet0f226952018-10-22 09:29:56 +02005543/*
5544 * Capture headers from message <htx> according to header list <cap_hdr>, and
5545 * fill the <cap> pointers appropriately.
5546 */
5547static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5548{
5549 struct cap_hdr *h;
5550 int32_t pos;
5551
5552 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5553 struct htx_blk *blk = htx_get_blk(htx, pos);
5554 enum htx_blk_type type = htx_get_blk_type(blk);
5555 struct ist n, v;
5556
5557 if (type == HTX_BLK_EOH)
5558 break;
5559 if (type != HTX_BLK_HDR)
5560 continue;
5561
5562 n = htx_get_blk_name(htx, blk);
5563
5564 for (h = cap_hdr; h; h = h->next) {
5565 if (h->namelen && (h->namelen == n.len) &&
5566 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5567 if (cap[h->index] == NULL)
5568 cap[h->index] =
5569 pool_alloc(h->pool);
5570
5571 if (cap[h->index] == NULL) {
5572 ha_alert("HTTP capture : out of memory.\n");
5573 break;
5574 }
5575
5576 v = htx_get_blk_value(htx, blk);
5577 if (v.len > h->len)
5578 v.len = h->len;
5579
5580 memcpy(cap[h->index], v.ptr, v.len);
5581 cap[h->index][v.len]=0;
5582 }
5583 }
5584 }
5585}
5586
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005587/* Delete a value in a header between delimiters <from> and <next>. The header
5588 * itself is delimited by <start> and <end> pointers. The number of characters
5589 * displaced is returned, and the pointer to the first delimiter is updated if
5590 * required. The function tries as much as possible to respect the following
5591 * principles :
5592 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5593 * in which case <next> is simply removed
5594 * - set exactly one space character after the new first delimiter, unless there
5595 * are not enough characters in the block being moved to do so.
5596 * - remove unneeded spaces before the previous delimiter and after the new
5597 * one.
5598 *
5599 * It is the caller's responsibility to ensure that :
5600 * - <from> points to a valid delimiter or <start> ;
5601 * - <next> points to a valid delimiter or <end> ;
5602 * - there are non-space chars before <from>.
5603 */
5604static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5605{
5606 char *prev = *from;
5607
5608 if (prev == start) {
5609 /* We're removing the first value. eat the semicolon, if <next>
5610 * is lower than <end> */
5611 if (next < end)
5612 next++;
5613
5614 while (next < end && HTTP_IS_SPHT(*next))
5615 next++;
5616 }
5617 else {
5618 /* Remove useless spaces before the old delimiter. */
5619 while (HTTP_IS_SPHT(*(prev-1)))
5620 prev--;
5621 *from = prev;
5622
5623 /* copy the delimiter and if possible a space if we're
5624 * not at the end of the line.
5625 */
5626 if (next < end) {
5627 *prev++ = *next++;
5628 if (prev + 1 < next)
5629 *prev++ = ' ';
5630 while (next < end && HTTP_IS_SPHT(*next))
5631 next++;
5632 }
5633 }
5634 memmove(prev, next, end - next);
5635 return (prev - next);
5636}
5637
Christopher Faulet0f226952018-10-22 09:29:56 +02005638
5639/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005640 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005643{
5644 struct ist dst = ist2(str, 0);
5645
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005646 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005647 goto end;
5648 if (dst.len + 1 > len)
5649 goto end;
5650 dst.ptr[dst.len++] = ' ';
5651
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005652 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 goto end;
5654 if (dst.len + 1 > len)
5655 goto end;
5656 dst.ptr[dst.len++] = ' ';
5657
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005658 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005659 end:
5660 return dst.len;
5661}
5662
Christopher Fauletf0523542018-10-24 11:06:58 +02005663/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005664 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005665 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005666static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005667{
5668 struct ist dst = ist2(str, 0);
5669
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005670 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005671 goto end;
5672 if (dst.len + 1 > len)
5673 goto end;
5674 dst.ptr[dst.len++] = ' ';
5675
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005676 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005677 goto end;
5678 if (dst.len + 1 > len)
5679 goto end;
5680 dst.ptr[dst.len++] = ' ';
5681
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005682 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005683 end:
5684 return dst.len;
5685}
5686
5687
Christopher Faulet0f226952018-10-22 09:29:56 +02005688/*
5689 * Print a debug line with a start line.
5690 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005691static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005692{
5693 struct session *sess = strm_sess(s);
5694 int max;
5695
5696 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5697 dir,
5698 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5699 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5700
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005701 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005702 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005703 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005704 trash.area[trash.data++] = ' ';
5705
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005707 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005708 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005709 trash.area[trash.data++] = ' ';
5710
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005713 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005714 trash.area[trash.data++] = '\n';
5715
5716 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5717}
5718
5719/*
5720 * Print a debug line with a header.
5721 */
5722static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5723{
5724 struct session *sess = strm_sess(s);
5725 int max;
5726
5727 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5728 dir,
5729 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5730 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5731
5732 max = n.len;
5733 UBOUND(max, trash.size - trash.data - 3);
5734 chunk_memcat(&trash, n.ptr, max);
5735 trash.area[trash.data++] = ':';
5736 trash.area[trash.data++] = ' ';
5737
5738 max = v.len;
5739 UBOUND(max, trash.size - trash.data - 1);
5740 chunk_memcat(&trash, v.ptr, max);
5741 trash.area[trash.data++] = '\n';
5742
5743 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5744}
5745
5746
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005747__attribute__((constructor))
5748static void __htx_protocol_init(void)
5749{
5750}
5751
5752
5753/*
5754 * Local variables:
5755 * c-indent-level: 8
5756 * c-basic-offset: 8
5757 * End:
5758 */