blob: 41012b4720ce6b34b5b63d665c118dcef8b0d791 [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
1400 req = &s->req;
1401 res = &s->res;
1402 /* Remove any write error from the request, and read error from the response */
1403 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1404 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1405 res->analysers = 0;
1406 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1407 si->state = SI_ST_REQ;
1408 si->exp = TICK_ETERNITY;
1409 res->rex = TICK_ETERNITY;
1410 res->to_forward = 0;
1411 res->analyse_exp = TICK_ETERNITY;
1412 res->total = 0;
1413 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1414 si_release_endpoint(&s->si[1]);
1415 b_free(&req->buf);
1416 /* Swap the L7 buffer with the channel buffer */
1417 /* We know we stored the co_data as b_data, so get it there */
1418 co_data = b_data(&si->l7_buffer);
1419 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1420 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1421
1422 co_set_data(req, co_data);
1423 b_reset(&res->buf);
1424 co_set_data(res, 0);
1425 return 0;
1426}
1427
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1429 * processing can continue on next analysers, or zero if it either needs more
1430 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1431 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1432 * when it has nothing left to do, and may remove any analyser when it wants to
1433 * abort.
1434 */
1435int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1436{
Christopher Faulet9768c262018-10-22 09:34:31 +02001437 /*
1438 * We will analyze a complete HTTP response to check the its syntax.
1439 *
1440 * Once the start line and all headers are received, we may perform a
1441 * capture of the error (if any), and we will set a few fields. We also
1442 * logging and finally headers capture.
1443 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001444 struct session *sess = s->sess;
1445 struct http_txn *txn = s->txn;
1446 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001447 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001448 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001449 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001450 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001451 int n;
1452
1453 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1454 now_ms, __FUNCTION__,
1455 s,
1456 rep,
1457 rep->rex, rep->wex,
1458 rep->flags,
1459 ci_data(rep),
1460 rep->analysers);
1461
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001462 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001463
Willy Tarreau4236f032019-03-05 10:43:32 +01001464 /* Parsing errors are caught here */
1465 if (htx->flags & HTX_FL_PARSING_ERROR)
1466 goto return_bad_res;
1467
Christopher Faulete0768eb2018-10-03 16:38:02 +02001468 /*
1469 * Now we quickly check if we have found a full valid response.
1470 * If not so, we check the FD and buffer states before leaving.
1471 * A full response is indicated by the fact that we have seen
1472 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1473 * responses are checked first.
1474 *
1475 * Depending on whether the client is still there or not, we
1476 * may send an error response back or not. Note that normally
1477 * we should only check for HTTP status there, and check I/O
1478 * errors somewhere else.
1479 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001480 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001481 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001482 * First catch invalid response because of a parsing error or
1483 * because only part of headers have been transfered.
1484 * Multiplexers have the responsibility to emit all headers at
1485 * once. We must be sure to have forwarded all outgoing data
1486 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001487 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001488 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001489 goto return_bad_res;
1490
Christopher Faulet9768c262018-10-22 09:34:31 +02001491 /* 1: have we encountered a read error ? */
1492 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001493 struct connection *conn = NULL;
1494
Christopher Faulet9768c262018-10-22 09:34:31 +02001495 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 goto abort_keep_alive;
1497
Olivier Houchard865d8392019-05-03 22:46:27 +02001498 if (objt_cs(s->si[1].end))
1499 conn = objt_cs(s->si[1].end)->conn;
1500
1501 if (si_b->flags & SI_FL_L7_RETRY &&
1502 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001503 /* If we arrive here, then CF_READ_ERROR was
1504 * set by si_cs_recv() because we matched a
1505 * status, overwise it would have removed
1506 * the SI_FL_L7_RETRY flag, so it's ok not
1507 * to check s->be->retry_type.
1508 */
1509 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1510 return 0;
1511 }
1512
Olivier Houcharda798bf52019-03-08 18:52:00 +01001513 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001515 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001516 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001517 }
1518
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 rep->analysers &= AN_RES_FLT_END;
1520 txn->status = 502;
1521
1522 /* Check to see if the server refused the early data.
1523 * If so, just send a 425
1524 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001525 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1526 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
1527 do_l7_retry(s, si_b) == 0)
1528 return 0;
1529 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 }
1531
1532 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001533 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534
1535 if (!(s->flags & SF_ERR_MASK))
1536 s->flags |= SF_ERR_SRVCL;
1537 if (!(s->flags & SF_FINST_MASK))
1538 s->flags |= SF_FINST_H;
1539 return 0;
1540 }
1541
Christopher Faulet9768c262018-10-22 09:34:31 +02001542 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001543 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001544 if ((si_b->flags & SI_FL_L7_RETRY) &&
1545 (s->be->retry_type & PR_RE_TIMEOUT)) {
1546 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1547 return 0;
1548 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001549 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001551 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001552 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 }
1554
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 rep->analysers &= AN_RES_FLT_END;
1556 txn->status = 504;
1557 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001558 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559
1560 if (!(s->flags & SF_ERR_MASK))
1561 s->flags |= SF_ERR_SRVTO;
1562 if (!(s->flags & SF_FINST_MASK))
1563 s->flags |= SF_FINST_H;
1564 return 0;
1565 }
1566
Christopher Faulet9768c262018-10-22 09:34:31 +02001567 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001569 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1570 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001571 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001572 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573
1574 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001575 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001576 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577
1578 if (!(s->flags & SF_ERR_MASK))
1579 s->flags |= SF_ERR_CLICL;
1580 if (!(s->flags & SF_FINST_MASK))
1581 s->flags |= SF_FINST_H;
1582
1583 /* process_stream() will take care of the error */
1584 return 0;
1585 }
1586
Christopher Faulet9768c262018-10-22 09:34:31 +02001587 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001588 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001589 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001590 goto abort_keep_alive;
1591
Olivier Houcharda254a372019-04-05 15:30:12 +02001592 if ((si_b->flags & SI_FL_L7_RETRY) &&
1593 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1594 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1595 return 0;
1596 }
1597
Olivier Houcharda798bf52019-03-08 18:52:00 +01001598 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001599 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001600 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001601 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602 }
1603
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 rep->analysers &= AN_RES_FLT_END;
1605 txn->status = 502;
1606 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001607 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001608
1609 if (!(s->flags & SF_ERR_MASK))
1610 s->flags |= SF_ERR_SRVCL;
1611 if (!(s->flags & SF_FINST_MASK))
1612 s->flags |= SF_FINST_H;
1613 return 0;
1614 }
1615
Christopher Faulet9768c262018-10-22 09:34:31 +02001616 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001617 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001618 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001619 goto abort_keep_alive;
1620
Olivier Houcharda798bf52019-03-08 18:52:00 +01001621 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623
1624 if (!(s->flags & SF_ERR_MASK))
1625 s->flags |= SF_ERR_CLICL;
1626 if (!(s->flags & SF_FINST_MASK))
1627 s->flags |= SF_FINST_H;
1628
1629 /* process_stream() will take care of the error */
1630 return 0;
1631 }
1632
1633 channel_dont_close(rep);
1634 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1635 return 0;
1636 }
1637
1638 /* More interesting part now : we know that we have a complete
1639 * response which at least looks like HTTP. We have an indicator
1640 * of each header's length, so we can parse them quickly.
1641 */
1642
Christopher Faulet9768c262018-10-22 09:34:31 +02001643 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001644 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001645
Christopher Faulet9768c262018-10-22 09:34:31 +02001646 /* 0: we might have to print this header in debug mode */
1647 if (unlikely((global.mode & MODE_DEBUG) &&
1648 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1649 int32_t pos;
1650
Christopher Faulet03599112018-11-27 11:21:21 +01001651 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001652
1653 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1654 struct htx_blk *blk = htx_get_blk(htx, pos);
1655 enum htx_blk_type type = htx_get_blk_type(blk);
1656
1657 if (type == HTX_BLK_EOH)
1658 break;
1659 if (type != HTX_BLK_HDR)
1660 continue;
1661
1662 htx_debug_hdr("srvhdr", s,
1663 htx_get_blk_name(htx, blk),
1664 htx_get_blk_value(htx, blk));
1665 }
1666 }
1667
Christopher Faulet03599112018-11-27 11:21:21 +01001668 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001669 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001670 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001671 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001672 if (sl->flags & HTX_SL_F_XFER_LEN) {
1673 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001674 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001675 if (sl->flags & HTX_SL_F_BODYLESS)
1676 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001677 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001678
1679 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001680 if (n < 1 || n > 5)
1681 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001682
Christopher Faulete0768eb2018-10-03 16:38:02 +02001683 /* when the client triggers a 4xx from the server, it's most often due
1684 * to a missing object or permission. These events should be tracked
1685 * because if they happen often, it may indicate a brute force or a
1686 * vulnerability scan.
1687 */
1688 if (n == 4)
1689 stream_inc_http_err_ctr(s);
1690
1691 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001692 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001693
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694 /* Adjust server's health based on status code. Note: status codes 501
1695 * and 505 are triggered on demand by client request, so we must not
1696 * count them as server failures.
1697 */
1698 if (objt_server(s->target)) {
1699 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001700 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001701 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001702 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001703 }
1704
1705 /*
1706 * We may be facing a 100-continue response, or any other informational
1707 * 1xx response which is non-final, in which case this is not the right
1708 * response, and we're waiting for the next one. Let's allow this response
1709 * to go to the client and wait for the next one. There's an exception for
1710 * 101 which is used later in the code to switch protocols.
1711 */
1712 if (txn->status < 200 &&
1713 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001714 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001715 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001716 msg->msg_state = HTTP_MSG_RPBEFORE;
1717 txn->status = 0;
1718 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001719 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720 }
1721
1722 /*
1723 * 2: check for cacheability.
1724 */
1725
1726 switch (txn->status) {
1727 case 200:
1728 case 203:
1729 case 204:
1730 case 206:
1731 case 300:
1732 case 301:
1733 case 404:
1734 case 405:
1735 case 410:
1736 case 414:
1737 case 501:
1738 break;
1739 default:
1740 /* RFC7231#6.1:
1741 * Responses with status codes that are defined as
1742 * cacheable by default (e.g., 200, 203, 204, 206,
1743 * 300, 301, 404, 405, 410, 414, and 501 in this
1744 * specification) can be reused by a cache with
1745 * heuristic expiration unless otherwise indicated
1746 * by the method definition or explicit cache
1747 * controls [RFC7234]; all other status codes are
1748 * not cacheable by default.
1749 */
1750 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1751 break;
1752 }
1753
1754 /*
1755 * 3: we may need to capture headers
1756 */
1757 s->logs.logwait &= ~LW_RESP;
1758 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001759 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001760
Christopher Faulet9768c262018-10-22 09:34:31 +02001761 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001762 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1763 txn->status == 101)) {
1764 /* Either we've established an explicit tunnel, or we're
1765 * switching the protocol. In both cases, we're very unlikely
1766 * to understand the next protocols. We have to switch to tunnel
1767 * mode, so that we transfer the request and responses then let
1768 * this protocol pass unmodified. When we later implement specific
1769 * parsers for such protocols, we'll want to check the Upgrade
1770 * header which contains information about that protocol for
1771 * responses with status 101 (eg: see RFC2817 about TLS).
1772 */
1773 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001774 }
1775
Christopher Faulet61608322018-11-23 16:23:45 +01001776 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1777 * 407 (Proxy-Authenticate) responses and set the connection to private
1778 */
1779 srv_conn = cs_conn(objt_cs(s->si[1].end));
1780 if (srv_conn) {
1781 struct ist hdr;
1782 struct http_hdr_ctx ctx;
1783
1784 if (txn->status == 401)
1785 hdr = ist("WWW-Authenticate");
1786 else if (txn->status == 407)
1787 hdr = ist("Proxy-Authenticate");
1788 else
1789 goto end;
1790
1791 ctx.blk = NULL;
1792 while (http_find_header(htx, hdr, &ctx, 0)) {
1793 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1794 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1795 srv_conn->flags |= CO_FL_PRIVATE;
1796 }
1797 }
1798
1799 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001800 /* we want to have the response time before we start processing it */
1801 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1802
1803 /* end of job, return OK */
1804 rep->analysers &= ~an_bit;
1805 rep->analyse_exp = TICK_ETERNITY;
1806 channel_auto_close(rep);
1807 return 1;
1808
Christopher Faulet47365272018-10-31 17:40:50 +01001809 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001810 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001811 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001812 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001813 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001814 }
1815 txn->status = 502;
1816 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001817 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001818 rep->analysers &= AN_RES_FLT_END;
1819
1820 if (!(s->flags & SF_ERR_MASK))
1821 s->flags |= SF_ERR_PRXCOND;
1822 if (!(s->flags & SF_FINST_MASK))
1823 s->flags |= SF_FINST_H;
1824 return 0;
1825
Christopher Faulete0768eb2018-10-03 16:38:02 +02001826 abort_keep_alive:
1827 /* A keep-alive request to the server failed on a network error.
1828 * The client is required to retry. We need to close without returning
1829 * any other information so that the client retries.
1830 */
1831 txn->status = 0;
1832 rep->analysers &= AN_RES_FLT_END;
1833 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001834 s->logs.logwait = 0;
1835 s->logs.level = 0;
1836 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001837 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001838 return 0;
1839}
1840
1841/* This function performs all the processing enabled for the current response.
1842 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1843 * and updates s->res.analysers. It might make sense to explode it into several
1844 * other functions. It works like process_request (see indications above).
1845 */
1846int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1847{
1848 struct session *sess = s->sess;
1849 struct http_txn *txn = s->txn;
1850 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001851 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001852 struct proxy *cur_proxy;
1853 struct cond_wordlist *wl;
1854 enum rule_result ret = HTTP_RULE_RES_CONT;
1855
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001856 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1857 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001858
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1860 now_ms, __FUNCTION__,
1861 s,
1862 rep,
1863 rep->rex, rep->wex,
1864 rep->flags,
1865 ci_data(rep),
1866 rep->analysers);
1867
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001868 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869
1870 /* The stats applet needs to adjust the Connection header but we don't
1871 * apply any filter there.
1872 */
1873 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1874 rep->analysers &= ~an_bit;
1875 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001876 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001877 }
1878
1879 /*
1880 * We will have to evaluate the filters.
1881 * As opposed to version 1.2, now they will be evaluated in the
1882 * filters order and not in the header order. This means that
1883 * each filter has to be validated among all headers.
1884 *
1885 * Filters are tried with ->be first, then with ->fe if it is
1886 * different from ->be.
1887 *
1888 * Maybe we are in resume condiion. In this case I choose the
1889 * "struct proxy" which contains the rule list matching the resume
1890 * pointer. If none of theses "struct proxy" match, I initialise
1891 * the process with the first one.
1892 *
1893 * In fact, I check only correspondance betwwen the current list
1894 * pointer and the ->fe rule list. If it doesn't match, I initialize
1895 * the loop with the ->be.
1896 */
1897 if (s->current_rule_list == &sess->fe->http_res_rules)
1898 cur_proxy = sess->fe;
1899 else
1900 cur_proxy = s->be;
1901 while (1) {
1902 struct proxy *rule_set = cur_proxy;
1903
1904 /* evaluate http-response rules */
1905 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001906 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001907
1908 if (ret == HTTP_RULE_RES_BADREQ)
1909 goto return_srv_prx_502;
1910
1911 if (ret == HTTP_RULE_RES_DONE) {
1912 rep->analysers &= ~an_bit;
1913 rep->analyse_exp = TICK_ETERNITY;
1914 return 1;
1915 }
1916 }
1917
1918 /* we need to be called again. */
1919 if (ret == HTTP_RULE_RES_YIELD) {
1920 channel_dont_close(rep);
1921 return 0;
1922 }
1923
1924 /* try headers filters */
1925 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001926 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1927 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001928 }
1929
1930 /* has the response been denied ? */
1931 if (txn->flags & TX_SVDENY) {
1932 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001933 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001934
Olivier Houcharda798bf52019-03-08 18:52:00 +01001935 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1936 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001937 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001938 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001939 goto return_srv_prx_502;
1940 }
1941
1942 /* add response headers from the rule sets in the same order */
1943 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001944 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945 if (txn->status < 200 && txn->status != 101)
1946 break;
1947 if (wl->cond) {
1948 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1949 ret = acl_pass(ret);
1950 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1951 ret = !ret;
1952 if (!ret)
1953 continue;
1954 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001955
1956 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1957 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001958 goto return_bad_resp;
1959 }
1960
1961 /* check whether we're already working on the frontend */
1962 if (cur_proxy == sess->fe)
1963 break;
1964 cur_proxy = sess->fe;
1965 }
1966
1967 /* After this point, this anayzer can't return yield, so we can
1968 * remove the bit corresponding to this analyzer from the list.
1969 *
1970 * Note that the intermediate returns and goto found previously
1971 * reset the analyzers.
1972 */
1973 rep->analysers &= ~an_bit;
1974 rep->analyse_exp = TICK_ETERNITY;
1975
1976 /* OK that's all we can do for 1xx responses */
1977 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001978 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001979
1980 /*
1981 * Now check for a server cookie.
1982 */
1983 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001984 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001985
1986 /*
1987 * Check for cache-control or pragma headers if required.
1988 */
1989 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1990 check_response_for_cacheability(s, rep);
1991
1992 /*
1993 * Add server cookie in the response if needed
1994 */
1995 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1996 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1997 (!(s->flags & SF_DIRECT) ||
1998 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1999 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2000 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2001 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2002 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2003 !(s->flags & SF_IGNORE_PRST)) {
2004 /* the server is known, it's not the one the client requested, or the
2005 * cookie's last seen date needs to be refreshed. We have to
2006 * insert a set-cookie here, except if we want to insert only on POST
2007 * requests and this one isn't. Note that servers which don't have cookies
2008 * (eg: some backup servers) will return a full cookie removal request.
2009 */
2010 if (!objt_server(s->target)->cookie) {
2011 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002012 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002013 s->be->cookie_name);
2014 }
2015 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002016 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002017
2018 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2019 /* emit last_date, which is mandatory */
2020 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2021 s30tob64((date.tv_sec+3) >> 2,
2022 trash.area + trash.data);
2023 trash.data += 5;
2024
2025 if (s->be->cookie_maxlife) {
2026 /* emit first_date, which is either the original one or
2027 * the current date.
2028 */
2029 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2030 s30tob64(txn->cookie_first_date ?
2031 txn->cookie_first_date >> 2 :
2032 (date.tv_sec+3) >> 2,
2033 trash.area + trash.data);
2034 trash.data += 5;
2035 }
2036 }
2037 chunk_appendf(&trash, "; path=/");
2038 }
2039
2040 if (s->be->cookie_domain)
2041 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2042
2043 if (s->be->ck_opts & PR_CK_HTTPONLY)
2044 chunk_appendf(&trash, "; HttpOnly");
2045
2046 if (s->be->ck_opts & PR_CK_SECURE)
2047 chunk_appendf(&trash, "; Secure");
2048
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002050 goto return_bad_resp;
2051
2052 txn->flags &= ~TX_SCK_MASK;
2053 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2054 /* the server did not change, only the date was updated */
2055 txn->flags |= TX_SCK_UPDATED;
2056 else
2057 txn->flags |= TX_SCK_INSERTED;
2058
2059 /* Here, we will tell an eventual cache on the client side that we don't
2060 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2061 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2062 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2063 */
2064 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2065
2066 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2067
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002068 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002069 goto return_bad_resp;
2070 }
2071 }
2072
2073 /*
2074 * Check if result will be cacheable with a cookie.
2075 * We'll block the response if security checks have caught
2076 * nasty things such as a cacheable cookie.
2077 */
2078 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2079 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2080 (s->be->options & PR_O_CHK_CACHE)) {
2081 /* we're in presence of a cacheable response containing
2082 * a set-cookie header. We'll block it as requested by
2083 * the 'checkcache' option, and send an alert.
2084 */
2085 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002086 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002087
Olivier Houcharda798bf52019-03-08 18:52:00 +01002088 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2089 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002091 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002092
2093 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2094 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2095 send_log(s->be, LOG_ALERT,
2096 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2097 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2098 goto return_srv_prx_502;
2099 }
2100
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002101 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002102 /* Always enter in the body analyzer */
2103 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2104 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2105
2106 /* if the user wants to log as soon as possible, without counting
2107 * bytes from the server, then this is the right moment. We have
2108 * to temporarily assign bytes_out to log what we currently have.
2109 */
2110 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2111 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002113 s->do_log(s);
2114 s->logs.bytes_out = 0;
2115 }
2116 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002117
2118 return_bad_resp:
2119 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002120 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002121 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002122 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002123 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002124
2125 return_srv_prx_502:
2126 rep->analysers &= AN_RES_FLT_END;
2127 txn->status = 502;
2128 s->logs.t_data = -1; /* was not a valid response */
2129 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002130 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002131 if (!(s->flags & SF_ERR_MASK))
2132 s->flags |= SF_ERR_PRXCOND;
2133 if (!(s->flags & SF_FINST_MASK))
2134 s->flags |= SF_FINST_H;
2135 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136}
2137
2138/* This function is an analyser which forwards response body (including chunk
2139 * sizes if any). It is called as soon as we must forward, even if we forward
2140 * zero byte. The only situation where it must not be called is when we're in
2141 * tunnel mode and we want to forward till the close. It's used both to forward
2142 * remaining data and to resync after end of body. It expects the msg_state to
2143 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2144 * read more data, or 1 once we can go on with next request or end the stream.
2145 *
2146 * It is capable of compressing response data both in content-length mode and
2147 * in chunked mode. The state machines follows different flows depending on
2148 * whether content-length and chunked modes are used, since there are no
2149 * trailers in content-length :
2150 *
2151 * chk-mode cl-mode
2152 * ,----- BODY -----.
2153 * / \
2154 * V size > 0 V chk-mode
2155 * .--> SIZE -------------> DATA -------------> CRLF
2156 * | | size == 0 | last byte |
2157 * | v final crlf v inspected |
2158 * | TRAILERS -----------> DONE |
2159 * | |
2160 * `----------------------------------------------'
2161 *
2162 * Compression only happens in the DATA state, and must be flushed in final
2163 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2164 * is performed at once on final states for all bytes parsed, or when leaving
2165 * on missing data.
2166 */
2167int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2168{
2169 struct session *sess = s->sess;
2170 struct http_txn *txn = s->txn;
2171 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002172 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002173 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002174
2175 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2176 now_ms, __FUNCTION__,
2177 s,
2178 res,
2179 res->rex, res->wex,
2180 res->flags,
2181 ci_data(res),
2182 res->analysers);
2183
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002184 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002185
2186 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002187 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002188 /* Output closed while we were sending data. We must abort and
2189 * wake the other side up.
2190 */
2191 msg->err_state = msg->msg_state;
2192 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002193 htx_end_response(s);
2194 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002195 return 1;
2196 }
2197
Christopher Faulet9768c262018-10-22 09:34:31 +02002198 if (msg->msg_state == HTTP_MSG_BODY)
2199 msg->msg_state = HTTP_MSG_DATA;
2200
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201 /* in most states, we should abort in case of early close */
2202 channel_auto_close(res);
2203
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002205 if (res->to_forward == CHN_INFINITE_FORWARD) {
2206 if (res->flags & (CF_SHUTR|CF_EOI)) {
2207 msg->msg_state = HTTP_MSG_DONE;
2208 res->to_forward = 0;
2209 goto done;
2210 }
2211 }
2212 else {
2213 /* We can't process the buffer's contents yet */
2214 res->flags |= CF_WAKE_WRITE;
2215 goto missing_data_or_waiting;
2216 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217 }
2218
Christopher Faulet9768c262018-10-22 09:34:31 +02002219 if (msg->msg_state >= HTTP_MSG_DONE)
2220 goto done;
2221
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002222 /* Forward input data. We get it by removing all outgoing data not
2223 * forwarded yet from HTX data size. If there are some data filters, we
2224 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002225 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002226 if (HAS_RSP_DATA_FILTERS(s)) {
2227 ret = flt_http_payload(s, msg, htx->data);
2228 if (ret < 0)
2229 goto return_bad_res;
2230 c_adv(res, ret);
2231 if (htx->data != co_data(res) || htx->extra)
2232 goto missing_data_or_waiting;
2233 }
2234 else {
2235 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002236 if (msg->flags & HTTP_MSGF_XFER_LEN)
2237 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002238 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002239
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002240 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2241 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2242 msg->msg_state = HTTP_MSG_TUNNEL;
2243 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 }
2245
Christopher Faulet9768c262018-10-22 09:34:31 +02002246 /* Check if the end-of-message is reached and if so, switch the message
2247 * in HTTP_MSG_DONE state.
2248 */
2249 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2250 goto missing_data_or_waiting;
2251
2252 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002253 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002254
2255 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002257 channel_dont_close(res);
2258
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002259 if (HAS_RSP_DATA_FILTERS(s)) {
2260 ret = flt_http_end(s, msg);
2261 if (ret <= 0) {
2262 if (!ret)
2263 goto missing_data_or_waiting;
2264 goto return_bad_res;
2265 }
2266 }
2267
Christopher Fauletf2824e62018-10-01 12:12:37 +02002268 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002270 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002271 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2272 if (res->flags & CF_SHUTW) {
2273 /* response errors are most likely due to the
2274 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002277 goto return_bad_res;
2278 }
2279 return 1;
2280 }
2281 return 0;
2282
2283 missing_data_or_waiting:
2284 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002285 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286
Christopher Faulet47365272018-10-31 17:40:50 +01002287 if (htx->flags & HTX_FL_PARSING_ERROR)
2288 goto return_bad_res;
2289
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 /* stop waiting for data if the input is closed before the end. If the
2291 * client side was already closed, it means that the client has aborted,
2292 * so we don't want to count this as a server abort. Otherwise it's a
2293 * server abort.
2294 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002295 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002297 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002299 if (htx_is_empty(htx))
2300 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301 }
2302
Christopher Faulete0768eb2018-10-03 16:38:02 +02002303 /* When TE: chunked is used, we need to get there again to parse
2304 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002305 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2306 * are filters registered on the stream, we don't want to forward a
2307 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002308 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002309 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002310 channel_dont_close(res);
2311
2312 /* We know that more data are expected, but we couldn't send more that
2313 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2314 * system knows it must not set a PUSH on this first part. Interactive
2315 * modes are already handled by the stream sock layer. We must not do
2316 * this in content-length mode because it could present the MSG_MORE
2317 * flag with the last block of forwarded data, which would cause an
2318 * additional delay to be observed by the receiver.
2319 */
2320 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2321 res->flags |= CF_EXPECT_MORE;
2322
2323 /* the stream handler will take care of timeouts and errors */
2324 return 0;
2325
Christopher Faulet93e02d82019-03-08 14:18:50 +01002326 return_srv_abort:
2327 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2328 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002329 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002330 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2331 if (!(s->flags & SF_ERR_MASK))
2332 s->flags |= SF_ERR_SRVCL;
2333 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002334
Christopher Faulet93e02d82019-03-08 14:18:50 +01002335 return_cli_abort:
2336 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2337 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002339 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2340 if (!(s->flags & SF_ERR_MASK))
2341 s->flags |= SF_ERR_CLICL;
2342 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343
Christopher Faulet93e02d82019-03-08 14:18:50 +01002344 return_bad_res:
2345 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2346 if (objt_server(s->target)) {
2347 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2348 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2349 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002350 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002351 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002352
Christopher Faulet93e02d82019-03-08 14:18:50 +01002353 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002354 txn->rsp.err_state = txn->rsp.msg_state;
2355 txn->rsp.msg_state = HTTP_MSG_ERROR;
2356 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002357 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 res->analysers &= AN_RES_FLT_END;
2359 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 +02002360 if (!(s->flags & SF_FINST_MASK))
2361 s->flags |= SF_FINST_D;
2362 return 0;
2363}
2364
Christopher Fauletf2824e62018-10-01 12:12:37 +02002365/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002366 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002367 * as too large a request to build a valid response.
2368 */
2369int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2370{
Christopher Faulet99daf282018-11-28 22:58:13 +01002371 struct channel *req = &s->req;
2372 struct channel *res = &s->res;
2373 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002374 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002375 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002376 struct ist status, reason, location;
2377 unsigned int flags;
2378 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379
2380 chunk = alloc_trash_chunk();
2381 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
Christopher Faulet99daf282018-11-28 22:58:13 +01002384 /*
2385 * Create the location
2386 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002387 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 case REDIRECT_TYPE_SCHEME: {
2390 struct http_hdr_ctx ctx;
2391 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002392
Christopher Faulet99daf282018-11-28 22:58:13 +01002393 host = ist("");
2394 ctx.blk = NULL;
2395 if (http_find_header(htx, ist("Host"), &ctx, 0))
2396 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397
Christopher Faulet99daf282018-11-28 22:58:13 +01002398 sl = http_find_stline(htx);
2399 path = http_get_path(htx_sl_req_uri(sl));
2400 /* build message using path */
2401 if (path.ptr) {
2402 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2403 int qs = 0;
2404 while (qs < path.len) {
2405 if (*(path.ptr + qs) == '?') {
2406 path.len = qs;
2407 break;
2408 }
2409 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411 }
2412 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002413 else
2414 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415
Christopher Faulet99daf282018-11-28 22:58:13 +01002416 if (rule->rdr_str) { /* this is an old "redirect" rule */
2417 /* add scheme */
2418 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2419 goto fail;
2420 }
2421 else {
2422 /* add scheme with executing log format */
2423 chunk->data += build_logline(s, chunk->area + chunk->data,
2424 chunk->size - chunk->data,
2425 &rule->rdr_fmt);
2426 }
2427 /* add "://" + host + path */
2428 if (!chunk_memcat(chunk, "://", 3) ||
2429 !chunk_memcat(chunk, host.ptr, host.len) ||
2430 !chunk_memcat(chunk, path.ptr, path.len))
2431 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 /* append a slash at the end of the location if needed and missing */
2434 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2435 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2436 if (chunk->data + 1 >= chunk->size)
2437 goto fail;
2438 chunk->area[chunk->data++] = '/';
2439 }
2440 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 case REDIRECT_TYPE_PREFIX: {
2444 struct ist path;
2445
2446 sl = http_find_stline(htx);
2447 path = http_get_path(htx_sl_req_uri(sl));
2448 /* build message using path */
2449 if (path.ptr) {
2450 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2451 int qs = 0;
2452 while (qs < path.len) {
2453 if (*(path.ptr + qs) == '?') {
2454 path.len = qs;
2455 break;
2456 }
2457 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002458 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459 }
2460 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002461 else
2462 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463
Christopher Faulet99daf282018-11-28 22:58:13 +01002464 if (rule->rdr_str) { /* this is an old "redirect" rule */
2465 /* add prefix. Note that if prefix == "/", we don't want to
2466 * add anything, otherwise it makes it hard for the user to
2467 * configure a self-redirection.
2468 */
2469 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2470 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2471 goto fail;
2472 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 else {
2475 /* add prefix with executing log format */
2476 chunk->data += build_logline(s, chunk->area + chunk->data,
2477 chunk->size - chunk->data,
2478 &rule->rdr_fmt);
2479 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002480
Christopher Faulet99daf282018-11-28 22:58:13 +01002481 /* add path */
2482 if (!chunk_memcat(chunk, path.ptr, path.len))
2483 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002484
Christopher Faulet99daf282018-11-28 22:58:13 +01002485 /* append a slash at the end of the location if needed and missing */
2486 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2487 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2488 if (chunk->data + 1 >= chunk->size)
2489 goto fail;
2490 chunk->area[chunk->data++] = '/';
2491 }
2492 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 case REDIRECT_TYPE_LOCATION:
2495 default:
2496 if (rule->rdr_str) { /* this is an old "redirect" rule */
2497 /* add location */
2498 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2499 goto fail;
2500 }
2501 else {
2502 /* add location with executing log format */
2503 chunk->data += build_logline(s, chunk->area + chunk->data,
2504 chunk->size - chunk->data,
2505 &rule->rdr_fmt);
2506 }
2507 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 location = ist2(chunk->area, chunk->data);
2510
2511 /*
2512 * Create the 30x response
2513 */
2514 switch (rule->code) {
2515 case 308:
2516 status = ist("308");
2517 reason = ist("Permanent Redirect");
2518 break;
2519 case 307:
2520 status = ist("307");
2521 reason = ist("Temporary Redirect");
2522 break;
2523 case 303:
2524 status = ist("303");
2525 reason = ist("See Other");
2526 break;
2527 case 301:
2528 status = ist("301");
2529 reason = ist("Moved Permanently");
2530 break;
2531 case 302:
2532 default:
2533 status = ist("302");
2534 reason = ist("Found");
2535 break;
2536 }
2537
2538 htx = htx_from_buf(&res->buf);
2539 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2540 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2541 if (!sl)
2542 goto fail;
2543 sl->info.res.status = rule->code;
2544 s->txn->status = rule->code;
2545
2546 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2547 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2548 !htx_add_header(htx, ist("Location"), location))
2549 goto fail;
2550
2551 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2552 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2553 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002554 }
2555
2556 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002557 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2558 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002559 }
2560
Christopher Faulet99daf282018-11-28 22:58:13 +01002561 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2562 goto fail;
2563
Christopher Fauletf2824e62018-10-01 12:12:37 +02002564 /* let's log the request time */
2565 s->logs.tv_request = now;
2566
Christopher Faulet99daf282018-11-28 22:58:13 +01002567 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002568 c_adv(res, data);
2569 res->total += data;
2570
2571 channel_auto_read(req);
2572 channel_abort(req);
2573 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002574 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002575
2576 res->wex = tick_add_ifset(now_ms, res->wto);
2577 channel_auto_read(res);
2578 channel_auto_close(res);
2579 channel_shutr_now(res);
2580
2581 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002582
2583 if (!(s->flags & SF_ERR_MASK))
2584 s->flags |= SF_ERR_LOCAL;
2585 if (!(s->flags & SF_FINST_MASK))
2586 s->flags |= SF_FINST_R;
2587
Christopher Faulet99daf282018-11-28 22:58:13 +01002588 free_trash_chunk(chunk);
2589 return 1;
2590
2591 fail:
2592 /* If an error occurred, remove the incomplete HTTP response from the
2593 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002594 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002595 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002596 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002597}
2598
Christopher Faulet72333522018-10-24 11:25:02 +02002599int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2600 struct ist name, const char *str, struct my_regex *re, int action)
2601{
2602 struct http_hdr_ctx ctx;
2603 struct buffer *output = get_trash_chunk();
2604
2605 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2606 ctx.blk = NULL;
2607 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2608 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2609 continue;
2610
2611 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2612 if (output->data == -1)
2613 return -1;
2614 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2615 return -1;
2616 }
2617 return 0;
2618}
2619
2620static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2621 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2622{
2623 struct buffer *replace;
2624 int ret = -1;
2625
2626 replace = alloc_trash_chunk();
2627 if (!replace)
2628 goto leave;
2629
2630 replace->data = build_logline(s, replace->area, replace->size, fmt);
2631 if (replace->data >= replace->size - 1)
2632 goto leave;
2633
2634 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2635
2636 leave:
2637 free_trash_chunk(replace);
2638 return ret;
2639}
2640
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002641
2642/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2643 * on success and -1 on error. The response channel is updated accordingly.
2644 */
2645static int htx_reply_103_early_hints(struct channel *res)
2646{
2647 struct htx *htx = htx_from_buf(&res->buf);
2648 size_t data;
2649
2650 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2651 /* If an error occurred during an Early-hint rule,
2652 * remove the incomplete HTTP 103 response from the
2653 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002654 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002655 return -1;
2656 }
2657
2658 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002659 c_adv(res, data);
2660 res->total += data;
2661 return 0;
2662}
2663
Christopher Faulet6eb92892018-11-15 16:39:29 +01002664/*
2665 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2666 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002667 * If <early_hints> is 0, it is starts a new response by adding the start
2668 * line. If an error occurred -1 is returned. On success 0 is returned. The
2669 * channel is not updated here. It must be done calling the function
2670 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002671 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002672static 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 +01002673{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002674 struct channel *res = &s->res;
2675 struct htx *htx = htx_from_buf(&res->buf);
2676 struct buffer *value = alloc_trash_chunk();
2677
Christopher Faulet6eb92892018-11-15 16:39:29 +01002678 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002679 struct htx_sl *sl;
2680 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2681 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2682
2683 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2684 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2685 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002686 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002687 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002688 }
2689
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2691 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002692 goto fail;
2693
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002694 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002696
2697 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002698 /* If an error occurred during an Early-hint rule, remove the incomplete
2699 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002700 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002701 free_trash_chunk(value);
2702 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002703}
2704
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002705/* This function executes one of the set-{method,path,query,uri} actions. It
2706 * takes the string from the variable 'replace' with length 'len', then modifies
2707 * the relevant part of the request line accordingly. Then it updates various
2708 * pointers to the next elements which were moved, and the total buffer length.
2709 * It finds the action to be performed in p[2], previously filled by function
2710 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2711 * error, though this can be revisited when this code is finally exploited.
2712 *
2713 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2714 * query string and 3 to replace uri.
2715 *
2716 * In query string case, the mark question '?' must be set at the start of the
2717 * string by the caller, event if the replacement query string is empty.
2718 */
2719int htx_req_replace_stline(int action, const char *replace, int len,
2720 struct proxy *px, struct stream *s)
2721{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002722 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002723
2724 switch (action) {
2725 case 0: // method
2726 if (!http_replace_req_meth(htx, ist2(replace, len)))
2727 return -1;
2728 break;
2729
2730 case 1: // path
2731 if (!http_replace_req_path(htx, ist2(replace, len)))
2732 return -1;
2733 break;
2734
2735 case 2: // query
2736 if (!http_replace_req_query(htx, ist2(replace, len)))
2737 return -1;
2738 break;
2739
2740 case 3: // uri
2741 if (!http_replace_req_uri(htx, ist2(replace, len)))
2742 return -1;
2743 break;
2744
2745 default:
2746 return -1;
2747 }
2748 return 0;
2749}
2750
2751/* This function replace the HTTP status code and the associated message. The
2752 * variable <status> contains the new status code. This function never fails.
2753 */
2754void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2755{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002756 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002757 char *res;
2758
2759 chunk_reset(&trash);
2760 res = ultoa_o(status, trash.area, trash.size);
2761 trash.data = res - trash.area;
2762
2763 /* Do we have a custom reason format string? */
2764 if (reason == NULL)
2765 reason = http_get_reason(status);
2766
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002767 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002768 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2769}
2770
Christopher Faulet3e964192018-10-24 11:39:23 +02002771/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2772 * transaction <txn>. Returns the verdict of the first rule that prevents
2773 * further processing of the request (auth, deny, ...), and defaults to
2774 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2775 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2776 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2777 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2778 * status.
2779 */
2780static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2781 struct stream *s, int *deny_status)
2782{
2783 struct session *sess = strm_sess(s);
2784 struct http_txn *txn = s->txn;
2785 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002786 struct act_rule *rule;
2787 struct http_hdr_ctx ctx;
2788 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002789 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2790 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002791 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002792
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002793 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002794
2795 /* If "the current_rule_list" match the executed rule list, we are in
2796 * resume condition. If a resume is needed it is always in the action
2797 * and never in the ACL or converters. In this case, we initialise the
2798 * current rule, and go to the action execution point.
2799 */
2800 if (s->current_rule) {
2801 rule = s->current_rule;
2802 s->current_rule = NULL;
2803 if (s->current_rule_list == rules)
2804 goto resume_execution;
2805 }
2806 s->current_rule_list = rules;
2807
2808 list_for_each_entry(rule, rules, list) {
2809 /* check optional condition */
2810 if (rule->cond) {
2811 int ret;
2812
2813 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2814 ret = acl_pass(ret);
2815
2816 if (rule->cond->pol == ACL_COND_UNLESS)
2817 ret = !ret;
2818
2819 if (!ret) /* condition not matched */
2820 continue;
2821 }
2822
2823 act_flags |= ACT_FLAG_FIRST;
2824 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002825 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2826 early_hints = 0;
2827 if (htx_reply_103_early_hints(&s->res) == -1) {
2828 rule_ret = HTTP_RULE_RES_BADREQ;
2829 goto end;
2830 }
2831 }
2832
Christopher Faulet3e964192018-10-24 11:39:23 +02002833 switch (rule->action) {
2834 case ACT_ACTION_ALLOW:
2835 rule_ret = HTTP_RULE_RES_STOP;
2836 goto end;
2837
2838 case ACT_ACTION_DENY:
2839 if (deny_status)
2840 *deny_status = rule->deny_status;
2841 rule_ret = HTTP_RULE_RES_DENY;
2842 goto end;
2843
2844 case ACT_HTTP_REQ_TARPIT:
2845 txn->flags |= TX_CLTARPIT;
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_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002852 /* Auth might be performed on regular http-req rules as well as on stats */
2853 auth_realm = rule->arg.auth.realm;
2854 if (!auth_realm) {
2855 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2856 auth_realm = STATS_DEFAULT_REALM;
2857 else
2858 auth_realm = px->id;
2859 }
2860 /* send 401/407 depending on whether we use a proxy or not. We still
2861 * count one error, because normal browsing won't significantly
2862 * increase the counter but brute force attempts will.
2863 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002864 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002865 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2866 rule_ret = HTTP_RULE_RES_BADREQ;
2867 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002868 goto end;
2869
2870 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002871 rule_ret = HTTP_RULE_RES_DONE;
2872 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2873 rule_ret = HTTP_RULE_RES_BADREQ;
2874 goto end;
2875
2876 case ACT_HTTP_SET_NICE:
2877 s->task->nice = rule->arg.nice;
2878 break;
2879
2880 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002881 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002882 break;
2883
2884 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002885 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002886 break;
2887
2888 case ACT_HTTP_SET_LOGL:
2889 s->logs.level = rule->arg.loglevel;
2890 break;
2891
2892 case ACT_HTTP_REPLACE_HDR:
2893 case ACT_HTTP_REPLACE_VAL:
2894 if (htx_transform_header(s, &s->req, htx,
2895 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2896 &rule->arg.hdr_add.fmt,
2897 &rule->arg.hdr_add.re, rule->action)) {
2898 rule_ret = HTTP_RULE_RES_BADREQ;
2899 goto end;
2900 }
2901 break;
2902
2903 case ACT_HTTP_DEL_HDR:
2904 /* remove all occurrences of the header */
2905 ctx.blk = NULL;
2906 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2907 http_remove_header(htx, &ctx);
2908 break;
2909
2910 case ACT_HTTP_SET_HDR:
2911 case ACT_HTTP_ADD_HDR: {
2912 /* The scope of the trash buffer must be limited to this function. The
2913 * build_logline() function can execute a lot of other function which
2914 * can use the trash buffer. So for limiting the scope of this global
2915 * buffer, we build first the header value using build_logline, and
2916 * after we store the header name.
2917 */
2918 struct buffer *replace;
2919 struct ist n, v;
2920
2921 replace = alloc_trash_chunk();
2922 if (!replace) {
2923 rule_ret = HTTP_RULE_RES_BADREQ;
2924 goto end;
2925 }
2926
2927 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2928 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2929 v = ist2(replace->area, replace->data);
2930
2931 if (rule->action == ACT_HTTP_SET_HDR) {
2932 /* remove all occurrences of the header */
2933 ctx.blk = NULL;
2934 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2935 http_remove_header(htx, &ctx);
2936 }
2937
2938 if (!http_add_header(htx, n, v)) {
2939 static unsigned char rate_limit = 0;
2940
2941 if ((rate_limit++ & 255) == 0) {
2942 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);
2943 }
2944
Olivier Houcharda798bf52019-03-08 18:52:00 +01002945 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002946 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002947 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002948 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002949 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002950 }
2951 free_trash_chunk(replace);
2952 break;
2953 }
2954
2955 case ACT_HTTP_DEL_ACL:
2956 case ACT_HTTP_DEL_MAP: {
2957 struct pat_ref *ref;
2958 struct buffer *key;
2959
2960 /* collect reference */
2961 ref = pat_ref_lookup(rule->arg.map.ref);
2962 if (!ref)
2963 continue;
2964
2965 /* allocate key */
2966 key = alloc_trash_chunk();
2967 if (!key) {
2968 rule_ret = HTTP_RULE_RES_BADREQ;
2969 goto end;
2970 }
2971
2972 /* collect key */
2973 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2974 key->area[key->data] = '\0';
2975
2976 /* perform update */
2977 /* returned code: 1=ok, 0=ko */
2978 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2979 pat_ref_delete(ref, key->area);
2980 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2981
2982 free_trash_chunk(key);
2983 break;
2984 }
2985
2986 case ACT_HTTP_ADD_ACL: {
2987 struct pat_ref *ref;
2988 struct buffer *key;
2989
2990 /* collect reference */
2991 ref = pat_ref_lookup(rule->arg.map.ref);
2992 if (!ref)
2993 continue;
2994
2995 /* allocate key */
2996 key = alloc_trash_chunk();
2997 if (!key) {
2998 rule_ret = HTTP_RULE_RES_BADREQ;
2999 goto end;
3000 }
3001
3002 /* collect key */
3003 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3004 key->area[key->data] = '\0';
3005
3006 /* perform update */
3007 /* add entry only if it does not already exist */
3008 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3009 if (pat_ref_find_elt(ref, key->area) == NULL)
3010 pat_ref_add(ref, key->area, NULL, NULL);
3011 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3012
3013 free_trash_chunk(key);
3014 break;
3015 }
3016
3017 case ACT_HTTP_SET_MAP: {
3018 struct pat_ref *ref;
3019 struct buffer *key, *value;
3020
3021 /* collect reference */
3022 ref = pat_ref_lookup(rule->arg.map.ref);
3023 if (!ref)
3024 continue;
3025
3026 /* allocate key */
3027 key = alloc_trash_chunk();
3028 if (!key) {
3029 rule_ret = HTTP_RULE_RES_BADREQ;
3030 goto end;
3031 }
3032
3033 /* allocate value */
3034 value = alloc_trash_chunk();
3035 if (!value) {
3036 free_trash_chunk(key);
3037 rule_ret = HTTP_RULE_RES_BADREQ;
3038 goto end;
3039 }
3040
3041 /* collect key */
3042 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3043 key->area[key->data] = '\0';
3044
3045 /* collect value */
3046 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3047 value->area[value->data] = '\0';
3048
3049 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003050 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003051 if (pat_ref_find_elt(ref, key->area) != NULL)
3052 /* update entry if it exists */
3053 pat_ref_set(ref, key->area, value->area, NULL);
3054 else
3055 /* insert a new entry */
3056 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003057 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003058 free_trash_chunk(key);
3059 free_trash_chunk(value);
3060 break;
3061 }
3062
3063 case ACT_HTTP_EARLY_HINT:
3064 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3065 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003066 early_hints = htx_add_early_hint_header(s, early_hints,
3067 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003068 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003069 if (early_hints == -1) {
3070 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003071 goto end;
3072 }
3073 break;
3074
3075 case ACT_CUSTOM:
3076 if ((s->req.flags & CF_READ_ERROR) ||
3077 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003078 (px->options & PR_O_ABRT_CLOSE)))
3079 act_flags |= ACT_FLAG_FINAL;
3080
3081 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3082 case ACT_RET_ERR:
3083 case ACT_RET_CONT:
3084 break;
3085 case ACT_RET_STOP:
3086 rule_ret = HTTP_RULE_RES_DONE;
3087 goto end;
3088 case ACT_RET_YIELD:
3089 s->current_rule = rule;
3090 rule_ret = HTTP_RULE_RES_YIELD;
3091 goto end;
3092 }
3093 break;
3094
3095 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3096 /* Note: only the first valid tracking parameter of each
3097 * applies.
3098 */
3099
3100 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3101 struct stktable *t;
3102 struct stksess *ts;
3103 struct stktable_key *key;
3104 void *ptr1, *ptr2;
3105
3106 t = rule->arg.trk_ctr.table.t;
3107 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3108 rule->arg.trk_ctr.expr, NULL);
3109
3110 if (key && (ts = stktable_get_entry(t, key))) {
3111 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3112
3113 /* let's count a new HTTP request as it's the first time we do it */
3114 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3115 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3116 if (ptr1 || ptr2) {
3117 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3118
3119 if (ptr1)
3120 stktable_data_cast(ptr1, http_req_cnt)++;
3121
3122 if (ptr2)
3123 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3124 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3125
3126 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3127
3128 /* If data was modified, we need to touch to re-schedule sync */
3129 stktable_touch_local(t, ts, 0);
3130 }
3131
3132 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3133 if (sess->fe != s->be)
3134 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3135 }
3136 }
3137 break;
3138
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003139 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003140 default:
3141 break;
3142 }
3143 }
3144
3145 end:
3146 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003147 if (htx_reply_103_early_hints(&s->res) == -1)
3148 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003149 }
3150
3151 /* we reached the end of the rules, nothing to report */
3152 return rule_ret;
3153}
3154
3155/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3156 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3157 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3158 * is returned, the process can continue the evaluation of next rule list. If
3159 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3160 * is returned, it means the operation could not be processed and a server error
3161 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3162 * deny rule. If *YIELD is returned, the caller must call again the function
3163 * with the same context.
3164 */
3165static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3166 struct stream *s)
3167{
3168 struct session *sess = strm_sess(s);
3169 struct http_txn *txn = s->txn;
3170 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003171 struct act_rule *rule;
3172 struct http_hdr_ctx ctx;
3173 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3174 int act_flags = 0;
3175
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003176 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003177
3178 /* If "the current_rule_list" match the executed rule list, we are in
3179 * resume condition. If a resume is needed it is always in the action
3180 * and never in the ACL or converters. In this case, we initialise the
3181 * current rule, and go to the action execution point.
3182 */
3183 if (s->current_rule) {
3184 rule = s->current_rule;
3185 s->current_rule = NULL;
3186 if (s->current_rule_list == rules)
3187 goto resume_execution;
3188 }
3189 s->current_rule_list = rules;
3190
3191 list_for_each_entry(rule, rules, list) {
3192 /* check optional condition */
3193 if (rule->cond) {
3194 int ret;
3195
3196 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3197 ret = acl_pass(ret);
3198
3199 if (rule->cond->pol == ACL_COND_UNLESS)
3200 ret = !ret;
3201
3202 if (!ret) /* condition not matched */
3203 continue;
3204 }
3205
3206 act_flags |= ACT_FLAG_FIRST;
3207resume_execution:
3208 switch (rule->action) {
3209 case ACT_ACTION_ALLOW:
3210 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3211 goto end;
3212
3213 case ACT_ACTION_DENY:
3214 txn->flags |= TX_SVDENY;
3215 rule_ret = HTTP_RULE_RES_STOP;
3216 goto end;
3217
3218 case ACT_HTTP_SET_NICE:
3219 s->task->nice = rule->arg.nice;
3220 break;
3221
3222 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003223 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003224 break;
3225
3226 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003227 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003228 break;
3229
3230 case ACT_HTTP_SET_LOGL:
3231 s->logs.level = rule->arg.loglevel;
3232 break;
3233
3234 case ACT_HTTP_REPLACE_HDR:
3235 case ACT_HTTP_REPLACE_VAL:
3236 if (htx_transform_header(s, &s->res, htx,
3237 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3238 &rule->arg.hdr_add.fmt,
3239 &rule->arg.hdr_add.re, rule->action)) {
3240 rule_ret = HTTP_RULE_RES_BADREQ;
3241 goto end;
3242 }
3243 break;
3244
3245 case ACT_HTTP_DEL_HDR:
3246 /* remove all occurrences of the header */
3247 ctx.blk = NULL;
3248 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3249 http_remove_header(htx, &ctx);
3250 break;
3251
3252 case ACT_HTTP_SET_HDR:
3253 case ACT_HTTP_ADD_HDR: {
3254 struct buffer *replace;
3255 struct ist n, v;
3256
3257 replace = alloc_trash_chunk();
3258 if (!replace) {
3259 rule_ret = HTTP_RULE_RES_BADREQ;
3260 goto end;
3261 }
3262
3263 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3264 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3265 v = ist2(replace->area, replace->data);
3266
3267 if (rule->action == ACT_HTTP_SET_HDR) {
3268 /* remove all occurrences of the header */
3269 ctx.blk = NULL;
3270 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3271 http_remove_header(htx, &ctx);
3272 }
3273
3274 if (!http_add_header(htx, n, v)) {
3275 static unsigned char rate_limit = 0;
3276
3277 if ((rate_limit++ & 255) == 0) {
3278 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);
3279 }
3280
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003283 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003284 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003285 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003286 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003287 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003288 }
3289 free_trash_chunk(replace);
3290 break;
3291 }
3292
3293 case ACT_HTTP_DEL_ACL:
3294 case ACT_HTTP_DEL_MAP: {
3295 struct pat_ref *ref;
3296 struct buffer *key;
3297
3298 /* collect reference */
3299 ref = pat_ref_lookup(rule->arg.map.ref);
3300 if (!ref)
3301 continue;
3302
3303 /* allocate key */
3304 key = alloc_trash_chunk();
3305 if (!key) {
3306 rule_ret = HTTP_RULE_RES_BADREQ;
3307 goto end;
3308 }
3309
3310 /* collect key */
3311 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3312 key->area[key->data] = '\0';
3313
3314 /* perform update */
3315 /* returned code: 1=ok, 0=ko */
3316 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3317 pat_ref_delete(ref, key->area);
3318 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3319
3320 free_trash_chunk(key);
3321 break;
3322 }
3323
3324 case ACT_HTTP_ADD_ACL: {
3325 struct pat_ref *ref;
3326 struct buffer *key;
3327
3328 /* collect reference */
3329 ref = pat_ref_lookup(rule->arg.map.ref);
3330 if (!ref)
3331 continue;
3332
3333 /* allocate key */
3334 key = alloc_trash_chunk();
3335 if (!key) {
3336 rule_ret = HTTP_RULE_RES_BADREQ;
3337 goto end;
3338 }
3339
3340 /* collect key */
3341 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3342 key->area[key->data] = '\0';
3343
3344 /* perform update */
3345 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003346 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003347 if (pat_ref_find_elt(ref, key->area) == NULL)
3348 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003349 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003350 free_trash_chunk(key);
3351 break;
3352 }
3353
3354 case ACT_HTTP_SET_MAP: {
3355 struct pat_ref *ref;
3356 struct buffer *key, *value;
3357
3358 /* collect reference */
3359 ref = pat_ref_lookup(rule->arg.map.ref);
3360 if (!ref)
3361 continue;
3362
3363 /* allocate key */
3364 key = alloc_trash_chunk();
3365 if (!key) {
3366 rule_ret = HTTP_RULE_RES_BADREQ;
3367 goto end;
3368 }
3369
3370 /* allocate value */
3371 value = alloc_trash_chunk();
3372 if (!value) {
3373 free_trash_chunk(key);
3374 rule_ret = HTTP_RULE_RES_BADREQ;
3375 goto end;
3376 }
3377
3378 /* collect key */
3379 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3380 key->area[key->data] = '\0';
3381
3382 /* collect value */
3383 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3384 value->area[value->data] = '\0';
3385
3386 /* perform update */
3387 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3388 if (pat_ref_find_elt(ref, key->area) != NULL)
3389 /* update entry if it exists */
3390 pat_ref_set(ref, key->area, value->area, NULL);
3391 else
3392 /* insert a new entry */
3393 pat_ref_add(ref, key->area, value->area, NULL);
3394 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3395 free_trash_chunk(key);
3396 free_trash_chunk(value);
3397 break;
3398 }
3399
3400 case ACT_HTTP_REDIR:
3401 rule_ret = HTTP_RULE_RES_DONE;
3402 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3403 rule_ret = HTTP_RULE_RES_BADREQ;
3404 goto end;
3405
3406 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3407 /* Note: only the first valid tracking parameter of each
3408 * applies.
3409 */
3410 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3411 struct stktable *t;
3412 struct stksess *ts;
3413 struct stktable_key *key;
3414 void *ptr;
3415
3416 t = rule->arg.trk_ctr.table.t;
3417 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3418 rule->arg.trk_ctr.expr, NULL);
3419
3420 if (key && (ts = stktable_get_entry(t, key))) {
3421 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3422
3423 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3424
3425 /* let's count a new HTTP request as it's the first time we do it */
3426 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3427 if (ptr)
3428 stktable_data_cast(ptr, http_req_cnt)++;
3429
3430 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3431 if (ptr)
3432 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3433 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3434
3435 /* When the client triggers a 4xx from the server, it's most often due
3436 * to a missing object or permission. These events should be tracked
3437 * because if they happen often, it may indicate a brute force or a
3438 * vulnerability scan. Normally this is done when receiving the response
3439 * but here we're tracking after this ought to have been done so we have
3440 * to do it on purpose.
3441 */
3442 if ((unsigned)(txn->status - 400) < 100) {
3443 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3444 if (ptr)
3445 stktable_data_cast(ptr, http_err_cnt)++;
3446
3447 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3448 if (ptr)
3449 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3450 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3451 }
3452
3453 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3454
3455 /* If data was modified, we need to touch to re-schedule sync */
3456 stktable_touch_local(t, ts, 0);
3457
3458 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3459 if (sess->fe != s->be)
3460 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3461 }
3462 }
3463 break;
3464
3465 case ACT_CUSTOM:
3466 if ((s->req.flags & CF_READ_ERROR) ||
3467 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003468 (px->options & PR_O_ABRT_CLOSE)))
3469 act_flags |= ACT_FLAG_FINAL;
3470
3471 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3472 case ACT_RET_ERR:
3473 case ACT_RET_CONT:
3474 break;
3475 case ACT_RET_STOP:
3476 rule_ret = HTTP_RULE_RES_STOP;
3477 goto end;
3478 case ACT_RET_YIELD:
3479 s->current_rule = rule;
3480 rule_ret = HTTP_RULE_RES_YIELD;
3481 goto end;
3482 }
3483 break;
3484
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003485 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003486 default:
3487 break;
3488 }
3489 }
3490
3491 end:
3492 /* we reached the end of the rules, nothing to report */
3493 return rule_ret;
3494}
3495
Christopher Faulet33640082018-10-24 11:53:01 +02003496/* Iterate the same filter through all request headers.
3497 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3498 * Since it can manage the switch to another backend, it updates the per-proxy
3499 * DENY stats.
3500 */
3501static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3502{
3503 struct http_txn *txn = s->txn;
3504 struct htx *htx;
3505 struct buffer *hdr = get_trash_chunk();
3506 int32_t pos;
3507
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003508 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003509
3510 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3511 struct htx_blk *blk = htx_get_blk(htx, pos);
3512 enum htx_blk_type type;
3513 struct ist n, v;
3514
3515 next_hdr:
3516 type = htx_get_blk_type(blk);
3517 if (type == HTX_BLK_EOH)
3518 break;
3519 if (type != HTX_BLK_HDR)
3520 continue;
3521
3522 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3523 return 1;
3524 else if (unlikely(txn->flags & TX_CLALLOW) &&
3525 (exp->action == ACT_ALLOW ||
3526 exp->action == ACT_DENY ||
3527 exp->action == ACT_TARPIT))
3528 return 0;
3529
3530 n = htx_get_blk_name(htx, blk);
3531 v = htx_get_blk_value(htx, blk);
3532
Christopher Faulet02e771a2019-02-26 15:36:05 +01003533 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003534 hdr->area[hdr->data++] = ':';
3535 hdr->area[hdr->data++] = ' ';
3536 chunk_memcat(hdr, v.ptr, v.len);
3537
3538 /* Now we have one header in <hdr> */
3539
3540 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3541 struct http_hdr_ctx ctx;
3542 int len;
3543
3544 switch (exp->action) {
3545 case ACT_ALLOW:
3546 txn->flags |= TX_CLALLOW;
3547 goto end;
3548
3549 case ACT_DENY:
3550 txn->flags |= TX_CLDENY;
3551 goto end;
3552
3553 case ACT_TARPIT:
3554 txn->flags |= TX_CLTARPIT;
3555 goto end;
3556
3557 case ACT_REPLACE:
3558 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3559 if (len < 0)
3560 return -1;
3561
3562 http_parse_header(ist2(trash.area, len), &n, &v);
3563 ctx.blk = blk;
3564 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003565 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003566 if (!http_replace_header(htx, &ctx, n, v))
3567 return -1;
3568 if (!ctx.blk)
3569 goto end;
3570 pos = htx_get_blk_pos(htx, blk);
3571 break;
3572
3573 case ACT_REMOVE:
3574 ctx.blk = blk;
3575 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003576 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003577 if (!http_remove_header(htx, &ctx))
3578 return -1;
3579 if (!ctx.blk)
3580 goto end;
3581 pos = htx_get_blk_pos(htx, blk);
3582 goto next_hdr;
3583
3584 }
3585 }
3586 }
3587 end:
3588 return 0;
3589}
3590
3591/* Apply the filter to the request line.
3592 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3593 * or -1 if a replacement resulted in an invalid request line.
3594 * Since it can manage the switch to another backend, it updates the per-proxy
3595 * DENY stats.
3596 */
3597static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3598{
3599 struct http_txn *txn = s->txn;
3600 struct htx *htx;
3601 struct buffer *reqline = get_trash_chunk();
3602 int done;
3603
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003604 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003605
3606 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3607 return 1;
3608 else if (unlikely(txn->flags & TX_CLALLOW) &&
3609 (exp->action == ACT_ALLOW ||
3610 exp->action == ACT_DENY ||
3611 exp->action == ACT_TARPIT))
3612 return 0;
3613 else if (exp->action == ACT_REMOVE)
3614 return 0;
3615
3616 done = 0;
3617
3618 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3619
3620 /* Now we have the request line between cur_ptr and cur_end */
3621 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003622 struct htx_sl *sl = http_find_stline(htx);
3623 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003624 int len;
3625
3626 switch (exp->action) {
3627 case ACT_ALLOW:
3628 txn->flags |= TX_CLALLOW;
3629 done = 1;
3630 break;
3631
3632 case ACT_DENY:
3633 txn->flags |= TX_CLDENY;
3634 done = 1;
3635 break;
3636
3637 case ACT_TARPIT:
3638 txn->flags |= TX_CLTARPIT;
3639 done = 1;
3640 break;
3641
3642 case ACT_REPLACE:
3643 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3644 if (len < 0)
3645 return -1;
3646
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003647 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3648 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3649 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003650 return -1;
3651 done = 1;
3652 break;
3653 }
3654 }
3655 return done;
3656}
3657
3658/*
3659 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3660 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3661 * unparsable request. Since it can manage the switch to another backend, it
3662 * updates the per-proxy DENY stats.
3663 */
3664static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3665{
3666 struct session *sess = s->sess;
3667 struct http_txn *txn = s->txn;
3668 struct hdr_exp *exp;
3669
3670 for (exp = px->req_exp; exp; exp = exp->next) {
3671 int ret;
3672
3673 /*
3674 * The interleaving of transformations and verdicts
3675 * makes it difficult to decide to continue or stop
3676 * the evaluation.
3677 */
3678
3679 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3680 break;
3681
3682 if ((txn->flags & TX_CLALLOW) &&
3683 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3684 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3685 continue;
3686
3687 /* if this filter had a condition, evaluate it now and skip to
3688 * next filter if the condition does not match.
3689 */
3690 if (exp->cond) {
3691 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3692 ret = acl_pass(ret);
3693 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3694 ret = !ret;
3695
3696 if (!ret)
3697 continue;
3698 }
3699
3700 /* Apply the filter to the request line. */
3701 ret = htx_apply_filter_to_req_line(s, req, exp);
3702 if (unlikely(ret < 0))
3703 return -1;
3704
3705 if (likely(ret == 0)) {
3706 /* The filter did not match the request, it can be
3707 * iterated through all headers.
3708 */
3709 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3710 return -1;
3711 }
3712 }
3713 return 0;
3714}
3715
3716/* Iterate the same filter through all response headers contained in <res>.
3717 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3718 */
3719static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3720{
3721 struct http_txn *txn = s->txn;
3722 struct htx *htx;
3723 struct buffer *hdr = get_trash_chunk();
3724 int32_t pos;
3725
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003726 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003727
3728 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3729 struct htx_blk *blk = htx_get_blk(htx, pos);
3730 enum htx_blk_type type;
3731 struct ist n, v;
3732
3733 next_hdr:
3734 type = htx_get_blk_type(blk);
3735 if (type == HTX_BLK_EOH)
3736 break;
3737 if (type != HTX_BLK_HDR)
3738 continue;
3739
3740 if (unlikely(txn->flags & TX_SVDENY))
3741 return 1;
3742 else if (unlikely(txn->flags & TX_SVALLOW) &&
3743 (exp->action == ACT_ALLOW ||
3744 exp->action == ACT_DENY))
3745 return 0;
3746
3747 n = htx_get_blk_name(htx, blk);
3748 v = htx_get_blk_value(htx, blk);
3749
Christopher Faulet02e771a2019-02-26 15:36:05 +01003750 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003751 hdr->area[hdr->data++] = ':';
3752 hdr->area[hdr->data++] = ' ';
3753 chunk_memcat(hdr, v.ptr, v.len);
3754
3755 /* Now we have one header in <hdr> */
3756
3757 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3758 struct http_hdr_ctx ctx;
3759 int len;
3760
3761 switch (exp->action) {
3762 case ACT_ALLOW:
3763 txn->flags |= TX_SVALLOW;
3764 goto end;
3765 break;
3766
3767 case ACT_DENY:
3768 txn->flags |= TX_SVDENY;
3769 goto end;
3770 break;
3771
3772 case ACT_REPLACE:
3773 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3774 if (len < 0)
3775 return -1;
3776
3777 http_parse_header(ist2(trash.area, len), &n, &v);
3778 ctx.blk = blk;
3779 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003780 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003781 if (!http_replace_header(htx, &ctx, n, v))
3782 return -1;
3783 if (!ctx.blk)
3784 goto end;
3785 pos = htx_get_blk_pos(htx, blk);
3786 break;
3787
3788 case ACT_REMOVE:
3789 ctx.blk = blk;
3790 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003791 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003792 if (!http_remove_header(htx, &ctx))
3793 return -1;
3794 if (!ctx.blk)
3795 goto end;
3796 pos = htx_get_blk_pos(htx, blk);
3797 goto next_hdr;
3798 }
3799 }
3800
3801 }
3802 end:
3803 return 0;
3804}
3805
3806/* Apply the filter to the status line in the response buffer <res>.
3807 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3808 * or -1 if a replacement resulted in an invalid status line.
3809 */
3810static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3811{
3812 struct http_txn *txn = s->txn;
3813 struct htx *htx;
3814 struct buffer *resline = get_trash_chunk();
3815 int done;
3816
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003817 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003818
3819 if (unlikely(txn->flags & TX_SVDENY))
3820 return 1;
3821 else if (unlikely(txn->flags & TX_SVALLOW) &&
3822 (exp->action == ACT_ALLOW ||
3823 exp->action == ACT_DENY))
3824 return 0;
3825 else if (exp->action == ACT_REMOVE)
3826 return 0;
3827
3828 done = 0;
3829 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3830
3831 /* Now we have the status line between cur_ptr and cur_end */
3832 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003833 struct htx_sl *sl = http_find_stline(htx);
3834 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003835 int len;
3836
3837 switch (exp->action) {
3838 case ACT_ALLOW:
3839 txn->flags |= TX_SVALLOW;
3840 done = 1;
3841 break;
3842
3843 case ACT_DENY:
3844 txn->flags |= TX_SVDENY;
3845 done = 1;
3846 break;
3847
3848 case ACT_REPLACE:
3849 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3850 if (len < 0)
3851 return -1;
3852
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003853 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3854 sl->info.res.status = strl2ui(code.ptr, code.len);
3855 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003856 return -1;
3857
3858 done = 1;
3859 return 1;
3860 }
3861 }
3862 return done;
3863}
3864
3865/*
3866 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3867 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3868 * unparsable response.
3869 */
3870static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3871{
3872 struct session *sess = s->sess;
3873 struct http_txn *txn = s->txn;
3874 struct hdr_exp *exp;
3875
3876 for (exp = px->rsp_exp; exp; exp = exp->next) {
3877 int ret;
3878
3879 /*
3880 * The interleaving of transformations and verdicts
3881 * makes it difficult to decide to continue or stop
3882 * the evaluation.
3883 */
3884
3885 if (txn->flags & TX_SVDENY)
3886 break;
3887
3888 if ((txn->flags & TX_SVALLOW) &&
3889 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3890 exp->action == ACT_PASS)) {
3891 exp = exp->next;
3892 continue;
3893 }
3894
3895 /* if this filter had a condition, evaluate it now and skip to
3896 * next filter if the condition does not match.
3897 */
3898 if (exp->cond) {
3899 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3900 ret = acl_pass(ret);
3901 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3902 ret = !ret;
3903 if (!ret)
3904 continue;
3905 }
3906
3907 /* Apply the filter to the status line. */
3908 ret = htx_apply_filter_to_sts_line(s, res, exp);
3909 if (unlikely(ret < 0))
3910 return -1;
3911
3912 if (likely(ret == 0)) {
3913 /* The filter did not match the response, it can be
3914 * iterated through all headers.
3915 */
3916 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3917 return -1;
3918 }
3919 }
3920 return 0;
3921}
3922
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003923/*
3924 * Manage client-side cookie. It can impact performance by about 2% so it is
3925 * desirable to call it only when needed. This code is quite complex because
3926 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3927 * highly recommended not to touch this part without a good reason !
3928 */
3929static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3930{
3931 struct session *sess = s->sess;
3932 struct http_txn *txn = s->txn;
3933 struct htx *htx;
3934 struct http_hdr_ctx ctx;
3935 char *hdr_beg, *hdr_end, *del_from;
3936 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3937 int preserve_hdr;
3938
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003939 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003940 ctx.blk = NULL;
3941 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3942 del_from = NULL; /* nothing to be deleted */
3943 preserve_hdr = 0; /* assume we may kill the whole header */
3944
3945 /* Now look for cookies. Conforming to RFC2109, we have to support
3946 * attributes whose name begin with a '$', and associate them with
3947 * the right cookie, if we want to delete this cookie.
3948 * So there are 3 cases for each cookie read :
3949 * 1) it's a special attribute, beginning with a '$' : ignore it.
3950 * 2) it's a server id cookie that we *MAY* want to delete : save
3951 * some pointers on it (last semi-colon, beginning of cookie...)
3952 * 3) it's an application cookie : we *MAY* have to delete a previous
3953 * "special" cookie.
3954 * At the end of loop, if a "special" cookie remains, we may have to
3955 * remove it. If no application cookie persists in the header, we
3956 * *MUST* delete it.
3957 *
3958 * Note: RFC2965 is unclear about the processing of spaces around
3959 * the equal sign in the ATTR=VALUE form. A careful inspection of
3960 * the RFC explicitly allows spaces before it, and not within the
3961 * tokens (attrs or values). An inspection of RFC2109 allows that
3962 * too but section 10.1.3 lets one think that spaces may be allowed
3963 * after the equal sign too, resulting in some (rare) buggy
3964 * implementations trying to do that. So let's do what servers do.
3965 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3966 * allowed quoted strings in values, with any possible character
3967 * after a backslash, including control chars and delimitors, which
3968 * causes parsing to become ambiguous. Browsers also allow spaces
3969 * within values even without quotes.
3970 *
3971 * We have to keep multiple pointers in order to support cookie
3972 * removal at the beginning, middle or end of header without
3973 * corrupting the header. All of these headers are valid :
3974 *
3975 * hdr_beg hdr_end
3976 * | |
3977 * v |
3978 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3979 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3980 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3981 * | | | | | | |
3982 * | | | | | | |
3983 * | | | | | | +--> next
3984 * | | | | | +----> val_end
3985 * | | | | +-----------> val_beg
3986 * | | | +--------------> equal
3987 * | | +----------------> att_end
3988 * | +---------------------> att_beg
3989 * +--------------------------> prev
3990 *
3991 */
3992 hdr_beg = ctx.value.ptr;
3993 hdr_end = hdr_beg + ctx.value.len;
3994 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3995 /* Iterate through all cookies on this line */
3996
3997 /* find att_beg */
3998 att_beg = prev;
3999 if (prev > hdr_beg)
4000 att_beg++;
4001
4002 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4003 att_beg++;
4004
4005 /* find att_end : this is the first character after the last non
4006 * space before the equal. It may be equal to hdr_end.
4007 */
4008 equal = att_end = att_beg;
4009 while (equal < hdr_end) {
4010 if (*equal == '=' || *equal == ',' || *equal == ';')
4011 break;
4012 if (HTTP_IS_SPHT(*equal++))
4013 continue;
4014 att_end = equal;
4015 }
4016
4017 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4018 * is between <att_beg> and <equal>, both may be identical.
4019 */
4020 /* look for end of cookie if there is an equal sign */
4021 if (equal < hdr_end && *equal == '=') {
4022 /* look for the beginning of the value */
4023 val_beg = equal + 1;
4024 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4025 val_beg++;
4026
4027 /* find the end of the value, respecting quotes */
4028 next = http_find_cookie_value_end(val_beg, hdr_end);
4029
4030 /* make val_end point to the first white space or delimitor after the value */
4031 val_end = next;
4032 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4033 val_end--;
4034 }
4035 else
4036 val_beg = val_end = next = equal;
4037
4038 /* We have nothing to do with attributes beginning with
4039 * '$'. However, they will automatically be removed if a
4040 * header before them is removed, since they're supposed
4041 * to be linked together.
4042 */
4043 if (*att_beg == '$')
4044 continue;
4045
4046 /* Ignore cookies with no equal sign */
4047 if (equal == next) {
4048 /* This is not our cookie, so we must preserve it. But if we already
4049 * scheduled another cookie for removal, we cannot remove the
4050 * complete header, but we can remove the previous block itself.
4051 */
4052 preserve_hdr = 1;
4053 if (del_from != NULL) {
4054 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4055 val_end += delta;
4056 next += delta;
4057 hdr_end += delta;
4058 prev = del_from;
4059 del_from = NULL;
4060 }
4061 continue;
4062 }
4063
4064 /* if there are spaces around the equal sign, we need to
4065 * strip them otherwise we'll get trouble for cookie captures,
4066 * or even for rewrites. Since this happens extremely rarely,
4067 * it does not hurt performance.
4068 */
4069 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4070 int stripped_before = 0;
4071 int stripped_after = 0;
4072
4073 if (att_end != equal) {
4074 memmove(att_end, equal, hdr_end - equal);
4075 stripped_before = (att_end - equal);
4076 equal += stripped_before;
4077 val_beg += stripped_before;
4078 }
4079
4080 if (val_beg > equal + 1) {
4081 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4082 stripped_after = (equal + 1) - val_beg;
4083 val_beg += stripped_after;
4084 stripped_before += stripped_after;
4085 }
4086
4087 val_end += stripped_before;
4088 next += stripped_before;
4089 hdr_end += stripped_before;
4090 }
4091 /* now everything is as on the diagram above */
4092
4093 /* First, let's see if we want to capture this cookie. We check
4094 * that we don't already have a client side cookie, because we
4095 * can only capture one. Also as an optimisation, we ignore
4096 * cookies shorter than the declared name.
4097 */
4098 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4099 (val_end - att_beg >= sess->fe->capture_namelen) &&
4100 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4101 int log_len = val_end - att_beg;
4102
4103 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4104 ha_alert("HTTP logging : out of memory.\n");
4105 } else {
4106 if (log_len > sess->fe->capture_len)
4107 log_len = sess->fe->capture_len;
4108 memcpy(txn->cli_cookie, att_beg, log_len);
4109 txn->cli_cookie[log_len] = 0;
4110 }
4111 }
4112
4113 /* Persistence cookies in passive, rewrite or insert mode have the
4114 * following form :
4115 *
4116 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4117 *
4118 * For cookies in prefix mode, the form is :
4119 *
4120 * Cookie: NAME=SRV~VALUE
4121 */
4122 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4123 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4124 struct server *srv = s->be->srv;
4125 char *delim;
4126
4127 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4128 * have the server ID between val_beg and delim, and the original cookie between
4129 * delim+1 and val_end. Otherwise, delim==val_end :
4130 *
4131 * hdr_beg
4132 * |
4133 * v
4134 * NAME=SRV; # in all but prefix modes
4135 * NAME=SRV~OPAQUE ; # in prefix mode
4136 * || || | |+-> next
4137 * || || | +--> val_end
4138 * || || +---------> delim
4139 * || |+------------> val_beg
4140 * || +-------------> att_end = equal
4141 * |+-----------------> att_beg
4142 * +------------------> prev
4143 *
4144 */
4145 if (s->be->ck_opts & PR_CK_PFX) {
4146 for (delim = val_beg; delim < val_end; delim++)
4147 if (*delim == COOKIE_DELIM)
4148 break;
4149 }
4150 else {
4151 char *vbar1;
4152 delim = val_end;
4153 /* Now check if the cookie contains a date field, which would
4154 * appear after a vertical bar ('|') just after the server name
4155 * and before the delimiter.
4156 */
4157 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4158 if (vbar1) {
4159 /* OK, so left of the bar is the server's cookie and
4160 * right is the last seen date. It is a base64 encoded
4161 * 30-bit value representing the UNIX date since the
4162 * epoch in 4-second quantities.
4163 */
4164 int val;
4165 delim = vbar1++;
4166 if (val_end - vbar1 >= 5) {
4167 val = b64tos30(vbar1);
4168 if (val > 0)
4169 txn->cookie_last_date = val << 2;
4170 }
4171 /* look for a second vertical bar */
4172 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4173 if (vbar1 && (val_end - vbar1 > 5)) {
4174 val = b64tos30(vbar1 + 1);
4175 if (val > 0)
4176 txn->cookie_first_date = val << 2;
4177 }
4178 }
4179 }
4180
4181 /* if the cookie has an expiration date and the proxy wants to check
4182 * it, then we do that now. We first check if the cookie is too old,
4183 * then only if it has expired. We detect strict overflow because the
4184 * time resolution here is not great (4 seconds). Cookies with dates
4185 * in the future are ignored if their offset is beyond one day. This
4186 * allows an admin to fix timezone issues without expiring everyone
4187 * and at the same time avoids keeping unwanted side effects for too
4188 * long.
4189 */
4190 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4191 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4192 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4193 txn->flags &= ~TX_CK_MASK;
4194 txn->flags |= TX_CK_OLD;
4195 delim = val_beg; // let's pretend we have not found the cookie
4196 txn->cookie_first_date = 0;
4197 txn->cookie_last_date = 0;
4198 }
4199 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4200 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4201 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4202 txn->flags &= ~TX_CK_MASK;
4203 txn->flags |= TX_CK_EXPIRED;
4204 delim = val_beg; // let's pretend we have not found the cookie
4205 txn->cookie_first_date = 0;
4206 txn->cookie_last_date = 0;
4207 }
4208
4209 /* Here, we'll look for the first running server which supports the cookie.
4210 * This allows to share a same cookie between several servers, for example
4211 * to dedicate backup servers to specific servers only.
4212 * However, to prevent clients from sticking to cookie-less backup server
4213 * when they have incidentely learned an empty cookie, we simply ignore
4214 * empty cookies and mark them as invalid.
4215 * The same behaviour is applied when persistence must be ignored.
4216 */
4217 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4218 srv = NULL;
4219
4220 while (srv) {
4221 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4222 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4223 if ((srv->cur_state != SRV_ST_STOPPED) ||
4224 (s->be->options & PR_O_PERSIST) ||
4225 (s->flags & SF_FORCE_PRST)) {
4226 /* we found the server and we can use it */
4227 txn->flags &= ~TX_CK_MASK;
4228 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4229 s->flags |= SF_DIRECT | SF_ASSIGNED;
4230 s->target = &srv->obj_type;
4231 break;
4232 } else {
4233 /* we found a server, but it's down,
4234 * mark it as such and go on in case
4235 * another one is available.
4236 */
4237 txn->flags &= ~TX_CK_MASK;
4238 txn->flags |= TX_CK_DOWN;
4239 }
4240 }
4241 srv = srv->next;
4242 }
4243
4244 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4245 /* no server matched this cookie or we deliberately skipped it */
4246 txn->flags &= ~TX_CK_MASK;
4247 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4248 txn->flags |= TX_CK_UNUSED;
4249 else
4250 txn->flags |= TX_CK_INVALID;
4251 }
4252
4253 /* depending on the cookie mode, we may have to either :
4254 * - delete the complete cookie if we're in insert+indirect mode, so that
4255 * the server never sees it ;
4256 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004257 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004258 * if we're in cookie prefix mode
4259 */
4260 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4261 int delta; /* negative */
4262
4263 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4264 delta = val_beg - (delim + 1);
4265 val_end += delta;
4266 next += delta;
4267 hdr_end += delta;
4268 del_from = NULL;
4269 preserve_hdr = 1; /* we want to keep this cookie */
4270 }
4271 else if (del_from == NULL &&
4272 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4273 del_from = prev;
4274 }
4275 }
4276 else {
4277 /* This is not our cookie, so we must preserve it. But if we already
4278 * scheduled another cookie for removal, we cannot remove the
4279 * complete header, but we can remove the previous block itself.
4280 */
4281 preserve_hdr = 1;
4282
4283 if (del_from != NULL) {
4284 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4285 if (att_beg >= del_from)
4286 att_beg += delta;
4287 if (att_end >= del_from)
4288 att_end += delta;
4289 val_beg += delta;
4290 val_end += delta;
4291 next += delta;
4292 hdr_end += delta;
4293 prev = del_from;
4294 del_from = NULL;
4295 }
4296 }
4297
4298 /* continue with next cookie on this header line */
4299 att_beg = next;
4300 } /* for each cookie */
4301
4302
4303 /* There are no more cookies on this line.
4304 * We may still have one (or several) marked for deletion at the
4305 * end of the line. We must do this now in two ways :
4306 * - if some cookies must be preserved, we only delete from the
4307 * mark to the end of line ;
4308 * - if nothing needs to be preserved, simply delete the whole header
4309 */
4310 if (del_from) {
4311 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4312 }
4313 if ((hdr_end - hdr_beg) != ctx.value.len) {
4314 if (hdr_beg != hdr_end) {
4315 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004316 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004317 }
4318 else
4319 http_remove_header(htx, &ctx);
4320 }
4321 } /* for each "Cookie header */
4322}
4323
4324/*
4325 * Manage server-side cookies. It can impact performance by about 2% so it is
4326 * desirable to call it only when needed. This function is also used when we
4327 * just need to know if there is a cookie (eg: for check-cache).
4328 */
4329static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4330{
4331 struct session *sess = s->sess;
4332 struct http_txn *txn = s->txn;
4333 struct htx *htx;
4334 struct http_hdr_ctx ctx;
4335 struct server *srv;
4336 char *hdr_beg, *hdr_end;
4337 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004338 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004339
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004340 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004341
4342 ctx.blk = NULL;
4343 while (1) {
4344 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4345 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4346 break;
4347 is_cookie2 = 1;
4348 }
4349
4350 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4351 * <prev> points to the colon.
4352 */
4353 txn->flags |= TX_SCK_PRESENT;
4354
4355 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4356 * check-cache is enabled) and we are not interested in checking
4357 * them. Warning, the cookie capture is declared in the frontend.
4358 */
4359 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4360 break;
4361
4362 /* OK so now we know we have to process this response cookie.
4363 * The format of the Set-Cookie header is slightly different
4364 * from the format of the Cookie header in that it does not
4365 * support the comma as a cookie delimiter (thus the header
4366 * cannot be folded) because the Expires attribute described in
4367 * the original Netscape's spec may contain an unquoted date
4368 * with a comma inside. We have to live with this because
4369 * many browsers don't support Max-Age and some browsers don't
4370 * support quoted strings. However the Set-Cookie2 header is
4371 * clean.
4372 *
4373 * We have to keep multiple pointers in order to support cookie
4374 * removal at the beginning, middle or end of header without
4375 * corrupting the header (in case of set-cookie2). A special
4376 * pointer, <scav> points to the beginning of the set-cookie-av
4377 * fields after the first semi-colon. The <next> pointer points
4378 * either to the end of line (set-cookie) or next unquoted comma
4379 * (set-cookie2). All of these headers are valid :
4380 *
4381 * hdr_beg hdr_end
4382 * | |
4383 * v |
4384 * NAME1 = VALUE 1 ; Secure; Path="/" |
4385 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4386 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4387 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4388 * | | | | | | | |
4389 * | | | | | | | +-> next
4390 * | | | | | | +------------> scav
4391 * | | | | | +--------------> val_end
4392 * | | | | +--------------------> val_beg
4393 * | | | +----------------------> equal
4394 * | | +------------------------> att_end
4395 * | +----------------------------> att_beg
4396 * +------------------------------> prev
4397 * -------------------------------> hdr_beg
4398 */
4399 hdr_beg = ctx.value.ptr;
4400 hdr_end = hdr_beg + ctx.value.len;
4401 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4402
4403 /* Iterate through all cookies on this line */
4404
4405 /* find att_beg */
4406 att_beg = prev;
4407 if (prev > hdr_beg)
4408 att_beg++;
4409
4410 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4411 att_beg++;
4412
4413 /* find att_end : this is the first character after the last non
4414 * space before the equal. It may be equal to hdr_end.
4415 */
4416 equal = att_end = att_beg;
4417
4418 while (equal < hdr_end) {
4419 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4420 break;
4421 if (HTTP_IS_SPHT(*equal++))
4422 continue;
4423 att_end = equal;
4424 }
4425
4426 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4427 * is between <att_beg> and <equal>, both may be identical.
4428 */
4429
4430 /* look for end of cookie if there is an equal sign */
4431 if (equal < hdr_end && *equal == '=') {
4432 /* look for the beginning of the value */
4433 val_beg = equal + 1;
4434 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4435 val_beg++;
4436
4437 /* find the end of the value, respecting quotes */
4438 next = http_find_cookie_value_end(val_beg, hdr_end);
4439
4440 /* make val_end point to the first white space or delimitor after the value */
4441 val_end = next;
4442 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4443 val_end--;
4444 }
4445 else {
4446 /* <equal> points to next comma, semi-colon or EOL */
4447 val_beg = val_end = next = equal;
4448 }
4449
4450 if (next < hdr_end) {
4451 /* Set-Cookie2 supports multiple cookies, and <next> points to
4452 * a colon or semi-colon before the end. So skip all attr-value
4453 * pairs and look for the next comma. For Set-Cookie, since
4454 * commas are permitted in values, skip to the end.
4455 */
4456 if (is_cookie2)
4457 next = http_find_hdr_value_end(next, hdr_end);
4458 else
4459 next = hdr_end;
4460 }
4461
4462 /* Now everything is as on the diagram above */
4463
4464 /* Ignore cookies with no equal sign */
4465 if (equal == val_end)
4466 continue;
4467
4468 /* If there are spaces around the equal sign, we need to
4469 * strip them otherwise we'll get trouble for cookie captures,
4470 * or even for rewrites. Since this happens extremely rarely,
4471 * it does not hurt performance.
4472 */
4473 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4474 int stripped_before = 0;
4475 int stripped_after = 0;
4476
4477 if (att_end != equal) {
4478 memmove(att_end, equal, hdr_end - equal);
4479 stripped_before = (att_end - equal);
4480 equal += stripped_before;
4481 val_beg += stripped_before;
4482 }
4483
4484 if (val_beg > equal + 1) {
4485 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4486 stripped_after = (equal + 1) - val_beg;
4487 val_beg += stripped_after;
4488 stripped_before += stripped_after;
4489 }
4490
4491 val_end += stripped_before;
4492 next += stripped_before;
4493 hdr_end += stripped_before;
4494
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004495 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4496 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004497 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004498 }
4499
4500 /* First, let's see if we want to capture this cookie. We check
4501 * that we don't already have a server side cookie, because we
4502 * can only capture one. Also as an optimisation, we ignore
4503 * cookies shorter than the declared name.
4504 */
4505 if (sess->fe->capture_name != NULL &&
4506 txn->srv_cookie == NULL &&
4507 (val_end - att_beg >= sess->fe->capture_namelen) &&
4508 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4509 int log_len = val_end - att_beg;
4510 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4511 ha_alert("HTTP logging : out of memory.\n");
4512 }
4513 else {
4514 if (log_len > sess->fe->capture_len)
4515 log_len = sess->fe->capture_len;
4516 memcpy(txn->srv_cookie, att_beg, log_len);
4517 txn->srv_cookie[log_len] = 0;
4518 }
4519 }
4520
4521 srv = objt_server(s->target);
4522 /* now check if we need to process it for persistence */
4523 if (!(s->flags & SF_IGNORE_PRST) &&
4524 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4525 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4526 /* assume passive cookie by default */
4527 txn->flags &= ~TX_SCK_MASK;
4528 txn->flags |= TX_SCK_FOUND;
4529
4530 /* If the cookie is in insert mode on a known server, we'll delete
4531 * this occurrence because we'll insert another one later.
4532 * We'll delete it too if the "indirect" option is set and we're in
4533 * a direct access.
4534 */
4535 if (s->be->ck_opts & PR_CK_PSV) {
4536 /* The "preserve" flag was set, we don't want to touch the
4537 * server's cookie.
4538 */
4539 }
4540 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4541 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4542 /* this cookie must be deleted */
4543 if (prev == hdr_beg && next == hdr_end) {
4544 /* whole header */
4545 http_remove_header(htx, &ctx);
4546 /* note: while both invalid now, <next> and <hdr_end>
4547 * are still equal, so the for() will stop as expected.
4548 */
4549 } else {
4550 /* just remove the value */
4551 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4552 next = prev;
4553 hdr_end += delta;
4554 }
4555 txn->flags &= ~TX_SCK_MASK;
4556 txn->flags |= TX_SCK_DELETED;
4557 /* and go on with next cookie */
4558 }
4559 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4560 /* replace bytes val_beg->val_end with the cookie name associated
4561 * with this server since we know it.
4562 */
4563 int sliding, delta;
4564
4565 ctx.value = ist2(val_beg, val_end - val_beg);
4566 ctx.lws_before = ctx.lws_after = 0;
4567 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4568 delta = srv->cklen - (val_end - val_beg);
4569 sliding = (ctx.value.ptr - val_beg);
4570 hdr_beg += sliding;
4571 val_beg += sliding;
4572 next += sliding + delta;
4573 hdr_end += sliding + delta;
4574
4575 txn->flags &= ~TX_SCK_MASK;
4576 txn->flags |= TX_SCK_REPLACED;
4577 }
4578 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4579 /* insert the cookie name associated with this server
4580 * before existing cookie, and insert a delimiter between them..
4581 */
4582 int sliding, delta;
4583 ctx.value = ist2(val_beg, 0);
4584 ctx.lws_before = ctx.lws_after = 0;
4585 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4586 delta = srv->cklen + 1;
4587 sliding = (ctx.value.ptr - val_beg);
4588 hdr_beg += sliding;
4589 val_beg += sliding;
4590 next += sliding + delta;
4591 hdr_end += sliding + delta;
4592
4593 val_beg[srv->cklen] = COOKIE_DELIM;
4594 txn->flags &= ~TX_SCK_MASK;
4595 txn->flags |= TX_SCK_REPLACED;
4596 }
4597 }
4598 /* that's done for this cookie, check the next one on the same
4599 * line when next != hdr_end (only if is_cookie2).
4600 */
4601 }
4602 }
4603}
4604
Christopher Faulet25a02f62018-10-24 12:00:25 +02004605/*
4606 * Parses the Cache-Control and Pragma request header fields to determine if
4607 * the request may be served from the cache and/or if it is cacheable. Updates
4608 * s->txn->flags.
4609 */
4610void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4611{
4612 struct http_txn *txn = s->txn;
4613 struct htx *htx;
4614 int32_t pos;
4615 int pragma_found, cc_found, i;
4616
4617 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4618 return; /* nothing more to do here */
4619
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004620 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004621 pragma_found = cc_found = 0;
4622 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4623 struct htx_blk *blk = htx_get_blk(htx, pos);
4624 enum htx_blk_type type = htx_get_blk_type(blk);
4625 struct ist n, v;
4626
4627 if (type == HTX_BLK_EOH)
4628 break;
4629 if (type != HTX_BLK_HDR)
4630 continue;
4631
4632 n = htx_get_blk_name(htx, blk);
4633 v = htx_get_blk_value(htx, blk);
4634
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004635 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004636 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4637 pragma_found = 1;
4638 continue;
4639 }
4640 }
4641
4642 /* Don't use the cache and don't try to store if we found the
4643 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4646 txn->flags |= TX_CACHE_IGNORE;
4647 continue;
4648 }
4649
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004650 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004651 continue;
4652
4653 /* OK, right now we know we have a cache-control header */
4654 cc_found = 1;
4655 if (!v.len) /* no info */
4656 continue;
4657
4658 i = 0;
4659 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4660 !isspace((unsigned char)*(v.ptr+i)))
4661 i++;
4662
4663 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4664 * values after max-age, max-stale nor min-fresh, we simply don't
4665 * use the cache when they're specified.
4666 */
4667 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4668 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4669 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4670 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4671 txn->flags |= TX_CACHE_IGNORE;
4672 continue;
4673 }
4674
4675 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4676 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4677 continue;
4678 }
4679 }
4680
4681 /* RFC7234#5.4:
4682 * When the Cache-Control header field is also present and
4683 * understood in a request, Pragma is ignored.
4684 * When the Cache-Control header field is not present in a
4685 * request, caches MUST consider the no-cache request
4686 * pragma-directive as having the same effect as if
4687 * "Cache-Control: no-cache" were present.
4688 */
4689 if (!cc_found && pragma_found)
4690 txn->flags |= TX_CACHE_IGNORE;
4691}
4692
4693/*
4694 * Check if response is cacheable or not. Updates s->txn->flags.
4695 */
4696void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4697{
4698 struct http_txn *txn = s->txn;
4699 struct htx *htx;
4700 int32_t pos;
4701 int i;
4702
4703 if (txn->status < 200) {
4704 /* do not try to cache interim responses! */
4705 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4706 return;
4707 }
4708
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004709 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004710 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4711 struct htx_blk *blk = htx_get_blk(htx, pos);
4712 enum htx_blk_type type = htx_get_blk_type(blk);
4713 struct ist n, v;
4714
4715 if (type == HTX_BLK_EOH)
4716 break;
4717 if (type != HTX_BLK_HDR)
4718 continue;
4719
4720 n = htx_get_blk_name(htx, blk);
4721 v = htx_get_blk_value(htx, blk);
4722
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004723 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004724 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4725 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4726 return;
4727 }
4728 }
4729
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004730 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004731 continue;
4732
4733 /* OK, right now we know we have a cache-control header */
4734 if (!v.len) /* no info */
4735 continue;
4736
4737 i = 0;
4738 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4739 !isspace((unsigned char)*(v.ptr+i)))
4740 i++;
4741
4742 /* we have a complete value between v.ptr and (v.ptr+i) */
4743 if (i < v.len && *(v.ptr + i) == '=') {
4744 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4745 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4746 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4747 continue;
4748 }
4749
4750 /* we have something of the form no-cache="set-cookie" */
4751 if ((v.len >= 21) &&
4752 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4753 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4754 txn->flags &= ~TX_CACHE_COOK;
4755 continue;
4756 }
4757
4758 /* OK, so we know that either p2 points to the end of string or to a comma */
4759 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4760 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4761 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4762 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4763 return;
4764 }
4765
4766 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4767 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4768 continue;
4769 }
4770 }
4771}
4772
Christopher Faulet64159df2018-10-24 21:15:35 +02004773/* send a server's name with an outgoing request over an established connection.
4774 * Note: this function is designed to be called once the request has been
4775 * scheduled for being forwarded. This is the reason why the number of forwarded
4776 * bytes have to be adjusted.
4777 */
4778int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4779{
4780 struct htx *htx;
4781 struct http_hdr_ctx ctx;
4782 struct ist hdr;
4783 uint32_t data;
4784
4785 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004786 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004787 data = htx->data;
4788
4789 ctx.blk = NULL;
4790 while (http_find_header(htx, hdr, &ctx, 1))
4791 http_remove_header(htx, &ctx);
4792 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4793
4794 if (co_data(&s->req)) {
4795 if (data >= htx->data)
4796 c_rew(&s->req, data - htx->data);
4797 else
4798 c_adv(&s->req, htx->data - data);
4799 }
4800 return 0;
4801}
4802
Christopher Faulet377c5a52018-10-24 21:21:30 +02004803/*
4804 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4805 * for the current backend.
4806 *
4807 * It is assumed that the request is either a HEAD, GET, or POST and that the
4808 * uri_auth field is valid.
4809 *
4810 * Returns 1 if stats should be provided, otherwise 0.
4811 */
4812static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4813{
4814 struct uri_auth *uri_auth = backend->uri_auth;
4815 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004816 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004817 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004818
4819 if (!uri_auth)
4820 return 0;
4821
4822 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4823 return 0;
4824
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004825 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004826 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004827 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004828
4829 /* check URI size */
4830 if (uri_auth->uri_len > uri.len)
4831 return 0;
4832
4833 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4834 return 0;
4835
4836 return 1;
4837}
4838
4839/* This function prepares an applet to handle the stats. It can deal with the
4840 * "100-continue" expectation, check that admin rules are met for POST requests,
4841 * and program a response message if something was unexpected. It cannot fail
4842 * and always relies on the stats applet to complete the job. It does not touch
4843 * analysers nor counters, which are left to the caller. It does not touch
4844 * s->target which is supposed to already point to the stats applet. The caller
4845 * is expected to have already assigned an appctx to the stream.
4846 */
4847static int htx_handle_stats(struct stream *s, struct channel *req)
4848{
4849 struct stats_admin_rule *stats_admin_rule;
4850 struct stream_interface *si = &s->si[1];
4851 struct session *sess = s->sess;
4852 struct http_txn *txn = s->txn;
4853 struct http_msg *msg = &txn->req;
4854 struct uri_auth *uri_auth = s->be->uri_auth;
4855 const char *h, *lookup, *end;
4856 struct appctx *appctx;
4857 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004858 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004859
4860 appctx = si_appctx(si);
4861 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4862 appctx->st1 = appctx->st2 = 0;
4863 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4864 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4865 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4866 appctx->ctx.stats.flags |= STAT_CHUNKED;
4867
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004868 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004869 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004870 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4871 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004872
4873 for (h = lookup; h <= end - 3; h++) {
4874 if (memcmp(h, ";up", 3) == 0) {
4875 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4876 break;
4877 }
4878 }
4879
4880 if (uri_auth->refresh) {
4881 for (h = lookup; h <= end - 10; h++) {
4882 if (memcmp(h, ";norefresh", 10) == 0) {
4883 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4884 break;
4885 }
4886 }
4887 }
4888
4889 for (h = lookup; h <= end - 4; h++) {
4890 if (memcmp(h, ";csv", 4) == 0) {
4891 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4892 break;
4893 }
4894 }
4895
4896 for (h = lookup; h <= end - 6; h++) {
4897 if (memcmp(h, ";typed", 6) == 0) {
4898 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4899 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4900 break;
4901 }
4902 }
4903
4904 for (h = lookup; h <= end - 8; h++) {
4905 if (memcmp(h, ";st=", 4) == 0) {
4906 int i;
4907 h += 4;
4908 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4909 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4910 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4911 appctx->ctx.stats.st_code = i;
4912 break;
4913 }
4914 }
4915 break;
4916 }
4917 }
4918
4919 appctx->ctx.stats.scope_str = 0;
4920 appctx->ctx.stats.scope_len = 0;
4921 for (h = lookup; h <= end - 8; h++) {
4922 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4923 int itx = 0;
4924 const char *h2;
4925 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4926 const char *err;
4927
4928 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4929 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004930 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4931 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004932 if (*h == ';' || *h == '&' || *h == ' ')
4933 break;
4934 itx++;
4935 h++;
4936 }
4937
4938 if (itx > STAT_SCOPE_TXT_MAXLEN)
4939 itx = STAT_SCOPE_TXT_MAXLEN;
4940 appctx->ctx.stats.scope_len = itx;
4941
4942 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4943 memcpy(scope_txt, h2, itx);
4944 scope_txt[itx] = '\0';
4945 err = invalid_char(scope_txt);
4946 if (err) {
4947 /* bad char in search text => clear scope */
4948 appctx->ctx.stats.scope_str = 0;
4949 appctx->ctx.stats.scope_len = 0;
4950 }
4951 break;
4952 }
4953 }
4954
4955 /* now check whether we have some admin rules for this request */
4956 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4957 int ret = 1;
4958
4959 if (stats_admin_rule->cond) {
4960 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4961 ret = acl_pass(ret);
4962 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4963 ret = !ret;
4964 }
4965
4966 if (ret) {
4967 /* no rule, or the rule matches */
4968 appctx->ctx.stats.flags |= STAT_ADMIN;
4969 break;
4970 }
4971 }
4972
Christopher Faulet5d45e382019-02-27 15:15:23 +01004973 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4974 appctx->st0 = STAT_HTTP_HEAD;
4975 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004976 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004977 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004978 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004979 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004980 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4981 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4982 appctx->st0 = STAT_HTTP_LAST;
4983 }
4984 }
4985 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004986 /* Unsupported method */
4987 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4988 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4989 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004990 }
4991
4992 s->task->nice = -32; /* small boost for HTTP statistics */
4993 return 1;
4994}
4995
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004996void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4997{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004998 struct channel *req = &s->req;
4999 struct channel *res = &s->res;
5000 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005001 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005002 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 struct ist path, location;
5004 unsigned int flags;
5005 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005006
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005007 /*
5008 * Create the location
5009 */
5010 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005013 /* special prefix "/" means don't change URL */
5014 srv = __objt_server(s->target);
5015 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5016 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5017 return;
5018 }
5019
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005020 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005021 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005023 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024 if (!path.ptr)
5025 return;
5026
5027 if (!chunk_memcat(&trash, path.ptr, path.len))
5028 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005030
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005031 /*
5032 * Create the 302 respone
5033 */
5034 htx = htx_from_buf(&res->buf);
5035 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5036 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5037 ist("HTTP/1.1"), ist("302"), ist("Found"));
5038 if (!sl)
5039 goto fail;
5040 sl->info.res.status = 302;
5041 s->txn->status = 302;
5042
5043 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5044 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5045 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5046 !htx_add_header(htx, ist("Location"), location))
5047 goto fail;
5048
5049 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5050 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005052 /*
5053 * Send the message
5054 */
5055 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005056 c_adv(res, data);
5057 res->total += data;
5058
5059 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005060 si_shutr(si);
5061 si_shutw(si);
5062 si->err_type = SI_ET_NONE;
5063 si->state = SI_ST_CLO;
5064
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005065 channel_auto_read(req);
5066 channel_abort(req);
5067 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005068 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005069 channel_auto_read(res);
5070 channel_auto_close(res);
5071
5072 if (!(s->flags & SF_ERR_MASK))
5073 s->flags |= SF_ERR_LOCAL;
5074 if (!(s->flags & SF_FINST_MASK))
5075 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005076
5077 /* FIXME: we should increase a counter of redirects per server and per backend. */
5078 srv_inc_sess_ctr(srv);
5079 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005080 return;
5081
5082 fail:
5083 /* If an error occurred, remove the incomplete HTTP response from the
5084 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005085 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005086}
5087
Christopher Fauletf2824e62018-10-01 12:12:37 +02005088/* This function terminates the request because it was completly analyzed or
5089 * because an error was triggered during the body forwarding.
5090 */
5091static void htx_end_request(struct stream *s)
5092{
5093 struct channel *chn = &s->req;
5094 struct http_txn *txn = s->txn;
5095
5096 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5097 now_ms, __FUNCTION__, s,
5098 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5099 s->req.analysers, s->res.analysers);
5100
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005101 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5102 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005104 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005105 goto end;
5106 }
5107
5108 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5109 return;
5110
5111 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005112 /* No need to read anymore, the request was completely parsed.
5113 * We can shut the read side unless we want to abort_on_close,
5114 * or we have a POST request. The issue with POST requests is
5115 * that some browsers still send a CRLF after the request, and
5116 * this CRLF must be read so that it does not remain in the kernel
5117 * buffers, otherwise a close could cause an RST on some systems
5118 * (eg: Linux).
5119 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005120 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 channel_dont_read(chn);
5122
5123 /* if the server closes the connection, we want to immediately react
5124 * and close the socket to save packets and syscalls.
5125 */
5126 s->si[1].flags |= SI_FL_NOHALF;
5127
5128 /* In any case we've finished parsing the request so we must
5129 * disable Nagle when sending data because 1) we're not going
5130 * to shut this side, and 2) the server is waiting for us to
5131 * send pending data.
5132 */
5133 chn->flags |= CF_NEVER_WAIT;
5134
Christopher Fauletd01ce402019-01-02 17:44:13 +01005135 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5136 /* The server has not finished to respond, so we
5137 * don't want to move in order not to upset it.
5138 */
5139 return;
5140 }
5141
Christopher Fauletf2824e62018-10-01 12:12:37 +02005142 /* When we get here, it means that both the request and the
5143 * response have finished receiving. Depending on the connection
5144 * mode, we'll have to wait for the last bytes to leave in either
5145 * direction, and sometimes for a close to be effective.
5146 */
5147 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5148 /* Tunnel mode will not have any analyser so it needs to
5149 * poll for reads.
5150 */
5151 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005152 if (b_data(&chn->buf))
5153 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005154 txn->req.msg_state = HTTP_MSG_TUNNEL;
5155 }
5156 else {
5157 /* we're not expecting any new data to come for this
5158 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005159 *
5160 * However, there is an exception if the response
5161 * length is undefined. In this case, we need to wait
5162 * the close from the server. The response will be
5163 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005164 */
5165 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5166 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005167 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168
5169 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5170 channel_shutr_now(chn);
5171 channel_shutw_now(chn);
5172 }
5173 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005174 goto check_channel_flags;
5175 }
5176
5177 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5178 http_msg_closing:
5179 /* nothing else to forward, just waiting for the output buffer
5180 * to be empty and for the shutw_now to take effect.
5181 */
5182 if (channel_is_empty(chn)) {
5183 txn->req.msg_state = HTTP_MSG_CLOSED;
5184 goto http_msg_closed;
5185 }
5186 else if (chn->flags & CF_SHUTW) {
5187 txn->req.err_state = txn->req.msg_state;
5188 txn->req.msg_state = HTTP_MSG_ERROR;
5189 goto end;
5190 }
5191 return;
5192 }
5193
5194 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5195 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005196 /* if we don't know whether the server will close, we need to hard close */
5197 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5198 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005199 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005200 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005201 channel_dont_read(chn);
5202 goto end;
5203 }
5204
5205 check_channel_flags:
5206 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5207 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5208 /* if we've just closed an output, let's switch */
5209 txn->req.msg_state = HTTP_MSG_CLOSING;
5210 goto http_msg_closing;
5211 }
5212
5213 end:
5214 chn->analysers &= AN_REQ_FLT_END;
5215 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5216 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5217 channel_auto_close(chn);
5218 channel_auto_read(chn);
5219}
5220
5221
5222/* This function terminates the response because it was completly analyzed or
5223 * because an error was triggered during the body forwarding.
5224 */
5225static void htx_end_response(struct stream *s)
5226{
5227 struct channel *chn = &s->res;
5228 struct http_txn *txn = s->txn;
5229
5230 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5231 now_ms, __FUNCTION__, s,
5232 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5233 s->req.analysers, s->res.analysers);
5234
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005235 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5236 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005237 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005238 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005239 goto end;
5240 }
5241
5242 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5243 return;
5244
5245 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5246 /* In theory, we don't need to read anymore, but we must
5247 * still monitor the server connection for a possible close
5248 * while the request is being uploaded, so we don't disable
5249 * reading.
5250 */
5251 /* channel_dont_read(chn); */
5252
5253 if (txn->req.msg_state < HTTP_MSG_DONE) {
5254 /* The client seems to still be sending data, probably
5255 * because we got an error response during an upload.
5256 * We have the choice of either breaking the connection
5257 * or letting it pass through. Let's do the later.
5258 */
5259 return;
5260 }
5261
5262 /* When we get here, it means that both the request and the
5263 * response have finished receiving. Depending on the connection
5264 * mode, we'll have to wait for the last bytes to leave in either
5265 * direction, and sometimes for a close to be effective.
5266 */
5267 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5268 channel_auto_read(chn);
5269 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005270 if (b_data(&chn->buf))
5271 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005272 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5273 }
5274 else {
5275 /* we're not expecting any new data to come for this
5276 * transaction, so we can close it.
5277 */
5278 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5279 channel_shutr_now(chn);
5280 channel_shutw_now(chn);
5281 }
5282 }
5283 goto check_channel_flags;
5284 }
5285
5286 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5287 http_msg_closing:
5288 /* nothing else to forward, just waiting for the output buffer
5289 * to be empty and for the shutw_now to take effect.
5290 */
5291 if (channel_is_empty(chn)) {
5292 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5293 goto http_msg_closed;
5294 }
5295 else if (chn->flags & CF_SHUTW) {
5296 txn->rsp.err_state = txn->rsp.msg_state;
5297 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005298 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005300 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005301 goto end;
5302 }
5303 return;
5304 }
5305
5306 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5307 http_msg_closed:
5308 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005309 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005310 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005311 goto end;
5312 }
5313
5314 check_channel_flags:
5315 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5316 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5317 /* if we've just closed an output, let's switch */
5318 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5319 goto http_msg_closing;
5320 }
5321
5322 end:
5323 chn->analysers &= AN_RES_FLT_END;
5324 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5325 chn->analysers |= AN_RES_FLT_XFER_DATA;
5326 channel_auto_close(chn);
5327 channel_auto_read(chn);
5328}
5329
Christopher Faulet0f226952018-10-22 09:29:56 +02005330void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5331 int finst, const struct buffer *msg)
5332{
5333 channel_auto_read(si_oc(si));
5334 channel_abort(si_oc(si));
5335 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005336 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005337 channel_auto_close(si_ic(si));
5338 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005339
5340 /* <msg> is an HTX structure. So we copy it in the response's
5341 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005342 if (msg) {
5343 struct channel *chn = si_ic(si);
5344 struct htx *htx;
5345
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005346 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005347 chn->buf.data = msg->data;
5348 memcpy(chn->buf.area, msg->area, msg->data);
5349 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005350 c_adv(chn, htx->data);
5351 chn->total += htx->data;
5352 }
5353 if (!(s->flags & SF_ERR_MASK))
5354 s->flags |= err;
5355 if (!(s->flags & SF_FINST_MASK))
5356 s->flags |= finst;
5357}
5358
5359void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5360{
5361 channel_auto_read(&s->req);
5362 channel_abort(&s->req);
5363 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005364 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5365 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005366
5367 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005368
5369 /* <msg> is an HTX structure. So we copy it in the response's
5370 * channel */
5371 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005372 if (msg) {
5373 struct channel *chn = &s->res;
5374 struct htx *htx;
5375
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005376 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005377 chn->buf.data = msg->data;
5378 memcpy(chn->buf.area, msg->area, msg->data);
5379 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005380 c_adv(chn, htx->data);
5381 chn->total += htx->data;
5382 }
5383
5384 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5385 channel_auto_read(&s->res);
5386 channel_auto_close(&s->res);
5387 channel_shutr_now(&s->res);
5388}
5389
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005390struct buffer *htx_error_message(struct stream *s)
5391{
5392 const int msgnum = http_get_status_idx(s->txn->status);
5393
5394 if (s->be->errmsg[msgnum].area)
5395 return &s->be->errmsg[msgnum];
5396 else if (strm_fe(s)->errmsg[msgnum].area)
5397 return &strm_fe(s)->errmsg[msgnum];
5398 else
5399 return &htx_err_chunks[msgnum];
5400}
5401
5402
Christopher Faulet4a28a532019-03-01 11:19:40 +01005403/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5404 * on success and -1 on error.
5405 */
5406static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5407{
5408 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5409 * then we must send an HTTP/1.1 100 Continue intermediate response.
5410 */
5411 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5412 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5413 struct ist hdr = { .ptr = "Expect", .len = 6 };
5414 struct http_hdr_ctx ctx;
5415
5416 ctx.blk = NULL;
5417 /* Expect is allowed in 1.1, look for it */
5418 if (http_find_header(htx, hdr, &ctx, 0) &&
5419 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5420 if (htx_reply_100_continue(s) == -1)
5421 return -1;
5422 http_remove_header(htx, &ctx);
5423 }
5424 }
5425 return 0;
5426}
5427
Christopher Faulet23a3c792018-11-28 10:01:23 +01005428/* Send a 100-Continue response to the client. It returns 0 on success and -1
5429 * on error. The response channel is updated accordingly.
5430 */
5431static int htx_reply_100_continue(struct stream *s)
5432{
5433 struct channel *res = &s->res;
5434 struct htx *htx = htx_from_buf(&res->buf);
5435 struct htx_sl *sl;
5436 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5437 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5438 size_t data;
5439
5440 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5441 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5442 if (!sl)
5443 goto fail;
5444 sl->info.res.status = 100;
5445
5446 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5447 goto fail;
5448
5449 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005450 c_adv(res, data);
5451 res->total += data;
5452 return 0;
5453
5454 fail:
5455 /* If an error occurred, remove the incomplete HTTP response from the
5456 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005457 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005458 return -1;
5459}
5460
Christopher Faulet12c51e22018-11-28 15:59:42 +01005461
5462/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5463 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5464 * error. The response channel is updated accordingly.
5465 */
5466static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5467{
5468 struct channel *res = &s->res;
5469 struct htx *htx = htx_from_buf(&res->buf);
5470 struct htx_sl *sl;
5471 struct ist code, body;
5472 int status;
5473 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5474 size_t data;
5475
5476 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5477 status = 401;
5478 code = ist("401");
5479 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5480 "You need a valid user and password to access this content.\n"
5481 "</body></html>\n");
5482 }
5483 else {
5484 status = 407;
5485 code = ist("407");
5486 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5487 "You need a valid user and password to access this content.\n"
5488 "</body></html>\n");
5489 }
5490
5491 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5492 ist("HTTP/1.1"), code, ist("Unauthorized"));
5493 if (!sl)
5494 goto fail;
5495 sl->info.res.status = status;
5496 s->txn->status = status;
5497
5498 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5499 goto fail;
5500
5501 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5502 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005503 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5504 goto fail;
5505 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5506 goto fail;
5507 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005508 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005509 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5510 goto fail;
5511
5512 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005513 c_adv(res, data);
5514 res->total += data;
5515
5516 channel_auto_read(&s->req);
5517 channel_abort(&s->req);
5518 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005519 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005520
5521 res->wex = tick_add_ifset(now_ms, res->wto);
5522 channel_auto_read(res);
5523 channel_auto_close(res);
5524 channel_shutr_now(res);
5525 return 0;
5526
5527 fail:
5528 /* If an error occurred, remove the incomplete HTTP response from the
5529 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005530 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005531 return -1;
5532}
5533
Christopher Faulet0f226952018-10-22 09:29:56 +02005534/*
5535 * Capture headers from message <htx> according to header list <cap_hdr>, and
5536 * fill the <cap> pointers appropriately.
5537 */
5538static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5539{
5540 struct cap_hdr *h;
5541 int32_t pos;
5542
5543 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5544 struct htx_blk *blk = htx_get_blk(htx, pos);
5545 enum htx_blk_type type = htx_get_blk_type(blk);
5546 struct ist n, v;
5547
5548 if (type == HTX_BLK_EOH)
5549 break;
5550 if (type != HTX_BLK_HDR)
5551 continue;
5552
5553 n = htx_get_blk_name(htx, blk);
5554
5555 for (h = cap_hdr; h; h = h->next) {
5556 if (h->namelen && (h->namelen == n.len) &&
5557 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5558 if (cap[h->index] == NULL)
5559 cap[h->index] =
5560 pool_alloc(h->pool);
5561
5562 if (cap[h->index] == NULL) {
5563 ha_alert("HTTP capture : out of memory.\n");
5564 break;
5565 }
5566
5567 v = htx_get_blk_value(htx, blk);
5568 if (v.len > h->len)
5569 v.len = h->len;
5570
5571 memcpy(cap[h->index], v.ptr, v.len);
5572 cap[h->index][v.len]=0;
5573 }
5574 }
5575 }
5576}
5577
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005578/* Delete a value in a header between delimiters <from> and <next>. The header
5579 * itself is delimited by <start> and <end> pointers. The number of characters
5580 * displaced is returned, and the pointer to the first delimiter is updated if
5581 * required. The function tries as much as possible to respect the following
5582 * principles :
5583 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5584 * in which case <next> is simply removed
5585 * - set exactly one space character after the new first delimiter, unless there
5586 * are not enough characters in the block being moved to do so.
5587 * - remove unneeded spaces before the previous delimiter and after the new
5588 * one.
5589 *
5590 * It is the caller's responsibility to ensure that :
5591 * - <from> points to a valid delimiter or <start> ;
5592 * - <next> points to a valid delimiter or <end> ;
5593 * - there are non-space chars before <from>.
5594 */
5595static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5596{
5597 char *prev = *from;
5598
5599 if (prev == start) {
5600 /* We're removing the first value. eat the semicolon, if <next>
5601 * is lower than <end> */
5602 if (next < end)
5603 next++;
5604
5605 while (next < end && HTTP_IS_SPHT(*next))
5606 next++;
5607 }
5608 else {
5609 /* Remove useless spaces before the old delimiter. */
5610 while (HTTP_IS_SPHT(*(prev-1)))
5611 prev--;
5612 *from = prev;
5613
5614 /* copy the delimiter and if possible a space if we're
5615 * not at the end of the line.
5616 */
5617 if (next < end) {
5618 *prev++ = *next++;
5619 if (prev + 1 < next)
5620 *prev++ = ' ';
5621 while (next < end && HTTP_IS_SPHT(*next))
5622 next++;
5623 }
5624 }
5625 memmove(prev, next, end - next);
5626 return (prev - next);
5627}
5628
Christopher Faulet0f226952018-10-22 09:29:56 +02005629
5630/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005631 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005632 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005634{
5635 struct ist dst = ist2(str, 0);
5636
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005638 goto end;
5639 if (dst.len + 1 > len)
5640 goto end;
5641 dst.ptr[dst.len++] = ' ';
5642
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 goto end;
5645 if (dst.len + 1 > len)
5646 goto end;
5647 dst.ptr[dst.len++] = ' ';
5648
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005649 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005650 end:
5651 return dst.len;
5652}
5653
Christopher Fauletf0523542018-10-24 11:06:58 +02005654/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005655 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005656 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005657static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005658{
5659 struct ist dst = ist2(str, 0);
5660
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005661 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005662 goto end;
5663 if (dst.len + 1 > len)
5664 goto end;
5665 dst.ptr[dst.len++] = ' ';
5666
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005667 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005668 goto end;
5669 if (dst.len + 1 > len)
5670 goto end;
5671 dst.ptr[dst.len++] = ' ';
5672
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005673 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005674 end:
5675 return dst.len;
5676}
5677
5678
Christopher Faulet0f226952018-10-22 09:29:56 +02005679/*
5680 * Print a debug line with a start line.
5681 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005682static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005683{
5684 struct session *sess = strm_sess(s);
5685 int max;
5686
5687 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5688 dir,
5689 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5690 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5691
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005692 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005693 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005694 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005695 trash.area[trash.data++] = ' ';
5696
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005697 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005698 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 trash.area[trash.data++] = ' ';
5701
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005702 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005703 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 trash.area[trash.data++] = '\n';
5706
5707 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5708}
5709
5710/*
5711 * Print a debug line with a header.
5712 */
5713static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5714{
5715 struct session *sess = strm_sess(s);
5716 int max;
5717
5718 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5719 dir,
5720 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5721 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5722
5723 max = n.len;
5724 UBOUND(max, trash.size - trash.data - 3);
5725 chunk_memcat(&trash, n.ptr, max);
5726 trash.area[trash.data++] = ':';
5727 trash.area[trash.data++] = ' ';
5728
5729 max = v.len;
5730 UBOUND(max, trash.size - trash.data - 1);
5731 chunk_memcat(&trash, v.ptr, max);
5732 trash.area[trash.data++] = '\n';
5733
5734 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5735}
5736
5737
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005738__attribute__((constructor))
5739static void __htx_protocol_init(void)
5740{
5741}
5742
5743
5744/*
5745 * Local variables:
5746 * c-indent-level: 8
5747 * c-basic-offset: 8
5748 * End:
5749 */