blob: 2d1d8fb82b4b79a4edf0ca25605aac24dc912517 [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) &&
1531 do_l7_retry(s, si_b) == 0)
1532 return 0;
1533 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
1536 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_SRVCL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001548 if ((si_b->flags & SI_FL_L7_RETRY) &&
1549 (s->be->retry_type & PR_RE_TIMEOUT)) {
1550 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1551 return 0;
1552 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001555 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001556 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 }
1558
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 rep->analysers &= AN_RES_FLT_END;
1560 txn->status = 504;
1561 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001562 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563
1564 if (!(s->flags & SF_ERR_MASK))
1565 s->flags |= SF_ERR_SRVTO;
1566 if (!(s->flags & SF_FINST_MASK))
1567 s->flags |= SF_FINST_H;
1568 return 0;
1569 }
1570
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001573 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1574 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001575 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001576 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577
1578 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001580 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001581
1582 if (!(s->flags & SF_ERR_MASK))
1583 s->flags |= SF_ERR_CLICL;
1584 if (!(s->flags & SF_FINST_MASK))
1585 s->flags |= SF_FINST_H;
1586
1587 /* process_stream() will take care of the error */
1588 return 0;
1589 }
1590
Christopher Faulet9768c262018-10-22 09:34:31 +02001591 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001592 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001593 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001594 goto abort_keep_alive;
1595
Olivier Houcharda254a372019-04-05 15:30:12 +02001596 if ((si_b->flags & SI_FL_L7_RETRY) &&
1597 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1598 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1599 return 0;
1600 }
1601
Olivier Houcharda798bf52019-03-08 18:52:00 +01001602 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001604 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001605 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001606 }
1607
Christopher Faulete0768eb2018-10-03 16:38:02 +02001608 rep->analysers &= AN_RES_FLT_END;
1609 txn->status = 502;
1610 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001611 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612
1613 if (!(s->flags & SF_ERR_MASK))
1614 s->flags |= SF_ERR_SRVCL;
1615 if (!(s->flags & SF_FINST_MASK))
1616 s->flags |= SF_FINST_H;
1617 return 0;
1618 }
1619
Christopher Faulet9768c262018-10-22 09:34:31 +02001620 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001622 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 goto abort_keep_alive;
1624
Olivier Houcharda798bf52019-03-08 18:52:00 +01001625 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627
1628 if (!(s->flags & SF_ERR_MASK))
1629 s->flags |= SF_ERR_CLICL;
1630 if (!(s->flags & SF_FINST_MASK))
1631 s->flags |= SF_FINST_H;
1632
1633 /* process_stream() will take care of the error */
1634 return 0;
1635 }
1636
1637 channel_dont_close(rep);
1638 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1639 return 0;
1640 }
1641
1642 /* More interesting part now : we know that we have a complete
1643 * response which at least looks like HTTP. We have an indicator
1644 * of each header's length, so we can parse them quickly.
1645 */
1646
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001648 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001649
Christopher Faulet9768c262018-10-22 09:34:31 +02001650 /* 0: we might have to print this header in debug mode */
1651 if (unlikely((global.mode & MODE_DEBUG) &&
1652 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1653 int32_t pos;
1654
Christopher Faulet03599112018-11-27 11:21:21 +01001655 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001656
1657 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1658 struct htx_blk *blk = htx_get_blk(htx, pos);
1659 enum htx_blk_type type = htx_get_blk_type(blk);
1660
1661 if (type == HTX_BLK_EOH)
1662 break;
1663 if (type != HTX_BLK_HDR)
1664 continue;
1665
1666 htx_debug_hdr("srvhdr", s,
1667 htx_get_blk_name(htx, blk),
1668 htx_get_blk_value(htx, blk));
1669 }
1670 }
1671
Christopher Faulet03599112018-11-27 11:21:21 +01001672 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001673 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001674 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001675 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001676 if (sl->flags & HTX_SL_F_XFER_LEN) {
1677 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001678 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001679 if (sl->flags & HTX_SL_F_BODYLESS)
1680 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001681 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001682
1683 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001684 if (n < 1 || n > 5)
1685 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001686
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687 /* when the client triggers a 4xx from the server, it's most often due
1688 * to a missing object or permission. These events should be tracked
1689 * because if they happen often, it may indicate a brute force or a
1690 * vulnerability scan.
1691 */
1692 if (n == 4)
1693 stream_inc_http_err_ctr(s);
1694
1695 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001696 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697
Christopher Faulete0768eb2018-10-03 16:38:02 +02001698 /* Adjust server's health based on status code. Note: status codes 501
1699 * and 505 are triggered on demand by client request, so we must not
1700 * count them as server failures.
1701 */
1702 if (objt_server(s->target)) {
1703 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001704 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001706 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001707 }
1708
1709 /*
1710 * We may be facing a 100-continue response, or any other informational
1711 * 1xx response which is non-final, in which case this is not the right
1712 * response, and we're waiting for the next one. Let's allow this response
1713 * to go to the client and wait for the next one. There's an exception for
1714 * 101 which is used later in the code to switch protocols.
1715 */
1716 if (txn->status < 200 &&
1717 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001718 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001719 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720 msg->msg_state = HTTP_MSG_RPBEFORE;
1721 txn->status = 0;
1722 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001723 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001724 }
1725
1726 /*
1727 * 2: check for cacheability.
1728 */
1729
1730 switch (txn->status) {
1731 case 200:
1732 case 203:
1733 case 204:
1734 case 206:
1735 case 300:
1736 case 301:
1737 case 404:
1738 case 405:
1739 case 410:
1740 case 414:
1741 case 501:
1742 break;
1743 default:
1744 /* RFC7231#6.1:
1745 * Responses with status codes that are defined as
1746 * cacheable by default (e.g., 200, 203, 204, 206,
1747 * 300, 301, 404, 405, 410, 414, and 501 in this
1748 * specification) can be reused by a cache with
1749 * heuristic expiration unless otherwise indicated
1750 * by the method definition or explicit cache
1751 * controls [RFC7234]; all other status codes are
1752 * not cacheable by default.
1753 */
1754 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1755 break;
1756 }
1757
1758 /*
1759 * 3: we may need to capture headers
1760 */
1761 s->logs.logwait &= ~LW_RESP;
1762 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001763 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001764
Christopher Faulet9768c262018-10-22 09:34:31 +02001765 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001766 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1767 txn->status == 101)) {
1768 /* Either we've established an explicit tunnel, or we're
1769 * switching the protocol. In both cases, we're very unlikely
1770 * to understand the next protocols. We have to switch to tunnel
1771 * mode, so that we transfer the request and responses then let
1772 * this protocol pass unmodified. When we later implement specific
1773 * parsers for such protocols, we'll want to check the Upgrade
1774 * header which contains information about that protocol for
1775 * responses with status 101 (eg: see RFC2817 about TLS).
1776 */
1777 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001778 }
1779
Christopher Faulet61608322018-11-23 16:23:45 +01001780 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1781 * 407 (Proxy-Authenticate) responses and set the connection to private
1782 */
1783 srv_conn = cs_conn(objt_cs(s->si[1].end));
1784 if (srv_conn) {
1785 struct ist hdr;
1786 struct http_hdr_ctx ctx;
1787
1788 if (txn->status == 401)
1789 hdr = ist("WWW-Authenticate");
1790 else if (txn->status == 407)
1791 hdr = ist("Proxy-Authenticate");
1792 else
1793 goto end;
1794
1795 ctx.blk = NULL;
1796 while (http_find_header(htx, hdr, &ctx, 0)) {
1797 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1798 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1799 srv_conn->flags |= CO_FL_PRIVATE;
1800 }
1801 }
1802
1803 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 /* we want to have the response time before we start processing it */
1805 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1806
1807 /* end of job, return OK */
1808 rep->analysers &= ~an_bit;
1809 rep->analyse_exp = TICK_ETERNITY;
1810 channel_auto_close(rep);
1811 return 1;
1812
Christopher Faulet47365272018-10-31 17:40:50 +01001813 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001814 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001815 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001816 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001817 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001818 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001819 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
1820 do_l7_retry(s, si_b) == 0)
1821 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001822 txn->status = 502;
1823 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001824 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001825 rep->analysers &= AN_RES_FLT_END;
1826
1827 if (!(s->flags & SF_ERR_MASK))
1828 s->flags |= SF_ERR_PRXCOND;
1829 if (!(s->flags & SF_FINST_MASK))
1830 s->flags |= SF_FINST_H;
1831 return 0;
1832
Christopher Faulete0768eb2018-10-03 16:38:02 +02001833 abort_keep_alive:
1834 /* A keep-alive request to the server failed on a network error.
1835 * The client is required to retry. We need to close without returning
1836 * any other information so that the client retries.
1837 */
1838 txn->status = 0;
1839 rep->analysers &= AN_RES_FLT_END;
1840 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001841 s->logs.logwait = 0;
1842 s->logs.level = 0;
1843 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001844 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001845 return 0;
1846}
1847
1848/* This function performs all the processing enabled for the current response.
1849 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1850 * and updates s->res.analysers. It might make sense to explode it into several
1851 * other functions. It works like process_request (see indications above).
1852 */
1853int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1854{
1855 struct session *sess = s->sess;
1856 struct http_txn *txn = s->txn;
1857 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001858 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 struct proxy *cur_proxy;
1860 struct cond_wordlist *wl;
1861 enum rule_result ret = HTTP_RULE_RES_CONT;
1862
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001863 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1864 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001865
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1867 now_ms, __FUNCTION__,
1868 s,
1869 rep,
1870 rep->rex, rep->wex,
1871 rep->flags,
1872 ci_data(rep),
1873 rep->analysers);
1874
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001875 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001876
1877 /* The stats applet needs to adjust the Connection header but we don't
1878 * apply any filter there.
1879 */
1880 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1881 rep->analysers &= ~an_bit;
1882 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001883 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001884 }
1885
1886 /*
1887 * We will have to evaluate the filters.
1888 * As opposed to version 1.2, now they will be evaluated in the
1889 * filters order and not in the header order. This means that
1890 * each filter has to be validated among all headers.
1891 *
1892 * Filters are tried with ->be first, then with ->fe if it is
1893 * different from ->be.
1894 *
1895 * Maybe we are in resume condiion. In this case I choose the
1896 * "struct proxy" which contains the rule list matching the resume
1897 * pointer. If none of theses "struct proxy" match, I initialise
1898 * the process with the first one.
1899 *
1900 * In fact, I check only correspondance betwwen the current list
1901 * pointer and the ->fe rule list. If it doesn't match, I initialize
1902 * the loop with the ->be.
1903 */
1904 if (s->current_rule_list == &sess->fe->http_res_rules)
1905 cur_proxy = sess->fe;
1906 else
1907 cur_proxy = s->be;
1908 while (1) {
1909 struct proxy *rule_set = cur_proxy;
1910
1911 /* evaluate http-response rules */
1912 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001913 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001914
1915 if (ret == HTTP_RULE_RES_BADREQ)
1916 goto return_srv_prx_502;
1917
1918 if (ret == HTTP_RULE_RES_DONE) {
1919 rep->analysers &= ~an_bit;
1920 rep->analyse_exp = TICK_ETERNITY;
1921 return 1;
1922 }
1923 }
1924
1925 /* we need to be called again. */
1926 if (ret == HTTP_RULE_RES_YIELD) {
1927 channel_dont_close(rep);
1928 return 0;
1929 }
1930
1931 /* try headers filters */
1932 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001933 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1934 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001935 }
1936
1937 /* has the response been denied ? */
1938 if (txn->flags & TX_SVDENY) {
1939 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001940 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001941
Olivier Houcharda798bf52019-03-08 18:52:00 +01001942 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1943 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001945 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946 goto return_srv_prx_502;
1947 }
1948
1949 /* add response headers from the rule sets in the same order */
1950 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001951 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001952 if (txn->status < 200 && txn->status != 101)
1953 break;
1954 if (wl->cond) {
1955 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1956 ret = acl_pass(ret);
1957 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1958 ret = !ret;
1959 if (!ret)
1960 continue;
1961 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001962
1963 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1964 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001965 goto return_bad_resp;
1966 }
1967
1968 /* check whether we're already working on the frontend */
1969 if (cur_proxy == sess->fe)
1970 break;
1971 cur_proxy = sess->fe;
1972 }
1973
1974 /* After this point, this anayzer can't return yield, so we can
1975 * remove the bit corresponding to this analyzer from the list.
1976 *
1977 * Note that the intermediate returns and goto found previously
1978 * reset the analyzers.
1979 */
1980 rep->analysers &= ~an_bit;
1981 rep->analyse_exp = TICK_ETERNITY;
1982
1983 /* OK that's all we can do for 1xx responses */
1984 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001985 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001986
1987 /*
1988 * Now check for a server cookie.
1989 */
1990 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001991 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001992
1993 /*
1994 * Check for cache-control or pragma headers if required.
1995 */
1996 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1997 check_response_for_cacheability(s, rep);
1998
1999 /*
2000 * Add server cookie in the response if needed
2001 */
2002 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2003 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2004 (!(s->flags & SF_DIRECT) ||
2005 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2006 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2007 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2008 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2009 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2010 !(s->flags & SF_IGNORE_PRST)) {
2011 /* the server is known, it's not the one the client requested, or the
2012 * cookie's last seen date needs to be refreshed. We have to
2013 * insert a set-cookie here, except if we want to insert only on POST
2014 * requests and this one isn't. Note that servers which don't have cookies
2015 * (eg: some backup servers) will return a full cookie removal request.
2016 */
2017 if (!objt_server(s->target)->cookie) {
2018 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002019 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002020 s->be->cookie_name);
2021 }
2022 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002023 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024
2025 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2026 /* emit last_date, which is mandatory */
2027 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2028 s30tob64((date.tv_sec+3) >> 2,
2029 trash.area + trash.data);
2030 trash.data += 5;
2031
2032 if (s->be->cookie_maxlife) {
2033 /* emit first_date, which is either the original one or
2034 * the current date.
2035 */
2036 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2037 s30tob64(txn->cookie_first_date ?
2038 txn->cookie_first_date >> 2 :
2039 (date.tv_sec+3) >> 2,
2040 trash.area + trash.data);
2041 trash.data += 5;
2042 }
2043 }
2044 chunk_appendf(&trash, "; path=/");
2045 }
2046
2047 if (s->be->cookie_domain)
2048 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2049
2050 if (s->be->ck_opts & PR_CK_HTTPONLY)
2051 chunk_appendf(&trash, "; HttpOnly");
2052
2053 if (s->be->ck_opts & PR_CK_SECURE)
2054 chunk_appendf(&trash, "; Secure");
2055
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002057 goto return_bad_resp;
2058
2059 txn->flags &= ~TX_SCK_MASK;
2060 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2061 /* the server did not change, only the date was updated */
2062 txn->flags |= TX_SCK_UPDATED;
2063 else
2064 txn->flags |= TX_SCK_INSERTED;
2065
2066 /* Here, we will tell an eventual cache on the client side that we don't
2067 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2068 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2069 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2070 */
2071 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2072
2073 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2074
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002075 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002076 goto return_bad_resp;
2077 }
2078 }
2079
2080 /*
2081 * Check if result will be cacheable with a cookie.
2082 * We'll block the response if security checks have caught
2083 * nasty things such as a cacheable cookie.
2084 */
2085 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2086 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2087 (s->be->options & PR_O_CHK_CACHE)) {
2088 /* we're in presence of a cacheable response containing
2089 * a set-cookie header. We'll block it as requested by
2090 * the 'checkcache' option, and send an alert.
2091 */
2092 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002093 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002094
Olivier Houcharda798bf52019-03-08 18:52:00 +01002095 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2096 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002097 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002098 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002099
2100 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2101 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2102 send_log(s->be, LOG_ALERT,
2103 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2104 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2105 goto return_srv_prx_502;
2106 }
2107
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002108 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002109 /* Always enter in the body analyzer */
2110 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2111 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2112
2113 /* if the user wants to log as soon as possible, without counting
2114 * bytes from the server, then this is the right moment. We have
2115 * to temporarily assign bytes_out to log what we currently have.
2116 */
2117 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2118 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002119 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120 s->do_log(s);
2121 s->logs.bytes_out = 0;
2122 }
2123 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002124
2125 return_bad_resp:
2126 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002127 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002128 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002129 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002130 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002131
2132 return_srv_prx_502:
2133 rep->analysers &= AN_RES_FLT_END;
2134 txn->status = 502;
2135 s->logs.t_data = -1; /* was not a valid response */
2136 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002137 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002138 if (!(s->flags & SF_ERR_MASK))
2139 s->flags |= SF_ERR_PRXCOND;
2140 if (!(s->flags & SF_FINST_MASK))
2141 s->flags |= SF_FINST_H;
2142 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002143}
2144
2145/* This function is an analyser which forwards response body (including chunk
2146 * sizes if any). It is called as soon as we must forward, even if we forward
2147 * zero byte. The only situation where it must not be called is when we're in
2148 * tunnel mode and we want to forward till the close. It's used both to forward
2149 * remaining data and to resync after end of body. It expects the msg_state to
2150 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2151 * read more data, or 1 once we can go on with next request or end the stream.
2152 *
2153 * It is capable of compressing response data both in content-length mode and
2154 * in chunked mode. The state machines follows different flows depending on
2155 * whether content-length and chunked modes are used, since there are no
2156 * trailers in content-length :
2157 *
2158 * chk-mode cl-mode
2159 * ,----- BODY -----.
2160 * / \
2161 * V size > 0 V chk-mode
2162 * .--> SIZE -------------> DATA -------------> CRLF
2163 * | | size == 0 | last byte |
2164 * | v final crlf v inspected |
2165 * | TRAILERS -----------> DONE |
2166 * | |
2167 * `----------------------------------------------'
2168 *
2169 * Compression only happens in the DATA state, and must be flushed in final
2170 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2171 * is performed at once on final states for all bytes parsed, or when leaving
2172 * on missing data.
2173 */
2174int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2175{
2176 struct session *sess = s->sess;
2177 struct http_txn *txn = s->txn;
2178 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002179 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002180 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002181
2182 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2183 now_ms, __FUNCTION__,
2184 s,
2185 res,
2186 res->rex, res->wex,
2187 res->flags,
2188 ci_data(res),
2189 res->analysers);
2190
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002191 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192
2193 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002194 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002195 /* Output closed while we were sending data. We must abort and
2196 * wake the other side up.
2197 */
2198 msg->err_state = msg->msg_state;
2199 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002200 htx_end_response(s);
2201 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002202 return 1;
2203 }
2204
Christopher Faulet9768c262018-10-22 09:34:31 +02002205 if (msg->msg_state == HTTP_MSG_BODY)
2206 msg->msg_state = HTTP_MSG_DATA;
2207
Christopher Faulete0768eb2018-10-03 16:38:02 +02002208 /* in most states, we should abort in case of early close */
2209 channel_auto_close(res);
2210
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002212 if (res->to_forward == CHN_INFINITE_FORWARD) {
2213 if (res->flags & (CF_SHUTR|CF_EOI)) {
2214 msg->msg_state = HTTP_MSG_DONE;
2215 res->to_forward = 0;
2216 goto done;
2217 }
2218 }
2219 else {
2220 /* We can't process the buffer's contents yet */
2221 res->flags |= CF_WAKE_WRITE;
2222 goto missing_data_or_waiting;
2223 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 }
2225
Christopher Faulet9768c262018-10-22 09:34:31 +02002226 if (msg->msg_state >= HTTP_MSG_DONE)
2227 goto done;
2228
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002229 /* Forward input data. We get it by removing all outgoing data not
2230 * forwarded yet from HTX data size. If there are some data filters, we
2231 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002232 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002233 if (HAS_RSP_DATA_FILTERS(s)) {
2234 ret = flt_http_payload(s, msg, htx->data);
2235 if (ret < 0)
2236 goto return_bad_res;
2237 c_adv(res, ret);
2238 if (htx->data != co_data(res) || htx->extra)
2239 goto missing_data_or_waiting;
2240 }
2241 else {
2242 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002243 if (msg->flags & HTTP_MSGF_XFER_LEN)
2244 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002245 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002246
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002247 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2248 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2249 msg->msg_state = HTTP_MSG_TUNNEL;
2250 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 }
2252
Christopher Faulet9768c262018-10-22 09:34:31 +02002253 /* Check if the end-of-message is reached and if so, switch the message
2254 * in HTTP_MSG_DONE state.
2255 */
2256 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2257 goto missing_data_or_waiting;
2258
2259 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002260 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002261
2262 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002264 channel_dont_close(res);
2265
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002266 if (HAS_RSP_DATA_FILTERS(s)) {
2267 ret = flt_http_end(s, msg);
2268 if (ret <= 0) {
2269 if (!ret)
2270 goto missing_data_or_waiting;
2271 goto return_bad_res;
2272 }
2273 }
2274
Christopher Fauletf2824e62018-10-01 12:12:37 +02002275 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002277 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2279 if (res->flags & CF_SHUTW) {
2280 /* response errors are most likely due to the
2281 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002282 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 goto return_bad_res;
2285 }
2286 return 1;
2287 }
2288 return 0;
2289
2290 missing_data_or_waiting:
2291 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002292 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293
Christopher Faulet47365272018-10-31 17:40:50 +01002294 if (htx->flags & HTX_FL_PARSING_ERROR)
2295 goto return_bad_res;
2296
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 /* stop waiting for data if the input is closed before the end. If the
2298 * client side was already closed, it means that the client has aborted,
2299 * so we don't want to count this as a server abort. Otherwise it's a
2300 * server abort.
2301 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002302 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002303 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002304 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002306 if (htx_is_empty(htx))
2307 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002308 }
2309
Christopher Faulete0768eb2018-10-03 16:38:02 +02002310 /* When TE: chunked is used, we need to get there again to parse
2311 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002312 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2313 * are filters registered on the stream, we don't want to forward a
2314 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002315 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002316 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002317 channel_dont_close(res);
2318
2319 /* We know that more data are expected, but we couldn't send more that
2320 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2321 * system knows it must not set a PUSH on this first part. Interactive
2322 * modes are already handled by the stream sock layer. We must not do
2323 * this in content-length mode because it could present the MSG_MORE
2324 * flag with the last block of forwarded data, which would cause an
2325 * additional delay to be observed by the receiver.
2326 */
2327 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2328 res->flags |= CF_EXPECT_MORE;
2329
2330 /* the stream handler will take care of timeouts and errors */
2331 return 0;
2332
Christopher Faulet93e02d82019-03-08 14:18:50 +01002333 return_srv_abort:
2334 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2335 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002336 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002337 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2338 if (!(s->flags & SF_ERR_MASK))
2339 s->flags |= SF_ERR_SRVCL;
2340 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002341
Christopher Faulet93e02d82019-03-08 14:18:50 +01002342 return_cli_abort:
2343 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2344 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002345 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002346 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2347 if (!(s->flags & SF_ERR_MASK))
2348 s->flags |= SF_ERR_CLICL;
2349 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002350
Christopher Faulet93e02d82019-03-08 14:18:50 +01002351 return_bad_res:
2352 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2353 if (objt_server(s->target)) {
2354 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2355 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2356 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002357 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002358 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002359
Christopher Faulet93e02d82019-03-08 14:18:50 +01002360 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002361 txn->rsp.err_state = txn->rsp.msg_state;
2362 txn->rsp.msg_state = HTTP_MSG_ERROR;
2363 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002364 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002365 res->analysers &= AN_RES_FLT_END;
2366 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 +02002367 if (!(s->flags & SF_FINST_MASK))
2368 s->flags |= SF_FINST_D;
2369 return 0;
2370}
2371
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374 * as too large a request to build a valid response.
2375 */
2376int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2377{
Christopher Faulet99daf282018-11-28 22:58:13 +01002378 struct channel *req = &s->req;
2379 struct channel *res = &s->res;
2380 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002381 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002383 struct ist status, reason, location;
2384 unsigned int flags;
2385 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386
2387 chunk = alloc_trash_chunk();
2388 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 /*
2392 * Create the location
2393 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002394 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002396 case REDIRECT_TYPE_SCHEME: {
2397 struct http_hdr_ctx ctx;
2398 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002399
Christopher Faulet99daf282018-11-28 22:58:13 +01002400 host = ist("");
2401 ctx.blk = NULL;
2402 if (http_find_header(htx, ist("Host"), &ctx, 0))
2403 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 sl = http_find_stline(htx);
2406 path = http_get_path(htx_sl_req_uri(sl));
2407 /* build message using path */
2408 if (path.ptr) {
2409 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2410 int qs = 0;
2411 while (qs < path.len) {
2412 if (*(path.ptr + qs) == '?') {
2413 path.len = qs;
2414 break;
2415 }
2416 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418 }
2419 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002420 else
2421 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 if (rule->rdr_str) { /* this is an old "redirect" rule */
2424 /* add scheme */
2425 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2426 goto fail;
2427 }
2428 else {
2429 /* add scheme with executing log format */
2430 chunk->data += build_logline(s, chunk->area + chunk->data,
2431 chunk->size - chunk->data,
2432 &rule->rdr_fmt);
2433 }
2434 /* add "://" + host + path */
2435 if (!chunk_memcat(chunk, "://", 3) ||
2436 !chunk_memcat(chunk, host.ptr, host.len) ||
2437 !chunk_memcat(chunk, path.ptr, path.len))
2438 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439
Christopher Faulet99daf282018-11-28 22:58:13 +01002440 /* append a slash at the end of the location if needed and missing */
2441 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2442 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2443 if (chunk->data + 1 >= chunk->size)
2444 goto fail;
2445 chunk->area[chunk->data++] = '/';
2446 }
2447 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 case REDIRECT_TYPE_PREFIX: {
2451 struct ist path;
2452
2453 sl = http_find_stline(htx);
2454 path = http_get_path(htx_sl_req_uri(sl));
2455 /* build message using path */
2456 if (path.ptr) {
2457 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2458 int qs = 0;
2459 while (qs < path.len) {
2460 if (*(path.ptr + qs) == '?') {
2461 path.len = qs;
2462 break;
2463 }
2464 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002465 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466 }
2467 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002468 else
2469 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002470
Christopher Faulet99daf282018-11-28 22:58:13 +01002471 if (rule->rdr_str) { /* this is an old "redirect" rule */
2472 /* add prefix. Note that if prefix == "/", we don't want to
2473 * add anything, otherwise it makes it hard for the user to
2474 * configure a self-redirection.
2475 */
2476 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2477 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2478 goto fail;
2479 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002480 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002481 else {
2482 /* add prefix with executing log format */
2483 chunk->data += build_logline(s, chunk->area + chunk->data,
2484 chunk->size - chunk->data,
2485 &rule->rdr_fmt);
2486 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002487
Christopher Faulet99daf282018-11-28 22:58:13 +01002488 /* add path */
2489 if (!chunk_memcat(chunk, path.ptr, path.len))
2490 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002491
Christopher Faulet99daf282018-11-28 22:58:13 +01002492 /* append a slash at the end of the location if needed and missing */
2493 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2494 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2495 if (chunk->data + 1 >= chunk->size)
2496 goto fail;
2497 chunk->area[chunk->data++] = '/';
2498 }
2499 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002500 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002501 case REDIRECT_TYPE_LOCATION:
2502 default:
2503 if (rule->rdr_str) { /* this is an old "redirect" rule */
2504 /* add location */
2505 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2506 goto fail;
2507 }
2508 else {
2509 /* add location with executing log format */
2510 chunk->data += build_logline(s, chunk->area + chunk->data,
2511 chunk->size - chunk->data,
2512 &rule->rdr_fmt);
2513 }
2514 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002515 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002516 location = ist2(chunk->area, chunk->data);
2517
2518 /*
2519 * Create the 30x response
2520 */
2521 switch (rule->code) {
2522 case 308:
2523 status = ist("308");
2524 reason = ist("Permanent Redirect");
2525 break;
2526 case 307:
2527 status = ist("307");
2528 reason = ist("Temporary Redirect");
2529 break;
2530 case 303:
2531 status = ist("303");
2532 reason = ist("See Other");
2533 break;
2534 case 301:
2535 status = ist("301");
2536 reason = ist("Moved Permanently");
2537 break;
2538 case 302:
2539 default:
2540 status = ist("302");
2541 reason = ist("Found");
2542 break;
2543 }
2544
2545 htx = htx_from_buf(&res->buf);
2546 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2547 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2548 if (!sl)
2549 goto fail;
2550 sl->info.res.status = rule->code;
2551 s->txn->status = rule->code;
2552
2553 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2554 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2555 !htx_add_header(htx, ist("Location"), location))
2556 goto fail;
2557
2558 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2559 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2560 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002561 }
2562
2563 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002564 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2565 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002566 }
2567
Christopher Faulet99daf282018-11-28 22:58:13 +01002568 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2569 goto fail;
2570
Christopher Fauletf2824e62018-10-01 12:12:37 +02002571 /* let's log the request time */
2572 s->logs.tv_request = now;
2573
Christopher Faulet99daf282018-11-28 22:58:13 +01002574 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002575 c_adv(res, data);
2576 res->total += data;
2577
2578 channel_auto_read(req);
2579 channel_abort(req);
2580 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002581 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002582
2583 res->wex = tick_add_ifset(now_ms, res->wto);
2584 channel_auto_read(res);
2585 channel_auto_close(res);
2586 channel_shutr_now(res);
2587
2588 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002589
2590 if (!(s->flags & SF_ERR_MASK))
2591 s->flags |= SF_ERR_LOCAL;
2592 if (!(s->flags & SF_FINST_MASK))
2593 s->flags |= SF_FINST_R;
2594
Christopher Faulet99daf282018-11-28 22:58:13 +01002595 free_trash_chunk(chunk);
2596 return 1;
2597
2598 fail:
2599 /* If an error occurred, remove the incomplete HTTP response from the
2600 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002601 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002602 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002603 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002604}
2605
Christopher Faulet72333522018-10-24 11:25:02 +02002606int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2607 struct ist name, const char *str, struct my_regex *re, int action)
2608{
2609 struct http_hdr_ctx ctx;
2610 struct buffer *output = get_trash_chunk();
2611
2612 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2613 ctx.blk = NULL;
2614 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2615 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2616 continue;
2617
2618 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2619 if (output->data == -1)
2620 return -1;
2621 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2622 return -1;
2623 }
2624 return 0;
2625}
2626
2627static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2628 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2629{
2630 struct buffer *replace;
2631 int ret = -1;
2632
2633 replace = alloc_trash_chunk();
2634 if (!replace)
2635 goto leave;
2636
2637 replace->data = build_logline(s, replace->area, replace->size, fmt);
2638 if (replace->data >= replace->size - 1)
2639 goto leave;
2640
2641 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2642
2643 leave:
2644 free_trash_chunk(replace);
2645 return ret;
2646}
2647
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002648
2649/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2650 * on success and -1 on error. The response channel is updated accordingly.
2651 */
2652static int htx_reply_103_early_hints(struct channel *res)
2653{
2654 struct htx *htx = htx_from_buf(&res->buf);
2655 size_t data;
2656
2657 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2658 /* If an error occurred during an Early-hint rule,
2659 * remove the incomplete HTTP 103 response from the
2660 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002661 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 return -1;
2663 }
2664
2665 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002666 c_adv(res, data);
2667 res->total += data;
2668 return 0;
2669}
2670
Christopher Faulet6eb92892018-11-15 16:39:29 +01002671/*
2672 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2673 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002674 * If <early_hints> is 0, it is starts a new response by adding the start
2675 * line. If an error occurred -1 is returned. On success 0 is returned. The
2676 * channel is not updated here. It must be done calling the function
2677 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002678 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002679static 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 +01002680{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681 struct channel *res = &s->res;
2682 struct htx *htx = htx_from_buf(&res->buf);
2683 struct buffer *value = alloc_trash_chunk();
2684
Christopher Faulet6eb92892018-11-15 16:39:29 +01002685 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002686 struct htx_sl *sl;
2687 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2688 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2689
2690 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2691 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2692 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002693 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002694 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002695 }
2696
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002697 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2698 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002699 goto fail;
2700
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002701 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002702 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002703
2704 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002705 /* If an error occurred during an Early-hint rule, remove the incomplete
2706 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002707 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002708 free_trash_chunk(value);
2709 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002710}
2711
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002712/* This function executes one of the set-{method,path,query,uri} actions. It
2713 * takes the string from the variable 'replace' with length 'len', then modifies
2714 * the relevant part of the request line accordingly. Then it updates various
2715 * pointers to the next elements which were moved, and the total buffer length.
2716 * It finds the action to be performed in p[2], previously filled by function
2717 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2718 * error, though this can be revisited when this code is finally exploited.
2719 *
2720 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2721 * query string and 3 to replace uri.
2722 *
2723 * In query string case, the mark question '?' must be set at the start of the
2724 * string by the caller, event if the replacement query string is empty.
2725 */
2726int htx_req_replace_stline(int action, const char *replace, int len,
2727 struct proxy *px, struct stream *s)
2728{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002729 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002730
2731 switch (action) {
2732 case 0: // method
2733 if (!http_replace_req_meth(htx, ist2(replace, len)))
2734 return -1;
2735 break;
2736
2737 case 1: // path
2738 if (!http_replace_req_path(htx, ist2(replace, len)))
2739 return -1;
2740 break;
2741
2742 case 2: // query
2743 if (!http_replace_req_query(htx, ist2(replace, len)))
2744 return -1;
2745 break;
2746
2747 case 3: // uri
2748 if (!http_replace_req_uri(htx, ist2(replace, len)))
2749 return -1;
2750 break;
2751
2752 default:
2753 return -1;
2754 }
2755 return 0;
2756}
2757
2758/* This function replace the HTTP status code and the associated message. The
2759 * variable <status> contains the new status code. This function never fails.
2760 */
2761void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2762{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002763 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002764 char *res;
2765
2766 chunk_reset(&trash);
2767 res = ultoa_o(status, trash.area, trash.size);
2768 trash.data = res - trash.area;
2769
2770 /* Do we have a custom reason format string? */
2771 if (reason == NULL)
2772 reason = http_get_reason(status);
2773
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002774 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002775 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2776}
2777
Christopher Faulet3e964192018-10-24 11:39:23 +02002778/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2779 * transaction <txn>. Returns the verdict of the first rule that prevents
2780 * further processing of the request (auth, deny, ...), and defaults to
2781 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2782 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2783 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2784 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2785 * status.
2786 */
2787static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2788 struct stream *s, int *deny_status)
2789{
2790 struct session *sess = strm_sess(s);
2791 struct http_txn *txn = s->txn;
2792 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002793 struct act_rule *rule;
2794 struct http_hdr_ctx ctx;
2795 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002796 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2797 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002798 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002799
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002800 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002801
2802 /* If "the current_rule_list" match the executed rule list, we are in
2803 * resume condition. If a resume is needed it is always in the action
2804 * and never in the ACL or converters. In this case, we initialise the
2805 * current rule, and go to the action execution point.
2806 */
2807 if (s->current_rule) {
2808 rule = s->current_rule;
2809 s->current_rule = NULL;
2810 if (s->current_rule_list == rules)
2811 goto resume_execution;
2812 }
2813 s->current_rule_list = rules;
2814
2815 list_for_each_entry(rule, rules, list) {
2816 /* check optional condition */
2817 if (rule->cond) {
2818 int ret;
2819
2820 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2821 ret = acl_pass(ret);
2822
2823 if (rule->cond->pol == ACL_COND_UNLESS)
2824 ret = !ret;
2825
2826 if (!ret) /* condition not matched */
2827 continue;
2828 }
2829
2830 act_flags |= ACT_FLAG_FIRST;
2831 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002832 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2833 early_hints = 0;
2834 if (htx_reply_103_early_hints(&s->res) == -1) {
2835 rule_ret = HTTP_RULE_RES_BADREQ;
2836 goto end;
2837 }
2838 }
2839
Christopher Faulet3e964192018-10-24 11:39:23 +02002840 switch (rule->action) {
2841 case ACT_ACTION_ALLOW:
2842 rule_ret = HTTP_RULE_RES_STOP;
2843 goto end;
2844
2845 case ACT_ACTION_DENY:
2846 if (deny_status)
2847 *deny_status = rule->deny_status;
2848 rule_ret = HTTP_RULE_RES_DENY;
2849 goto end;
2850
2851 case ACT_HTTP_REQ_TARPIT:
2852 txn->flags |= TX_CLTARPIT;
2853 if (deny_status)
2854 *deny_status = rule->deny_status;
2855 rule_ret = HTTP_RULE_RES_DENY;
2856 goto end;
2857
2858 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002859 /* Auth might be performed on regular http-req rules as well as on stats */
2860 auth_realm = rule->arg.auth.realm;
2861 if (!auth_realm) {
2862 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2863 auth_realm = STATS_DEFAULT_REALM;
2864 else
2865 auth_realm = px->id;
2866 }
2867 /* send 401/407 depending on whether we use a proxy or not. We still
2868 * count one error, because normal browsing won't significantly
2869 * increase the counter but brute force attempts will.
2870 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002871 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002872 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2873 rule_ret = HTTP_RULE_RES_BADREQ;
2874 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002875 goto end;
2876
2877 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002878 rule_ret = HTTP_RULE_RES_DONE;
2879 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2880 rule_ret = HTTP_RULE_RES_BADREQ;
2881 goto end;
2882
2883 case ACT_HTTP_SET_NICE:
2884 s->task->nice = rule->arg.nice;
2885 break;
2886
2887 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002888 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002889 break;
2890
2891 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002892 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002893 break;
2894
2895 case ACT_HTTP_SET_LOGL:
2896 s->logs.level = rule->arg.loglevel;
2897 break;
2898
2899 case ACT_HTTP_REPLACE_HDR:
2900 case ACT_HTTP_REPLACE_VAL:
2901 if (htx_transform_header(s, &s->req, htx,
2902 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2903 &rule->arg.hdr_add.fmt,
2904 &rule->arg.hdr_add.re, rule->action)) {
2905 rule_ret = HTTP_RULE_RES_BADREQ;
2906 goto end;
2907 }
2908 break;
2909
2910 case ACT_HTTP_DEL_HDR:
2911 /* remove all occurrences of the header */
2912 ctx.blk = NULL;
2913 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2914 http_remove_header(htx, &ctx);
2915 break;
2916
2917 case ACT_HTTP_SET_HDR:
2918 case ACT_HTTP_ADD_HDR: {
2919 /* The scope of the trash buffer must be limited to this function. The
2920 * build_logline() function can execute a lot of other function which
2921 * can use the trash buffer. So for limiting the scope of this global
2922 * buffer, we build first the header value using build_logline, and
2923 * after we store the header name.
2924 */
2925 struct buffer *replace;
2926 struct ist n, v;
2927
2928 replace = alloc_trash_chunk();
2929 if (!replace) {
2930 rule_ret = HTTP_RULE_RES_BADREQ;
2931 goto end;
2932 }
2933
2934 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2935 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2936 v = ist2(replace->area, replace->data);
2937
2938 if (rule->action == ACT_HTTP_SET_HDR) {
2939 /* remove all occurrences of the header */
2940 ctx.blk = NULL;
2941 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2942 http_remove_header(htx, &ctx);
2943 }
2944
2945 if (!http_add_header(htx, n, v)) {
2946 static unsigned char rate_limit = 0;
2947
2948 if ((rate_limit++ & 255) == 0) {
2949 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);
2950 }
2951
Olivier Houcharda798bf52019-03-08 18:52:00 +01002952 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002953 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002954 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002955 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002956 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002957 }
2958 free_trash_chunk(replace);
2959 break;
2960 }
2961
2962 case ACT_HTTP_DEL_ACL:
2963 case ACT_HTTP_DEL_MAP: {
2964 struct pat_ref *ref;
2965 struct buffer *key;
2966
2967 /* collect reference */
2968 ref = pat_ref_lookup(rule->arg.map.ref);
2969 if (!ref)
2970 continue;
2971
2972 /* allocate key */
2973 key = alloc_trash_chunk();
2974 if (!key) {
2975 rule_ret = HTTP_RULE_RES_BADREQ;
2976 goto end;
2977 }
2978
2979 /* collect key */
2980 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2981 key->area[key->data] = '\0';
2982
2983 /* perform update */
2984 /* returned code: 1=ok, 0=ko */
2985 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2986 pat_ref_delete(ref, key->area);
2987 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2988
2989 free_trash_chunk(key);
2990 break;
2991 }
2992
2993 case ACT_HTTP_ADD_ACL: {
2994 struct pat_ref *ref;
2995 struct buffer *key;
2996
2997 /* collect reference */
2998 ref = pat_ref_lookup(rule->arg.map.ref);
2999 if (!ref)
3000 continue;
3001
3002 /* allocate key */
3003 key = alloc_trash_chunk();
3004 if (!key) {
3005 rule_ret = HTTP_RULE_RES_BADREQ;
3006 goto end;
3007 }
3008
3009 /* collect key */
3010 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3011 key->area[key->data] = '\0';
3012
3013 /* perform update */
3014 /* add entry only if it does not already exist */
3015 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3016 if (pat_ref_find_elt(ref, key->area) == NULL)
3017 pat_ref_add(ref, key->area, NULL, NULL);
3018 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3019
3020 free_trash_chunk(key);
3021 break;
3022 }
3023
3024 case ACT_HTTP_SET_MAP: {
3025 struct pat_ref *ref;
3026 struct buffer *key, *value;
3027
3028 /* collect reference */
3029 ref = pat_ref_lookup(rule->arg.map.ref);
3030 if (!ref)
3031 continue;
3032
3033 /* allocate key */
3034 key = alloc_trash_chunk();
3035 if (!key) {
3036 rule_ret = HTTP_RULE_RES_BADREQ;
3037 goto end;
3038 }
3039
3040 /* allocate value */
3041 value = alloc_trash_chunk();
3042 if (!value) {
3043 free_trash_chunk(key);
3044 rule_ret = HTTP_RULE_RES_BADREQ;
3045 goto end;
3046 }
3047
3048 /* collect key */
3049 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3050 key->area[key->data] = '\0';
3051
3052 /* collect value */
3053 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3054 value->area[value->data] = '\0';
3055
3056 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003057 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003058 if (pat_ref_find_elt(ref, key->area) != NULL)
3059 /* update entry if it exists */
3060 pat_ref_set(ref, key->area, value->area, NULL);
3061 else
3062 /* insert a new entry */
3063 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003064 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003065 free_trash_chunk(key);
3066 free_trash_chunk(value);
3067 break;
3068 }
3069
3070 case ACT_HTTP_EARLY_HINT:
3071 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3072 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003073 early_hints = htx_add_early_hint_header(s, early_hints,
3074 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003075 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003076 if (early_hints == -1) {
3077 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003078 goto end;
3079 }
3080 break;
3081
3082 case ACT_CUSTOM:
3083 if ((s->req.flags & CF_READ_ERROR) ||
3084 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003085 (px->options & PR_O_ABRT_CLOSE)))
3086 act_flags |= ACT_FLAG_FINAL;
3087
3088 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3089 case ACT_RET_ERR:
3090 case ACT_RET_CONT:
3091 break;
3092 case ACT_RET_STOP:
3093 rule_ret = HTTP_RULE_RES_DONE;
3094 goto end;
3095 case ACT_RET_YIELD:
3096 s->current_rule = rule;
3097 rule_ret = HTTP_RULE_RES_YIELD;
3098 goto end;
3099 }
3100 break;
3101
3102 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3103 /* Note: only the first valid tracking parameter of each
3104 * applies.
3105 */
3106
3107 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3108 struct stktable *t;
3109 struct stksess *ts;
3110 struct stktable_key *key;
3111 void *ptr1, *ptr2;
3112
3113 t = rule->arg.trk_ctr.table.t;
3114 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3115 rule->arg.trk_ctr.expr, NULL);
3116
3117 if (key && (ts = stktable_get_entry(t, key))) {
3118 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3119
3120 /* let's count a new HTTP request as it's the first time we do it */
3121 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3122 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3123 if (ptr1 || ptr2) {
3124 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3125
3126 if (ptr1)
3127 stktable_data_cast(ptr1, http_req_cnt)++;
3128
3129 if (ptr2)
3130 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3131 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3132
3133 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3134
3135 /* If data was modified, we need to touch to re-schedule sync */
3136 stktable_touch_local(t, ts, 0);
3137 }
3138
3139 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3140 if (sess->fe != s->be)
3141 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3142 }
3143 }
3144 break;
3145
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003146 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003147 default:
3148 break;
3149 }
3150 }
3151
3152 end:
3153 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003154 if (htx_reply_103_early_hints(&s->res) == -1)
3155 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003156 }
3157
3158 /* we reached the end of the rules, nothing to report */
3159 return rule_ret;
3160}
3161
3162/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3163 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3164 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3165 * is returned, the process can continue the evaluation of next rule list. If
3166 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3167 * is returned, it means the operation could not be processed and a server error
3168 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3169 * deny rule. If *YIELD is returned, the caller must call again the function
3170 * with the same context.
3171 */
3172static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3173 struct stream *s)
3174{
3175 struct session *sess = strm_sess(s);
3176 struct http_txn *txn = s->txn;
3177 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003178 struct act_rule *rule;
3179 struct http_hdr_ctx ctx;
3180 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3181 int act_flags = 0;
3182
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003183 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003184
3185 /* If "the current_rule_list" match the executed rule list, we are in
3186 * resume condition. If a resume is needed it is always in the action
3187 * and never in the ACL or converters. In this case, we initialise the
3188 * current rule, and go to the action execution point.
3189 */
3190 if (s->current_rule) {
3191 rule = s->current_rule;
3192 s->current_rule = NULL;
3193 if (s->current_rule_list == rules)
3194 goto resume_execution;
3195 }
3196 s->current_rule_list = rules;
3197
3198 list_for_each_entry(rule, rules, list) {
3199 /* check optional condition */
3200 if (rule->cond) {
3201 int ret;
3202
3203 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3204 ret = acl_pass(ret);
3205
3206 if (rule->cond->pol == ACL_COND_UNLESS)
3207 ret = !ret;
3208
3209 if (!ret) /* condition not matched */
3210 continue;
3211 }
3212
3213 act_flags |= ACT_FLAG_FIRST;
3214resume_execution:
3215 switch (rule->action) {
3216 case ACT_ACTION_ALLOW:
3217 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3218 goto end;
3219
3220 case ACT_ACTION_DENY:
3221 txn->flags |= TX_SVDENY;
3222 rule_ret = HTTP_RULE_RES_STOP;
3223 goto end;
3224
3225 case ACT_HTTP_SET_NICE:
3226 s->task->nice = rule->arg.nice;
3227 break;
3228
3229 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003230 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003231 break;
3232
3233 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003234 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003235 break;
3236
3237 case ACT_HTTP_SET_LOGL:
3238 s->logs.level = rule->arg.loglevel;
3239 break;
3240
3241 case ACT_HTTP_REPLACE_HDR:
3242 case ACT_HTTP_REPLACE_VAL:
3243 if (htx_transform_header(s, &s->res, htx,
3244 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3245 &rule->arg.hdr_add.fmt,
3246 &rule->arg.hdr_add.re, rule->action)) {
3247 rule_ret = HTTP_RULE_RES_BADREQ;
3248 goto end;
3249 }
3250 break;
3251
3252 case ACT_HTTP_DEL_HDR:
3253 /* remove all occurrences of the header */
3254 ctx.blk = NULL;
3255 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3256 http_remove_header(htx, &ctx);
3257 break;
3258
3259 case ACT_HTTP_SET_HDR:
3260 case ACT_HTTP_ADD_HDR: {
3261 struct buffer *replace;
3262 struct ist n, v;
3263
3264 replace = alloc_trash_chunk();
3265 if (!replace) {
3266 rule_ret = HTTP_RULE_RES_BADREQ;
3267 goto end;
3268 }
3269
3270 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3271 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3272 v = ist2(replace->area, replace->data);
3273
3274 if (rule->action == ACT_HTTP_SET_HDR) {
3275 /* remove all occurrences of the header */
3276 ctx.blk = NULL;
3277 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3278 http_remove_header(htx, &ctx);
3279 }
3280
3281 if (!http_add_header(htx, n, v)) {
3282 static unsigned char rate_limit = 0;
3283
3284 if ((rate_limit++ & 255) == 0) {
3285 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);
3286 }
3287
Olivier Houcharda798bf52019-03-08 18:52:00 +01003288 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003289 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003290 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003291 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003292 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003293 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003294 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003295 }
3296 free_trash_chunk(replace);
3297 break;
3298 }
3299
3300 case ACT_HTTP_DEL_ACL:
3301 case ACT_HTTP_DEL_MAP: {
3302 struct pat_ref *ref;
3303 struct buffer *key;
3304
3305 /* collect reference */
3306 ref = pat_ref_lookup(rule->arg.map.ref);
3307 if (!ref)
3308 continue;
3309
3310 /* allocate key */
3311 key = alloc_trash_chunk();
3312 if (!key) {
3313 rule_ret = HTTP_RULE_RES_BADREQ;
3314 goto end;
3315 }
3316
3317 /* collect key */
3318 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3319 key->area[key->data] = '\0';
3320
3321 /* perform update */
3322 /* returned code: 1=ok, 0=ko */
3323 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3324 pat_ref_delete(ref, key->area);
3325 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3326
3327 free_trash_chunk(key);
3328 break;
3329 }
3330
3331 case ACT_HTTP_ADD_ACL: {
3332 struct pat_ref *ref;
3333 struct buffer *key;
3334
3335 /* collect reference */
3336 ref = pat_ref_lookup(rule->arg.map.ref);
3337 if (!ref)
3338 continue;
3339
3340 /* allocate key */
3341 key = alloc_trash_chunk();
3342 if (!key) {
3343 rule_ret = HTTP_RULE_RES_BADREQ;
3344 goto end;
3345 }
3346
3347 /* collect key */
3348 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3349 key->area[key->data] = '\0';
3350
3351 /* perform update */
3352 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003353 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003354 if (pat_ref_find_elt(ref, key->area) == NULL)
3355 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003356 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003357 free_trash_chunk(key);
3358 break;
3359 }
3360
3361 case ACT_HTTP_SET_MAP: {
3362 struct pat_ref *ref;
3363 struct buffer *key, *value;
3364
3365 /* collect reference */
3366 ref = pat_ref_lookup(rule->arg.map.ref);
3367 if (!ref)
3368 continue;
3369
3370 /* allocate key */
3371 key = alloc_trash_chunk();
3372 if (!key) {
3373 rule_ret = HTTP_RULE_RES_BADREQ;
3374 goto end;
3375 }
3376
3377 /* allocate value */
3378 value = alloc_trash_chunk();
3379 if (!value) {
3380 free_trash_chunk(key);
3381 rule_ret = HTTP_RULE_RES_BADREQ;
3382 goto end;
3383 }
3384
3385 /* collect key */
3386 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3387 key->area[key->data] = '\0';
3388
3389 /* collect value */
3390 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3391 value->area[value->data] = '\0';
3392
3393 /* perform update */
3394 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3395 if (pat_ref_find_elt(ref, key->area) != NULL)
3396 /* update entry if it exists */
3397 pat_ref_set(ref, key->area, value->area, NULL);
3398 else
3399 /* insert a new entry */
3400 pat_ref_add(ref, key->area, value->area, NULL);
3401 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3402 free_trash_chunk(key);
3403 free_trash_chunk(value);
3404 break;
3405 }
3406
3407 case ACT_HTTP_REDIR:
3408 rule_ret = HTTP_RULE_RES_DONE;
3409 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3410 rule_ret = HTTP_RULE_RES_BADREQ;
3411 goto end;
3412
3413 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3414 /* Note: only the first valid tracking parameter of each
3415 * applies.
3416 */
3417 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3418 struct stktable *t;
3419 struct stksess *ts;
3420 struct stktable_key *key;
3421 void *ptr;
3422
3423 t = rule->arg.trk_ctr.table.t;
3424 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3425 rule->arg.trk_ctr.expr, NULL);
3426
3427 if (key && (ts = stktable_get_entry(t, key))) {
3428 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3429
3430 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3431
3432 /* let's count a new HTTP request as it's the first time we do it */
3433 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3434 if (ptr)
3435 stktable_data_cast(ptr, http_req_cnt)++;
3436
3437 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3438 if (ptr)
3439 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3440 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3441
3442 /* When the client triggers a 4xx from the server, it's most often due
3443 * to a missing object or permission. These events should be tracked
3444 * because if they happen often, it may indicate a brute force or a
3445 * vulnerability scan. Normally this is done when receiving the response
3446 * but here we're tracking after this ought to have been done so we have
3447 * to do it on purpose.
3448 */
3449 if ((unsigned)(txn->status - 400) < 100) {
3450 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3451 if (ptr)
3452 stktable_data_cast(ptr, http_err_cnt)++;
3453
3454 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3455 if (ptr)
3456 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3457 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3458 }
3459
3460 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3461
3462 /* If data was modified, we need to touch to re-schedule sync */
3463 stktable_touch_local(t, ts, 0);
3464
3465 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3466 if (sess->fe != s->be)
3467 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3468 }
3469 }
3470 break;
3471
3472 case ACT_CUSTOM:
3473 if ((s->req.flags & CF_READ_ERROR) ||
3474 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003475 (px->options & PR_O_ABRT_CLOSE)))
3476 act_flags |= ACT_FLAG_FINAL;
3477
3478 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3479 case ACT_RET_ERR:
3480 case ACT_RET_CONT:
3481 break;
3482 case ACT_RET_STOP:
3483 rule_ret = HTTP_RULE_RES_STOP;
3484 goto end;
3485 case ACT_RET_YIELD:
3486 s->current_rule = rule;
3487 rule_ret = HTTP_RULE_RES_YIELD;
3488 goto end;
3489 }
3490 break;
3491
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003492 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003493 default:
3494 break;
3495 }
3496 }
3497
3498 end:
3499 /* we reached the end of the rules, nothing to report */
3500 return rule_ret;
3501}
3502
Christopher Faulet33640082018-10-24 11:53:01 +02003503/* Iterate the same filter through all request headers.
3504 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3505 * Since it can manage the switch to another backend, it updates the per-proxy
3506 * DENY stats.
3507 */
3508static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3509{
3510 struct http_txn *txn = s->txn;
3511 struct htx *htx;
3512 struct buffer *hdr = get_trash_chunk();
3513 int32_t pos;
3514
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003515 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003516
3517 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3518 struct htx_blk *blk = htx_get_blk(htx, pos);
3519 enum htx_blk_type type;
3520 struct ist n, v;
3521
3522 next_hdr:
3523 type = htx_get_blk_type(blk);
3524 if (type == HTX_BLK_EOH)
3525 break;
3526 if (type != HTX_BLK_HDR)
3527 continue;
3528
3529 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3530 return 1;
3531 else if (unlikely(txn->flags & TX_CLALLOW) &&
3532 (exp->action == ACT_ALLOW ||
3533 exp->action == ACT_DENY ||
3534 exp->action == ACT_TARPIT))
3535 return 0;
3536
3537 n = htx_get_blk_name(htx, blk);
3538 v = htx_get_blk_value(htx, blk);
3539
Christopher Faulet02e771a2019-02-26 15:36:05 +01003540 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003541 hdr->area[hdr->data++] = ':';
3542 hdr->area[hdr->data++] = ' ';
3543 chunk_memcat(hdr, v.ptr, v.len);
3544
3545 /* Now we have one header in <hdr> */
3546
3547 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3548 struct http_hdr_ctx ctx;
3549 int len;
3550
3551 switch (exp->action) {
3552 case ACT_ALLOW:
3553 txn->flags |= TX_CLALLOW;
3554 goto end;
3555
3556 case ACT_DENY:
3557 txn->flags |= TX_CLDENY;
3558 goto end;
3559
3560 case ACT_TARPIT:
3561 txn->flags |= TX_CLTARPIT;
3562 goto end;
3563
3564 case ACT_REPLACE:
3565 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3566 if (len < 0)
3567 return -1;
3568
3569 http_parse_header(ist2(trash.area, len), &n, &v);
3570 ctx.blk = blk;
3571 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003572 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003573 if (!http_replace_header(htx, &ctx, n, v))
3574 return -1;
3575 if (!ctx.blk)
3576 goto end;
3577 pos = htx_get_blk_pos(htx, blk);
3578 break;
3579
3580 case ACT_REMOVE:
3581 ctx.blk = blk;
3582 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003583 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003584 if (!http_remove_header(htx, &ctx))
3585 return -1;
3586 if (!ctx.blk)
3587 goto end;
3588 pos = htx_get_blk_pos(htx, blk);
3589 goto next_hdr;
3590
3591 }
3592 }
3593 }
3594 end:
3595 return 0;
3596}
3597
3598/* Apply the filter to the request line.
3599 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3600 * or -1 if a replacement resulted in an invalid request line.
3601 * Since it can manage the switch to another backend, it updates the per-proxy
3602 * DENY stats.
3603 */
3604static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3605{
3606 struct http_txn *txn = s->txn;
3607 struct htx *htx;
3608 struct buffer *reqline = get_trash_chunk();
3609 int done;
3610
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003611 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003612
3613 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3614 return 1;
3615 else if (unlikely(txn->flags & TX_CLALLOW) &&
3616 (exp->action == ACT_ALLOW ||
3617 exp->action == ACT_DENY ||
3618 exp->action == ACT_TARPIT))
3619 return 0;
3620 else if (exp->action == ACT_REMOVE)
3621 return 0;
3622
3623 done = 0;
3624
3625 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3626
3627 /* Now we have the request line between cur_ptr and cur_end */
3628 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003629 struct htx_sl *sl = http_find_stline(htx);
3630 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003631 int len;
3632
3633 switch (exp->action) {
3634 case ACT_ALLOW:
3635 txn->flags |= TX_CLALLOW;
3636 done = 1;
3637 break;
3638
3639 case ACT_DENY:
3640 txn->flags |= TX_CLDENY;
3641 done = 1;
3642 break;
3643
3644 case ACT_TARPIT:
3645 txn->flags |= TX_CLTARPIT;
3646 done = 1;
3647 break;
3648
3649 case ACT_REPLACE:
3650 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3651 if (len < 0)
3652 return -1;
3653
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003654 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3655 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3656 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003657 return -1;
3658 done = 1;
3659 break;
3660 }
3661 }
3662 return done;
3663}
3664
3665/*
3666 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3667 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3668 * unparsable request. Since it can manage the switch to another backend, it
3669 * updates the per-proxy DENY stats.
3670 */
3671static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3672{
3673 struct session *sess = s->sess;
3674 struct http_txn *txn = s->txn;
3675 struct hdr_exp *exp;
3676
3677 for (exp = px->req_exp; exp; exp = exp->next) {
3678 int ret;
3679
3680 /*
3681 * The interleaving of transformations and verdicts
3682 * makes it difficult to decide to continue or stop
3683 * the evaluation.
3684 */
3685
3686 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3687 break;
3688
3689 if ((txn->flags & TX_CLALLOW) &&
3690 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3691 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3692 continue;
3693
3694 /* if this filter had a condition, evaluate it now and skip to
3695 * next filter if the condition does not match.
3696 */
3697 if (exp->cond) {
3698 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3699 ret = acl_pass(ret);
3700 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3701 ret = !ret;
3702
3703 if (!ret)
3704 continue;
3705 }
3706
3707 /* Apply the filter to the request line. */
3708 ret = htx_apply_filter_to_req_line(s, req, exp);
3709 if (unlikely(ret < 0))
3710 return -1;
3711
3712 if (likely(ret == 0)) {
3713 /* The filter did not match the request, it can be
3714 * iterated through all headers.
3715 */
3716 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3717 return -1;
3718 }
3719 }
3720 return 0;
3721}
3722
3723/* Iterate the same filter through all response headers contained in <res>.
3724 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3725 */
3726static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3727{
3728 struct http_txn *txn = s->txn;
3729 struct htx *htx;
3730 struct buffer *hdr = get_trash_chunk();
3731 int32_t pos;
3732
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003733 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003734
3735 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3736 struct htx_blk *blk = htx_get_blk(htx, pos);
3737 enum htx_blk_type type;
3738 struct ist n, v;
3739
3740 next_hdr:
3741 type = htx_get_blk_type(blk);
3742 if (type == HTX_BLK_EOH)
3743 break;
3744 if (type != HTX_BLK_HDR)
3745 continue;
3746
3747 if (unlikely(txn->flags & TX_SVDENY))
3748 return 1;
3749 else if (unlikely(txn->flags & TX_SVALLOW) &&
3750 (exp->action == ACT_ALLOW ||
3751 exp->action == ACT_DENY))
3752 return 0;
3753
3754 n = htx_get_blk_name(htx, blk);
3755 v = htx_get_blk_value(htx, blk);
3756
Christopher Faulet02e771a2019-02-26 15:36:05 +01003757 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003758 hdr->area[hdr->data++] = ':';
3759 hdr->area[hdr->data++] = ' ';
3760 chunk_memcat(hdr, v.ptr, v.len);
3761
3762 /* Now we have one header in <hdr> */
3763
3764 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3765 struct http_hdr_ctx ctx;
3766 int len;
3767
3768 switch (exp->action) {
3769 case ACT_ALLOW:
3770 txn->flags |= TX_SVALLOW;
3771 goto end;
3772 break;
3773
3774 case ACT_DENY:
3775 txn->flags |= TX_SVDENY;
3776 goto end;
3777 break;
3778
3779 case ACT_REPLACE:
3780 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3781 if (len < 0)
3782 return -1;
3783
3784 http_parse_header(ist2(trash.area, len), &n, &v);
3785 ctx.blk = blk;
3786 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003787 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003788 if (!http_replace_header(htx, &ctx, n, v))
3789 return -1;
3790 if (!ctx.blk)
3791 goto end;
3792 pos = htx_get_blk_pos(htx, blk);
3793 break;
3794
3795 case ACT_REMOVE:
3796 ctx.blk = blk;
3797 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003798 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003799 if (!http_remove_header(htx, &ctx))
3800 return -1;
3801 if (!ctx.blk)
3802 goto end;
3803 pos = htx_get_blk_pos(htx, blk);
3804 goto next_hdr;
3805 }
3806 }
3807
3808 }
3809 end:
3810 return 0;
3811}
3812
3813/* Apply the filter to the status line in the response buffer <res>.
3814 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3815 * or -1 if a replacement resulted in an invalid status line.
3816 */
3817static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3818{
3819 struct http_txn *txn = s->txn;
3820 struct htx *htx;
3821 struct buffer *resline = get_trash_chunk();
3822 int done;
3823
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003824 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003825
3826 if (unlikely(txn->flags & TX_SVDENY))
3827 return 1;
3828 else if (unlikely(txn->flags & TX_SVALLOW) &&
3829 (exp->action == ACT_ALLOW ||
3830 exp->action == ACT_DENY))
3831 return 0;
3832 else if (exp->action == ACT_REMOVE)
3833 return 0;
3834
3835 done = 0;
3836 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3837
3838 /* Now we have the status line between cur_ptr and cur_end */
3839 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003840 struct htx_sl *sl = http_find_stline(htx);
3841 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003842 int len;
3843
3844 switch (exp->action) {
3845 case ACT_ALLOW:
3846 txn->flags |= TX_SVALLOW;
3847 done = 1;
3848 break;
3849
3850 case ACT_DENY:
3851 txn->flags |= TX_SVDENY;
3852 done = 1;
3853 break;
3854
3855 case ACT_REPLACE:
3856 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3857 if (len < 0)
3858 return -1;
3859
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003860 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3861 sl->info.res.status = strl2ui(code.ptr, code.len);
3862 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003863 return -1;
3864
3865 done = 1;
3866 return 1;
3867 }
3868 }
3869 return done;
3870}
3871
3872/*
3873 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3874 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3875 * unparsable response.
3876 */
3877static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3878{
3879 struct session *sess = s->sess;
3880 struct http_txn *txn = s->txn;
3881 struct hdr_exp *exp;
3882
3883 for (exp = px->rsp_exp; exp; exp = exp->next) {
3884 int ret;
3885
3886 /*
3887 * The interleaving of transformations and verdicts
3888 * makes it difficult to decide to continue or stop
3889 * the evaluation.
3890 */
3891
3892 if (txn->flags & TX_SVDENY)
3893 break;
3894
3895 if ((txn->flags & TX_SVALLOW) &&
3896 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3897 exp->action == ACT_PASS)) {
3898 exp = exp->next;
3899 continue;
3900 }
3901
3902 /* if this filter had a condition, evaluate it now and skip to
3903 * next filter if the condition does not match.
3904 */
3905 if (exp->cond) {
3906 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3907 ret = acl_pass(ret);
3908 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3909 ret = !ret;
3910 if (!ret)
3911 continue;
3912 }
3913
3914 /* Apply the filter to the status line. */
3915 ret = htx_apply_filter_to_sts_line(s, res, exp);
3916 if (unlikely(ret < 0))
3917 return -1;
3918
3919 if (likely(ret == 0)) {
3920 /* The filter did not match the response, it can be
3921 * iterated through all headers.
3922 */
3923 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3924 return -1;
3925 }
3926 }
3927 return 0;
3928}
3929
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003930/*
3931 * Manage client-side cookie. It can impact performance by about 2% so it is
3932 * desirable to call it only when needed. This code is quite complex because
3933 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3934 * highly recommended not to touch this part without a good reason !
3935 */
3936static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3937{
3938 struct session *sess = s->sess;
3939 struct http_txn *txn = s->txn;
3940 struct htx *htx;
3941 struct http_hdr_ctx ctx;
3942 char *hdr_beg, *hdr_end, *del_from;
3943 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3944 int preserve_hdr;
3945
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003946 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003947 ctx.blk = NULL;
3948 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3949 del_from = NULL; /* nothing to be deleted */
3950 preserve_hdr = 0; /* assume we may kill the whole header */
3951
3952 /* Now look for cookies. Conforming to RFC2109, we have to support
3953 * attributes whose name begin with a '$', and associate them with
3954 * the right cookie, if we want to delete this cookie.
3955 * So there are 3 cases for each cookie read :
3956 * 1) it's a special attribute, beginning with a '$' : ignore it.
3957 * 2) it's a server id cookie that we *MAY* want to delete : save
3958 * some pointers on it (last semi-colon, beginning of cookie...)
3959 * 3) it's an application cookie : we *MAY* have to delete a previous
3960 * "special" cookie.
3961 * At the end of loop, if a "special" cookie remains, we may have to
3962 * remove it. If no application cookie persists in the header, we
3963 * *MUST* delete it.
3964 *
3965 * Note: RFC2965 is unclear about the processing of spaces around
3966 * the equal sign in the ATTR=VALUE form. A careful inspection of
3967 * the RFC explicitly allows spaces before it, and not within the
3968 * tokens (attrs or values). An inspection of RFC2109 allows that
3969 * too but section 10.1.3 lets one think that spaces may be allowed
3970 * after the equal sign too, resulting in some (rare) buggy
3971 * implementations trying to do that. So let's do what servers do.
3972 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3973 * allowed quoted strings in values, with any possible character
3974 * after a backslash, including control chars and delimitors, which
3975 * causes parsing to become ambiguous. Browsers also allow spaces
3976 * within values even without quotes.
3977 *
3978 * We have to keep multiple pointers in order to support cookie
3979 * removal at the beginning, middle or end of header without
3980 * corrupting the header. All of these headers are valid :
3981 *
3982 * hdr_beg hdr_end
3983 * | |
3984 * v |
3985 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3986 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3987 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3988 * | | | | | | |
3989 * | | | | | | |
3990 * | | | | | | +--> next
3991 * | | | | | +----> val_end
3992 * | | | | +-----------> val_beg
3993 * | | | +--------------> equal
3994 * | | +----------------> att_end
3995 * | +---------------------> att_beg
3996 * +--------------------------> prev
3997 *
3998 */
3999 hdr_beg = ctx.value.ptr;
4000 hdr_end = hdr_beg + ctx.value.len;
4001 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4002 /* Iterate through all cookies on this line */
4003
4004 /* find att_beg */
4005 att_beg = prev;
4006 if (prev > hdr_beg)
4007 att_beg++;
4008
4009 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4010 att_beg++;
4011
4012 /* find att_end : this is the first character after the last non
4013 * space before the equal. It may be equal to hdr_end.
4014 */
4015 equal = att_end = att_beg;
4016 while (equal < hdr_end) {
4017 if (*equal == '=' || *equal == ',' || *equal == ';')
4018 break;
4019 if (HTTP_IS_SPHT(*equal++))
4020 continue;
4021 att_end = equal;
4022 }
4023
4024 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4025 * is between <att_beg> and <equal>, both may be identical.
4026 */
4027 /* look for end of cookie if there is an equal sign */
4028 if (equal < hdr_end && *equal == '=') {
4029 /* look for the beginning of the value */
4030 val_beg = equal + 1;
4031 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4032 val_beg++;
4033
4034 /* find the end of the value, respecting quotes */
4035 next = http_find_cookie_value_end(val_beg, hdr_end);
4036
4037 /* make val_end point to the first white space or delimitor after the value */
4038 val_end = next;
4039 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4040 val_end--;
4041 }
4042 else
4043 val_beg = val_end = next = equal;
4044
4045 /* We have nothing to do with attributes beginning with
4046 * '$'. However, they will automatically be removed if a
4047 * header before them is removed, since they're supposed
4048 * to be linked together.
4049 */
4050 if (*att_beg == '$')
4051 continue;
4052
4053 /* Ignore cookies with no equal sign */
4054 if (equal == next) {
4055 /* This is not our cookie, so we must preserve it. But if we already
4056 * scheduled another cookie for removal, we cannot remove the
4057 * complete header, but we can remove the previous block itself.
4058 */
4059 preserve_hdr = 1;
4060 if (del_from != NULL) {
4061 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4062 val_end += delta;
4063 next += delta;
4064 hdr_end += delta;
4065 prev = del_from;
4066 del_from = NULL;
4067 }
4068 continue;
4069 }
4070
4071 /* if there are spaces around the equal sign, we need to
4072 * strip them otherwise we'll get trouble for cookie captures,
4073 * or even for rewrites. Since this happens extremely rarely,
4074 * it does not hurt performance.
4075 */
4076 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4077 int stripped_before = 0;
4078 int stripped_after = 0;
4079
4080 if (att_end != equal) {
4081 memmove(att_end, equal, hdr_end - equal);
4082 stripped_before = (att_end - equal);
4083 equal += stripped_before;
4084 val_beg += stripped_before;
4085 }
4086
4087 if (val_beg > equal + 1) {
4088 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4089 stripped_after = (equal + 1) - val_beg;
4090 val_beg += stripped_after;
4091 stripped_before += stripped_after;
4092 }
4093
4094 val_end += stripped_before;
4095 next += stripped_before;
4096 hdr_end += stripped_before;
4097 }
4098 /* now everything is as on the diagram above */
4099
4100 /* First, let's see if we want to capture this cookie. We check
4101 * that we don't already have a client side cookie, because we
4102 * can only capture one. Also as an optimisation, we ignore
4103 * cookies shorter than the declared name.
4104 */
4105 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4106 (val_end - att_beg >= sess->fe->capture_namelen) &&
4107 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4108 int log_len = val_end - att_beg;
4109
4110 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4111 ha_alert("HTTP logging : out of memory.\n");
4112 } else {
4113 if (log_len > sess->fe->capture_len)
4114 log_len = sess->fe->capture_len;
4115 memcpy(txn->cli_cookie, att_beg, log_len);
4116 txn->cli_cookie[log_len] = 0;
4117 }
4118 }
4119
4120 /* Persistence cookies in passive, rewrite or insert mode have the
4121 * following form :
4122 *
4123 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4124 *
4125 * For cookies in prefix mode, the form is :
4126 *
4127 * Cookie: NAME=SRV~VALUE
4128 */
4129 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4130 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4131 struct server *srv = s->be->srv;
4132 char *delim;
4133
4134 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4135 * have the server ID between val_beg and delim, and the original cookie between
4136 * delim+1 and val_end. Otherwise, delim==val_end :
4137 *
4138 * hdr_beg
4139 * |
4140 * v
4141 * NAME=SRV; # in all but prefix modes
4142 * NAME=SRV~OPAQUE ; # in prefix mode
4143 * || || | |+-> next
4144 * || || | +--> val_end
4145 * || || +---------> delim
4146 * || |+------------> val_beg
4147 * || +-------------> att_end = equal
4148 * |+-----------------> att_beg
4149 * +------------------> prev
4150 *
4151 */
4152 if (s->be->ck_opts & PR_CK_PFX) {
4153 for (delim = val_beg; delim < val_end; delim++)
4154 if (*delim == COOKIE_DELIM)
4155 break;
4156 }
4157 else {
4158 char *vbar1;
4159 delim = val_end;
4160 /* Now check if the cookie contains a date field, which would
4161 * appear after a vertical bar ('|') just after the server name
4162 * and before the delimiter.
4163 */
4164 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4165 if (vbar1) {
4166 /* OK, so left of the bar is the server's cookie and
4167 * right is the last seen date. It is a base64 encoded
4168 * 30-bit value representing the UNIX date since the
4169 * epoch in 4-second quantities.
4170 */
4171 int val;
4172 delim = vbar1++;
4173 if (val_end - vbar1 >= 5) {
4174 val = b64tos30(vbar1);
4175 if (val > 0)
4176 txn->cookie_last_date = val << 2;
4177 }
4178 /* look for a second vertical bar */
4179 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4180 if (vbar1 && (val_end - vbar1 > 5)) {
4181 val = b64tos30(vbar1 + 1);
4182 if (val > 0)
4183 txn->cookie_first_date = val << 2;
4184 }
4185 }
4186 }
4187
4188 /* if the cookie has an expiration date and the proxy wants to check
4189 * it, then we do that now. We first check if the cookie is too old,
4190 * then only if it has expired. We detect strict overflow because the
4191 * time resolution here is not great (4 seconds). Cookies with dates
4192 * in the future are ignored if their offset is beyond one day. This
4193 * allows an admin to fix timezone issues without expiring everyone
4194 * and at the same time avoids keeping unwanted side effects for too
4195 * long.
4196 */
4197 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4198 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4199 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4200 txn->flags &= ~TX_CK_MASK;
4201 txn->flags |= TX_CK_OLD;
4202 delim = val_beg; // let's pretend we have not found the cookie
4203 txn->cookie_first_date = 0;
4204 txn->cookie_last_date = 0;
4205 }
4206 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4207 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4208 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4209 txn->flags &= ~TX_CK_MASK;
4210 txn->flags |= TX_CK_EXPIRED;
4211 delim = val_beg; // let's pretend we have not found the cookie
4212 txn->cookie_first_date = 0;
4213 txn->cookie_last_date = 0;
4214 }
4215
4216 /* Here, we'll look for the first running server which supports the cookie.
4217 * This allows to share a same cookie between several servers, for example
4218 * to dedicate backup servers to specific servers only.
4219 * However, to prevent clients from sticking to cookie-less backup server
4220 * when they have incidentely learned an empty cookie, we simply ignore
4221 * empty cookies and mark them as invalid.
4222 * The same behaviour is applied when persistence must be ignored.
4223 */
4224 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4225 srv = NULL;
4226
4227 while (srv) {
4228 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4229 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4230 if ((srv->cur_state != SRV_ST_STOPPED) ||
4231 (s->be->options & PR_O_PERSIST) ||
4232 (s->flags & SF_FORCE_PRST)) {
4233 /* we found the server and we can use it */
4234 txn->flags &= ~TX_CK_MASK;
4235 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4236 s->flags |= SF_DIRECT | SF_ASSIGNED;
4237 s->target = &srv->obj_type;
4238 break;
4239 } else {
4240 /* we found a server, but it's down,
4241 * mark it as such and go on in case
4242 * another one is available.
4243 */
4244 txn->flags &= ~TX_CK_MASK;
4245 txn->flags |= TX_CK_DOWN;
4246 }
4247 }
4248 srv = srv->next;
4249 }
4250
4251 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4252 /* no server matched this cookie or we deliberately skipped it */
4253 txn->flags &= ~TX_CK_MASK;
4254 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4255 txn->flags |= TX_CK_UNUSED;
4256 else
4257 txn->flags |= TX_CK_INVALID;
4258 }
4259
4260 /* depending on the cookie mode, we may have to either :
4261 * - delete the complete cookie if we're in insert+indirect mode, so that
4262 * the server never sees it ;
4263 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004264 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004265 * if we're in cookie prefix mode
4266 */
4267 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4268 int delta; /* negative */
4269
4270 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4271 delta = val_beg - (delim + 1);
4272 val_end += delta;
4273 next += delta;
4274 hdr_end += delta;
4275 del_from = NULL;
4276 preserve_hdr = 1; /* we want to keep this cookie */
4277 }
4278 else if (del_from == NULL &&
4279 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4280 del_from = prev;
4281 }
4282 }
4283 else {
4284 /* This is not our cookie, so we must preserve it. But if we already
4285 * scheduled another cookie for removal, we cannot remove the
4286 * complete header, but we can remove the previous block itself.
4287 */
4288 preserve_hdr = 1;
4289
4290 if (del_from != NULL) {
4291 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4292 if (att_beg >= del_from)
4293 att_beg += delta;
4294 if (att_end >= del_from)
4295 att_end += delta;
4296 val_beg += delta;
4297 val_end += delta;
4298 next += delta;
4299 hdr_end += delta;
4300 prev = del_from;
4301 del_from = NULL;
4302 }
4303 }
4304
4305 /* continue with next cookie on this header line */
4306 att_beg = next;
4307 } /* for each cookie */
4308
4309
4310 /* There are no more cookies on this line.
4311 * We may still have one (or several) marked for deletion at the
4312 * end of the line. We must do this now in two ways :
4313 * - if some cookies must be preserved, we only delete from the
4314 * mark to the end of line ;
4315 * - if nothing needs to be preserved, simply delete the whole header
4316 */
4317 if (del_from) {
4318 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4319 }
4320 if ((hdr_end - hdr_beg) != ctx.value.len) {
4321 if (hdr_beg != hdr_end) {
4322 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004323 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004324 }
4325 else
4326 http_remove_header(htx, &ctx);
4327 }
4328 } /* for each "Cookie header */
4329}
4330
4331/*
4332 * Manage server-side cookies. It can impact performance by about 2% so it is
4333 * desirable to call it only when needed. This function is also used when we
4334 * just need to know if there is a cookie (eg: for check-cache).
4335 */
4336static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4337{
4338 struct session *sess = s->sess;
4339 struct http_txn *txn = s->txn;
4340 struct htx *htx;
4341 struct http_hdr_ctx ctx;
4342 struct server *srv;
4343 char *hdr_beg, *hdr_end;
4344 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004345 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004346
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004347 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004348
4349 ctx.blk = NULL;
4350 while (1) {
4351 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4352 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4353 break;
4354 is_cookie2 = 1;
4355 }
4356
4357 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4358 * <prev> points to the colon.
4359 */
4360 txn->flags |= TX_SCK_PRESENT;
4361
4362 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4363 * check-cache is enabled) and we are not interested in checking
4364 * them. Warning, the cookie capture is declared in the frontend.
4365 */
4366 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4367 break;
4368
4369 /* OK so now we know we have to process this response cookie.
4370 * The format of the Set-Cookie header is slightly different
4371 * from the format of the Cookie header in that it does not
4372 * support the comma as a cookie delimiter (thus the header
4373 * cannot be folded) because the Expires attribute described in
4374 * the original Netscape's spec may contain an unquoted date
4375 * with a comma inside. We have to live with this because
4376 * many browsers don't support Max-Age and some browsers don't
4377 * support quoted strings. However the Set-Cookie2 header is
4378 * clean.
4379 *
4380 * We have to keep multiple pointers in order to support cookie
4381 * removal at the beginning, middle or end of header without
4382 * corrupting the header (in case of set-cookie2). A special
4383 * pointer, <scav> points to the beginning of the set-cookie-av
4384 * fields after the first semi-colon. The <next> pointer points
4385 * either to the end of line (set-cookie) or next unquoted comma
4386 * (set-cookie2). All of these headers are valid :
4387 *
4388 * hdr_beg hdr_end
4389 * | |
4390 * v |
4391 * NAME1 = VALUE 1 ; Secure; Path="/" |
4392 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4393 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4394 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4395 * | | | | | | | |
4396 * | | | | | | | +-> next
4397 * | | | | | | +------------> scav
4398 * | | | | | +--------------> val_end
4399 * | | | | +--------------------> val_beg
4400 * | | | +----------------------> equal
4401 * | | +------------------------> att_end
4402 * | +----------------------------> att_beg
4403 * +------------------------------> prev
4404 * -------------------------------> hdr_beg
4405 */
4406 hdr_beg = ctx.value.ptr;
4407 hdr_end = hdr_beg + ctx.value.len;
4408 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4409
4410 /* Iterate through all cookies on this line */
4411
4412 /* find att_beg */
4413 att_beg = prev;
4414 if (prev > hdr_beg)
4415 att_beg++;
4416
4417 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4418 att_beg++;
4419
4420 /* find att_end : this is the first character after the last non
4421 * space before the equal. It may be equal to hdr_end.
4422 */
4423 equal = att_end = att_beg;
4424
4425 while (equal < hdr_end) {
4426 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4427 break;
4428 if (HTTP_IS_SPHT(*equal++))
4429 continue;
4430 att_end = equal;
4431 }
4432
4433 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4434 * is between <att_beg> and <equal>, both may be identical.
4435 */
4436
4437 /* look for end of cookie if there is an equal sign */
4438 if (equal < hdr_end && *equal == '=') {
4439 /* look for the beginning of the value */
4440 val_beg = equal + 1;
4441 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4442 val_beg++;
4443
4444 /* find the end of the value, respecting quotes */
4445 next = http_find_cookie_value_end(val_beg, hdr_end);
4446
4447 /* make val_end point to the first white space or delimitor after the value */
4448 val_end = next;
4449 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4450 val_end--;
4451 }
4452 else {
4453 /* <equal> points to next comma, semi-colon or EOL */
4454 val_beg = val_end = next = equal;
4455 }
4456
4457 if (next < hdr_end) {
4458 /* Set-Cookie2 supports multiple cookies, and <next> points to
4459 * a colon or semi-colon before the end. So skip all attr-value
4460 * pairs and look for the next comma. For Set-Cookie, since
4461 * commas are permitted in values, skip to the end.
4462 */
4463 if (is_cookie2)
4464 next = http_find_hdr_value_end(next, hdr_end);
4465 else
4466 next = hdr_end;
4467 }
4468
4469 /* Now everything is as on the diagram above */
4470
4471 /* Ignore cookies with no equal sign */
4472 if (equal == val_end)
4473 continue;
4474
4475 /* If there are spaces around the equal sign, we need to
4476 * strip them otherwise we'll get trouble for cookie captures,
4477 * or even for rewrites. Since this happens extremely rarely,
4478 * it does not hurt performance.
4479 */
4480 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4481 int stripped_before = 0;
4482 int stripped_after = 0;
4483
4484 if (att_end != equal) {
4485 memmove(att_end, equal, hdr_end - equal);
4486 stripped_before = (att_end - equal);
4487 equal += stripped_before;
4488 val_beg += stripped_before;
4489 }
4490
4491 if (val_beg > equal + 1) {
4492 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4493 stripped_after = (equal + 1) - val_beg;
4494 val_beg += stripped_after;
4495 stripped_before += stripped_after;
4496 }
4497
4498 val_end += stripped_before;
4499 next += stripped_before;
4500 hdr_end += stripped_before;
4501
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004502 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4503 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004504 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004505 }
4506
4507 /* First, let's see if we want to capture this cookie. We check
4508 * that we don't already have a server side cookie, because we
4509 * can only capture one. Also as an optimisation, we ignore
4510 * cookies shorter than the declared name.
4511 */
4512 if (sess->fe->capture_name != NULL &&
4513 txn->srv_cookie == NULL &&
4514 (val_end - att_beg >= sess->fe->capture_namelen) &&
4515 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4516 int log_len = val_end - att_beg;
4517 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4518 ha_alert("HTTP logging : out of memory.\n");
4519 }
4520 else {
4521 if (log_len > sess->fe->capture_len)
4522 log_len = sess->fe->capture_len;
4523 memcpy(txn->srv_cookie, att_beg, log_len);
4524 txn->srv_cookie[log_len] = 0;
4525 }
4526 }
4527
4528 srv = objt_server(s->target);
4529 /* now check if we need to process it for persistence */
4530 if (!(s->flags & SF_IGNORE_PRST) &&
4531 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4532 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4533 /* assume passive cookie by default */
4534 txn->flags &= ~TX_SCK_MASK;
4535 txn->flags |= TX_SCK_FOUND;
4536
4537 /* If the cookie is in insert mode on a known server, we'll delete
4538 * this occurrence because we'll insert another one later.
4539 * We'll delete it too if the "indirect" option is set and we're in
4540 * a direct access.
4541 */
4542 if (s->be->ck_opts & PR_CK_PSV) {
4543 /* The "preserve" flag was set, we don't want to touch the
4544 * server's cookie.
4545 */
4546 }
4547 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4548 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4549 /* this cookie must be deleted */
4550 if (prev == hdr_beg && next == hdr_end) {
4551 /* whole header */
4552 http_remove_header(htx, &ctx);
4553 /* note: while both invalid now, <next> and <hdr_end>
4554 * are still equal, so the for() will stop as expected.
4555 */
4556 } else {
4557 /* just remove the value */
4558 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4559 next = prev;
4560 hdr_end += delta;
4561 }
4562 txn->flags &= ~TX_SCK_MASK;
4563 txn->flags |= TX_SCK_DELETED;
4564 /* and go on with next cookie */
4565 }
4566 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4567 /* replace bytes val_beg->val_end with the cookie name associated
4568 * with this server since we know it.
4569 */
4570 int sliding, delta;
4571
4572 ctx.value = ist2(val_beg, val_end - val_beg);
4573 ctx.lws_before = ctx.lws_after = 0;
4574 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4575 delta = srv->cklen - (val_end - val_beg);
4576 sliding = (ctx.value.ptr - val_beg);
4577 hdr_beg += sliding;
4578 val_beg += sliding;
4579 next += sliding + delta;
4580 hdr_end += sliding + delta;
4581
4582 txn->flags &= ~TX_SCK_MASK;
4583 txn->flags |= TX_SCK_REPLACED;
4584 }
4585 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4586 /* insert the cookie name associated with this server
4587 * before existing cookie, and insert a delimiter between them..
4588 */
4589 int sliding, delta;
4590 ctx.value = ist2(val_beg, 0);
4591 ctx.lws_before = ctx.lws_after = 0;
4592 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4593 delta = srv->cklen + 1;
4594 sliding = (ctx.value.ptr - val_beg);
4595 hdr_beg += sliding;
4596 val_beg += sliding;
4597 next += sliding + delta;
4598 hdr_end += sliding + delta;
4599
4600 val_beg[srv->cklen] = COOKIE_DELIM;
4601 txn->flags &= ~TX_SCK_MASK;
4602 txn->flags |= TX_SCK_REPLACED;
4603 }
4604 }
4605 /* that's done for this cookie, check the next one on the same
4606 * line when next != hdr_end (only if is_cookie2).
4607 */
4608 }
4609 }
4610}
4611
Christopher Faulet25a02f62018-10-24 12:00:25 +02004612/*
4613 * Parses the Cache-Control and Pragma request header fields to determine if
4614 * the request may be served from the cache and/or if it is cacheable. Updates
4615 * s->txn->flags.
4616 */
4617void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4618{
4619 struct http_txn *txn = s->txn;
4620 struct htx *htx;
4621 int32_t pos;
4622 int pragma_found, cc_found, i;
4623
4624 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4625 return; /* nothing more to do here */
4626
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004627 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004628 pragma_found = cc_found = 0;
4629 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4630 struct htx_blk *blk = htx_get_blk(htx, pos);
4631 enum htx_blk_type type = htx_get_blk_type(blk);
4632 struct ist n, v;
4633
4634 if (type == HTX_BLK_EOH)
4635 break;
4636 if (type != HTX_BLK_HDR)
4637 continue;
4638
4639 n = htx_get_blk_name(htx, blk);
4640 v = htx_get_blk_value(htx, blk);
4641
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004642 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004643 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4644 pragma_found = 1;
4645 continue;
4646 }
4647 }
4648
4649 /* Don't use the cache and don't try to store if we found the
4650 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004651 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004652 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4653 txn->flags |= TX_CACHE_IGNORE;
4654 continue;
4655 }
4656
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004657 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004658 continue;
4659
4660 /* OK, right now we know we have a cache-control header */
4661 cc_found = 1;
4662 if (!v.len) /* no info */
4663 continue;
4664
4665 i = 0;
4666 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4667 !isspace((unsigned char)*(v.ptr+i)))
4668 i++;
4669
4670 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4671 * values after max-age, max-stale nor min-fresh, we simply don't
4672 * use the cache when they're specified.
4673 */
4674 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4675 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4676 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4677 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4678 txn->flags |= TX_CACHE_IGNORE;
4679 continue;
4680 }
4681
4682 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4683 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4684 continue;
4685 }
4686 }
4687
4688 /* RFC7234#5.4:
4689 * When the Cache-Control header field is also present and
4690 * understood in a request, Pragma is ignored.
4691 * When the Cache-Control header field is not present in a
4692 * request, caches MUST consider the no-cache request
4693 * pragma-directive as having the same effect as if
4694 * "Cache-Control: no-cache" were present.
4695 */
4696 if (!cc_found && pragma_found)
4697 txn->flags |= TX_CACHE_IGNORE;
4698}
4699
4700/*
4701 * Check if response is cacheable or not. Updates s->txn->flags.
4702 */
4703void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4704{
4705 struct http_txn *txn = s->txn;
4706 struct htx *htx;
4707 int32_t pos;
4708 int i;
4709
4710 if (txn->status < 200) {
4711 /* do not try to cache interim responses! */
4712 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4713 return;
4714 }
4715
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004716 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004717 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4718 struct htx_blk *blk = htx_get_blk(htx, pos);
4719 enum htx_blk_type type = htx_get_blk_type(blk);
4720 struct ist n, v;
4721
4722 if (type == HTX_BLK_EOH)
4723 break;
4724 if (type != HTX_BLK_HDR)
4725 continue;
4726
4727 n = htx_get_blk_name(htx, blk);
4728 v = htx_get_blk_value(htx, blk);
4729
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004730 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004731 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4732 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4733 return;
4734 }
4735 }
4736
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004737 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004738 continue;
4739
4740 /* OK, right now we know we have a cache-control header */
4741 if (!v.len) /* no info */
4742 continue;
4743
4744 i = 0;
4745 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4746 !isspace((unsigned char)*(v.ptr+i)))
4747 i++;
4748
4749 /* we have a complete value between v.ptr and (v.ptr+i) */
4750 if (i < v.len && *(v.ptr + i) == '=') {
4751 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4752 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4753 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4754 continue;
4755 }
4756
4757 /* we have something of the form no-cache="set-cookie" */
4758 if ((v.len >= 21) &&
4759 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4760 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4761 txn->flags &= ~TX_CACHE_COOK;
4762 continue;
4763 }
4764
4765 /* OK, so we know that either p2 points to the end of string or to a comma */
4766 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4767 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4768 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4769 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4770 return;
4771 }
4772
4773 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4774 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4775 continue;
4776 }
4777 }
4778}
4779
Christopher Faulet64159df2018-10-24 21:15:35 +02004780/* send a server's name with an outgoing request over an established connection.
4781 * Note: this function is designed to be called once the request has been
4782 * scheduled for being forwarded. This is the reason why the number of forwarded
4783 * bytes have to be adjusted.
4784 */
4785int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4786{
4787 struct htx *htx;
4788 struct http_hdr_ctx ctx;
4789 struct ist hdr;
4790 uint32_t data;
4791
4792 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004793 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004794 data = htx->data;
4795
4796 ctx.blk = NULL;
4797 while (http_find_header(htx, hdr, &ctx, 1))
4798 http_remove_header(htx, &ctx);
4799 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4800
4801 if (co_data(&s->req)) {
4802 if (data >= htx->data)
4803 c_rew(&s->req, data - htx->data);
4804 else
4805 c_adv(&s->req, htx->data - data);
4806 }
4807 return 0;
4808}
4809
Christopher Faulet377c5a52018-10-24 21:21:30 +02004810/*
4811 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4812 * for the current backend.
4813 *
4814 * It is assumed that the request is either a HEAD, GET, or POST and that the
4815 * uri_auth field is valid.
4816 *
4817 * Returns 1 if stats should be provided, otherwise 0.
4818 */
4819static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4820{
4821 struct uri_auth *uri_auth = backend->uri_auth;
4822 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004823 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004824 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004825
4826 if (!uri_auth)
4827 return 0;
4828
4829 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4830 return 0;
4831
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004832 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004833 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004834 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004835
4836 /* check URI size */
4837 if (uri_auth->uri_len > uri.len)
4838 return 0;
4839
4840 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4841 return 0;
4842
4843 return 1;
4844}
4845
4846/* This function prepares an applet to handle the stats. It can deal with the
4847 * "100-continue" expectation, check that admin rules are met for POST requests,
4848 * and program a response message if something was unexpected. It cannot fail
4849 * and always relies on the stats applet to complete the job. It does not touch
4850 * analysers nor counters, which are left to the caller. It does not touch
4851 * s->target which is supposed to already point to the stats applet. The caller
4852 * is expected to have already assigned an appctx to the stream.
4853 */
4854static int htx_handle_stats(struct stream *s, struct channel *req)
4855{
4856 struct stats_admin_rule *stats_admin_rule;
4857 struct stream_interface *si = &s->si[1];
4858 struct session *sess = s->sess;
4859 struct http_txn *txn = s->txn;
4860 struct http_msg *msg = &txn->req;
4861 struct uri_auth *uri_auth = s->be->uri_auth;
4862 const char *h, *lookup, *end;
4863 struct appctx *appctx;
4864 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004865 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004866
4867 appctx = si_appctx(si);
4868 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4869 appctx->st1 = appctx->st2 = 0;
4870 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4871 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4872 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4873 appctx->ctx.stats.flags |= STAT_CHUNKED;
4874
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004875 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004876 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004877 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4878 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004879
4880 for (h = lookup; h <= end - 3; h++) {
4881 if (memcmp(h, ";up", 3) == 0) {
4882 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4883 break;
4884 }
4885 }
4886
4887 if (uri_auth->refresh) {
4888 for (h = lookup; h <= end - 10; h++) {
4889 if (memcmp(h, ";norefresh", 10) == 0) {
4890 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4891 break;
4892 }
4893 }
4894 }
4895
4896 for (h = lookup; h <= end - 4; h++) {
4897 if (memcmp(h, ";csv", 4) == 0) {
4898 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4899 break;
4900 }
4901 }
4902
4903 for (h = lookup; h <= end - 6; h++) {
4904 if (memcmp(h, ";typed", 6) == 0) {
4905 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4906 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4907 break;
4908 }
4909 }
4910
4911 for (h = lookup; h <= end - 8; h++) {
4912 if (memcmp(h, ";st=", 4) == 0) {
4913 int i;
4914 h += 4;
4915 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4916 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4917 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4918 appctx->ctx.stats.st_code = i;
4919 break;
4920 }
4921 }
4922 break;
4923 }
4924 }
4925
4926 appctx->ctx.stats.scope_str = 0;
4927 appctx->ctx.stats.scope_len = 0;
4928 for (h = lookup; h <= end - 8; h++) {
4929 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4930 int itx = 0;
4931 const char *h2;
4932 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4933 const char *err;
4934
4935 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4936 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004937 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4938 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004939 if (*h == ';' || *h == '&' || *h == ' ')
4940 break;
4941 itx++;
4942 h++;
4943 }
4944
4945 if (itx > STAT_SCOPE_TXT_MAXLEN)
4946 itx = STAT_SCOPE_TXT_MAXLEN;
4947 appctx->ctx.stats.scope_len = itx;
4948
4949 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4950 memcpy(scope_txt, h2, itx);
4951 scope_txt[itx] = '\0';
4952 err = invalid_char(scope_txt);
4953 if (err) {
4954 /* bad char in search text => clear scope */
4955 appctx->ctx.stats.scope_str = 0;
4956 appctx->ctx.stats.scope_len = 0;
4957 }
4958 break;
4959 }
4960 }
4961
4962 /* now check whether we have some admin rules for this request */
4963 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4964 int ret = 1;
4965
4966 if (stats_admin_rule->cond) {
4967 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4968 ret = acl_pass(ret);
4969 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4970 ret = !ret;
4971 }
4972
4973 if (ret) {
4974 /* no rule, or the rule matches */
4975 appctx->ctx.stats.flags |= STAT_ADMIN;
4976 break;
4977 }
4978 }
4979
Christopher Faulet5d45e382019-02-27 15:15:23 +01004980 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4981 appctx->st0 = STAT_HTTP_HEAD;
4982 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004983 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004984 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004985 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004986 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004987 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4988 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4989 appctx->st0 = STAT_HTTP_LAST;
4990 }
4991 }
4992 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004993 /* Unsupported method */
4994 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4995 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4996 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004997 }
4998
4999 s->task->nice = -32; /* small boost for HTTP statistics */
5000 return 1;
5001}
5002
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005003void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5004{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005005 struct channel *req = &s->req;
5006 struct channel *res = &s->res;
5007 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005008 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005009 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005010 struct ist path, location;
5011 unsigned int flags;
5012 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005013
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005014 /*
5015 * Create the location
5016 */
5017 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005019 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005020 /* special prefix "/" means don't change URL */
5021 srv = __objt_server(s->target);
5022 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5023 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5024 return;
5025 }
5026
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005027 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005028 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005029 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005030 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005031 if (!path.ptr)
5032 return;
5033
5034 if (!chunk_memcat(&trash, path.ptr, path.len))
5035 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005036 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005037
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005038 /*
5039 * Create the 302 respone
5040 */
5041 htx = htx_from_buf(&res->buf);
5042 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5043 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5044 ist("HTTP/1.1"), ist("302"), ist("Found"));
5045 if (!sl)
5046 goto fail;
5047 sl->info.res.status = 302;
5048 s->txn->status = 302;
5049
5050 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5051 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5052 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5053 !htx_add_header(htx, ist("Location"), location))
5054 goto fail;
5055
5056 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5057 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005058
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005059 /*
5060 * Send the message
5061 */
5062 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 c_adv(res, data);
5064 res->total += data;
5065
5066 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005067 si_shutr(si);
5068 si_shutw(si);
5069 si->err_type = SI_ET_NONE;
5070 si->state = SI_ST_CLO;
5071
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005072 channel_auto_read(req);
5073 channel_abort(req);
5074 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005075 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005076 channel_auto_read(res);
5077 channel_auto_close(res);
5078
5079 if (!(s->flags & SF_ERR_MASK))
5080 s->flags |= SF_ERR_LOCAL;
5081 if (!(s->flags & SF_FINST_MASK))
5082 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005083
5084 /* FIXME: we should increase a counter of redirects per server and per backend. */
5085 srv_inc_sess_ctr(srv);
5086 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005087 return;
5088
5089 fail:
5090 /* If an error occurred, remove the incomplete HTTP response from the
5091 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005092 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005093}
5094
Christopher Fauletf2824e62018-10-01 12:12:37 +02005095/* This function terminates the request because it was completly analyzed or
5096 * because an error was triggered during the body forwarding.
5097 */
5098static void htx_end_request(struct stream *s)
5099{
5100 struct channel *chn = &s->req;
5101 struct http_txn *txn = s->txn;
5102
5103 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5104 now_ms, __FUNCTION__, s,
5105 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5106 s->req.analysers, s->res.analysers);
5107
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005108 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5109 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005110 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005111 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005112 goto end;
5113 }
5114
5115 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5116 return;
5117
5118 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005119 /* No need to read anymore, the request was completely parsed.
5120 * We can shut the read side unless we want to abort_on_close,
5121 * or we have a POST request. The issue with POST requests is
5122 * that some browsers still send a CRLF after the request, and
5123 * this CRLF must be read so that it does not remain in the kernel
5124 * buffers, otherwise a close could cause an RST on some systems
5125 * (eg: Linux).
5126 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005127 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005128 channel_dont_read(chn);
5129
5130 /* if the server closes the connection, we want to immediately react
5131 * and close the socket to save packets and syscalls.
5132 */
5133 s->si[1].flags |= SI_FL_NOHALF;
5134
5135 /* In any case we've finished parsing the request so we must
5136 * disable Nagle when sending data because 1) we're not going
5137 * to shut this side, and 2) the server is waiting for us to
5138 * send pending data.
5139 */
5140 chn->flags |= CF_NEVER_WAIT;
5141
Christopher Fauletd01ce402019-01-02 17:44:13 +01005142 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5143 /* The server has not finished to respond, so we
5144 * don't want to move in order not to upset it.
5145 */
5146 return;
5147 }
5148
Christopher Fauletf2824e62018-10-01 12:12:37 +02005149 /* When we get here, it means that both the request and the
5150 * response have finished receiving. Depending on the connection
5151 * mode, we'll have to wait for the last bytes to leave in either
5152 * direction, and sometimes for a close to be effective.
5153 */
5154 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5155 /* Tunnel mode will not have any analyser so it needs to
5156 * poll for reads.
5157 */
5158 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005159 if (b_data(&chn->buf))
5160 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005161 txn->req.msg_state = HTTP_MSG_TUNNEL;
5162 }
5163 else {
5164 /* we're not expecting any new data to come for this
5165 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005166 *
5167 * However, there is an exception if the response
5168 * length is undefined. In this case, we need to wait
5169 * the close from the server. The response will be
5170 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005171 */
5172 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5173 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005174 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005175
5176 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5177 channel_shutr_now(chn);
5178 channel_shutw_now(chn);
5179 }
5180 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005181 goto check_channel_flags;
5182 }
5183
5184 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5185 http_msg_closing:
5186 /* nothing else to forward, just waiting for the output buffer
5187 * to be empty and for the shutw_now to take effect.
5188 */
5189 if (channel_is_empty(chn)) {
5190 txn->req.msg_state = HTTP_MSG_CLOSED;
5191 goto http_msg_closed;
5192 }
5193 else if (chn->flags & CF_SHUTW) {
5194 txn->req.err_state = txn->req.msg_state;
5195 txn->req.msg_state = HTTP_MSG_ERROR;
5196 goto end;
5197 }
5198 return;
5199 }
5200
5201 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5202 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005203 /* if we don't know whether the server will close, we need to hard close */
5204 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5205 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005206 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005207 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005208 channel_dont_read(chn);
5209 goto end;
5210 }
5211
5212 check_channel_flags:
5213 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5214 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5215 /* if we've just closed an output, let's switch */
5216 txn->req.msg_state = HTTP_MSG_CLOSING;
5217 goto http_msg_closing;
5218 }
5219
5220 end:
5221 chn->analysers &= AN_REQ_FLT_END;
5222 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5223 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5224 channel_auto_close(chn);
5225 channel_auto_read(chn);
5226}
5227
5228
5229/* This function terminates the response because it was completly analyzed or
5230 * because an error was triggered during the body forwarding.
5231 */
5232static void htx_end_response(struct stream *s)
5233{
5234 struct channel *chn = &s->res;
5235 struct http_txn *txn = s->txn;
5236
5237 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5238 now_ms, __FUNCTION__, s,
5239 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5240 s->req.analysers, s->res.analysers);
5241
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005242 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5243 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005244 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005245 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005246 goto end;
5247 }
5248
5249 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5250 return;
5251
5252 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5253 /* In theory, we don't need to read anymore, but we must
5254 * still monitor the server connection for a possible close
5255 * while the request is being uploaded, so we don't disable
5256 * reading.
5257 */
5258 /* channel_dont_read(chn); */
5259
5260 if (txn->req.msg_state < HTTP_MSG_DONE) {
5261 /* The client seems to still be sending data, probably
5262 * because we got an error response during an upload.
5263 * We have the choice of either breaking the connection
5264 * or letting it pass through. Let's do the later.
5265 */
5266 return;
5267 }
5268
5269 /* When we get here, it means that both the request and the
5270 * response have finished receiving. Depending on the connection
5271 * mode, we'll have to wait for the last bytes to leave in either
5272 * direction, and sometimes for a close to be effective.
5273 */
5274 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5275 channel_auto_read(chn);
5276 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005277 if (b_data(&chn->buf))
5278 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005279 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5280 }
5281 else {
5282 /* we're not expecting any new data to come for this
5283 * transaction, so we can close it.
5284 */
5285 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5286 channel_shutr_now(chn);
5287 channel_shutw_now(chn);
5288 }
5289 }
5290 goto check_channel_flags;
5291 }
5292
5293 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5294 http_msg_closing:
5295 /* nothing else to forward, just waiting for the output buffer
5296 * to be empty and for the shutw_now to take effect.
5297 */
5298 if (channel_is_empty(chn)) {
5299 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5300 goto http_msg_closed;
5301 }
5302 else if (chn->flags & CF_SHUTW) {
5303 txn->rsp.err_state = txn->rsp.msg_state;
5304 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005305 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005306 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005307 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005308 goto end;
5309 }
5310 return;
5311 }
5312
5313 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5314 http_msg_closed:
5315 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005316 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005317 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005318 goto end;
5319 }
5320
5321 check_channel_flags:
5322 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5323 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5324 /* if we've just closed an output, let's switch */
5325 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5326 goto http_msg_closing;
5327 }
5328
5329 end:
5330 chn->analysers &= AN_RES_FLT_END;
5331 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5332 chn->analysers |= AN_RES_FLT_XFER_DATA;
5333 channel_auto_close(chn);
5334 channel_auto_read(chn);
5335}
5336
Christopher Faulet0f226952018-10-22 09:29:56 +02005337void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5338 int finst, const struct buffer *msg)
5339{
5340 channel_auto_read(si_oc(si));
5341 channel_abort(si_oc(si));
5342 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005343 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005344 channel_auto_close(si_ic(si));
5345 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005346
5347 /* <msg> is an HTX structure. So we copy it in the response's
5348 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005349 if (msg) {
5350 struct channel *chn = si_ic(si);
5351 struct htx *htx;
5352
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005353 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005354 chn->buf.data = msg->data;
5355 memcpy(chn->buf.area, msg->area, msg->data);
5356 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005357 c_adv(chn, htx->data);
5358 chn->total += htx->data;
5359 }
5360 if (!(s->flags & SF_ERR_MASK))
5361 s->flags |= err;
5362 if (!(s->flags & SF_FINST_MASK))
5363 s->flags |= finst;
5364}
5365
5366void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5367{
5368 channel_auto_read(&s->req);
5369 channel_abort(&s->req);
5370 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005371 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5372 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005373
5374 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005375
5376 /* <msg> is an HTX structure. So we copy it in the response's
5377 * channel */
5378 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005379 if (msg) {
5380 struct channel *chn = &s->res;
5381 struct htx *htx;
5382
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005383 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005384 chn->buf.data = msg->data;
5385 memcpy(chn->buf.area, msg->area, msg->data);
5386 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005387 c_adv(chn, htx->data);
5388 chn->total += htx->data;
5389 }
5390
5391 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5392 channel_auto_read(&s->res);
5393 channel_auto_close(&s->res);
5394 channel_shutr_now(&s->res);
5395}
5396
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005397struct buffer *htx_error_message(struct stream *s)
5398{
5399 const int msgnum = http_get_status_idx(s->txn->status);
5400
5401 if (s->be->errmsg[msgnum].area)
5402 return &s->be->errmsg[msgnum];
5403 else if (strm_fe(s)->errmsg[msgnum].area)
5404 return &strm_fe(s)->errmsg[msgnum];
5405 else
5406 return &htx_err_chunks[msgnum];
5407}
5408
5409
Christopher Faulet4a28a532019-03-01 11:19:40 +01005410/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5411 * on success and -1 on error.
5412 */
5413static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5414{
5415 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5416 * then we must send an HTTP/1.1 100 Continue intermediate response.
5417 */
5418 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5419 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5420 struct ist hdr = { .ptr = "Expect", .len = 6 };
5421 struct http_hdr_ctx ctx;
5422
5423 ctx.blk = NULL;
5424 /* Expect is allowed in 1.1, look for it */
5425 if (http_find_header(htx, hdr, &ctx, 0) &&
5426 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5427 if (htx_reply_100_continue(s) == -1)
5428 return -1;
5429 http_remove_header(htx, &ctx);
5430 }
5431 }
5432 return 0;
5433}
5434
Christopher Faulet23a3c792018-11-28 10:01:23 +01005435/* Send a 100-Continue response to the client. It returns 0 on success and -1
5436 * on error. The response channel is updated accordingly.
5437 */
5438static int htx_reply_100_continue(struct stream *s)
5439{
5440 struct channel *res = &s->res;
5441 struct htx *htx = htx_from_buf(&res->buf);
5442 struct htx_sl *sl;
5443 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5444 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5445 size_t data;
5446
5447 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5448 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5449 if (!sl)
5450 goto fail;
5451 sl->info.res.status = 100;
5452
5453 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5454 goto fail;
5455
5456 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005457 c_adv(res, data);
5458 res->total += data;
5459 return 0;
5460
5461 fail:
5462 /* If an error occurred, remove the incomplete HTTP response from the
5463 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005464 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005465 return -1;
5466}
5467
Christopher Faulet12c51e22018-11-28 15:59:42 +01005468
5469/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5470 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5471 * error. The response channel is updated accordingly.
5472 */
5473static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5474{
5475 struct channel *res = &s->res;
5476 struct htx *htx = htx_from_buf(&res->buf);
5477 struct htx_sl *sl;
5478 struct ist code, body;
5479 int status;
5480 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5481 size_t data;
5482
5483 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5484 status = 401;
5485 code = ist("401");
5486 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5487 "You need a valid user and password to access this content.\n"
5488 "</body></html>\n");
5489 }
5490 else {
5491 status = 407;
5492 code = ist("407");
5493 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5494 "You need a valid user and password to access this content.\n"
5495 "</body></html>\n");
5496 }
5497
5498 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5499 ist("HTTP/1.1"), code, ist("Unauthorized"));
5500 if (!sl)
5501 goto fail;
5502 sl->info.res.status = status;
5503 s->txn->status = status;
5504
5505 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5506 goto fail;
5507
5508 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5509 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005510 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5511 goto fail;
5512 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5513 goto fail;
5514 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005515 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005516 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5517 goto fail;
5518
5519 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005520 c_adv(res, data);
5521 res->total += data;
5522
5523 channel_auto_read(&s->req);
5524 channel_abort(&s->req);
5525 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005526 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005527
5528 res->wex = tick_add_ifset(now_ms, res->wto);
5529 channel_auto_read(res);
5530 channel_auto_close(res);
5531 channel_shutr_now(res);
5532 return 0;
5533
5534 fail:
5535 /* If an error occurred, remove the incomplete HTTP response from the
5536 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005537 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005538 return -1;
5539}
5540
Christopher Faulet0f226952018-10-22 09:29:56 +02005541/*
5542 * Capture headers from message <htx> according to header list <cap_hdr>, and
5543 * fill the <cap> pointers appropriately.
5544 */
5545static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5546{
5547 struct cap_hdr *h;
5548 int32_t pos;
5549
5550 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5551 struct htx_blk *blk = htx_get_blk(htx, pos);
5552 enum htx_blk_type type = htx_get_blk_type(blk);
5553 struct ist n, v;
5554
5555 if (type == HTX_BLK_EOH)
5556 break;
5557 if (type != HTX_BLK_HDR)
5558 continue;
5559
5560 n = htx_get_blk_name(htx, blk);
5561
5562 for (h = cap_hdr; h; h = h->next) {
5563 if (h->namelen && (h->namelen == n.len) &&
5564 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5565 if (cap[h->index] == NULL)
5566 cap[h->index] =
5567 pool_alloc(h->pool);
5568
5569 if (cap[h->index] == NULL) {
5570 ha_alert("HTTP capture : out of memory.\n");
5571 break;
5572 }
5573
5574 v = htx_get_blk_value(htx, blk);
5575 if (v.len > h->len)
5576 v.len = h->len;
5577
5578 memcpy(cap[h->index], v.ptr, v.len);
5579 cap[h->index][v.len]=0;
5580 }
5581 }
5582 }
5583}
5584
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005585/* Delete a value in a header between delimiters <from> and <next>. The header
5586 * itself is delimited by <start> and <end> pointers. The number of characters
5587 * displaced is returned, and the pointer to the first delimiter is updated if
5588 * required. The function tries as much as possible to respect the following
5589 * principles :
5590 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5591 * in which case <next> is simply removed
5592 * - set exactly one space character after the new first delimiter, unless there
5593 * are not enough characters in the block being moved to do so.
5594 * - remove unneeded spaces before the previous delimiter and after the new
5595 * one.
5596 *
5597 * It is the caller's responsibility to ensure that :
5598 * - <from> points to a valid delimiter or <start> ;
5599 * - <next> points to a valid delimiter or <end> ;
5600 * - there are non-space chars before <from>.
5601 */
5602static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5603{
5604 char *prev = *from;
5605
5606 if (prev == start) {
5607 /* We're removing the first value. eat the semicolon, if <next>
5608 * is lower than <end> */
5609 if (next < end)
5610 next++;
5611
5612 while (next < end && HTTP_IS_SPHT(*next))
5613 next++;
5614 }
5615 else {
5616 /* Remove useless spaces before the old delimiter. */
5617 while (HTTP_IS_SPHT(*(prev-1)))
5618 prev--;
5619 *from = prev;
5620
5621 /* copy the delimiter and if possible a space if we're
5622 * not at the end of the line.
5623 */
5624 if (next < end) {
5625 *prev++ = *next++;
5626 if (prev + 1 < next)
5627 *prev++ = ' ';
5628 while (next < end && HTTP_IS_SPHT(*next))
5629 next++;
5630 }
5631 }
5632 memmove(prev, next, end - next);
5633 return (prev - next);
5634}
5635
Christopher Faulet0f226952018-10-22 09:29:56 +02005636
5637/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005638 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005641{
5642 struct ist dst = ist2(str, 0);
5643
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005644 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005645 goto end;
5646 if (dst.len + 1 > len)
5647 goto end;
5648 dst.ptr[dst.len++] = ' ';
5649
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005650 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005651 goto end;
5652 if (dst.len + 1 > len)
5653 goto end;
5654 dst.ptr[dst.len++] = ' ';
5655
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005656 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005657 end:
5658 return dst.len;
5659}
5660
Christopher Fauletf0523542018-10-24 11:06:58 +02005661/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005662 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005663 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005664static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005665{
5666 struct ist dst = ist2(str, 0);
5667
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005668 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005669 goto end;
5670 if (dst.len + 1 > len)
5671 goto end;
5672 dst.ptr[dst.len++] = ' ';
5673
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005674 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005675 goto end;
5676 if (dst.len + 1 > len)
5677 goto end;
5678 dst.ptr[dst.len++] = ' ';
5679
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005680 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005681 end:
5682 return dst.len;
5683}
5684
5685
Christopher Faulet0f226952018-10-22 09:29:56 +02005686/*
5687 * Print a debug line with a start line.
5688 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005689static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005690{
5691 struct session *sess = strm_sess(s);
5692 int max;
5693
5694 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5695 dir,
5696 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5697 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5698
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005701 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005702 trash.area[trash.data++] = ' ';
5703
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005707 trash.area[trash.data++] = ' ';
5708
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005709 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 trash.area[trash.data++] = '\n';
5713
5714 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5715}
5716
5717/*
5718 * Print a debug line with a header.
5719 */
5720static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5721{
5722 struct session *sess = strm_sess(s);
5723 int max;
5724
5725 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5726 dir,
5727 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5728 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5729
5730 max = n.len;
5731 UBOUND(max, trash.size - trash.data - 3);
5732 chunk_memcat(&trash, n.ptr, max);
5733 trash.area[trash.data++] = ':';
5734 trash.area[trash.data++] = ' ';
5735
5736 max = v.len;
5737 UBOUND(max, trash.size - trash.data - 1);
5738 chunk_memcat(&trash, v.ptr, max);
5739 trash.area[trash.data++] = '\n';
5740
5741 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5742}
5743
5744
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005745__attribute__((constructor))
5746static void __htx_protocol_init(void)
5747{
5748}
5749
5750
5751/*
5752 * Local variables:
5753 * c-indent-level: 8
5754 * c-basic-offset: 8
5755 * End:
5756 */