blob: d8363a23da056ab328976f2943a657b86995fbe4 [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) {
1493 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494 goto abort_keep_alive;
1495
Olivier Houcharda254a372019-04-05 15:30:12 +02001496 if (si_b->flags & SI_FL_L7_RETRY) {
1497 /* If we arrive here, then CF_READ_ERROR was
1498 * set by si_cs_recv() because we matched a
1499 * status, overwise it would have removed
1500 * the SI_FL_L7_RETRY flag, so it's ok not
1501 * to check s->be->retry_type.
1502 */
1503 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1504 return 0;
1505 }
1506
Olivier Houcharda798bf52019-03-08 18:52:00 +01001507 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001509 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001510 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511 }
1512
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513 rep->analysers &= AN_RES_FLT_END;
1514 txn->status = 502;
1515
1516 /* Check to see if the server refused the early data.
1517 * If so, just send a 425
1518 */
1519 if (objt_cs(s->si[1].end)) {
1520 struct connection *conn = objt_cs(s->si[1].end)->conn;
1521
1522 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1523 txn->status = 425;
1524 }
1525
1526 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001527 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528
1529 if (!(s->flags & SF_ERR_MASK))
1530 s->flags |= SF_ERR_SRVCL;
1531 if (!(s->flags & SF_FINST_MASK))
1532 s->flags |= SF_FINST_H;
1533 return 0;
1534 }
1535
Christopher Faulet9768c262018-10-22 09:34:31 +02001536 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001538 if ((si_b->flags & SI_FL_L7_RETRY) &&
1539 (s->be->retry_type & PR_RE_TIMEOUT)) {
1540 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1541 return 0;
1542 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001543 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001545 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001546 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 }
1548
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 rep->analysers &= AN_RES_FLT_END;
1550 txn->status = 504;
1551 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001552 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553
1554 if (!(s->flags & SF_ERR_MASK))
1555 s->flags |= SF_ERR_SRVTO;
1556 if (!(s->flags & SF_FINST_MASK))
1557 s->flags |= SF_FINST_H;
1558 return 0;
1559 }
1560
Christopher Faulet9768c262018-10-22 09:34:31 +02001561 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001563 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1564 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001566 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001567
1568 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001570 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001571
1572 if (!(s->flags & SF_ERR_MASK))
1573 s->flags |= SF_ERR_CLICL;
1574 if (!(s->flags & SF_FINST_MASK))
1575 s->flags |= SF_FINST_H;
1576
1577 /* process_stream() will take care of the error */
1578 return 0;
1579 }
1580
Christopher Faulet9768c262018-10-22 09:34:31 +02001581 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001582 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001583 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584 goto abort_keep_alive;
1585
Olivier Houcharda254a372019-04-05 15:30:12 +02001586 if ((si_b->flags & SI_FL_L7_RETRY) &&
1587 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1588 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1589 return 0;
1590 }
1591
Olivier Houcharda798bf52019-03-08 18:52:00 +01001592 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001594 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001595 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596 }
1597
Christopher Faulete0768eb2018-10-03 16:38:02 +02001598 rep->analysers &= AN_RES_FLT_END;
1599 txn->status = 502;
1600 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001601 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602
1603 if (!(s->flags & SF_ERR_MASK))
1604 s->flags |= SF_ERR_SRVCL;
1605 if (!(s->flags & SF_FINST_MASK))
1606 s->flags |= SF_FINST_H;
1607 return 0;
1608 }
1609
Christopher Faulet9768c262018-10-22 09:34:31 +02001610 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001611 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001612 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001613 goto abort_keep_alive;
1614
Olivier Houcharda798bf52019-03-08 18:52:00 +01001615 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001616 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001617
1618 if (!(s->flags & SF_ERR_MASK))
1619 s->flags |= SF_ERR_CLICL;
1620 if (!(s->flags & SF_FINST_MASK))
1621 s->flags |= SF_FINST_H;
1622
1623 /* process_stream() will take care of the error */
1624 return 0;
1625 }
1626
1627 channel_dont_close(rep);
1628 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1629 return 0;
1630 }
1631
1632 /* More interesting part now : we know that we have a complete
1633 * response which at least looks like HTTP. We have an indicator
1634 * of each header's length, so we can parse them quickly.
1635 */
1636
Christopher Faulet9768c262018-10-22 09:34:31 +02001637 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001638 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639
Christopher Faulet9768c262018-10-22 09:34:31 +02001640 /* 0: we might have to print this header in debug mode */
1641 if (unlikely((global.mode & MODE_DEBUG) &&
1642 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1643 int32_t pos;
1644
Christopher Faulet03599112018-11-27 11:21:21 +01001645 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001646
1647 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1648 struct htx_blk *blk = htx_get_blk(htx, pos);
1649 enum htx_blk_type type = htx_get_blk_type(blk);
1650
1651 if (type == HTX_BLK_EOH)
1652 break;
1653 if (type != HTX_BLK_HDR)
1654 continue;
1655
1656 htx_debug_hdr("srvhdr", s,
1657 htx_get_blk_name(htx, blk),
1658 htx_get_blk_value(htx, blk));
1659 }
1660 }
1661
Christopher Faulet03599112018-11-27 11:21:21 +01001662 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001663 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001664 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001665 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001666 if (sl->flags & HTX_SL_F_XFER_LEN) {
1667 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001668 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001669 if (sl->flags & HTX_SL_F_BODYLESS)
1670 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001671 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001672
1673 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001674 if (n < 1 || n > 5)
1675 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001676
Christopher Faulete0768eb2018-10-03 16:38:02 +02001677 /* when the client triggers a 4xx from the server, it's most often due
1678 * to a missing object or permission. These events should be tracked
1679 * because if they happen often, it may indicate a brute force or a
1680 * vulnerability scan.
1681 */
1682 if (n == 4)
1683 stream_inc_http_err_ctr(s);
1684
1685 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001686 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687
Christopher Faulete0768eb2018-10-03 16:38:02 +02001688 /* Adjust server's health based on status code. Note: status codes 501
1689 * and 505 are triggered on demand by client request, so we must not
1690 * count them as server failures.
1691 */
1692 if (objt_server(s->target)) {
1693 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001694 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001696 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697 }
1698
1699 /*
1700 * We may be facing a 100-continue response, or any other informational
1701 * 1xx response which is non-final, in which case this is not the right
1702 * response, and we're waiting for the next one. Let's allow this response
1703 * to go to the client and wait for the next one. There's an exception for
1704 * 101 which is used later in the code to switch protocols.
1705 */
1706 if (txn->status < 200 &&
1707 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001708 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001709 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001710 msg->msg_state = HTTP_MSG_RPBEFORE;
1711 txn->status = 0;
1712 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001713 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001714 }
1715
1716 /*
1717 * 2: check for cacheability.
1718 */
1719
1720 switch (txn->status) {
1721 case 200:
1722 case 203:
1723 case 204:
1724 case 206:
1725 case 300:
1726 case 301:
1727 case 404:
1728 case 405:
1729 case 410:
1730 case 414:
1731 case 501:
1732 break;
1733 default:
1734 /* RFC7231#6.1:
1735 * Responses with status codes that are defined as
1736 * cacheable by default (e.g., 200, 203, 204, 206,
1737 * 300, 301, 404, 405, 410, 414, and 501 in this
1738 * specification) can be reused by a cache with
1739 * heuristic expiration unless otherwise indicated
1740 * by the method definition or explicit cache
1741 * controls [RFC7234]; all other status codes are
1742 * not cacheable by default.
1743 */
1744 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1745 break;
1746 }
1747
1748 /*
1749 * 3: we may need to capture headers
1750 */
1751 s->logs.logwait &= ~LW_RESP;
1752 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001753 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001754
Christopher Faulet9768c262018-10-22 09:34:31 +02001755 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001756 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1757 txn->status == 101)) {
1758 /* Either we've established an explicit tunnel, or we're
1759 * switching the protocol. In both cases, we're very unlikely
1760 * to understand the next protocols. We have to switch to tunnel
1761 * mode, so that we transfer the request and responses then let
1762 * this protocol pass unmodified. When we later implement specific
1763 * parsers for such protocols, we'll want to check the Upgrade
1764 * header which contains information about that protocol for
1765 * responses with status 101 (eg: see RFC2817 about TLS).
1766 */
1767 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001768 }
1769
Christopher Faulet61608322018-11-23 16:23:45 +01001770 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1771 * 407 (Proxy-Authenticate) responses and set the connection to private
1772 */
1773 srv_conn = cs_conn(objt_cs(s->si[1].end));
1774 if (srv_conn) {
1775 struct ist hdr;
1776 struct http_hdr_ctx ctx;
1777
1778 if (txn->status == 401)
1779 hdr = ist("WWW-Authenticate");
1780 else if (txn->status == 407)
1781 hdr = ist("Proxy-Authenticate");
1782 else
1783 goto end;
1784
1785 ctx.blk = NULL;
1786 while (http_find_header(htx, hdr, &ctx, 0)) {
1787 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1788 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1789 srv_conn->flags |= CO_FL_PRIVATE;
1790 }
1791 }
1792
1793 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001794 /* we want to have the response time before we start processing it */
1795 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1796
1797 /* end of job, return OK */
1798 rep->analysers &= ~an_bit;
1799 rep->analyse_exp = TICK_ETERNITY;
1800 channel_auto_close(rep);
1801 return 1;
1802
Christopher Faulet47365272018-10-31 17:40:50 +01001803 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001804 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001805 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001806 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001807 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001808 }
1809 txn->status = 502;
1810 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001811 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001812 rep->analysers &= AN_RES_FLT_END;
1813
1814 if (!(s->flags & SF_ERR_MASK))
1815 s->flags |= SF_ERR_PRXCOND;
1816 if (!(s->flags & SF_FINST_MASK))
1817 s->flags |= SF_FINST_H;
1818 return 0;
1819
Christopher Faulete0768eb2018-10-03 16:38:02 +02001820 abort_keep_alive:
1821 /* A keep-alive request to the server failed on a network error.
1822 * The client is required to retry. We need to close without returning
1823 * any other information so that the client retries.
1824 */
1825 txn->status = 0;
1826 rep->analysers &= AN_RES_FLT_END;
1827 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001828 s->logs.logwait = 0;
1829 s->logs.level = 0;
1830 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001831 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001832 return 0;
1833}
1834
1835/* This function performs all the processing enabled for the current response.
1836 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1837 * and updates s->res.analysers. It might make sense to explode it into several
1838 * other functions. It works like process_request (see indications above).
1839 */
1840int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1841{
1842 struct session *sess = s->sess;
1843 struct http_txn *txn = s->txn;
1844 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001845 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001846 struct proxy *cur_proxy;
1847 struct cond_wordlist *wl;
1848 enum rule_result ret = HTTP_RULE_RES_CONT;
1849
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001850 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1851 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001852
Christopher Faulete0768eb2018-10-03 16:38:02 +02001853 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1854 now_ms, __FUNCTION__,
1855 s,
1856 rep,
1857 rep->rex, rep->wex,
1858 rep->flags,
1859 ci_data(rep),
1860 rep->analysers);
1861
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001862 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001863
1864 /* The stats applet needs to adjust the Connection header but we don't
1865 * apply any filter there.
1866 */
1867 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1868 rep->analysers &= ~an_bit;
1869 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001870 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 }
1872
1873 /*
1874 * We will have to evaluate the filters.
1875 * As opposed to version 1.2, now they will be evaluated in the
1876 * filters order and not in the header order. This means that
1877 * each filter has to be validated among all headers.
1878 *
1879 * Filters are tried with ->be first, then with ->fe if it is
1880 * different from ->be.
1881 *
1882 * Maybe we are in resume condiion. In this case I choose the
1883 * "struct proxy" which contains the rule list matching the resume
1884 * pointer. If none of theses "struct proxy" match, I initialise
1885 * the process with the first one.
1886 *
1887 * In fact, I check only correspondance betwwen the current list
1888 * pointer and the ->fe rule list. If it doesn't match, I initialize
1889 * the loop with the ->be.
1890 */
1891 if (s->current_rule_list == &sess->fe->http_res_rules)
1892 cur_proxy = sess->fe;
1893 else
1894 cur_proxy = s->be;
1895 while (1) {
1896 struct proxy *rule_set = cur_proxy;
1897
1898 /* evaluate http-response rules */
1899 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001900 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001901
1902 if (ret == HTTP_RULE_RES_BADREQ)
1903 goto return_srv_prx_502;
1904
1905 if (ret == HTTP_RULE_RES_DONE) {
1906 rep->analysers &= ~an_bit;
1907 rep->analyse_exp = TICK_ETERNITY;
1908 return 1;
1909 }
1910 }
1911
1912 /* we need to be called again. */
1913 if (ret == HTTP_RULE_RES_YIELD) {
1914 channel_dont_close(rep);
1915 return 0;
1916 }
1917
1918 /* try headers filters */
1919 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001920 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1921 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001922 }
1923
1924 /* has the response been denied ? */
1925 if (txn->flags & TX_SVDENY) {
1926 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001927 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001928
Olivier Houcharda798bf52019-03-08 18:52:00 +01001929 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1930 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001931 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001932 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933 goto return_srv_prx_502;
1934 }
1935
1936 /* add response headers from the rule sets in the same order */
1937 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001938 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001939 if (txn->status < 200 && txn->status != 101)
1940 break;
1941 if (wl->cond) {
1942 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1943 ret = acl_pass(ret);
1944 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1945 ret = !ret;
1946 if (!ret)
1947 continue;
1948 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001949
1950 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1951 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001952 goto return_bad_resp;
1953 }
1954
1955 /* check whether we're already working on the frontend */
1956 if (cur_proxy == sess->fe)
1957 break;
1958 cur_proxy = sess->fe;
1959 }
1960
1961 /* After this point, this anayzer can't return yield, so we can
1962 * remove the bit corresponding to this analyzer from the list.
1963 *
1964 * Note that the intermediate returns and goto found previously
1965 * reset the analyzers.
1966 */
1967 rep->analysers &= ~an_bit;
1968 rep->analyse_exp = TICK_ETERNITY;
1969
1970 /* OK that's all we can do for 1xx responses */
1971 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001972 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001973
1974 /*
1975 * Now check for a server cookie.
1976 */
1977 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001978 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001979
1980 /*
1981 * Check for cache-control or pragma headers if required.
1982 */
1983 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1984 check_response_for_cacheability(s, rep);
1985
1986 /*
1987 * Add server cookie in the response if needed
1988 */
1989 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1990 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1991 (!(s->flags & SF_DIRECT) ||
1992 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1993 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1994 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1995 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1996 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1997 !(s->flags & SF_IGNORE_PRST)) {
1998 /* the server is known, it's not the one the client requested, or the
1999 * cookie's last seen date needs to be refreshed. We have to
2000 * insert a set-cookie here, except if we want to insert only on POST
2001 * requests and this one isn't. Note that servers which don't have cookies
2002 * (eg: some backup servers) will return a full cookie removal request.
2003 */
2004 if (!objt_server(s->target)->cookie) {
2005 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002006 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002007 s->be->cookie_name);
2008 }
2009 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002010 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002011
2012 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2013 /* emit last_date, which is mandatory */
2014 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2015 s30tob64((date.tv_sec+3) >> 2,
2016 trash.area + trash.data);
2017 trash.data += 5;
2018
2019 if (s->be->cookie_maxlife) {
2020 /* emit first_date, which is either the original one or
2021 * the current date.
2022 */
2023 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2024 s30tob64(txn->cookie_first_date ?
2025 txn->cookie_first_date >> 2 :
2026 (date.tv_sec+3) >> 2,
2027 trash.area + trash.data);
2028 trash.data += 5;
2029 }
2030 }
2031 chunk_appendf(&trash, "; path=/");
2032 }
2033
2034 if (s->be->cookie_domain)
2035 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2036
2037 if (s->be->ck_opts & PR_CK_HTTPONLY)
2038 chunk_appendf(&trash, "; HttpOnly");
2039
2040 if (s->be->ck_opts & PR_CK_SECURE)
2041 chunk_appendf(&trash, "; Secure");
2042
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002043 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002044 goto return_bad_resp;
2045
2046 txn->flags &= ~TX_SCK_MASK;
2047 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2048 /* the server did not change, only the date was updated */
2049 txn->flags |= TX_SCK_UPDATED;
2050 else
2051 txn->flags |= TX_SCK_INSERTED;
2052
2053 /* Here, we will tell an eventual cache on the client side that we don't
2054 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2055 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2056 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2057 */
2058 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2059
2060 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2061
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002063 goto return_bad_resp;
2064 }
2065 }
2066
2067 /*
2068 * Check if result will be cacheable with a cookie.
2069 * We'll block the response if security checks have caught
2070 * nasty things such as a cacheable cookie.
2071 */
2072 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2073 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2074 (s->be->options & PR_O_CHK_CACHE)) {
2075 /* we're in presence of a cacheable response containing
2076 * a set-cookie header. We'll block it as requested by
2077 * the 'checkcache' option, and send an alert.
2078 */
2079 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002080 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002081
Olivier Houcharda798bf52019-03-08 18:52:00 +01002082 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2083 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002084 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002085 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002086
2087 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2088 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2089 send_log(s->be, LOG_ALERT,
2090 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2091 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2092 goto return_srv_prx_502;
2093 }
2094
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002095 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002096 /* Always enter in the body analyzer */
2097 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2098 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2099
2100 /* if the user wants to log as soon as possible, without counting
2101 * bytes from the server, then this is the right moment. We have
2102 * to temporarily assign bytes_out to log what we currently have.
2103 */
2104 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2105 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002106 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002107 s->do_log(s);
2108 s->logs.bytes_out = 0;
2109 }
2110 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002111
2112 return_bad_resp:
2113 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002114 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002115 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002116 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002117 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002118
2119 return_srv_prx_502:
2120 rep->analysers &= AN_RES_FLT_END;
2121 txn->status = 502;
2122 s->logs.t_data = -1; /* was not a valid response */
2123 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002124 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002125 if (!(s->flags & SF_ERR_MASK))
2126 s->flags |= SF_ERR_PRXCOND;
2127 if (!(s->flags & SF_FINST_MASK))
2128 s->flags |= SF_FINST_H;
2129 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002130}
2131
2132/* This function is an analyser which forwards response body (including chunk
2133 * sizes if any). It is called as soon as we must forward, even if we forward
2134 * zero byte. The only situation where it must not be called is when we're in
2135 * tunnel mode and we want to forward till the close. It's used both to forward
2136 * remaining data and to resync after end of body. It expects the msg_state to
2137 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2138 * read more data, or 1 once we can go on with next request or end the stream.
2139 *
2140 * It is capable of compressing response data both in content-length mode and
2141 * in chunked mode. The state machines follows different flows depending on
2142 * whether content-length and chunked modes are used, since there are no
2143 * trailers in content-length :
2144 *
2145 * chk-mode cl-mode
2146 * ,----- BODY -----.
2147 * / \
2148 * V size > 0 V chk-mode
2149 * .--> SIZE -------------> DATA -------------> CRLF
2150 * | | size == 0 | last byte |
2151 * | v final crlf v inspected |
2152 * | TRAILERS -----------> DONE |
2153 * | |
2154 * `----------------------------------------------'
2155 *
2156 * Compression only happens in the DATA state, and must be flushed in final
2157 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2158 * is performed at once on final states for all bytes parsed, or when leaving
2159 * on missing data.
2160 */
2161int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2162{
2163 struct session *sess = s->sess;
2164 struct http_txn *txn = s->txn;
2165 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002166 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002167 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002168
2169 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2170 now_ms, __FUNCTION__,
2171 s,
2172 res,
2173 res->rex, res->wex,
2174 res->flags,
2175 ci_data(res),
2176 res->analysers);
2177
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002178 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002179
2180 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002181 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002182 /* Output closed while we were sending data. We must abort and
2183 * wake the other side up.
2184 */
2185 msg->err_state = msg->msg_state;
2186 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002187 htx_end_response(s);
2188 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002189 return 1;
2190 }
2191
Christopher Faulet9768c262018-10-22 09:34:31 +02002192 if (msg->msg_state == HTTP_MSG_BODY)
2193 msg->msg_state = HTTP_MSG_DATA;
2194
Christopher Faulete0768eb2018-10-03 16:38:02 +02002195 /* in most states, we should abort in case of early close */
2196 channel_auto_close(res);
2197
Christopher Faulete0768eb2018-10-03 16:38:02 +02002198 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002199 if (res->to_forward == CHN_INFINITE_FORWARD) {
2200 if (res->flags & (CF_SHUTR|CF_EOI)) {
2201 msg->msg_state = HTTP_MSG_DONE;
2202 res->to_forward = 0;
2203 goto done;
2204 }
2205 }
2206 else {
2207 /* We can't process the buffer's contents yet */
2208 res->flags |= CF_WAKE_WRITE;
2209 goto missing_data_or_waiting;
2210 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 }
2212
Christopher Faulet9768c262018-10-22 09:34:31 +02002213 if (msg->msg_state >= HTTP_MSG_DONE)
2214 goto done;
2215
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002216 /* Forward input data. We get it by removing all outgoing data not
2217 * forwarded yet from HTX data size. If there are some data filters, we
2218 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002219 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002220 if (HAS_RSP_DATA_FILTERS(s)) {
2221 ret = flt_http_payload(s, msg, htx->data);
2222 if (ret < 0)
2223 goto return_bad_res;
2224 c_adv(res, ret);
2225 if (htx->data != co_data(res) || htx->extra)
2226 goto missing_data_or_waiting;
2227 }
2228 else {
2229 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002230 if (msg->flags & HTTP_MSGF_XFER_LEN)
2231 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002232 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002233
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002234 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2235 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2236 msg->msg_state = HTTP_MSG_TUNNEL;
2237 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002238 }
2239
Christopher Faulet9768c262018-10-22 09:34:31 +02002240 /* Check if the end-of-message is reached and if so, switch the message
2241 * in HTTP_MSG_DONE state.
2242 */
2243 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2244 goto missing_data_or_waiting;
2245
2246 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002247 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002248
2249 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002250 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002251 channel_dont_close(res);
2252
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002253 if (HAS_RSP_DATA_FILTERS(s)) {
2254 ret = flt_http_end(s, msg);
2255 if (ret <= 0) {
2256 if (!ret)
2257 goto missing_data_or_waiting;
2258 goto return_bad_res;
2259 }
2260 }
2261
Christopher Fauletf2824e62018-10-01 12:12:37 +02002262 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002264 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2266 if (res->flags & CF_SHUTW) {
2267 /* response errors are most likely due to the
2268 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002269 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002270 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002271 goto return_bad_res;
2272 }
2273 return 1;
2274 }
2275 return 0;
2276
2277 missing_data_or_waiting:
2278 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002279 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280
Christopher Faulet47365272018-10-31 17:40:50 +01002281 if (htx->flags & HTX_FL_PARSING_ERROR)
2282 goto return_bad_res;
2283
Christopher Faulete0768eb2018-10-03 16:38:02 +02002284 /* stop waiting for data if the input is closed before the end. If the
2285 * client side was already closed, it means that the client has aborted,
2286 * so we don't want to count this as a server abort. Otherwise it's a
2287 * server abort.
2288 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002289 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002291 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002292 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002293 if (htx_is_empty(htx))
2294 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295 }
2296
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 /* When TE: chunked is used, we need to get there again to parse
2298 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002299 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2300 * are filters registered on the stream, we don't want to forward a
2301 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002303 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002304 channel_dont_close(res);
2305
2306 /* We know that more data are expected, but we couldn't send more that
2307 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2308 * system knows it must not set a PUSH on this first part. Interactive
2309 * modes are already handled by the stream sock layer. We must not do
2310 * this in content-length mode because it could present the MSG_MORE
2311 * flag with the last block of forwarded data, which would cause an
2312 * additional delay to be observed by the receiver.
2313 */
2314 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2315 res->flags |= CF_EXPECT_MORE;
2316
2317 /* the stream handler will take care of timeouts and errors */
2318 return 0;
2319
Christopher Faulet93e02d82019-03-08 14:18:50 +01002320 return_srv_abort:
2321 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2322 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002323 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002324 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2325 if (!(s->flags & SF_ERR_MASK))
2326 s->flags |= SF_ERR_SRVCL;
2327 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 return_cli_abort:
2330 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2331 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002333 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2334 if (!(s->flags & SF_ERR_MASK))
2335 s->flags |= SF_ERR_CLICL;
2336 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337
Christopher Faulet93e02d82019-03-08 14:18:50 +01002338 return_bad_res:
2339 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2340 if (objt_server(s->target)) {
2341 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2342 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2343 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002344 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002345 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002346
Christopher Faulet93e02d82019-03-08 14:18:50 +01002347 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002348 txn->rsp.err_state = txn->rsp.msg_state;
2349 txn->rsp.msg_state = HTTP_MSG_ERROR;
2350 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002351 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002352 res->analysers &= AN_RES_FLT_END;
2353 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 +02002354 if (!(s->flags & SF_FINST_MASK))
2355 s->flags |= SF_FINST_D;
2356 return 0;
2357}
2358
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002360 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002361 * as too large a request to build a valid response.
2362 */
2363int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2364{
Christopher Faulet99daf282018-11-28 22:58:13 +01002365 struct channel *req = &s->req;
2366 struct channel *res = &s->res;
2367 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002368 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 struct ist status, reason, location;
2371 unsigned int flags;
2372 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373
2374 chunk = alloc_trash_chunk();
2375 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002376 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002377
Christopher Faulet99daf282018-11-28 22:58:13 +01002378 /*
2379 * Create the location
2380 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002381 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002383 case REDIRECT_TYPE_SCHEME: {
2384 struct http_hdr_ctx ctx;
2385 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386
Christopher Faulet99daf282018-11-28 22:58:13 +01002387 host = ist("");
2388 ctx.blk = NULL;
2389 if (http_find_header(htx, ist("Host"), &ctx, 0))
2390 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002391
Christopher Faulet99daf282018-11-28 22:58:13 +01002392 sl = http_find_stline(htx);
2393 path = http_get_path(htx_sl_req_uri(sl));
2394 /* build message using path */
2395 if (path.ptr) {
2396 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2397 int qs = 0;
2398 while (qs < path.len) {
2399 if (*(path.ptr + qs) == '?') {
2400 path.len = qs;
2401 break;
2402 }
2403 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405 }
2406 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 else
2408 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409
Christopher Faulet99daf282018-11-28 22:58:13 +01002410 if (rule->rdr_str) { /* this is an old "redirect" rule */
2411 /* add scheme */
2412 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2413 goto fail;
2414 }
2415 else {
2416 /* add scheme with executing log format */
2417 chunk->data += build_logline(s, chunk->area + chunk->data,
2418 chunk->size - chunk->data,
2419 &rule->rdr_fmt);
2420 }
2421 /* add "://" + host + path */
2422 if (!chunk_memcat(chunk, "://", 3) ||
2423 !chunk_memcat(chunk, host.ptr, host.len) ||
2424 !chunk_memcat(chunk, path.ptr, path.len))
2425 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 /* append a slash at the end of the location if needed and missing */
2428 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2429 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2430 if (chunk->data + 1 >= chunk->size)
2431 goto fail;
2432 chunk->area[chunk->data++] = '/';
2433 }
2434 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002436
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 case REDIRECT_TYPE_PREFIX: {
2438 struct ist path;
2439
2440 sl = http_find_stline(htx);
2441 path = http_get_path(htx_sl_req_uri(sl));
2442 /* build message using path */
2443 if (path.ptr) {
2444 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2445 int qs = 0;
2446 while (qs < path.len) {
2447 if (*(path.ptr + qs) == '?') {
2448 path.len = qs;
2449 break;
2450 }
2451 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453 }
2454 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 else
2456 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002457
Christopher Faulet99daf282018-11-28 22:58:13 +01002458 if (rule->rdr_str) { /* this is an old "redirect" rule */
2459 /* add prefix. Note that if prefix == "/", we don't want to
2460 * add anything, otherwise it makes it hard for the user to
2461 * configure a self-redirection.
2462 */
2463 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2464 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2465 goto fail;
2466 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002467 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002468 else {
2469 /* add prefix with executing log format */
2470 chunk->data += build_logline(s, chunk->area + chunk->data,
2471 chunk->size - chunk->data,
2472 &rule->rdr_fmt);
2473 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002474
Christopher Faulet99daf282018-11-28 22:58:13 +01002475 /* add path */
2476 if (!chunk_memcat(chunk, path.ptr, path.len))
2477 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002478
Christopher Faulet99daf282018-11-28 22:58:13 +01002479 /* append a slash at the end of the location if needed and missing */
2480 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2481 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2482 if (chunk->data + 1 >= chunk->size)
2483 goto fail;
2484 chunk->area[chunk->data++] = '/';
2485 }
2486 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002487 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002488 case REDIRECT_TYPE_LOCATION:
2489 default:
2490 if (rule->rdr_str) { /* this is an old "redirect" rule */
2491 /* add location */
2492 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2493 goto fail;
2494 }
2495 else {
2496 /* add location with executing log format */
2497 chunk->data += build_logline(s, chunk->area + chunk->data,
2498 chunk->size - chunk->data,
2499 &rule->rdr_fmt);
2500 }
2501 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002503 location = ist2(chunk->area, chunk->data);
2504
2505 /*
2506 * Create the 30x response
2507 */
2508 switch (rule->code) {
2509 case 308:
2510 status = ist("308");
2511 reason = ist("Permanent Redirect");
2512 break;
2513 case 307:
2514 status = ist("307");
2515 reason = ist("Temporary Redirect");
2516 break;
2517 case 303:
2518 status = ist("303");
2519 reason = ist("See Other");
2520 break;
2521 case 301:
2522 status = ist("301");
2523 reason = ist("Moved Permanently");
2524 break;
2525 case 302:
2526 default:
2527 status = ist("302");
2528 reason = ist("Found");
2529 break;
2530 }
2531
2532 htx = htx_from_buf(&res->buf);
2533 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2534 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2535 if (!sl)
2536 goto fail;
2537 sl->info.res.status = rule->code;
2538 s->txn->status = rule->code;
2539
2540 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2541 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2542 !htx_add_header(htx, ist("Location"), location))
2543 goto fail;
2544
2545 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2546 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2547 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002548 }
2549
2550 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002551 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2552 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002553 }
2554
Christopher Faulet99daf282018-11-28 22:58:13 +01002555 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2556 goto fail;
2557
Christopher Fauletf2824e62018-10-01 12:12:37 +02002558 /* let's log the request time */
2559 s->logs.tv_request = now;
2560
Christopher Faulet99daf282018-11-28 22:58:13 +01002561 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002562 c_adv(res, data);
2563 res->total += data;
2564
2565 channel_auto_read(req);
2566 channel_abort(req);
2567 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002568 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002569
2570 res->wex = tick_add_ifset(now_ms, res->wto);
2571 channel_auto_read(res);
2572 channel_auto_close(res);
2573 channel_shutr_now(res);
2574
2575 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002576
2577 if (!(s->flags & SF_ERR_MASK))
2578 s->flags |= SF_ERR_LOCAL;
2579 if (!(s->flags & SF_FINST_MASK))
2580 s->flags |= SF_FINST_R;
2581
Christopher Faulet99daf282018-11-28 22:58:13 +01002582 free_trash_chunk(chunk);
2583 return 1;
2584
2585 fail:
2586 /* If an error occurred, remove the incomplete HTTP response from the
2587 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002588 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002589 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002590 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591}
2592
Christopher Faulet72333522018-10-24 11:25:02 +02002593int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2594 struct ist name, const char *str, struct my_regex *re, int action)
2595{
2596 struct http_hdr_ctx ctx;
2597 struct buffer *output = get_trash_chunk();
2598
2599 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2600 ctx.blk = NULL;
2601 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2602 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2603 continue;
2604
2605 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2606 if (output->data == -1)
2607 return -1;
2608 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2609 return -1;
2610 }
2611 return 0;
2612}
2613
2614static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2615 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2616{
2617 struct buffer *replace;
2618 int ret = -1;
2619
2620 replace = alloc_trash_chunk();
2621 if (!replace)
2622 goto leave;
2623
2624 replace->data = build_logline(s, replace->area, replace->size, fmt);
2625 if (replace->data >= replace->size - 1)
2626 goto leave;
2627
2628 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2629
2630 leave:
2631 free_trash_chunk(replace);
2632 return ret;
2633}
2634
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002635
2636/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2637 * on success and -1 on error. The response channel is updated accordingly.
2638 */
2639static int htx_reply_103_early_hints(struct channel *res)
2640{
2641 struct htx *htx = htx_from_buf(&res->buf);
2642 size_t data;
2643
2644 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2645 /* If an error occurred during an Early-hint rule,
2646 * remove the incomplete HTTP 103 response from the
2647 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002648 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002649 return -1;
2650 }
2651
2652 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002653 c_adv(res, data);
2654 res->total += data;
2655 return 0;
2656}
2657
Christopher Faulet6eb92892018-11-15 16:39:29 +01002658/*
2659 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2660 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 * If <early_hints> is 0, it is starts a new response by adding the start
2662 * line. If an error occurred -1 is returned. On success 0 is returned. The
2663 * channel is not updated here. It must be done calling the function
2664 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002665 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002666static 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 +01002667{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002668 struct channel *res = &s->res;
2669 struct htx *htx = htx_from_buf(&res->buf);
2670 struct buffer *value = alloc_trash_chunk();
2671
Christopher Faulet6eb92892018-11-15 16:39:29 +01002672 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002673 struct htx_sl *sl;
2674 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2675 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2676
2677 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2678 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2679 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002680 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002682 }
2683
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002684 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2685 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002686 goto fail;
2687
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002688 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002689 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002690
2691 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 /* If an error occurred during an Early-hint rule, remove the incomplete
2693 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002694 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 free_trash_chunk(value);
2696 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002697}
2698
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002699/* This function executes one of the set-{method,path,query,uri} actions. It
2700 * takes the string from the variable 'replace' with length 'len', then modifies
2701 * the relevant part of the request line accordingly. Then it updates various
2702 * pointers to the next elements which were moved, and the total buffer length.
2703 * It finds the action to be performed in p[2], previously filled by function
2704 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2705 * error, though this can be revisited when this code is finally exploited.
2706 *
2707 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2708 * query string and 3 to replace uri.
2709 *
2710 * In query string case, the mark question '?' must be set at the start of the
2711 * string by the caller, event if the replacement query string is empty.
2712 */
2713int htx_req_replace_stline(int action, const char *replace, int len,
2714 struct proxy *px, struct stream *s)
2715{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002716 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002717
2718 switch (action) {
2719 case 0: // method
2720 if (!http_replace_req_meth(htx, ist2(replace, len)))
2721 return -1;
2722 break;
2723
2724 case 1: // path
2725 if (!http_replace_req_path(htx, ist2(replace, len)))
2726 return -1;
2727 break;
2728
2729 case 2: // query
2730 if (!http_replace_req_query(htx, ist2(replace, len)))
2731 return -1;
2732 break;
2733
2734 case 3: // uri
2735 if (!http_replace_req_uri(htx, ist2(replace, len)))
2736 return -1;
2737 break;
2738
2739 default:
2740 return -1;
2741 }
2742 return 0;
2743}
2744
2745/* This function replace the HTTP status code and the associated message. The
2746 * variable <status> contains the new status code. This function never fails.
2747 */
2748void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2749{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002750 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002751 char *res;
2752
2753 chunk_reset(&trash);
2754 res = ultoa_o(status, trash.area, trash.size);
2755 trash.data = res - trash.area;
2756
2757 /* Do we have a custom reason format string? */
2758 if (reason == NULL)
2759 reason = http_get_reason(status);
2760
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002761 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002762 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2763}
2764
Christopher Faulet3e964192018-10-24 11:39:23 +02002765/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2766 * transaction <txn>. Returns the verdict of the first rule that prevents
2767 * further processing of the request (auth, deny, ...), and defaults to
2768 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2769 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2770 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2771 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2772 * status.
2773 */
2774static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2775 struct stream *s, int *deny_status)
2776{
2777 struct session *sess = strm_sess(s);
2778 struct http_txn *txn = s->txn;
2779 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002780 struct act_rule *rule;
2781 struct http_hdr_ctx ctx;
2782 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002783 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2784 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002785 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002786
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002787 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002788
2789 /* If "the current_rule_list" match the executed rule list, we are in
2790 * resume condition. If a resume is needed it is always in the action
2791 * and never in the ACL or converters. In this case, we initialise the
2792 * current rule, and go to the action execution point.
2793 */
2794 if (s->current_rule) {
2795 rule = s->current_rule;
2796 s->current_rule = NULL;
2797 if (s->current_rule_list == rules)
2798 goto resume_execution;
2799 }
2800 s->current_rule_list = rules;
2801
2802 list_for_each_entry(rule, rules, list) {
2803 /* check optional condition */
2804 if (rule->cond) {
2805 int ret;
2806
2807 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2808 ret = acl_pass(ret);
2809
2810 if (rule->cond->pol == ACL_COND_UNLESS)
2811 ret = !ret;
2812
2813 if (!ret) /* condition not matched */
2814 continue;
2815 }
2816
2817 act_flags |= ACT_FLAG_FIRST;
2818 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002819 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2820 early_hints = 0;
2821 if (htx_reply_103_early_hints(&s->res) == -1) {
2822 rule_ret = HTTP_RULE_RES_BADREQ;
2823 goto end;
2824 }
2825 }
2826
Christopher Faulet3e964192018-10-24 11:39:23 +02002827 switch (rule->action) {
2828 case ACT_ACTION_ALLOW:
2829 rule_ret = HTTP_RULE_RES_STOP;
2830 goto end;
2831
2832 case ACT_ACTION_DENY:
2833 if (deny_status)
2834 *deny_status = rule->deny_status;
2835 rule_ret = HTTP_RULE_RES_DENY;
2836 goto end;
2837
2838 case ACT_HTTP_REQ_TARPIT:
2839 txn->flags |= TX_CLTARPIT;
2840 if (deny_status)
2841 *deny_status = rule->deny_status;
2842 rule_ret = HTTP_RULE_RES_DENY;
2843 goto end;
2844
2845 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002846 /* Auth might be performed on regular http-req rules as well as on stats */
2847 auth_realm = rule->arg.auth.realm;
2848 if (!auth_realm) {
2849 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2850 auth_realm = STATS_DEFAULT_REALM;
2851 else
2852 auth_realm = px->id;
2853 }
2854 /* send 401/407 depending on whether we use a proxy or not. We still
2855 * count one error, because normal browsing won't significantly
2856 * increase the counter but brute force attempts will.
2857 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002858 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002859 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2860 rule_ret = HTTP_RULE_RES_BADREQ;
2861 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 goto end;
2863
2864 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002865 rule_ret = HTTP_RULE_RES_DONE;
2866 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2867 rule_ret = HTTP_RULE_RES_BADREQ;
2868 goto end;
2869
2870 case ACT_HTTP_SET_NICE:
2871 s->task->nice = rule->arg.nice;
2872 break;
2873
2874 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002875 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002876 break;
2877
2878 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002879 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002880 break;
2881
2882 case ACT_HTTP_SET_LOGL:
2883 s->logs.level = rule->arg.loglevel;
2884 break;
2885
2886 case ACT_HTTP_REPLACE_HDR:
2887 case ACT_HTTP_REPLACE_VAL:
2888 if (htx_transform_header(s, &s->req, htx,
2889 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2890 &rule->arg.hdr_add.fmt,
2891 &rule->arg.hdr_add.re, rule->action)) {
2892 rule_ret = HTTP_RULE_RES_BADREQ;
2893 goto end;
2894 }
2895 break;
2896
2897 case ACT_HTTP_DEL_HDR:
2898 /* remove all occurrences of the header */
2899 ctx.blk = NULL;
2900 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2901 http_remove_header(htx, &ctx);
2902 break;
2903
2904 case ACT_HTTP_SET_HDR:
2905 case ACT_HTTP_ADD_HDR: {
2906 /* The scope of the trash buffer must be limited to this function. The
2907 * build_logline() function can execute a lot of other function which
2908 * can use the trash buffer. So for limiting the scope of this global
2909 * buffer, we build first the header value using build_logline, and
2910 * after we store the header name.
2911 */
2912 struct buffer *replace;
2913 struct ist n, v;
2914
2915 replace = alloc_trash_chunk();
2916 if (!replace) {
2917 rule_ret = HTTP_RULE_RES_BADREQ;
2918 goto end;
2919 }
2920
2921 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2922 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2923 v = ist2(replace->area, replace->data);
2924
2925 if (rule->action == ACT_HTTP_SET_HDR) {
2926 /* remove all occurrences of the header */
2927 ctx.blk = NULL;
2928 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2929 http_remove_header(htx, &ctx);
2930 }
2931
2932 if (!http_add_header(htx, n, v)) {
2933 static unsigned char rate_limit = 0;
2934
2935 if ((rate_limit++ & 255) == 0) {
2936 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);
2937 }
2938
Olivier Houcharda798bf52019-03-08 18:52:00 +01002939 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002940 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002941 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002943 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 }
2945 free_trash_chunk(replace);
2946 break;
2947 }
2948
2949 case ACT_HTTP_DEL_ACL:
2950 case ACT_HTTP_DEL_MAP: {
2951 struct pat_ref *ref;
2952 struct buffer *key;
2953
2954 /* collect reference */
2955 ref = pat_ref_lookup(rule->arg.map.ref);
2956 if (!ref)
2957 continue;
2958
2959 /* allocate key */
2960 key = alloc_trash_chunk();
2961 if (!key) {
2962 rule_ret = HTTP_RULE_RES_BADREQ;
2963 goto end;
2964 }
2965
2966 /* collect key */
2967 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2968 key->area[key->data] = '\0';
2969
2970 /* perform update */
2971 /* returned code: 1=ok, 0=ko */
2972 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2973 pat_ref_delete(ref, key->area);
2974 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2975
2976 free_trash_chunk(key);
2977 break;
2978 }
2979
2980 case ACT_HTTP_ADD_ACL: {
2981 struct pat_ref *ref;
2982 struct buffer *key;
2983
2984 /* collect reference */
2985 ref = pat_ref_lookup(rule->arg.map.ref);
2986 if (!ref)
2987 continue;
2988
2989 /* allocate key */
2990 key = alloc_trash_chunk();
2991 if (!key) {
2992 rule_ret = HTTP_RULE_RES_BADREQ;
2993 goto end;
2994 }
2995
2996 /* collect key */
2997 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2998 key->area[key->data] = '\0';
2999
3000 /* perform update */
3001 /* add entry only if it does not already exist */
3002 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3003 if (pat_ref_find_elt(ref, key->area) == NULL)
3004 pat_ref_add(ref, key->area, NULL, NULL);
3005 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3006
3007 free_trash_chunk(key);
3008 break;
3009 }
3010
3011 case ACT_HTTP_SET_MAP: {
3012 struct pat_ref *ref;
3013 struct buffer *key, *value;
3014
3015 /* collect reference */
3016 ref = pat_ref_lookup(rule->arg.map.ref);
3017 if (!ref)
3018 continue;
3019
3020 /* allocate key */
3021 key = alloc_trash_chunk();
3022 if (!key) {
3023 rule_ret = HTTP_RULE_RES_BADREQ;
3024 goto end;
3025 }
3026
3027 /* allocate value */
3028 value = alloc_trash_chunk();
3029 if (!value) {
3030 free_trash_chunk(key);
3031 rule_ret = HTTP_RULE_RES_BADREQ;
3032 goto end;
3033 }
3034
3035 /* collect key */
3036 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3037 key->area[key->data] = '\0';
3038
3039 /* collect value */
3040 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3041 value->area[value->data] = '\0';
3042
3043 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003044 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003045 if (pat_ref_find_elt(ref, key->area) != NULL)
3046 /* update entry if it exists */
3047 pat_ref_set(ref, key->area, value->area, NULL);
3048 else
3049 /* insert a new entry */
3050 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003051 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003052 free_trash_chunk(key);
3053 free_trash_chunk(value);
3054 break;
3055 }
3056
3057 case ACT_HTTP_EARLY_HINT:
3058 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3059 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003060 early_hints = htx_add_early_hint_header(s, early_hints,
3061 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003062 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003063 if (early_hints == -1) {
3064 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003065 goto end;
3066 }
3067 break;
3068
3069 case ACT_CUSTOM:
3070 if ((s->req.flags & CF_READ_ERROR) ||
3071 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003072 (px->options & PR_O_ABRT_CLOSE)))
3073 act_flags |= ACT_FLAG_FINAL;
3074
3075 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3076 case ACT_RET_ERR:
3077 case ACT_RET_CONT:
3078 break;
3079 case ACT_RET_STOP:
3080 rule_ret = HTTP_RULE_RES_DONE;
3081 goto end;
3082 case ACT_RET_YIELD:
3083 s->current_rule = rule;
3084 rule_ret = HTTP_RULE_RES_YIELD;
3085 goto end;
3086 }
3087 break;
3088
3089 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3090 /* Note: only the first valid tracking parameter of each
3091 * applies.
3092 */
3093
3094 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3095 struct stktable *t;
3096 struct stksess *ts;
3097 struct stktable_key *key;
3098 void *ptr1, *ptr2;
3099
3100 t = rule->arg.trk_ctr.table.t;
3101 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3102 rule->arg.trk_ctr.expr, NULL);
3103
3104 if (key && (ts = stktable_get_entry(t, key))) {
3105 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3106
3107 /* let's count a new HTTP request as it's the first time we do it */
3108 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3109 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3110 if (ptr1 || ptr2) {
3111 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3112
3113 if (ptr1)
3114 stktable_data_cast(ptr1, http_req_cnt)++;
3115
3116 if (ptr2)
3117 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3118 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3119
3120 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3121
3122 /* If data was modified, we need to touch to re-schedule sync */
3123 stktable_touch_local(t, ts, 0);
3124 }
3125
3126 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3127 if (sess->fe != s->be)
3128 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3129 }
3130 }
3131 break;
3132
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003133 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003134 default:
3135 break;
3136 }
3137 }
3138
3139 end:
3140 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003141 if (htx_reply_103_early_hints(&s->res) == -1)
3142 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003143 }
3144
3145 /* we reached the end of the rules, nothing to report */
3146 return rule_ret;
3147}
3148
3149/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3150 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3151 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3152 * is returned, the process can continue the evaluation of next rule list. If
3153 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3154 * is returned, it means the operation could not be processed and a server error
3155 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3156 * deny rule. If *YIELD is returned, the caller must call again the function
3157 * with the same context.
3158 */
3159static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3160 struct stream *s)
3161{
3162 struct session *sess = strm_sess(s);
3163 struct http_txn *txn = s->txn;
3164 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003165 struct act_rule *rule;
3166 struct http_hdr_ctx ctx;
3167 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3168 int act_flags = 0;
3169
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003170 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003171
3172 /* If "the current_rule_list" match the executed rule list, we are in
3173 * resume condition. If a resume is needed it is always in the action
3174 * and never in the ACL or converters. In this case, we initialise the
3175 * current rule, and go to the action execution point.
3176 */
3177 if (s->current_rule) {
3178 rule = s->current_rule;
3179 s->current_rule = NULL;
3180 if (s->current_rule_list == rules)
3181 goto resume_execution;
3182 }
3183 s->current_rule_list = rules;
3184
3185 list_for_each_entry(rule, rules, list) {
3186 /* check optional condition */
3187 if (rule->cond) {
3188 int ret;
3189
3190 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3191 ret = acl_pass(ret);
3192
3193 if (rule->cond->pol == ACL_COND_UNLESS)
3194 ret = !ret;
3195
3196 if (!ret) /* condition not matched */
3197 continue;
3198 }
3199
3200 act_flags |= ACT_FLAG_FIRST;
3201resume_execution:
3202 switch (rule->action) {
3203 case ACT_ACTION_ALLOW:
3204 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3205 goto end;
3206
3207 case ACT_ACTION_DENY:
3208 txn->flags |= TX_SVDENY;
3209 rule_ret = HTTP_RULE_RES_STOP;
3210 goto end;
3211
3212 case ACT_HTTP_SET_NICE:
3213 s->task->nice = rule->arg.nice;
3214 break;
3215
3216 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003217 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003218 break;
3219
3220 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003221 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 break;
3223
3224 case ACT_HTTP_SET_LOGL:
3225 s->logs.level = rule->arg.loglevel;
3226 break;
3227
3228 case ACT_HTTP_REPLACE_HDR:
3229 case ACT_HTTP_REPLACE_VAL:
3230 if (htx_transform_header(s, &s->res, htx,
3231 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3232 &rule->arg.hdr_add.fmt,
3233 &rule->arg.hdr_add.re, rule->action)) {
3234 rule_ret = HTTP_RULE_RES_BADREQ;
3235 goto end;
3236 }
3237 break;
3238
3239 case ACT_HTTP_DEL_HDR:
3240 /* remove all occurrences of the header */
3241 ctx.blk = NULL;
3242 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3243 http_remove_header(htx, &ctx);
3244 break;
3245
3246 case ACT_HTTP_SET_HDR:
3247 case ACT_HTTP_ADD_HDR: {
3248 struct buffer *replace;
3249 struct ist n, v;
3250
3251 replace = alloc_trash_chunk();
3252 if (!replace) {
3253 rule_ret = HTTP_RULE_RES_BADREQ;
3254 goto end;
3255 }
3256
3257 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3258 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3259 v = ist2(replace->area, replace->data);
3260
3261 if (rule->action == ACT_HTTP_SET_HDR) {
3262 /* remove all occurrences of the header */
3263 ctx.blk = NULL;
3264 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3265 http_remove_header(htx, &ctx);
3266 }
3267
3268 if (!http_add_header(htx, n, v)) {
3269 static unsigned char rate_limit = 0;
3270
3271 if ((rate_limit++ & 255) == 0) {
3272 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);
3273 }
3274
Olivier Houcharda798bf52019-03-08 18:52:00 +01003275 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003276 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003277 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003278 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 }
3283 free_trash_chunk(replace);
3284 break;
3285 }
3286
3287 case ACT_HTTP_DEL_ACL:
3288 case ACT_HTTP_DEL_MAP: {
3289 struct pat_ref *ref;
3290 struct buffer *key;
3291
3292 /* collect reference */
3293 ref = pat_ref_lookup(rule->arg.map.ref);
3294 if (!ref)
3295 continue;
3296
3297 /* allocate key */
3298 key = alloc_trash_chunk();
3299 if (!key) {
3300 rule_ret = HTTP_RULE_RES_BADREQ;
3301 goto end;
3302 }
3303
3304 /* collect key */
3305 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3306 key->area[key->data] = '\0';
3307
3308 /* perform update */
3309 /* returned code: 1=ok, 0=ko */
3310 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3311 pat_ref_delete(ref, key->area);
3312 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3313
3314 free_trash_chunk(key);
3315 break;
3316 }
3317
3318 case ACT_HTTP_ADD_ACL: {
3319 struct pat_ref *ref;
3320 struct buffer *key;
3321
3322 /* collect reference */
3323 ref = pat_ref_lookup(rule->arg.map.ref);
3324 if (!ref)
3325 continue;
3326
3327 /* allocate key */
3328 key = alloc_trash_chunk();
3329 if (!key) {
3330 rule_ret = HTTP_RULE_RES_BADREQ;
3331 goto end;
3332 }
3333
3334 /* collect key */
3335 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3336 key->area[key->data] = '\0';
3337
3338 /* perform update */
3339 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003340 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003341 if (pat_ref_find_elt(ref, key->area) == NULL)
3342 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003343 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003344 free_trash_chunk(key);
3345 break;
3346 }
3347
3348 case ACT_HTTP_SET_MAP: {
3349 struct pat_ref *ref;
3350 struct buffer *key, *value;
3351
3352 /* collect reference */
3353 ref = pat_ref_lookup(rule->arg.map.ref);
3354 if (!ref)
3355 continue;
3356
3357 /* allocate key */
3358 key = alloc_trash_chunk();
3359 if (!key) {
3360 rule_ret = HTTP_RULE_RES_BADREQ;
3361 goto end;
3362 }
3363
3364 /* allocate value */
3365 value = alloc_trash_chunk();
3366 if (!value) {
3367 free_trash_chunk(key);
3368 rule_ret = HTTP_RULE_RES_BADREQ;
3369 goto end;
3370 }
3371
3372 /* collect key */
3373 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3374 key->area[key->data] = '\0';
3375
3376 /* collect value */
3377 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3378 value->area[value->data] = '\0';
3379
3380 /* perform update */
3381 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3382 if (pat_ref_find_elt(ref, key->area) != NULL)
3383 /* update entry if it exists */
3384 pat_ref_set(ref, key->area, value->area, NULL);
3385 else
3386 /* insert a new entry */
3387 pat_ref_add(ref, key->area, value->area, NULL);
3388 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3389 free_trash_chunk(key);
3390 free_trash_chunk(value);
3391 break;
3392 }
3393
3394 case ACT_HTTP_REDIR:
3395 rule_ret = HTTP_RULE_RES_DONE;
3396 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3397 rule_ret = HTTP_RULE_RES_BADREQ;
3398 goto end;
3399
3400 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3401 /* Note: only the first valid tracking parameter of each
3402 * applies.
3403 */
3404 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3405 struct stktable *t;
3406 struct stksess *ts;
3407 struct stktable_key *key;
3408 void *ptr;
3409
3410 t = rule->arg.trk_ctr.table.t;
3411 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3412 rule->arg.trk_ctr.expr, NULL);
3413
3414 if (key && (ts = stktable_get_entry(t, key))) {
3415 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3416
3417 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3418
3419 /* let's count a new HTTP request as it's the first time we do it */
3420 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3421 if (ptr)
3422 stktable_data_cast(ptr, http_req_cnt)++;
3423
3424 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3425 if (ptr)
3426 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3427 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3428
3429 /* When the client triggers a 4xx from the server, it's most often due
3430 * to a missing object or permission. These events should be tracked
3431 * because if they happen often, it may indicate a brute force or a
3432 * vulnerability scan. Normally this is done when receiving the response
3433 * but here we're tracking after this ought to have been done so we have
3434 * to do it on purpose.
3435 */
3436 if ((unsigned)(txn->status - 400) < 100) {
3437 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3438 if (ptr)
3439 stktable_data_cast(ptr, http_err_cnt)++;
3440
3441 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3442 if (ptr)
3443 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3444 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3445 }
3446
3447 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3448
3449 /* If data was modified, we need to touch to re-schedule sync */
3450 stktable_touch_local(t, ts, 0);
3451
3452 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3453 if (sess->fe != s->be)
3454 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3455 }
3456 }
3457 break;
3458
3459 case ACT_CUSTOM:
3460 if ((s->req.flags & CF_READ_ERROR) ||
3461 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003462 (px->options & PR_O_ABRT_CLOSE)))
3463 act_flags |= ACT_FLAG_FINAL;
3464
3465 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3466 case ACT_RET_ERR:
3467 case ACT_RET_CONT:
3468 break;
3469 case ACT_RET_STOP:
3470 rule_ret = HTTP_RULE_RES_STOP;
3471 goto end;
3472 case ACT_RET_YIELD:
3473 s->current_rule = rule;
3474 rule_ret = HTTP_RULE_RES_YIELD;
3475 goto end;
3476 }
3477 break;
3478
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003479 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003480 default:
3481 break;
3482 }
3483 }
3484
3485 end:
3486 /* we reached the end of the rules, nothing to report */
3487 return rule_ret;
3488}
3489
Christopher Faulet33640082018-10-24 11:53:01 +02003490/* Iterate the same filter through all request headers.
3491 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3492 * Since it can manage the switch to another backend, it updates the per-proxy
3493 * DENY stats.
3494 */
3495static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3496{
3497 struct http_txn *txn = s->txn;
3498 struct htx *htx;
3499 struct buffer *hdr = get_trash_chunk();
3500 int32_t pos;
3501
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003502 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003503
3504 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3505 struct htx_blk *blk = htx_get_blk(htx, pos);
3506 enum htx_blk_type type;
3507 struct ist n, v;
3508
3509 next_hdr:
3510 type = htx_get_blk_type(blk);
3511 if (type == HTX_BLK_EOH)
3512 break;
3513 if (type != HTX_BLK_HDR)
3514 continue;
3515
3516 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3517 return 1;
3518 else if (unlikely(txn->flags & TX_CLALLOW) &&
3519 (exp->action == ACT_ALLOW ||
3520 exp->action == ACT_DENY ||
3521 exp->action == ACT_TARPIT))
3522 return 0;
3523
3524 n = htx_get_blk_name(htx, blk);
3525 v = htx_get_blk_value(htx, blk);
3526
Christopher Faulet02e771a2019-02-26 15:36:05 +01003527 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003528 hdr->area[hdr->data++] = ':';
3529 hdr->area[hdr->data++] = ' ';
3530 chunk_memcat(hdr, v.ptr, v.len);
3531
3532 /* Now we have one header in <hdr> */
3533
3534 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3535 struct http_hdr_ctx ctx;
3536 int len;
3537
3538 switch (exp->action) {
3539 case ACT_ALLOW:
3540 txn->flags |= TX_CLALLOW;
3541 goto end;
3542
3543 case ACT_DENY:
3544 txn->flags |= TX_CLDENY;
3545 goto end;
3546
3547 case ACT_TARPIT:
3548 txn->flags |= TX_CLTARPIT;
3549 goto end;
3550
3551 case ACT_REPLACE:
3552 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3553 if (len < 0)
3554 return -1;
3555
3556 http_parse_header(ist2(trash.area, len), &n, &v);
3557 ctx.blk = blk;
3558 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003559 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003560 if (!http_replace_header(htx, &ctx, n, v))
3561 return -1;
3562 if (!ctx.blk)
3563 goto end;
3564 pos = htx_get_blk_pos(htx, blk);
3565 break;
3566
3567 case ACT_REMOVE:
3568 ctx.blk = blk;
3569 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003570 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003571 if (!http_remove_header(htx, &ctx))
3572 return -1;
3573 if (!ctx.blk)
3574 goto end;
3575 pos = htx_get_blk_pos(htx, blk);
3576 goto next_hdr;
3577
3578 }
3579 }
3580 }
3581 end:
3582 return 0;
3583}
3584
3585/* Apply the filter to the request line.
3586 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3587 * or -1 if a replacement resulted in an invalid request line.
3588 * Since it can manage the switch to another backend, it updates the per-proxy
3589 * DENY stats.
3590 */
3591static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3592{
3593 struct http_txn *txn = s->txn;
3594 struct htx *htx;
3595 struct buffer *reqline = get_trash_chunk();
3596 int done;
3597
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003598 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003599
3600 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3601 return 1;
3602 else if (unlikely(txn->flags & TX_CLALLOW) &&
3603 (exp->action == ACT_ALLOW ||
3604 exp->action == ACT_DENY ||
3605 exp->action == ACT_TARPIT))
3606 return 0;
3607 else if (exp->action == ACT_REMOVE)
3608 return 0;
3609
3610 done = 0;
3611
3612 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3613
3614 /* Now we have the request line between cur_ptr and cur_end */
3615 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003616 struct htx_sl *sl = http_find_stline(htx);
3617 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003618 int len;
3619
3620 switch (exp->action) {
3621 case ACT_ALLOW:
3622 txn->flags |= TX_CLALLOW;
3623 done = 1;
3624 break;
3625
3626 case ACT_DENY:
3627 txn->flags |= TX_CLDENY;
3628 done = 1;
3629 break;
3630
3631 case ACT_TARPIT:
3632 txn->flags |= TX_CLTARPIT;
3633 done = 1;
3634 break;
3635
3636 case ACT_REPLACE:
3637 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3638 if (len < 0)
3639 return -1;
3640
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003641 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3642 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3643 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003644 return -1;
3645 done = 1;
3646 break;
3647 }
3648 }
3649 return done;
3650}
3651
3652/*
3653 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3654 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3655 * unparsable request. Since it can manage the switch to another backend, it
3656 * updates the per-proxy DENY stats.
3657 */
3658static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3659{
3660 struct session *sess = s->sess;
3661 struct http_txn *txn = s->txn;
3662 struct hdr_exp *exp;
3663
3664 for (exp = px->req_exp; exp; exp = exp->next) {
3665 int ret;
3666
3667 /*
3668 * The interleaving of transformations and verdicts
3669 * makes it difficult to decide to continue or stop
3670 * the evaluation.
3671 */
3672
3673 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3674 break;
3675
3676 if ((txn->flags & TX_CLALLOW) &&
3677 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3678 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3679 continue;
3680
3681 /* if this filter had a condition, evaluate it now and skip to
3682 * next filter if the condition does not match.
3683 */
3684 if (exp->cond) {
3685 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3686 ret = acl_pass(ret);
3687 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3688 ret = !ret;
3689
3690 if (!ret)
3691 continue;
3692 }
3693
3694 /* Apply the filter to the request line. */
3695 ret = htx_apply_filter_to_req_line(s, req, exp);
3696 if (unlikely(ret < 0))
3697 return -1;
3698
3699 if (likely(ret == 0)) {
3700 /* The filter did not match the request, it can be
3701 * iterated through all headers.
3702 */
3703 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3704 return -1;
3705 }
3706 }
3707 return 0;
3708}
3709
3710/* Iterate the same filter through all response headers contained in <res>.
3711 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3712 */
3713static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3714{
3715 struct http_txn *txn = s->txn;
3716 struct htx *htx;
3717 struct buffer *hdr = get_trash_chunk();
3718 int32_t pos;
3719
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003720 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003721
3722 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3723 struct htx_blk *blk = htx_get_blk(htx, pos);
3724 enum htx_blk_type type;
3725 struct ist n, v;
3726
3727 next_hdr:
3728 type = htx_get_blk_type(blk);
3729 if (type == HTX_BLK_EOH)
3730 break;
3731 if (type != HTX_BLK_HDR)
3732 continue;
3733
3734 if (unlikely(txn->flags & TX_SVDENY))
3735 return 1;
3736 else if (unlikely(txn->flags & TX_SVALLOW) &&
3737 (exp->action == ACT_ALLOW ||
3738 exp->action == ACT_DENY))
3739 return 0;
3740
3741 n = htx_get_blk_name(htx, blk);
3742 v = htx_get_blk_value(htx, blk);
3743
Christopher Faulet02e771a2019-02-26 15:36:05 +01003744 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003745 hdr->area[hdr->data++] = ':';
3746 hdr->area[hdr->data++] = ' ';
3747 chunk_memcat(hdr, v.ptr, v.len);
3748
3749 /* Now we have one header in <hdr> */
3750
3751 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3752 struct http_hdr_ctx ctx;
3753 int len;
3754
3755 switch (exp->action) {
3756 case ACT_ALLOW:
3757 txn->flags |= TX_SVALLOW;
3758 goto end;
3759 break;
3760
3761 case ACT_DENY:
3762 txn->flags |= TX_SVDENY;
3763 goto end;
3764 break;
3765
3766 case ACT_REPLACE:
3767 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3768 if (len < 0)
3769 return -1;
3770
3771 http_parse_header(ist2(trash.area, len), &n, &v);
3772 ctx.blk = blk;
3773 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003774 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003775 if (!http_replace_header(htx, &ctx, n, v))
3776 return -1;
3777 if (!ctx.blk)
3778 goto end;
3779 pos = htx_get_blk_pos(htx, blk);
3780 break;
3781
3782 case ACT_REMOVE:
3783 ctx.blk = blk;
3784 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003785 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003786 if (!http_remove_header(htx, &ctx))
3787 return -1;
3788 if (!ctx.blk)
3789 goto end;
3790 pos = htx_get_blk_pos(htx, blk);
3791 goto next_hdr;
3792 }
3793 }
3794
3795 }
3796 end:
3797 return 0;
3798}
3799
3800/* Apply the filter to the status line in the response buffer <res>.
3801 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3802 * or -1 if a replacement resulted in an invalid status line.
3803 */
3804static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3805{
3806 struct http_txn *txn = s->txn;
3807 struct htx *htx;
3808 struct buffer *resline = get_trash_chunk();
3809 int done;
3810
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003811 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003812
3813 if (unlikely(txn->flags & TX_SVDENY))
3814 return 1;
3815 else if (unlikely(txn->flags & TX_SVALLOW) &&
3816 (exp->action == ACT_ALLOW ||
3817 exp->action == ACT_DENY))
3818 return 0;
3819 else if (exp->action == ACT_REMOVE)
3820 return 0;
3821
3822 done = 0;
3823 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3824
3825 /* Now we have the status line between cur_ptr and cur_end */
3826 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003827 struct htx_sl *sl = http_find_stline(htx);
3828 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003829 int len;
3830
3831 switch (exp->action) {
3832 case ACT_ALLOW:
3833 txn->flags |= TX_SVALLOW;
3834 done = 1;
3835 break;
3836
3837 case ACT_DENY:
3838 txn->flags |= TX_SVDENY;
3839 done = 1;
3840 break;
3841
3842 case ACT_REPLACE:
3843 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3844 if (len < 0)
3845 return -1;
3846
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003847 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3848 sl->info.res.status = strl2ui(code.ptr, code.len);
3849 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003850 return -1;
3851
3852 done = 1;
3853 return 1;
3854 }
3855 }
3856 return done;
3857}
3858
3859/*
3860 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3861 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3862 * unparsable response.
3863 */
3864static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3865{
3866 struct session *sess = s->sess;
3867 struct http_txn *txn = s->txn;
3868 struct hdr_exp *exp;
3869
3870 for (exp = px->rsp_exp; exp; exp = exp->next) {
3871 int ret;
3872
3873 /*
3874 * The interleaving of transformations and verdicts
3875 * makes it difficult to decide to continue or stop
3876 * the evaluation.
3877 */
3878
3879 if (txn->flags & TX_SVDENY)
3880 break;
3881
3882 if ((txn->flags & TX_SVALLOW) &&
3883 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3884 exp->action == ACT_PASS)) {
3885 exp = exp->next;
3886 continue;
3887 }
3888
3889 /* if this filter had a condition, evaluate it now and skip to
3890 * next filter if the condition does not match.
3891 */
3892 if (exp->cond) {
3893 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3894 ret = acl_pass(ret);
3895 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3896 ret = !ret;
3897 if (!ret)
3898 continue;
3899 }
3900
3901 /* Apply the filter to the status line. */
3902 ret = htx_apply_filter_to_sts_line(s, res, exp);
3903 if (unlikely(ret < 0))
3904 return -1;
3905
3906 if (likely(ret == 0)) {
3907 /* The filter did not match the response, it can be
3908 * iterated through all headers.
3909 */
3910 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3911 return -1;
3912 }
3913 }
3914 return 0;
3915}
3916
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003917/*
3918 * Manage client-side cookie. It can impact performance by about 2% so it is
3919 * desirable to call it only when needed. This code is quite complex because
3920 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3921 * highly recommended not to touch this part without a good reason !
3922 */
3923static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3924{
3925 struct session *sess = s->sess;
3926 struct http_txn *txn = s->txn;
3927 struct htx *htx;
3928 struct http_hdr_ctx ctx;
3929 char *hdr_beg, *hdr_end, *del_from;
3930 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3931 int preserve_hdr;
3932
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003933 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003934 ctx.blk = NULL;
3935 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3936 del_from = NULL; /* nothing to be deleted */
3937 preserve_hdr = 0; /* assume we may kill the whole header */
3938
3939 /* Now look for cookies. Conforming to RFC2109, we have to support
3940 * attributes whose name begin with a '$', and associate them with
3941 * the right cookie, if we want to delete this cookie.
3942 * So there are 3 cases for each cookie read :
3943 * 1) it's a special attribute, beginning with a '$' : ignore it.
3944 * 2) it's a server id cookie that we *MAY* want to delete : save
3945 * some pointers on it (last semi-colon, beginning of cookie...)
3946 * 3) it's an application cookie : we *MAY* have to delete a previous
3947 * "special" cookie.
3948 * At the end of loop, if a "special" cookie remains, we may have to
3949 * remove it. If no application cookie persists in the header, we
3950 * *MUST* delete it.
3951 *
3952 * Note: RFC2965 is unclear about the processing of spaces around
3953 * the equal sign in the ATTR=VALUE form. A careful inspection of
3954 * the RFC explicitly allows spaces before it, and not within the
3955 * tokens (attrs or values). An inspection of RFC2109 allows that
3956 * too but section 10.1.3 lets one think that spaces may be allowed
3957 * after the equal sign too, resulting in some (rare) buggy
3958 * implementations trying to do that. So let's do what servers do.
3959 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3960 * allowed quoted strings in values, with any possible character
3961 * after a backslash, including control chars and delimitors, which
3962 * causes parsing to become ambiguous. Browsers also allow spaces
3963 * within values even without quotes.
3964 *
3965 * We have to keep multiple pointers in order to support cookie
3966 * removal at the beginning, middle or end of header without
3967 * corrupting the header. All of these headers are valid :
3968 *
3969 * hdr_beg hdr_end
3970 * | |
3971 * v |
3972 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3973 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3974 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3975 * | | | | | | |
3976 * | | | | | | |
3977 * | | | | | | +--> next
3978 * | | | | | +----> val_end
3979 * | | | | +-----------> val_beg
3980 * | | | +--------------> equal
3981 * | | +----------------> att_end
3982 * | +---------------------> att_beg
3983 * +--------------------------> prev
3984 *
3985 */
3986 hdr_beg = ctx.value.ptr;
3987 hdr_end = hdr_beg + ctx.value.len;
3988 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3989 /* Iterate through all cookies on this line */
3990
3991 /* find att_beg */
3992 att_beg = prev;
3993 if (prev > hdr_beg)
3994 att_beg++;
3995
3996 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3997 att_beg++;
3998
3999 /* find att_end : this is the first character after the last non
4000 * space before the equal. It may be equal to hdr_end.
4001 */
4002 equal = att_end = att_beg;
4003 while (equal < hdr_end) {
4004 if (*equal == '=' || *equal == ',' || *equal == ';')
4005 break;
4006 if (HTTP_IS_SPHT(*equal++))
4007 continue;
4008 att_end = equal;
4009 }
4010
4011 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4012 * is between <att_beg> and <equal>, both may be identical.
4013 */
4014 /* look for end of cookie if there is an equal sign */
4015 if (equal < hdr_end && *equal == '=') {
4016 /* look for the beginning of the value */
4017 val_beg = equal + 1;
4018 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4019 val_beg++;
4020
4021 /* find the end of the value, respecting quotes */
4022 next = http_find_cookie_value_end(val_beg, hdr_end);
4023
4024 /* make val_end point to the first white space or delimitor after the value */
4025 val_end = next;
4026 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4027 val_end--;
4028 }
4029 else
4030 val_beg = val_end = next = equal;
4031
4032 /* We have nothing to do with attributes beginning with
4033 * '$'. However, they will automatically be removed if a
4034 * header before them is removed, since they're supposed
4035 * to be linked together.
4036 */
4037 if (*att_beg == '$')
4038 continue;
4039
4040 /* Ignore cookies with no equal sign */
4041 if (equal == next) {
4042 /* This is not our cookie, so we must preserve it. But if we already
4043 * scheduled another cookie for removal, we cannot remove the
4044 * complete header, but we can remove the previous block itself.
4045 */
4046 preserve_hdr = 1;
4047 if (del_from != NULL) {
4048 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4049 val_end += delta;
4050 next += delta;
4051 hdr_end += delta;
4052 prev = del_from;
4053 del_from = NULL;
4054 }
4055 continue;
4056 }
4057
4058 /* if there are spaces around the equal sign, we need to
4059 * strip them otherwise we'll get trouble for cookie captures,
4060 * or even for rewrites. Since this happens extremely rarely,
4061 * it does not hurt performance.
4062 */
4063 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4064 int stripped_before = 0;
4065 int stripped_after = 0;
4066
4067 if (att_end != equal) {
4068 memmove(att_end, equal, hdr_end - equal);
4069 stripped_before = (att_end - equal);
4070 equal += stripped_before;
4071 val_beg += stripped_before;
4072 }
4073
4074 if (val_beg > equal + 1) {
4075 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4076 stripped_after = (equal + 1) - val_beg;
4077 val_beg += stripped_after;
4078 stripped_before += stripped_after;
4079 }
4080
4081 val_end += stripped_before;
4082 next += stripped_before;
4083 hdr_end += stripped_before;
4084 }
4085 /* now everything is as on the diagram above */
4086
4087 /* First, let's see if we want to capture this cookie. We check
4088 * that we don't already have a client side cookie, because we
4089 * can only capture one. Also as an optimisation, we ignore
4090 * cookies shorter than the declared name.
4091 */
4092 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4093 (val_end - att_beg >= sess->fe->capture_namelen) &&
4094 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4095 int log_len = val_end - att_beg;
4096
4097 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4098 ha_alert("HTTP logging : out of memory.\n");
4099 } else {
4100 if (log_len > sess->fe->capture_len)
4101 log_len = sess->fe->capture_len;
4102 memcpy(txn->cli_cookie, att_beg, log_len);
4103 txn->cli_cookie[log_len] = 0;
4104 }
4105 }
4106
4107 /* Persistence cookies in passive, rewrite or insert mode have the
4108 * following form :
4109 *
4110 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4111 *
4112 * For cookies in prefix mode, the form is :
4113 *
4114 * Cookie: NAME=SRV~VALUE
4115 */
4116 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4117 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4118 struct server *srv = s->be->srv;
4119 char *delim;
4120
4121 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4122 * have the server ID between val_beg and delim, and the original cookie between
4123 * delim+1 and val_end. Otherwise, delim==val_end :
4124 *
4125 * hdr_beg
4126 * |
4127 * v
4128 * NAME=SRV; # in all but prefix modes
4129 * NAME=SRV~OPAQUE ; # in prefix mode
4130 * || || | |+-> next
4131 * || || | +--> val_end
4132 * || || +---------> delim
4133 * || |+------------> val_beg
4134 * || +-------------> att_end = equal
4135 * |+-----------------> att_beg
4136 * +------------------> prev
4137 *
4138 */
4139 if (s->be->ck_opts & PR_CK_PFX) {
4140 for (delim = val_beg; delim < val_end; delim++)
4141 if (*delim == COOKIE_DELIM)
4142 break;
4143 }
4144 else {
4145 char *vbar1;
4146 delim = val_end;
4147 /* Now check if the cookie contains a date field, which would
4148 * appear after a vertical bar ('|') just after the server name
4149 * and before the delimiter.
4150 */
4151 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4152 if (vbar1) {
4153 /* OK, so left of the bar is the server's cookie and
4154 * right is the last seen date. It is a base64 encoded
4155 * 30-bit value representing the UNIX date since the
4156 * epoch in 4-second quantities.
4157 */
4158 int val;
4159 delim = vbar1++;
4160 if (val_end - vbar1 >= 5) {
4161 val = b64tos30(vbar1);
4162 if (val > 0)
4163 txn->cookie_last_date = val << 2;
4164 }
4165 /* look for a second vertical bar */
4166 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4167 if (vbar1 && (val_end - vbar1 > 5)) {
4168 val = b64tos30(vbar1 + 1);
4169 if (val > 0)
4170 txn->cookie_first_date = val << 2;
4171 }
4172 }
4173 }
4174
4175 /* if the cookie has an expiration date and the proxy wants to check
4176 * it, then we do that now. We first check if the cookie is too old,
4177 * then only if it has expired. We detect strict overflow because the
4178 * time resolution here is not great (4 seconds). Cookies with dates
4179 * in the future are ignored if their offset is beyond one day. This
4180 * allows an admin to fix timezone issues without expiring everyone
4181 * and at the same time avoids keeping unwanted side effects for too
4182 * long.
4183 */
4184 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4185 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4186 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4187 txn->flags &= ~TX_CK_MASK;
4188 txn->flags |= TX_CK_OLD;
4189 delim = val_beg; // let's pretend we have not found the cookie
4190 txn->cookie_first_date = 0;
4191 txn->cookie_last_date = 0;
4192 }
4193 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4194 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4195 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4196 txn->flags &= ~TX_CK_MASK;
4197 txn->flags |= TX_CK_EXPIRED;
4198 delim = val_beg; // let's pretend we have not found the cookie
4199 txn->cookie_first_date = 0;
4200 txn->cookie_last_date = 0;
4201 }
4202
4203 /* Here, we'll look for the first running server which supports the cookie.
4204 * This allows to share a same cookie between several servers, for example
4205 * to dedicate backup servers to specific servers only.
4206 * However, to prevent clients from sticking to cookie-less backup server
4207 * when they have incidentely learned an empty cookie, we simply ignore
4208 * empty cookies and mark them as invalid.
4209 * The same behaviour is applied when persistence must be ignored.
4210 */
4211 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4212 srv = NULL;
4213
4214 while (srv) {
4215 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4216 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4217 if ((srv->cur_state != SRV_ST_STOPPED) ||
4218 (s->be->options & PR_O_PERSIST) ||
4219 (s->flags & SF_FORCE_PRST)) {
4220 /* we found the server and we can use it */
4221 txn->flags &= ~TX_CK_MASK;
4222 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4223 s->flags |= SF_DIRECT | SF_ASSIGNED;
4224 s->target = &srv->obj_type;
4225 break;
4226 } else {
4227 /* we found a server, but it's down,
4228 * mark it as such and go on in case
4229 * another one is available.
4230 */
4231 txn->flags &= ~TX_CK_MASK;
4232 txn->flags |= TX_CK_DOWN;
4233 }
4234 }
4235 srv = srv->next;
4236 }
4237
4238 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4239 /* no server matched this cookie or we deliberately skipped it */
4240 txn->flags &= ~TX_CK_MASK;
4241 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4242 txn->flags |= TX_CK_UNUSED;
4243 else
4244 txn->flags |= TX_CK_INVALID;
4245 }
4246
4247 /* depending on the cookie mode, we may have to either :
4248 * - delete the complete cookie if we're in insert+indirect mode, so that
4249 * the server never sees it ;
4250 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004251 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004252 * if we're in cookie prefix mode
4253 */
4254 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4255 int delta; /* negative */
4256
4257 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4258 delta = val_beg - (delim + 1);
4259 val_end += delta;
4260 next += delta;
4261 hdr_end += delta;
4262 del_from = NULL;
4263 preserve_hdr = 1; /* we want to keep this cookie */
4264 }
4265 else if (del_from == NULL &&
4266 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4267 del_from = prev;
4268 }
4269 }
4270 else {
4271 /* This is not our cookie, so we must preserve it. But if we already
4272 * scheduled another cookie for removal, we cannot remove the
4273 * complete header, but we can remove the previous block itself.
4274 */
4275 preserve_hdr = 1;
4276
4277 if (del_from != NULL) {
4278 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4279 if (att_beg >= del_from)
4280 att_beg += delta;
4281 if (att_end >= del_from)
4282 att_end += delta;
4283 val_beg += delta;
4284 val_end += delta;
4285 next += delta;
4286 hdr_end += delta;
4287 prev = del_from;
4288 del_from = NULL;
4289 }
4290 }
4291
4292 /* continue with next cookie on this header line */
4293 att_beg = next;
4294 } /* for each cookie */
4295
4296
4297 /* There are no more cookies on this line.
4298 * We may still have one (or several) marked for deletion at the
4299 * end of the line. We must do this now in two ways :
4300 * - if some cookies must be preserved, we only delete from the
4301 * mark to the end of line ;
4302 * - if nothing needs to be preserved, simply delete the whole header
4303 */
4304 if (del_from) {
4305 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4306 }
4307 if ((hdr_end - hdr_beg) != ctx.value.len) {
4308 if (hdr_beg != hdr_end) {
4309 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004310 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004311 }
4312 else
4313 http_remove_header(htx, &ctx);
4314 }
4315 } /* for each "Cookie header */
4316}
4317
4318/*
4319 * Manage server-side cookies. It can impact performance by about 2% so it is
4320 * desirable to call it only when needed. This function is also used when we
4321 * just need to know if there is a cookie (eg: for check-cache).
4322 */
4323static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4324{
4325 struct session *sess = s->sess;
4326 struct http_txn *txn = s->txn;
4327 struct htx *htx;
4328 struct http_hdr_ctx ctx;
4329 struct server *srv;
4330 char *hdr_beg, *hdr_end;
4331 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004332 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004333
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004334 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004335
4336 ctx.blk = NULL;
4337 while (1) {
4338 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4339 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4340 break;
4341 is_cookie2 = 1;
4342 }
4343
4344 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4345 * <prev> points to the colon.
4346 */
4347 txn->flags |= TX_SCK_PRESENT;
4348
4349 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4350 * check-cache is enabled) and we are not interested in checking
4351 * them. Warning, the cookie capture is declared in the frontend.
4352 */
4353 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4354 break;
4355
4356 /* OK so now we know we have to process this response cookie.
4357 * The format of the Set-Cookie header is slightly different
4358 * from the format of the Cookie header in that it does not
4359 * support the comma as a cookie delimiter (thus the header
4360 * cannot be folded) because the Expires attribute described in
4361 * the original Netscape's spec may contain an unquoted date
4362 * with a comma inside. We have to live with this because
4363 * many browsers don't support Max-Age and some browsers don't
4364 * support quoted strings. However the Set-Cookie2 header is
4365 * clean.
4366 *
4367 * We have to keep multiple pointers in order to support cookie
4368 * removal at the beginning, middle or end of header without
4369 * corrupting the header (in case of set-cookie2). A special
4370 * pointer, <scav> points to the beginning of the set-cookie-av
4371 * fields after the first semi-colon. The <next> pointer points
4372 * either to the end of line (set-cookie) or next unquoted comma
4373 * (set-cookie2). All of these headers are valid :
4374 *
4375 * hdr_beg hdr_end
4376 * | |
4377 * v |
4378 * NAME1 = VALUE 1 ; Secure; Path="/" |
4379 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4380 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4381 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4382 * | | | | | | | |
4383 * | | | | | | | +-> next
4384 * | | | | | | +------------> scav
4385 * | | | | | +--------------> val_end
4386 * | | | | +--------------------> val_beg
4387 * | | | +----------------------> equal
4388 * | | +------------------------> att_end
4389 * | +----------------------------> att_beg
4390 * +------------------------------> prev
4391 * -------------------------------> hdr_beg
4392 */
4393 hdr_beg = ctx.value.ptr;
4394 hdr_end = hdr_beg + ctx.value.len;
4395 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4396
4397 /* Iterate through all cookies on this line */
4398
4399 /* find att_beg */
4400 att_beg = prev;
4401 if (prev > hdr_beg)
4402 att_beg++;
4403
4404 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4405 att_beg++;
4406
4407 /* find att_end : this is the first character after the last non
4408 * space before the equal. It may be equal to hdr_end.
4409 */
4410 equal = att_end = att_beg;
4411
4412 while (equal < hdr_end) {
4413 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4414 break;
4415 if (HTTP_IS_SPHT(*equal++))
4416 continue;
4417 att_end = equal;
4418 }
4419
4420 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4421 * is between <att_beg> and <equal>, both may be identical.
4422 */
4423
4424 /* look for end of cookie if there is an equal sign */
4425 if (equal < hdr_end && *equal == '=') {
4426 /* look for the beginning of the value */
4427 val_beg = equal + 1;
4428 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4429 val_beg++;
4430
4431 /* find the end of the value, respecting quotes */
4432 next = http_find_cookie_value_end(val_beg, hdr_end);
4433
4434 /* make val_end point to the first white space or delimitor after the value */
4435 val_end = next;
4436 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4437 val_end--;
4438 }
4439 else {
4440 /* <equal> points to next comma, semi-colon or EOL */
4441 val_beg = val_end = next = equal;
4442 }
4443
4444 if (next < hdr_end) {
4445 /* Set-Cookie2 supports multiple cookies, and <next> points to
4446 * a colon or semi-colon before the end. So skip all attr-value
4447 * pairs and look for the next comma. For Set-Cookie, since
4448 * commas are permitted in values, skip to the end.
4449 */
4450 if (is_cookie2)
4451 next = http_find_hdr_value_end(next, hdr_end);
4452 else
4453 next = hdr_end;
4454 }
4455
4456 /* Now everything is as on the diagram above */
4457
4458 /* Ignore cookies with no equal sign */
4459 if (equal == val_end)
4460 continue;
4461
4462 /* If there are spaces around the equal sign, we need to
4463 * strip them otherwise we'll get trouble for cookie captures,
4464 * or even for rewrites. Since this happens extremely rarely,
4465 * it does not hurt performance.
4466 */
4467 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4468 int stripped_before = 0;
4469 int stripped_after = 0;
4470
4471 if (att_end != equal) {
4472 memmove(att_end, equal, hdr_end - equal);
4473 stripped_before = (att_end - equal);
4474 equal += stripped_before;
4475 val_beg += stripped_before;
4476 }
4477
4478 if (val_beg > equal + 1) {
4479 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4480 stripped_after = (equal + 1) - val_beg;
4481 val_beg += stripped_after;
4482 stripped_before += stripped_after;
4483 }
4484
4485 val_end += stripped_before;
4486 next += stripped_before;
4487 hdr_end += stripped_before;
4488
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004489 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4490 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004491 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004492 }
4493
4494 /* First, let's see if we want to capture this cookie. We check
4495 * that we don't already have a server side cookie, because we
4496 * can only capture one. Also as an optimisation, we ignore
4497 * cookies shorter than the declared name.
4498 */
4499 if (sess->fe->capture_name != NULL &&
4500 txn->srv_cookie == NULL &&
4501 (val_end - att_beg >= sess->fe->capture_namelen) &&
4502 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4503 int log_len = val_end - att_beg;
4504 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4505 ha_alert("HTTP logging : out of memory.\n");
4506 }
4507 else {
4508 if (log_len > sess->fe->capture_len)
4509 log_len = sess->fe->capture_len;
4510 memcpy(txn->srv_cookie, att_beg, log_len);
4511 txn->srv_cookie[log_len] = 0;
4512 }
4513 }
4514
4515 srv = objt_server(s->target);
4516 /* now check if we need to process it for persistence */
4517 if (!(s->flags & SF_IGNORE_PRST) &&
4518 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4519 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4520 /* assume passive cookie by default */
4521 txn->flags &= ~TX_SCK_MASK;
4522 txn->flags |= TX_SCK_FOUND;
4523
4524 /* If the cookie is in insert mode on a known server, we'll delete
4525 * this occurrence because we'll insert another one later.
4526 * We'll delete it too if the "indirect" option is set and we're in
4527 * a direct access.
4528 */
4529 if (s->be->ck_opts & PR_CK_PSV) {
4530 /* The "preserve" flag was set, we don't want to touch the
4531 * server's cookie.
4532 */
4533 }
4534 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4535 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4536 /* this cookie must be deleted */
4537 if (prev == hdr_beg && next == hdr_end) {
4538 /* whole header */
4539 http_remove_header(htx, &ctx);
4540 /* note: while both invalid now, <next> and <hdr_end>
4541 * are still equal, so the for() will stop as expected.
4542 */
4543 } else {
4544 /* just remove the value */
4545 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4546 next = prev;
4547 hdr_end += delta;
4548 }
4549 txn->flags &= ~TX_SCK_MASK;
4550 txn->flags |= TX_SCK_DELETED;
4551 /* and go on with next cookie */
4552 }
4553 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4554 /* replace bytes val_beg->val_end with the cookie name associated
4555 * with this server since we know it.
4556 */
4557 int sliding, delta;
4558
4559 ctx.value = ist2(val_beg, val_end - val_beg);
4560 ctx.lws_before = ctx.lws_after = 0;
4561 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4562 delta = srv->cklen - (val_end - val_beg);
4563 sliding = (ctx.value.ptr - val_beg);
4564 hdr_beg += sliding;
4565 val_beg += sliding;
4566 next += sliding + delta;
4567 hdr_end += sliding + delta;
4568
4569 txn->flags &= ~TX_SCK_MASK;
4570 txn->flags |= TX_SCK_REPLACED;
4571 }
4572 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4573 /* insert the cookie name associated with this server
4574 * before existing cookie, and insert a delimiter between them..
4575 */
4576 int sliding, delta;
4577 ctx.value = ist2(val_beg, 0);
4578 ctx.lws_before = ctx.lws_after = 0;
4579 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4580 delta = srv->cklen + 1;
4581 sliding = (ctx.value.ptr - val_beg);
4582 hdr_beg += sliding;
4583 val_beg += sliding;
4584 next += sliding + delta;
4585 hdr_end += sliding + delta;
4586
4587 val_beg[srv->cklen] = COOKIE_DELIM;
4588 txn->flags &= ~TX_SCK_MASK;
4589 txn->flags |= TX_SCK_REPLACED;
4590 }
4591 }
4592 /* that's done for this cookie, check the next one on the same
4593 * line when next != hdr_end (only if is_cookie2).
4594 */
4595 }
4596 }
4597}
4598
Christopher Faulet25a02f62018-10-24 12:00:25 +02004599/*
4600 * Parses the Cache-Control and Pragma request header fields to determine if
4601 * the request may be served from the cache and/or if it is cacheable. Updates
4602 * s->txn->flags.
4603 */
4604void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4605{
4606 struct http_txn *txn = s->txn;
4607 struct htx *htx;
4608 int32_t pos;
4609 int pragma_found, cc_found, i;
4610
4611 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4612 return; /* nothing more to do here */
4613
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004614 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004615 pragma_found = cc_found = 0;
4616 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4617 struct htx_blk *blk = htx_get_blk(htx, pos);
4618 enum htx_blk_type type = htx_get_blk_type(blk);
4619 struct ist n, v;
4620
4621 if (type == HTX_BLK_EOH)
4622 break;
4623 if (type != HTX_BLK_HDR)
4624 continue;
4625
4626 n = htx_get_blk_name(htx, blk);
4627 v = htx_get_blk_value(htx, blk);
4628
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004629 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004630 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4631 pragma_found = 1;
4632 continue;
4633 }
4634 }
4635
4636 /* Don't use the cache and don't try to store if we found the
4637 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004638 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004639 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4640 txn->flags |= TX_CACHE_IGNORE;
4641 continue;
4642 }
4643
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 continue;
4646
4647 /* OK, right now we know we have a cache-control header */
4648 cc_found = 1;
4649 if (!v.len) /* no info */
4650 continue;
4651
4652 i = 0;
4653 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4654 !isspace((unsigned char)*(v.ptr+i)))
4655 i++;
4656
4657 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4658 * values after max-age, max-stale nor min-fresh, we simply don't
4659 * use the cache when they're specified.
4660 */
4661 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4662 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4663 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4664 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4665 txn->flags |= TX_CACHE_IGNORE;
4666 continue;
4667 }
4668
4669 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4670 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4671 continue;
4672 }
4673 }
4674
4675 /* RFC7234#5.4:
4676 * When the Cache-Control header field is also present and
4677 * understood in a request, Pragma is ignored.
4678 * When the Cache-Control header field is not present in a
4679 * request, caches MUST consider the no-cache request
4680 * pragma-directive as having the same effect as if
4681 * "Cache-Control: no-cache" were present.
4682 */
4683 if (!cc_found && pragma_found)
4684 txn->flags |= TX_CACHE_IGNORE;
4685}
4686
4687/*
4688 * Check if response is cacheable or not. Updates s->txn->flags.
4689 */
4690void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4691{
4692 struct http_txn *txn = s->txn;
4693 struct htx *htx;
4694 int32_t pos;
4695 int i;
4696
4697 if (txn->status < 200) {
4698 /* do not try to cache interim responses! */
4699 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4700 return;
4701 }
4702
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004703 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004704 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4705 struct htx_blk *blk = htx_get_blk(htx, pos);
4706 enum htx_blk_type type = htx_get_blk_type(blk);
4707 struct ist n, v;
4708
4709 if (type == HTX_BLK_EOH)
4710 break;
4711 if (type != HTX_BLK_HDR)
4712 continue;
4713
4714 n = htx_get_blk_name(htx, blk);
4715 v = htx_get_blk_value(htx, blk);
4716
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004717 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004718 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4719 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4720 return;
4721 }
4722 }
4723
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004724 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004725 continue;
4726
4727 /* OK, right now we know we have a cache-control header */
4728 if (!v.len) /* no info */
4729 continue;
4730
4731 i = 0;
4732 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4733 !isspace((unsigned char)*(v.ptr+i)))
4734 i++;
4735
4736 /* we have a complete value between v.ptr and (v.ptr+i) */
4737 if (i < v.len && *(v.ptr + i) == '=') {
4738 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4739 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4740 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4741 continue;
4742 }
4743
4744 /* we have something of the form no-cache="set-cookie" */
4745 if ((v.len >= 21) &&
4746 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4747 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4748 txn->flags &= ~TX_CACHE_COOK;
4749 continue;
4750 }
4751
4752 /* OK, so we know that either p2 points to the end of string or to a comma */
4753 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4754 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4755 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4756 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4757 return;
4758 }
4759
4760 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4761 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4762 continue;
4763 }
4764 }
4765}
4766
Christopher Faulet64159df2018-10-24 21:15:35 +02004767/* send a server's name with an outgoing request over an established connection.
4768 * Note: this function is designed to be called once the request has been
4769 * scheduled for being forwarded. This is the reason why the number of forwarded
4770 * bytes have to be adjusted.
4771 */
4772int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4773{
4774 struct htx *htx;
4775 struct http_hdr_ctx ctx;
4776 struct ist hdr;
4777 uint32_t data;
4778
4779 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004780 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004781 data = htx->data;
4782
4783 ctx.blk = NULL;
4784 while (http_find_header(htx, hdr, &ctx, 1))
4785 http_remove_header(htx, &ctx);
4786 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4787
4788 if (co_data(&s->req)) {
4789 if (data >= htx->data)
4790 c_rew(&s->req, data - htx->data);
4791 else
4792 c_adv(&s->req, htx->data - data);
4793 }
4794 return 0;
4795}
4796
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797/*
4798 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4799 * for the current backend.
4800 *
4801 * It is assumed that the request is either a HEAD, GET, or POST and that the
4802 * uri_auth field is valid.
4803 *
4804 * Returns 1 if stats should be provided, otherwise 0.
4805 */
4806static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4807{
4808 struct uri_auth *uri_auth = backend->uri_auth;
4809 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004810 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004811 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812
4813 if (!uri_auth)
4814 return 0;
4815
4816 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4817 return 0;
4818
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004819 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004820 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004821 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004822
4823 /* check URI size */
4824 if (uri_auth->uri_len > uri.len)
4825 return 0;
4826
4827 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4828 return 0;
4829
4830 return 1;
4831}
4832
4833/* This function prepares an applet to handle the stats. It can deal with the
4834 * "100-continue" expectation, check that admin rules are met for POST requests,
4835 * and program a response message if something was unexpected. It cannot fail
4836 * and always relies on the stats applet to complete the job. It does not touch
4837 * analysers nor counters, which are left to the caller. It does not touch
4838 * s->target which is supposed to already point to the stats applet. The caller
4839 * is expected to have already assigned an appctx to the stream.
4840 */
4841static int htx_handle_stats(struct stream *s, struct channel *req)
4842{
4843 struct stats_admin_rule *stats_admin_rule;
4844 struct stream_interface *si = &s->si[1];
4845 struct session *sess = s->sess;
4846 struct http_txn *txn = s->txn;
4847 struct http_msg *msg = &txn->req;
4848 struct uri_auth *uri_auth = s->be->uri_auth;
4849 const char *h, *lookup, *end;
4850 struct appctx *appctx;
4851 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004852 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004853
4854 appctx = si_appctx(si);
4855 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4856 appctx->st1 = appctx->st2 = 0;
4857 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4858 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4859 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4860 appctx->ctx.stats.flags |= STAT_CHUNKED;
4861
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004862 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004863 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004864 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4865 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004866
4867 for (h = lookup; h <= end - 3; h++) {
4868 if (memcmp(h, ";up", 3) == 0) {
4869 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4870 break;
4871 }
4872 }
4873
4874 if (uri_auth->refresh) {
4875 for (h = lookup; h <= end - 10; h++) {
4876 if (memcmp(h, ";norefresh", 10) == 0) {
4877 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4878 break;
4879 }
4880 }
4881 }
4882
4883 for (h = lookup; h <= end - 4; h++) {
4884 if (memcmp(h, ";csv", 4) == 0) {
4885 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4886 break;
4887 }
4888 }
4889
4890 for (h = lookup; h <= end - 6; h++) {
4891 if (memcmp(h, ";typed", 6) == 0) {
4892 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4893 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4894 break;
4895 }
4896 }
4897
4898 for (h = lookup; h <= end - 8; h++) {
4899 if (memcmp(h, ";st=", 4) == 0) {
4900 int i;
4901 h += 4;
4902 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4903 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4904 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4905 appctx->ctx.stats.st_code = i;
4906 break;
4907 }
4908 }
4909 break;
4910 }
4911 }
4912
4913 appctx->ctx.stats.scope_str = 0;
4914 appctx->ctx.stats.scope_len = 0;
4915 for (h = lookup; h <= end - 8; h++) {
4916 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4917 int itx = 0;
4918 const char *h2;
4919 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4920 const char *err;
4921
4922 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4923 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004924 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4925 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004926 if (*h == ';' || *h == '&' || *h == ' ')
4927 break;
4928 itx++;
4929 h++;
4930 }
4931
4932 if (itx > STAT_SCOPE_TXT_MAXLEN)
4933 itx = STAT_SCOPE_TXT_MAXLEN;
4934 appctx->ctx.stats.scope_len = itx;
4935
4936 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4937 memcpy(scope_txt, h2, itx);
4938 scope_txt[itx] = '\0';
4939 err = invalid_char(scope_txt);
4940 if (err) {
4941 /* bad char in search text => clear scope */
4942 appctx->ctx.stats.scope_str = 0;
4943 appctx->ctx.stats.scope_len = 0;
4944 }
4945 break;
4946 }
4947 }
4948
4949 /* now check whether we have some admin rules for this request */
4950 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4951 int ret = 1;
4952
4953 if (stats_admin_rule->cond) {
4954 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4955 ret = acl_pass(ret);
4956 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4957 ret = !ret;
4958 }
4959
4960 if (ret) {
4961 /* no rule, or the rule matches */
4962 appctx->ctx.stats.flags |= STAT_ADMIN;
4963 break;
4964 }
4965 }
4966
Christopher Faulet5d45e382019-02-27 15:15:23 +01004967 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4968 appctx->st0 = STAT_HTTP_HEAD;
4969 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004970 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004971 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004972 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004973 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004974 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4975 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4976 appctx->st0 = STAT_HTTP_LAST;
4977 }
4978 }
4979 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004980 /* Unsupported method */
4981 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4982 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4983 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004984 }
4985
4986 s->task->nice = -32; /* small boost for HTTP statistics */
4987 return 1;
4988}
4989
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4991{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004992 struct channel *req = &s->req;
4993 struct channel *res = &s->res;
4994 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004996 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 struct ist path, location;
4998 unsigned int flags;
4999 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005000
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 /*
5002 * Create the location
5003 */
5004 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005006 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007 /* special prefix "/" means don't change URL */
5008 srv = __objt_server(s->target);
5009 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5010 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5011 return;
5012 }
5013
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005014 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005015 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005016 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005017 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018 if (!path.ptr)
5019 return;
5020
5021 if (!chunk_memcat(&trash, path.ptr, path.len))
5022 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005023 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 /*
5026 * Create the 302 respone
5027 */
5028 htx = htx_from_buf(&res->buf);
5029 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5030 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5031 ist("HTTP/1.1"), ist("302"), ist("Found"));
5032 if (!sl)
5033 goto fail;
5034 sl->info.res.status = 302;
5035 s->txn->status = 302;
5036
5037 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5038 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5039 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5040 !htx_add_header(htx, ist("Location"), location))
5041 goto fail;
5042
5043 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5044 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005046 /*
5047 * Send the message
5048 */
5049 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 c_adv(res, data);
5051 res->total += data;
5052
5053 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005054 si_shutr(si);
5055 si_shutw(si);
5056 si->err_type = SI_ET_NONE;
5057 si->state = SI_ST_CLO;
5058
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005059 channel_auto_read(req);
5060 channel_abort(req);
5061 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005062 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 channel_auto_read(res);
5064 channel_auto_close(res);
5065
5066 if (!(s->flags & SF_ERR_MASK))
5067 s->flags |= SF_ERR_LOCAL;
5068 if (!(s->flags & SF_FINST_MASK))
5069 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005070
5071 /* FIXME: we should increase a counter of redirects per server and per backend. */
5072 srv_inc_sess_ctr(srv);
5073 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005074 return;
5075
5076 fail:
5077 /* If an error occurred, remove the incomplete HTTP response from the
5078 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005079 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080}
5081
Christopher Fauletf2824e62018-10-01 12:12:37 +02005082/* This function terminates the request because it was completly analyzed or
5083 * because an error was triggered during the body forwarding.
5084 */
5085static void htx_end_request(struct stream *s)
5086{
5087 struct channel *chn = &s->req;
5088 struct http_txn *txn = s->txn;
5089
5090 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5091 now_ms, __FUNCTION__, s,
5092 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5093 s->req.analysers, s->res.analysers);
5094
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005095 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5096 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005097 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005098 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 goto end;
5100 }
5101
5102 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5103 return;
5104
5105 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005106 /* No need to read anymore, the request was completely parsed.
5107 * We can shut the read side unless we want to abort_on_close,
5108 * or we have a POST request. The issue with POST requests is
5109 * that some browsers still send a CRLF after the request, and
5110 * this CRLF must be read so that it does not remain in the kernel
5111 * buffers, otherwise a close could cause an RST on some systems
5112 * (eg: Linux).
5113 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005114 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 channel_dont_read(chn);
5116
5117 /* if the server closes the connection, we want to immediately react
5118 * and close the socket to save packets and syscalls.
5119 */
5120 s->si[1].flags |= SI_FL_NOHALF;
5121
5122 /* In any case we've finished parsing the request so we must
5123 * disable Nagle when sending data because 1) we're not going
5124 * to shut this side, and 2) the server is waiting for us to
5125 * send pending data.
5126 */
5127 chn->flags |= CF_NEVER_WAIT;
5128
Christopher Fauletd01ce402019-01-02 17:44:13 +01005129 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5130 /* The server has not finished to respond, so we
5131 * don't want to move in order not to upset it.
5132 */
5133 return;
5134 }
5135
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136 /* When we get here, it means that both the request and the
5137 * response have finished receiving. Depending on the connection
5138 * mode, we'll have to wait for the last bytes to leave in either
5139 * direction, and sometimes for a close to be effective.
5140 */
5141 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5142 /* Tunnel mode will not have any analyser so it needs to
5143 * poll for reads.
5144 */
5145 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005146 if (b_data(&chn->buf))
5147 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005148 txn->req.msg_state = HTTP_MSG_TUNNEL;
5149 }
5150 else {
5151 /* we're not expecting any new data to come for this
5152 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005153 *
5154 * However, there is an exception if the response
5155 * length is undefined. In this case, we need to wait
5156 * the close from the server. The response will be
5157 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005158 */
5159 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5160 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005161 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162
5163 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5164 channel_shutr_now(chn);
5165 channel_shutw_now(chn);
5166 }
5167 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168 goto check_channel_flags;
5169 }
5170
5171 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5172 http_msg_closing:
5173 /* nothing else to forward, just waiting for the output buffer
5174 * to be empty and for the shutw_now to take effect.
5175 */
5176 if (channel_is_empty(chn)) {
5177 txn->req.msg_state = HTTP_MSG_CLOSED;
5178 goto http_msg_closed;
5179 }
5180 else if (chn->flags & CF_SHUTW) {
5181 txn->req.err_state = txn->req.msg_state;
5182 txn->req.msg_state = HTTP_MSG_ERROR;
5183 goto end;
5184 }
5185 return;
5186 }
5187
5188 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5189 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 /* if we don't know whether the server will close, we need to hard close */
5191 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5192 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005193 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005194 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 channel_dont_read(chn);
5196 goto end;
5197 }
5198
5199 check_channel_flags:
5200 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5201 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5202 /* if we've just closed an output, let's switch */
5203 txn->req.msg_state = HTTP_MSG_CLOSING;
5204 goto http_msg_closing;
5205 }
5206
5207 end:
5208 chn->analysers &= AN_REQ_FLT_END;
5209 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5210 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5211 channel_auto_close(chn);
5212 channel_auto_read(chn);
5213}
5214
5215
5216/* This function terminates the response because it was completly analyzed or
5217 * because an error was triggered during the body forwarding.
5218 */
5219static void htx_end_response(struct stream *s)
5220{
5221 struct channel *chn = &s->res;
5222 struct http_txn *txn = s->txn;
5223
5224 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5225 now_ms, __FUNCTION__, s,
5226 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5227 s->req.analysers, s->res.analysers);
5228
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005229 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5230 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005231 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005232 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 goto end;
5234 }
5235
5236 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5237 return;
5238
5239 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5240 /* In theory, we don't need to read anymore, but we must
5241 * still monitor the server connection for a possible close
5242 * while the request is being uploaded, so we don't disable
5243 * reading.
5244 */
5245 /* channel_dont_read(chn); */
5246
5247 if (txn->req.msg_state < HTTP_MSG_DONE) {
5248 /* The client seems to still be sending data, probably
5249 * because we got an error response during an upload.
5250 * We have the choice of either breaking the connection
5251 * or letting it pass through. Let's do the later.
5252 */
5253 return;
5254 }
5255
5256 /* When we get here, it means that both the request and the
5257 * response have finished receiving. Depending on the connection
5258 * mode, we'll have to wait for the last bytes to leave in either
5259 * direction, and sometimes for a close to be effective.
5260 */
5261 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5262 channel_auto_read(chn);
5263 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005264 if (b_data(&chn->buf))
5265 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005266 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5267 }
5268 else {
5269 /* we're not expecting any new data to come for this
5270 * transaction, so we can close it.
5271 */
5272 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5273 channel_shutr_now(chn);
5274 channel_shutw_now(chn);
5275 }
5276 }
5277 goto check_channel_flags;
5278 }
5279
5280 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5281 http_msg_closing:
5282 /* nothing else to forward, just waiting for the output buffer
5283 * to be empty and for the shutw_now to take effect.
5284 */
5285 if (channel_is_empty(chn)) {
5286 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5287 goto http_msg_closed;
5288 }
5289 else if (chn->flags & CF_SHUTW) {
5290 txn->rsp.err_state = txn->rsp.msg_state;
5291 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005292 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005293 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005294 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005295 goto end;
5296 }
5297 return;
5298 }
5299
5300 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5301 http_msg_closed:
5302 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005303 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005304 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005305 goto end;
5306 }
5307
5308 check_channel_flags:
5309 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5310 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5311 /* if we've just closed an output, let's switch */
5312 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5313 goto http_msg_closing;
5314 }
5315
5316 end:
5317 chn->analysers &= AN_RES_FLT_END;
5318 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5319 chn->analysers |= AN_RES_FLT_XFER_DATA;
5320 channel_auto_close(chn);
5321 channel_auto_read(chn);
5322}
5323
Christopher Faulet0f226952018-10-22 09:29:56 +02005324void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5325 int finst, const struct buffer *msg)
5326{
5327 channel_auto_read(si_oc(si));
5328 channel_abort(si_oc(si));
5329 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005330 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005331 channel_auto_close(si_ic(si));
5332 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005333
5334 /* <msg> is an HTX structure. So we copy it in the response's
5335 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005336 if (msg) {
5337 struct channel *chn = si_ic(si);
5338 struct htx *htx;
5339
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005340 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005341 chn->buf.data = msg->data;
5342 memcpy(chn->buf.area, msg->area, msg->data);
5343 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005344 c_adv(chn, htx->data);
5345 chn->total += htx->data;
5346 }
5347 if (!(s->flags & SF_ERR_MASK))
5348 s->flags |= err;
5349 if (!(s->flags & SF_FINST_MASK))
5350 s->flags |= finst;
5351}
5352
5353void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5354{
5355 channel_auto_read(&s->req);
5356 channel_abort(&s->req);
5357 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005358 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5359 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005360
5361 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005362
5363 /* <msg> is an HTX structure. So we copy it in the response's
5364 * channel */
5365 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005366 if (msg) {
5367 struct channel *chn = &s->res;
5368 struct htx *htx;
5369
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005370 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005371 chn->buf.data = msg->data;
5372 memcpy(chn->buf.area, msg->area, msg->data);
5373 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005374 c_adv(chn, htx->data);
5375 chn->total += htx->data;
5376 }
5377
5378 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5379 channel_auto_read(&s->res);
5380 channel_auto_close(&s->res);
5381 channel_shutr_now(&s->res);
5382}
5383
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005384struct buffer *htx_error_message(struct stream *s)
5385{
5386 const int msgnum = http_get_status_idx(s->txn->status);
5387
5388 if (s->be->errmsg[msgnum].area)
5389 return &s->be->errmsg[msgnum];
5390 else if (strm_fe(s)->errmsg[msgnum].area)
5391 return &strm_fe(s)->errmsg[msgnum];
5392 else
5393 return &htx_err_chunks[msgnum];
5394}
5395
5396
Christopher Faulet4a28a532019-03-01 11:19:40 +01005397/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5398 * on success and -1 on error.
5399 */
5400static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5401{
5402 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5403 * then we must send an HTTP/1.1 100 Continue intermediate response.
5404 */
5405 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5406 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5407 struct ist hdr = { .ptr = "Expect", .len = 6 };
5408 struct http_hdr_ctx ctx;
5409
5410 ctx.blk = NULL;
5411 /* Expect is allowed in 1.1, look for it */
5412 if (http_find_header(htx, hdr, &ctx, 0) &&
5413 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5414 if (htx_reply_100_continue(s) == -1)
5415 return -1;
5416 http_remove_header(htx, &ctx);
5417 }
5418 }
5419 return 0;
5420}
5421
Christopher Faulet23a3c792018-11-28 10:01:23 +01005422/* Send a 100-Continue response to the client. It returns 0 on success and -1
5423 * on error. The response channel is updated accordingly.
5424 */
5425static int htx_reply_100_continue(struct stream *s)
5426{
5427 struct channel *res = &s->res;
5428 struct htx *htx = htx_from_buf(&res->buf);
5429 struct htx_sl *sl;
5430 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5431 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5432 size_t data;
5433
5434 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5435 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5436 if (!sl)
5437 goto fail;
5438 sl->info.res.status = 100;
5439
5440 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5441 goto fail;
5442
5443 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005444 c_adv(res, data);
5445 res->total += data;
5446 return 0;
5447
5448 fail:
5449 /* If an error occurred, remove the incomplete HTTP response from the
5450 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005451 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005452 return -1;
5453}
5454
Christopher Faulet12c51e22018-11-28 15:59:42 +01005455
5456/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5457 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5458 * error. The response channel is updated accordingly.
5459 */
5460static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5461{
5462 struct channel *res = &s->res;
5463 struct htx *htx = htx_from_buf(&res->buf);
5464 struct htx_sl *sl;
5465 struct ist code, body;
5466 int status;
5467 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5468 size_t data;
5469
5470 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5471 status = 401;
5472 code = ist("401");
5473 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5474 "You need a valid user and password to access this content.\n"
5475 "</body></html>\n");
5476 }
5477 else {
5478 status = 407;
5479 code = ist("407");
5480 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5481 "You need a valid user and password to access this content.\n"
5482 "</body></html>\n");
5483 }
5484
5485 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5486 ist("HTTP/1.1"), code, ist("Unauthorized"));
5487 if (!sl)
5488 goto fail;
5489 sl->info.res.status = status;
5490 s->txn->status = status;
5491
5492 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5493 goto fail;
5494
5495 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5496 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005497 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5498 goto fail;
5499 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5500 goto fail;
5501 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005502 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005503 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5504 goto fail;
5505
5506 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005507 c_adv(res, data);
5508 res->total += data;
5509
5510 channel_auto_read(&s->req);
5511 channel_abort(&s->req);
5512 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005513 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005514
5515 res->wex = tick_add_ifset(now_ms, res->wto);
5516 channel_auto_read(res);
5517 channel_auto_close(res);
5518 channel_shutr_now(res);
5519 return 0;
5520
5521 fail:
5522 /* If an error occurred, remove the incomplete HTTP response from the
5523 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005524 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005525 return -1;
5526}
5527
Christopher Faulet0f226952018-10-22 09:29:56 +02005528/*
5529 * Capture headers from message <htx> according to header list <cap_hdr>, and
5530 * fill the <cap> pointers appropriately.
5531 */
5532static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5533{
5534 struct cap_hdr *h;
5535 int32_t pos;
5536
5537 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5538 struct htx_blk *blk = htx_get_blk(htx, pos);
5539 enum htx_blk_type type = htx_get_blk_type(blk);
5540 struct ist n, v;
5541
5542 if (type == HTX_BLK_EOH)
5543 break;
5544 if (type != HTX_BLK_HDR)
5545 continue;
5546
5547 n = htx_get_blk_name(htx, blk);
5548
5549 for (h = cap_hdr; h; h = h->next) {
5550 if (h->namelen && (h->namelen == n.len) &&
5551 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5552 if (cap[h->index] == NULL)
5553 cap[h->index] =
5554 pool_alloc(h->pool);
5555
5556 if (cap[h->index] == NULL) {
5557 ha_alert("HTTP capture : out of memory.\n");
5558 break;
5559 }
5560
5561 v = htx_get_blk_value(htx, blk);
5562 if (v.len > h->len)
5563 v.len = h->len;
5564
5565 memcpy(cap[h->index], v.ptr, v.len);
5566 cap[h->index][v.len]=0;
5567 }
5568 }
5569 }
5570}
5571
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005572/* Delete a value in a header between delimiters <from> and <next>. The header
5573 * itself is delimited by <start> and <end> pointers. The number of characters
5574 * displaced is returned, and the pointer to the first delimiter is updated if
5575 * required. The function tries as much as possible to respect the following
5576 * principles :
5577 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5578 * in which case <next> is simply removed
5579 * - set exactly one space character after the new first delimiter, unless there
5580 * are not enough characters in the block being moved to do so.
5581 * - remove unneeded spaces before the previous delimiter and after the new
5582 * one.
5583 *
5584 * It is the caller's responsibility to ensure that :
5585 * - <from> points to a valid delimiter or <start> ;
5586 * - <next> points to a valid delimiter or <end> ;
5587 * - there are non-space chars before <from>.
5588 */
5589static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5590{
5591 char *prev = *from;
5592
5593 if (prev == start) {
5594 /* We're removing the first value. eat the semicolon, if <next>
5595 * is lower than <end> */
5596 if (next < end)
5597 next++;
5598
5599 while (next < end && HTTP_IS_SPHT(*next))
5600 next++;
5601 }
5602 else {
5603 /* Remove useless spaces before the old delimiter. */
5604 while (HTTP_IS_SPHT(*(prev-1)))
5605 prev--;
5606 *from = prev;
5607
5608 /* copy the delimiter and if possible a space if we're
5609 * not at the end of the line.
5610 */
5611 if (next < end) {
5612 *prev++ = *next++;
5613 if (prev + 1 < next)
5614 *prev++ = ' ';
5615 while (next < end && HTTP_IS_SPHT(*next))
5616 next++;
5617 }
5618 }
5619 memmove(prev, next, end - next);
5620 return (prev - next);
5621}
5622
Christopher Faulet0f226952018-10-22 09:29:56 +02005623
5624/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005625 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005626 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005628{
5629 struct ist dst = ist2(str, 0);
5630
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005631 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005632 goto end;
5633 if (dst.len + 1 > len)
5634 goto end;
5635 dst.ptr[dst.len++] = ' ';
5636
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637 if (istcat(&dst, htx_sl_req_uri(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 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 end:
5645 return dst.len;
5646}
5647
Christopher Fauletf0523542018-10-24 11:06:58 +02005648/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005649 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005650 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005651static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005652{
5653 struct ist dst = ist2(str, 0);
5654
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005655 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005656 goto end;
5657 if (dst.len + 1 > len)
5658 goto end;
5659 dst.ptr[dst.len++] = ' ';
5660
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005661 if (istcat(&dst, htx_sl_res_code(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 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005668 end:
5669 return dst.len;
5670}
5671
5672
Christopher Faulet0f226952018-10-22 09:29:56 +02005673/*
5674 * Print a debug line with a start line.
5675 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005676static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005677{
5678 struct session *sess = strm_sess(s);
5679 int max;
5680
5681 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5682 dir,
5683 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5684 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5685
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005686 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005687 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005688 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005689 trash.area[trash.data++] = ' ';
5690
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005691 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005692 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005693 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005694 trash.area[trash.data++] = ' ';
5695
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005696 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005697 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005698 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005699 trash.area[trash.data++] = '\n';
5700
5701 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5702}
5703
5704/*
5705 * Print a debug line with a header.
5706 */
5707static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5708{
5709 struct session *sess = strm_sess(s);
5710 int max;
5711
5712 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5713 dir,
5714 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5715 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5716
5717 max = n.len;
5718 UBOUND(max, trash.size - trash.data - 3);
5719 chunk_memcat(&trash, n.ptr, max);
5720 trash.area[trash.data++] = ':';
5721 trash.area[trash.data++] = ' ';
5722
5723 max = v.len;
5724 UBOUND(max, trash.size - trash.data - 1);
5725 chunk_memcat(&trash, v.ptr, max);
5726 trash.area[trash.data++] = '\n';
5727
5728 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5729}
5730
5731
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005732__attribute__((constructor))
5733static void __htx_protocol_init(void)
5734{
5735}
5736
5737
5738/*
5739 * Local variables:
5740 * c-indent-level: 8
5741 * c-basic-offset: 8
5742 * End:
5743 */