blob: 7b3464bb207705158409fde364763d7a0a450d47 [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 Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulet9768c262018-10-22 09:34:31 +0200150 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 stream_inc_http_req_ctr(s);
152 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100153 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100155 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200156
Christopher Faulet9768c262018-10-22 09:34:31 +0200157 txn->status = 400;
158 msg->err_state = msg->msg_state;
159 msg->msg_state = HTTP_MSG_ERROR;
160 htx_reply_and_close(s, txn->status, NULL);
161 req->analysers &= AN_REQ_FLT_END;
162
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (!(s->flags & SF_FINST_MASK))
164 s->flags |= SF_FINST_R;
165 return 0;
166 }
167
Christopher Faulet9768c262018-10-22 09:34:31 +0200168 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200169 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
170 if (!(s->flags & SF_ERR_MASK))
171 s->flags |= SF_ERR_CLITO;
172
173 if (txn->flags & TX_WAIT_NEXT_RQ)
174 goto failed_keep_alive;
175
176 if (sess->fe->options & PR_O_IGNORE_PRB)
177 goto failed_keep_alive;
178
Christopher Faulet9768c262018-10-22 09:34:31 +0200179 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200180 stream_inc_http_req_ctr(s);
181 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100184 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200185
Christopher Faulet9768c262018-10-22 09:34:31 +0200186 txn->status = 408;
187 msg->err_state = msg->msg_state;
188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100189 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200190 req->analysers &= AN_REQ_FLT_END;
191
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (!(s->flags & SF_FINST_MASK))
193 s->flags |= SF_FINST_R;
194 return 0;
195 }
196
Christopher Faulet9768c262018-10-22 09:34:31 +0200197 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200198 else if (req->flags & CF_SHUTR) {
199 if (!(s->flags & SF_ERR_MASK))
200 s->flags |= SF_ERR_CLICL;
201
202 if (txn->flags & TX_WAIT_NEXT_RQ)
203 goto failed_keep_alive;
204
205 if (sess->fe->options & PR_O_IGNORE_PRB)
206 goto failed_keep_alive;
207
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 stream_inc_http_err_ctr(s);
209 stream_inc_http_req_ctr(s);
210 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100213 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200214
Christopher Faulet9768c262018-10-22 09:34:31 +0200215 txn->status = 400;
216 msg->err_state = msg->msg_state;
217 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100218 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200219 req->analysers &= AN_REQ_FLT_END;
220
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (!(s->flags & SF_FINST_MASK))
222 s->flags |= SF_FINST_R;
223 return 0;
224 }
225
226 channel_dont_connect(req);
227 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
228 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100229
Christopher Faulet9768c262018-10-22 09:34:31 +0200230 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
232 /* We need more data, we have to re-enable quick-ack in case we
233 * previously disabled it, otherwise we might cause the client
234 * to delay next data.
235 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet47365272018-10-31 17:40:50 +0100239 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 /* If the client starts to talk, let's fall back to
241 * request timeout processing.
242 */
243 txn->flags &= ~TX_WAIT_NEXT_RQ;
244 req->analyse_exp = TICK_ETERNITY;
245 }
246
247 /* just set the request timeout once at the beginning of the request */
248 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
251 else
252 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
253 }
254
255 /* we're not ready yet */
256 return 0;
257
258 failed_keep_alive:
259 /* Here we process low-level errors for keep-alive requests. In
260 * short, if the request is not the first one and it experiences
261 * a timeout, read error or shutdown, we just silently close so
262 * that the client can try again.
263 */
264 txn->status = 0;
265 msg->msg_state = HTTP_MSG_RQBEFORE;
266 req->analysers &= AN_REQ_FLT_END;
267 s->logs.logwait = 0;
268 s->logs.level = 0;
269 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200270 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200271 return 0;
272 }
273
Christopher Faulet9768c262018-10-22 09:34:31 +0200274 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200275 stream_inc_http_req_ctr(s);
276 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 /* kill the pending keep-alive timeout */
279 txn->flags &= ~TX_WAIT_NEXT_RQ;
280 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281
Christopher Faulet29f17582019-05-23 11:03:26 +0200282 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200283 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100284
Christopher Faulet9768c262018-10-22 09:34:31 +0200285 /* 0: we might have to print this header in debug mode */
286 if (unlikely((global.mode & MODE_DEBUG) &&
287 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
288 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200289
Christopher Faulet03599112018-11-27 11:21:21 +0100290 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200291
Christopher Fauleta3f15502019-05-13 15:27:23 +0200292 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 struct htx_blk *blk = htx_get_blk(htx, pos);
294 enum htx_blk_type type = htx_get_blk_type(blk);
295
296 if (type == HTX_BLK_EOH)
297 break;
298 if (type != HTX_BLK_HDR)
299 continue;
300
301 htx_debug_hdr("clihdr", s,
302 htx_get_blk_name(htx, blk),
303 htx_get_blk_value(htx, blk));
304 }
305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306
307 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100308 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200309 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100310 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200312 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100313 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100314 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100315 if (sl->flags & HTX_SL_F_BODYLESS)
316 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /* we can make use of server redirect on GET and HEAD */
319 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
320 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 goto return_bad_req;
324 }
325
326 /*
327 * 2: check if the URI matches the monitor_uri.
328 * We have to do this for every request which gets in, because
329 * the monitor-uri is defined by the frontend.
330 */
331 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet943ab4d2020-02-18 14:51:51 +0100332 isteq(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /*
334 * We have found the monitor URI
335 */
336 struct acl_cond *cond;
337
338 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200340
341 /* Check if we want to fail this monitor request or not */
342 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
343 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
344
345 ret = acl_pass(ret);
346 if (cond->pol == ACL_COND_UNLESS)
347 ret = !ret;
348
349 if (ret) {
350 /* we fail this request, let's return 503 service unavail */
351 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100352 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200353 if (!(s->flags & SF_ERR_MASK))
354 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
355 goto return_prx_cond;
356 }
357 }
358
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800359 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366
367 /*
368 * 3: Maybe we have to copy the original REQURI for the logs ?
369 * Note: we cannot log anymore if the request has been
370 * classified as invalid.
371 */
372 if (unlikely(s->logs.logwait & LW_REQ)) {
373 /* we have a complete HTTP request that we must log */
374 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulet9768c262018-10-22 09:34:31 +0200377 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
378 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200379
380 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
381 s->do_log(s);
382 } else {
383 ha_alert("HTTP logging : out of memory.\n");
384 }
385 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387 /* if the frontend has "option http-use-proxy-header", we'll check if
388 * we have what looks like a proxied connection instead of a connection,
389 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
390 * Note that this is *not* RFC-compliant, however browsers and proxies
391 * happen to do that despite being non-standard :-(
392 * We consider that a request not beginning with either '/' or '*' is
393 * a proxied connection, which covers both "scheme://location" and
394 * CONNECT ip:port.
395 */
396 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100397 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 txn->flags |= TX_USE_PX_CONN;
399
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400 /* 5: we may need to capture headers */
401 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200402 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100404 /* by default, close the stream at the end of the transaction. */
405 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100441 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100444 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
Olivier Houchard629693f2020-01-23 14:57:36 +0100527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Faulet4629d082019-07-04 11:27:15 +0200543 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100548 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200556 htx_handle_stats(s, req);
557 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
567 /* evaluate the req* rules except reqadd */
568 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200569 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200570 goto return_bad_req;
571
572 if (txn->flags & TX_CLDENY)
573 goto deny;
574
575 if (txn->flags & TX_CLTARPIT) {
576 deny_status = HTTP_ERR_500;
577 goto tarpit;
578 }
579 }
580
581 /* add request headers from the rule sets in the same order */
582 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200583 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200584 if (wl->cond) {
585 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
586 ret = acl_pass(ret);
587 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
588 ret = !ret;
589 if (!ret)
590 continue;
591 }
592
Christopher Fauletff2759f2018-10-24 11:13:16 +0200593 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
594 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 goto return_bad_req;
596 }
597
Christopher Faulet2571bc62019-03-01 11:44:26 +0100598 /* Proceed with the applets now. */
599 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100601 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100603 if (htx_handle_expect_hdr(s, htx, msg) == -1)
604 goto return_bad_req;
605
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
607 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
608 if (!(s->flags & SF_FINST_MASK))
609 s->flags |= SF_FINST_R;
610
611 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
612 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
613 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
614 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100615
616 req->flags |= CF_SEND_DONTWAIT;
617 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100666 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100685 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100698 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100704 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_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->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100766 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100775 struct htx_sl *sl;
776 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100784 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200793 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100794 uri = htx_sl_req_uri(sl);
795 path = http_get_path(uri);
796 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797 goto return_bad_req;
798
799 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 * uri.ptr and path.ptr (excluded). If it was not found, we need
801 * to replace from all the uri by a single "/".
802 *
803 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100804 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau3284dd22019-07-18 16:17:15 +0200808 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 }
810
811 /*
812 * 7: Now we can work with the cookies.
813 * Note that doing so might move headers in the request, but
814 * the fields will stay coherent and the URI will not move.
815 * This should only be performed in the backend.
816 */
817 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100818 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819
820 /* add unique-id if "header-unique-id" is specified */
821
822 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
823 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
824 goto return_bad_req;
825 s->unique_id[0] = '\0';
826 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
827 }
828
829 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200830 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
831 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
832
833 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 }
836
837 /*
838 * 9: add X-Forwarded-For if either the frontend or the backend
839 * asks for it.
840 */
841 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200842 struct http_hdr_ctx ctx = { .blk = NULL };
843 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
844 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
845
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200848 /* The header is set to be added only if none is present
849 * and we found it, so don't do anything.
850 */
851 }
852 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
853 /* Add an X-Forwarded-For header unless the source IP is
854 * in the 'except' network range.
855 */
856 if ((!sess->fe->except_mask.s_addr ||
857 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
858 != sess->fe->except_net.s_addr) &&
859 (!s->be->except_mask.s_addr ||
860 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
861 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863
864 /* Note: we rely on the backend to get the header name to be used for
865 * x-forwarded-for, because the header is really meant for the backends.
866 * However, if the backend did not specify any option, we have to rely
867 * on the frontend's header name.
868 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
870 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200871 goto return_bad_req;
872 }
873 }
874 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
875 /* FIXME: for the sake of completeness, we should also support
876 * 'except' here, although it is mostly useless in this case.
877 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200879
Christopher Faulete0768eb2018-10-03 16:38:02 +0200880 inet_ntop(AF_INET6,
881 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
882 pn, sizeof(pn));
883
884 /* Note: we rely on the backend to get the header name to be used for
885 * x-forwarded-for, because the header is really meant for the backends.
886 * However, if the backend did not specify any option, we have to rely
887 * on the frontend's header name.
888 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200889 chunk_printf(&trash, "%s", pn);
890 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 goto return_bad_req;
892 }
893 }
894
895 /*
896 * 10: add X-Original-To if either the frontend or the backend
897 * asks for it.
898 */
899 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
900
901 /* FIXME: don't know if IPv6 can handle that case too. */
902 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
903 /* Add an X-Original-To header unless the destination IP is
904 * in the 'except' network range.
905 */
906 conn_get_to_addr(cli_conn);
907
908 if (cli_conn->addr.to.ss_family == AF_INET &&
909 ((!sess->fe->except_mask_to.s_addr ||
910 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
911 != sess->fe->except_to.s_addr) &&
912 (!s->be->except_mask_to.s_addr ||
913 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
914 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200915 struct ist hdr;
916 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200917
918 /* Note: we rely on the backend to get the header name to be used for
919 * x-original-to, because the header is really meant for the backends.
920 * However, if the backend did not specify any option, we have to rely
921 * on the frontend's header name.
922 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200923 if (s->be->orgto_hdr_len)
924 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
925 else
926 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200927
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
929 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200930 goto return_bad_req;
931 }
932 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 }
934
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 /* If we have no server assigned yet and we're balancing on url_param
936 * with a POST request, we may be interested in checking the body for
937 * that parameter. This will be done in another analyser.
938 */
939 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100940 s->txn->meth == HTTP_METH_POST &&
941 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100948
Christopher Faulete0768eb2018-10-03 16:38:02 +0200949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200955 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957
958 /*************************************************************
959 * OK, that's finished for the headers. We have done what we *
960 * could. Let's switch to the DATA state. *
961 ************************************************************/
962 req->analyse_exp = TICK_ETERNITY;
963 req->analysers &= ~an_bit;
964
965 s->logs.tv_request = now;
966 /* OK let's go on with the BODY now */
967 return 1;
968
969 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200970 txn->req.err_state = txn->req.msg_state;
971 txn->req.msg_state = HTTP_MSG_ERROR;
972 txn->status = 400;
973 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100974 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100978 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_R;
984 return 0;
985}
986
987/* This function is an analyser which processes the HTTP tarpit. It always
988 * returns zero, at the beginning because it prevents any other processing
989 * from occurring, and at the end because it terminates the request.
990 */
991int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
992{
993 struct http_txn *txn = s->txn;
994
995 /* This connection is being tarpitted. The CLIENT side has
996 * already set the connect expiration date to the right
997 * timeout. We just have to check that the client is still
998 * there and that the timeout has not expired.
999 */
1000 channel_dont_connect(req);
1001 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1002 !tick_is_expired(req->analyse_exp, now_ms))
1003 return 0;
1004
1005 /* We will set the queue timer to the time spent, just for
1006 * logging purposes. We fake a 500 server error, so that the
1007 * attacker will not suspect his connection has been tarpitted.
1008 * It will not cause trouble to the logs because we can exclude
1009 * the tarpitted connections by filtering on the 'PT' status flags.
1010 */
1011 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1012
Christopher Fauletef9a1692020-02-21 10:20:46 +01001013 htx_reply_and_close(s, txn->status, (!(req->flags & CF_READ_ERROR) ? htx_error_message(s) : NULL));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001066 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1067 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 }
1069
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001070 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1073 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001075 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001076 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 goto http_end;
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1081 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001082 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
1084 if (!(s->flags & SF_ERR_MASK))
1085 s->flags |= SF_ERR_CLITO;
1086 if (!(s->flags & SF_FINST_MASK))
1087 s->flags |= SF_FINST_D;
1088 goto return_err_msg;
1089 }
1090
1091 /* we get here if we need to wait for more data */
1092 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1093 /* Not enough data. We'll re-use the http-request
1094 * timeout here. Ideally, we should set the timeout
1095 * relative to the accept() date. We just set the
1096 * request timeout once at the beginning of the
1097 * request.
1098 */
1099 channel_dont_connect(req);
1100 if (!tick_isset(req->analyse_exp))
1101 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1102 return 0;
1103 }
1104
1105 http_end:
1106 /* The situation will not evolve, so let's give up on the analysis. */
1107 s->logs.tv_request = now; /* update the request timer to reflect full request */
1108 req->analysers &= ~an_bit;
1109 req->analyse_exp = TICK_ETERNITY;
1110 return 1;
1111
1112 return_bad_req: /* let's centralize all bad requests */
1113 txn->req.err_state = txn->req.msg_state;
1114 txn->req.msg_state = HTTP_MSG_ERROR;
1115 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001116 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001117
1118 if (!(s->flags & SF_ERR_MASK))
1119 s->flags |= SF_ERR_PRXCOND;
1120 if (!(s->flags & SF_FINST_MASK))
1121 s->flags |= SF_FINST_R;
1122
1123 return_err_msg:
1124 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128 return 0;
1129}
1130
1131/* This function is an analyser which forwards request body (including chunk
1132 * sizes if any). It is called as soon as we must forward, even if we forward
1133 * zero byte. The only situation where it must not be called is when we're in
1134 * tunnel mode and we want to forward till the close. It's used both to forward
1135 * remaining data and to resync after end of body. It expects the msg_state to
1136 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1137 * read more data, or 1 once we can go on with next request or end the stream.
1138 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1139 * bytes of pending data + the headers if not already done.
1140 */
1141int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1142{
1143 struct session *sess = s->sess;
1144 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001145 struct http_msg *msg = &txn->req;
1146 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001147 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001148 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001149
1150 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1151 now_ms, __FUNCTION__,
1152 s,
1153 req,
1154 req->rex, req->wex,
1155 req->flags,
1156 ci_data(req),
1157 req->analysers);
1158
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001159 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1162 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1163 /* Output closed while we were sending data. We must abort and
1164 * wake the other side up.
1165 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001166 /* Don't abort yet if we had L7 retries activated and it
1167 * was a write error, we may recover.
1168 */
1169 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1170 (s->si[1].flags & SI_FL_L7_RETRY))
1171 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001172 msg->err_state = msg->msg_state;
1173 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001174 htx_end_request(s);
1175 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 return 1;
1177 }
1178
1179 /* Note that we don't have to send 100-continue back because we don't
1180 * need the data to complete our job, and it's up to the server to
1181 * decide whether to return 100, 417 or anything else in return of
1182 * an "Expect: 100-continue" header.
1183 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001184 if (msg->msg_state == HTTP_MSG_BODY)
1185 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 /* Some post-connect processing might want us to refrain from starting to
1188 * forward data. Currently, the only reason for this is "balance url_param"
1189 * whichs need to parse/process the request after we've enabled forwarding.
1190 */
1191 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1192 if (!(s->res.flags & CF_READ_ATTACHED)) {
1193 channel_auto_connect(req);
1194 req->flags |= CF_WAKE_CONNECT;
1195 channel_dont_close(req); /* don't fail on early shutr */
1196 goto waiting;
1197 }
1198 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1199 }
1200
1201 /* in most states, we should abort in case of early close */
1202 channel_auto_close(req);
1203
1204 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001205 if (req->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001206 if (req->flags & CF_EOI)
1207 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01001208 }
1209 else {
1210 /* We can't process the buffer's contents yet */
1211 req->flags |= CF_WAKE_WRITE;
1212 goto missing_data_or_waiting;
1213 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001214 }
1215
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001216 if (msg->msg_state >= HTTP_MSG_ENDING)
1217 goto ending;
1218
1219 if (txn->meth == HTTP_METH_CONNECT) {
1220 msg->msg_state = HTTP_MSG_ENDING;
1221 goto ending;
1222 }
1223
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 /* Forward input data. We get it by removing all outgoing data not
1225 * forwarded yet from HTX data size. If there are some data filters, we
1226 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 if (HAS_REQ_DATA_FILTERS(s)) {
1229 ret = flt_http_payload(s, msg, htx->data);
1230 if (ret < 0)
1231 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001232 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001233 }
1234 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001235 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001236 if (msg->flags & HTTP_MSGF_XFER_LEN)
1237 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001238 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001239
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001240 if (htx->data != co_data(req))
1241 goto missing_data_or_waiting;
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001242
Christopher Faulet9768c262018-10-22 09:34:31 +02001243 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001244 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1245 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001246 */
1247 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1248 goto missing_data_or_waiting;
1249
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001250 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02001251
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001252 ending:
1253 /* other states, ENDING...TUNNEL */
1254 if (msg->msg_state >= HTTP_MSG_DONE)
1255 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001256
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001257 if (HAS_REQ_DATA_FILTERS(s)) {
1258 ret = flt_http_end(s, msg);
1259 if (ret <= 0) {
1260 if (!ret)
1261 goto missing_data_or_waiting;
1262 goto return_bad_req;
1263 }
1264 }
1265
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001266 if (txn->meth == HTTP_METH_CONNECT)
1267 msg->msg_state = HTTP_MSG_TUNNEL;
1268 else {
1269 msg->msg_state = HTTP_MSG_DONE;
1270 req->to_forward = 0;
1271 }
1272
1273 done:
1274 /* we don't want to forward closes on DONE except in tunnel mode. */
1275 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1276 channel_dont_close(req);
1277
Christopher Fauletf2824e62018-10-01 12:12:37 +02001278 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001279 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001280 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1282 if (req->flags & CF_SHUTW) {
1283 /* request errors are most likely due to the
1284 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001285 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001287 goto return_bad_req;
1288 }
1289 return 1;
1290 }
1291
1292 /* If "option abortonclose" is set on the backend, we want to monitor
1293 * the client's connection and forward any shutdown notification to the
1294 * server, which will decide whether to close or to go on processing the
1295 * request. We only do that in tunnel mode, and not in other modes since
1296 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001297 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001298 channel_auto_read(req);
1299 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1300 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1301 s->si[1].flags |= SI_FL_NOLINGER;
1302 channel_auto_close(req);
1303 }
1304 else if (s->txn->meth == HTTP_METH_POST) {
1305 /* POST requests may require to read extra CRLF sent by broken
1306 * browsers and which could cause an RST to be sent upon close
1307 * on some systems (eg: Linux). */
1308 channel_auto_read(req);
1309 }
1310 return 0;
1311
1312 missing_data_or_waiting:
1313 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001314 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316
1317 waiting:
1318 /* waiting for the last bits to leave the buffer */
1319 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001320 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321
Christopher Faulet47365272018-10-31 17:40:50 +01001322 if (htx->flags & HTX_FL_PARSING_ERROR)
1323 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001324
Christopher Faulete0768eb2018-10-03 16:38:02 +02001325 /* When TE: chunked is used, we need to get there again to parse remaining
1326 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1327 * And when content-length is used, we never want to let the possible
1328 * shutdown be forwarded to the other side, as the state machine will
1329 * take care of it once the client responds. It's also important to
1330 * prevent TIME_WAITs from accumulating on the backend side, and for
1331 * HTTP/2 where the last frame comes with a shutdown.
1332 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001333 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001334 channel_dont_close(req);
1335
1336 /* We know that more data are expected, but we couldn't send more that
1337 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1338 * system knows it must not set a PUSH on this first part. Interactive
1339 * modes are already handled by the stream sock layer. We must not do
1340 * this in content-length mode because it could present the MSG_MORE
1341 * flag with the last block of forwarded data, which would cause an
1342 * additional delay to be observed by the receiver.
1343 */
1344 if (msg->flags & HTTP_MSGF_TE_CHNK)
1345 req->flags |= CF_EXPECT_MORE;
1346
1347 return 0;
1348
Christopher Faulet93e02d82019-03-08 14:18:50 +01001349 return_cli_abort:
1350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1351 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1352 if (objt_server(s->target))
1353 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1354 if (!(s->flags & SF_ERR_MASK))
1355 s->flags |= SF_ERR_CLICL;
1356 status = 400;
1357 goto return_error;
1358
1359 return_srv_abort:
1360 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1361 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1362 if (objt_server(s->target))
1363 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1364 if (!(s->flags & SF_ERR_MASK))
1365 s->flags |= SF_ERR_SRVCL;
1366 status = 502;
1367 goto return_error;
1368
1369 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001370 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001372 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001374 s->flags |= SF_ERR_CLICL;
1375 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376
Christopher Faulet93e02d82019-03-08 14:18:50 +01001377 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 txn->req.err_state = txn->req.msg_state;
1379 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001380 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001382 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001384 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001385 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 }
1387 req->analysers &= AN_REQ_FLT_END;
1388 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 +01001389 if (!(s->flags & SF_FINST_MASK))
1390 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 return 0;
1392}
1393
Olivier Houcharda254a372019-04-05 15:30:12 +02001394/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1395/* Returns 0 if we can attempt to retry, -1 otherwise */
1396static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1397{
1398 struct channel *req, *res;
1399 int co_data;
1400
1401 si->conn_retries--;
1402 if (si->conn_retries < 0)
1403 return -1;
1404
Willy Tarreau223995e2019-05-04 10:38:31 +02001405 if (objt_server(s->target))
1406 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1407 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1408
Olivier Houcharda254a372019-04-05 15:30:12 +02001409 req = &s->req;
1410 res = &s->res;
1411 /* Remove any write error from the request, and read error from the response */
1412 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1413 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1414 res->analysers = 0;
1415 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchardc86a9662020-05-12 22:18:14 +02001416 s->flags &= ~SF_ADDR_SET;
Olivier Houchard530249c2019-07-12 16:16:59 +02001417 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001418 si->exp = TICK_ETERNITY;
1419 res->rex = TICK_ETERNITY;
1420 res->to_forward = 0;
1421 res->analyse_exp = TICK_ETERNITY;
1422 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001423 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001424 si_release_endpoint(&s->si[1]);
1425 b_free(&req->buf);
1426 /* Swap the L7 buffer with the channel buffer */
1427 /* We know we stored the co_data as b_data, so get it there */
1428 co_data = b_data(&si->l7_buffer);
1429 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1430 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1431
1432 co_set_data(req, co_data);
1433 b_reset(&res->buf);
1434 co_set_data(res, 0);
1435 return 0;
1436}
1437
Christopher Faulete0768eb2018-10-03 16:38:02 +02001438/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1439 * processing can continue on next analysers, or zero if it either needs more
1440 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1441 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1442 * when it has nothing left to do, and may remove any analyser when it wants to
1443 * abort.
1444 */
1445int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1446{
Christopher Faulet9768c262018-10-22 09:34:31 +02001447 /*
1448 * We will analyze a complete HTTP response to check the its syntax.
1449 *
1450 * Once the start line and all headers are received, we may perform a
1451 * capture of the error (if any), and we will set a few fields. We also
1452 * logging and finally headers capture.
1453 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 struct session *sess = s->sess;
1455 struct http_txn *txn = s->txn;
1456 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001457 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001458 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001459 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001460 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 int n;
1462
1463 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1464 now_ms, __FUNCTION__,
1465 s,
1466 rep,
1467 rep->rex, rep->wex,
1468 rep->flags,
1469 ci_data(rep),
1470 rep->analysers);
1471
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001472 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473
Willy Tarreau4236f032019-03-05 10:43:32 +01001474 /* Parsing errors are caught here */
1475 if (htx->flags & HTX_FL_PARSING_ERROR)
1476 goto return_bad_res;
1477
Christopher Faulete0768eb2018-10-03 16:38:02 +02001478 /*
1479 * Now we quickly check if we have found a full valid response.
1480 * If not so, we check the FD and buffer states before leaving.
1481 * A full response is indicated by the fact that we have seen
1482 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1483 * responses are checked first.
1484 *
1485 * Depending on whether the client is still there or not, we
1486 * may send an error response back or not. Note that normally
1487 * we should only check for HTTP status there, and check I/O
1488 * errors somewhere else.
1489 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001490 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001491 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001492 /* 1: have we encountered a read error ? */
1493 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001494 struct connection *conn = NULL;
1495
Olivier Houchard865d8392019-05-03 22:46:27 +02001496 if (objt_cs(s->si[1].end))
1497 conn = objt_cs(s->si[1].end)->conn;
1498
1499 if (si_b->flags & SI_FL_L7_RETRY &&
1500 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001501 /* If we arrive here, then CF_READ_ERROR was
1502 * set by si_cs_recv() because we matched a
1503 * status, overwise it would have removed
1504 * the SI_FL_L7_RETRY flag, so it's ok not
1505 * to check s->be->retry_type.
1506 */
1507 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1508 return 0;
1509 }
1510
Olivier Houchard6db16992019-05-17 15:40:49 +02001511 if (txn->flags & TX_NOT_FIRST)
1512 goto abort_keep_alive;
1513
Olivier Houcharda798bf52019-03-08 18:52:00 +01001514 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001516 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001517 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 }
1519
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001521 s->req.analysers &= AN_REQ_FLT_END;
1522 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 txn->status = 502;
1524
1525 /* Check to see if the server refused the early data.
1526 * If so, just send a 425
1527 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001528 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1529 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001530 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001531 do_l7_retry(s, si_b) == 0)
1532 return 0;
1533 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
1536 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_SRVCL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001548 if ((si_b->flags & SI_FL_L7_RETRY) &&
1549 (s->be->retry_type & PR_RE_TIMEOUT)) {
1550 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1551 return 0;
1552 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001555 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001556 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 }
1558
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001560 s->req.analysers &= AN_REQ_FLT_END;
1561 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562 txn->status = 504;
1563 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565
1566 if (!(s->flags & SF_ERR_MASK))
1567 s->flags |= SF_ERR_SRVTO;
1568 if (!(s->flags & SF_FINST_MASK))
1569 s->flags |= SF_FINST_H;
1570 return 0;
1571 }
1572
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001575 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1576 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001578 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579
1580 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001581 s->req.analysers &= AN_REQ_FLT_END;
1582 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001584 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585
1586 if (!(s->flags & SF_ERR_MASK))
1587 s->flags |= SF_ERR_CLICL;
1588 if (!(s->flags & SF_FINST_MASK))
1589 s->flags |= SF_FINST_H;
1590
1591 /* process_stream() will take care of the error */
1592 return 0;
1593 }
1594
Christopher Faulet9768c262018-10-22 09:34:31 +02001595 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001597 if ((si_b->flags & SI_FL_L7_RETRY) &&
1598 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1599 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1600 return 0;
1601 }
1602
Olivier Houchard6db16992019-05-17 15:40:49 +02001603 if (txn->flags & TX_NOT_FIRST)
1604 goto abort_keep_alive;
1605
Olivier Houcharda798bf52019-03-08 18:52:00 +01001606 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001608 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001609 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610 }
1611
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001613 s->req.analysers &= AN_REQ_FLT_END;
1614 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 txn->status = 502;
1616 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001617 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618
1619 if (!(s->flags & SF_ERR_MASK))
1620 s->flags |= SF_ERR_SRVCL;
1621 if (!(s->flags & SF_FINST_MASK))
1622 s->flags |= SF_FINST_H;
1623 return 0;
1624 }
1625
Christopher Faulet9768c262018-10-22 09:34:31 +02001626 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 goto abort_keep_alive;
1630
Olivier Houcharda798bf52019-03-08 18:52:00 +01001631 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001632 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001633 s->req.analysers &= AN_REQ_FLT_END;
1634 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635
1636 if (!(s->flags & SF_ERR_MASK))
1637 s->flags |= SF_ERR_CLICL;
1638 if (!(s->flags & SF_FINST_MASK))
1639 s->flags |= SF_FINST_H;
1640
1641 /* process_stream() will take care of the error */
1642 return 0;
1643 }
1644
1645 channel_dont_close(rep);
1646 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1647 return 0;
1648 }
1649
1650 /* More interesting part now : we know that we have a complete
1651 * response which at least looks like HTTP. We have an indicator
1652 * of each header's length, so we can parse them quickly.
1653 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001654 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001655 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001656 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001657
Christopher Faulet9768c262018-10-22 09:34:31 +02001658 /* 0: we might have to print this header in debug mode */
1659 if (unlikely((global.mode & MODE_DEBUG) &&
1660 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1661 int32_t pos;
1662
Christopher Faulet03599112018-11-27 11:21:21 +01001663 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001664
Christopher Fauleta3f15502019-05-13 15:27:23 +02001665 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001666 struct htx_blk *blk = htx_get_blk(htx, pos);
1667 enum htx_blk_type type = htx_get_blk_type(blk);
1668
1669 if (type == HTX_BLK_EOH)
1670 break;
1671 if (type != HTX_BLK_HDR)
1672 continue;
1673
1674 htx_debug_hdr("srvhdr", s,
1675 htx_get_blk_name(htx, blk),
1676 htx_get_blk_value(htx, blk));
1677 }
1678 }
1679
Christopher Faulet03599112018-11-27 11:21:21 +01001680 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001681 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001682 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001683 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001684 if (sl->flags & HTX_SL_F_XFER_LEN) {
1685 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001686 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001687 if (sl->flags & HTX_SL_F_BODYLESS)
1688 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001689 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001690
1691 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692 if (n < 1 || n > 5)
1693 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001694
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695 /* when the client triggers a 4xx from the server, it's most often due
1696 * to a missing object or permission. These events should be tracked
1697 * because if they happen often, it may indicate a brute force or a
1698 * vulnerability scan.
1699 */
1700 if (n == 4)
1701 stream_inc_http_err_ctr(s);
1702
1703 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001704 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 /* Adjust server's health based on status code. Note: status codes 501
1707 * and 505 are triggered on demand by client request, so we must not
1708 * count them as server failures.
1709 */
1710 if (objt_server(s->target)) {
1711 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001712 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001714 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 }
1716
1717 /*
1718 * We may be facing a 100-continue response, or any other informational
1719 * 1xx response which is non-final, in which case this is not the right
1720 * response, and we're waiting for the next one. Let's allow this response
1721 * to go to the client and wait for the next one. There's an exception for
1722 * 101 which is used later in the code to switch protocols.
1723 */
1724 if (txn->status < 200 &&
1725 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001726 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001727 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001728 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001729 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001730 txn->status = 0;
1731 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001732 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001733 }
1734
1735 /*
1736 * 2: check for cacheability.
1737 */
1738
1739 switch (txn->status) {
1740 case 200:
1741 case 203:
1742 case 204:
1743 case 206:
1744 case 300:
1745 case 301:
1746 case 404:
1747 case 405:
1748 case 410:
1749 case 414:
1750 case 501:
1751 break;
1752 default:
1753 /* RFC7231#6.1:
1754 * Responses with status codes that are defined as
1755 * cacheable by default (e.g., 200, 203, 204, 206,
1756 * 300, 301, 404, 405, 410, 414, and 501 in this
1757 * specification) can be reused by a cache with
1758 * heuristic expiration unless otherwise indicated
1759 * by the method definition or explicit cache
1760 * controls [RFC7234]; all other status codes are
1761 * not cacheable by default.
1762 */
1763 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1764 break;
1765 }
1766
1767 /*
1768 * 3: we may need to capture headers
1769 */
1770 s->logs.logwait &= ~LW_RESP;
1771 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001772 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001773
Christopher Faulet9768c262018-10-22 09:34:31 +02001774 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001775 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1776 txn->status == 101)) {
1777 /* Either we've established an explicit tunnel, or we're
1778 * switching the protocol. In both cases, we're very unlikely
1779 * to understand the next protocols. We have to switch to tunnel
1780 * mode, so that we transfer the request and responses then let
1781 * this protocol pass unmodified. When we later implement specific
1782 * parsers for such protocols, we'll want to check the Upgrade
1783 * header which contains information about that protocol for
1784 * responses with status 101 (eg: see RFC2817 about TLS).
1785 */
1786 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001787 }
1788
Christopher Faulet61608322018-11-23 16:23:45 +01001789 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1790 * 407 (Proxy-Authenticate) responses and set the connection to private
1791 */
1792 srv_conn = cs_conn(objt_cs(s->si[1].end));
1793 if (srv_conn) {
1794 struct ist hdr;
1795 struct http_hdr_ctx ctx;
1796
1797 if (txn->status == 401)
1798 hdr = ist("WWW-Authenticate");
1799 else if (txn->status == 407)
1800 hdr = ist("Proxy-Authenticate");
1801 else
1802 goto end;
1803
1804 ctx.blk = NULL;
1805 while (http_find_header(htx, hdr, &ctx, 0)) {
1806 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchardd0cd72c2020-04-22 21:51:14 +02001807 (ctx.value.len >= 4 && !memcmp(ctx.value.ptr, "NTLM", 4))) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001808 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001809 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001810 }
Christopher Faulet61608322018-11-23 16:23:45 +01001811 }
1812 }
1813
1814 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001815 /* we want to have the response time before we start processing it */
1816 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1817
1818 /* end of job, return OK */
1819 rep->analysers &= ~an_bit;
1820 rep->analyse_exp = TICK_ETERNITY;
1821 channel_auto_close(rep);
1822 return 1;
1823
Christopher Faulet47365272018-10-31 17:40:50 +01001824 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001825 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001826 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001827 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001828 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001829 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001830 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001831 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001832 do_l7_retry(s, si_b) == 0)
1833 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001834 txn->status = 502;
1835 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001836 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001837 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001838 s->req.analysers &= AN_REQ_FLT_END;
1839 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001840
1841 if (!(s->flags & SF_ERR_MASK))
1842 s->flags |= SF_ERR_PRXCOND;
1843 if (!(s->flags & SF_FINST_MASK))
1844 s->flags |= SF_FINST_H;
1845 return 0;
1846
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 abort_keep_alive:
1848 /* A keep-alive request to the server failed on a network error.
1849 * The client is required to retry. We need to close without returning
1850 * any other information so that the client retries.
1851 */
1852 txn->status = 0;
1853 rep->analysers &= AN_RES_FLT_END;
1854 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001855 s->logs.logwait = 0;
1856 s->logs.level = 0;
1857 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001858 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 return 0;
1860}
1861
1862/* This function performs all the processing enabled for the current response.
1863 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1864 * and updates s->res.analysers. It might make sense to explode it into several
1865 * other functions. It works like process_request (see indications above).
1866 */
1867int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1868{
1869 struct session *sess = s->sess;
1870 struct http_txn *txn = s->txn;
1871 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001872 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001873 struct proxy *cur_proxy;
1874 struct cond_wordlist *wl;
1875 enum rule_result ret = HTTP_RULE_RES_CONT;
1876
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001877 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1878 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001879
Christopher Faulete0768eb2018-10-03 16:38:02 +02001880 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1881 now_ms, __FUNCTION__,
1882 s,
1883 rep,
1884 rep->rex, rep->wex,
1885 rep->flags,
1886 ci_data(rep),
1887 rep->analysers);
1888
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001889 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890
1891 /* The stats applet needs to adjust the Connection header but we don't
1892 * apply any filter there.
1893 */
1894 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1895 rep->analysers &= ~an_bit;
1896 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001897 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001898 }
1899
1900 /*
1901 * We will have to evaluate the filters.
1902 * As opposed to version 1.2, now they will be evaluated in the
1903 * filters order and not in the header order. This means that
1904 * each filter has to be validated among all headers.
1905 *
1906 * Filters are tried with ->be first, then with ->fe if it is
1907 * different from ->be.
1908 *
1909 * Maybe we are in resume condiion. In this case I choose the
1910 * "struct proxy" which contains the rule list matching the resume
1911 * pointer. If none of theses "struct proxy" match, I initialise
1912 * the process with the first one.
1913 *
1914 * In fact, I check only correspondance betwwen the current list
1915 * pointer and the ->fe rule list. If it doesn't match, I initialize
1916 * the loop with the ->be.
1917 */
1918 if (s->current_rule_list == &sess->fe->http_res_rules)
1919 cur_proxy = sess->fe;
1920 else
1921 cur_proxy = s->be;
1922 while (1) {
1923 struct proxy *rule_set = cur_proxy;
1924
1925 /* evaluate http-response rules */
1926 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001927 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001928
1929 if (ret == HTTP_RULE_RES_BADREQ)
1930 goto return_srv_prx_502;
1931
1932 if (ret == HTTP_RULE_RES_DONE) {
1933 rep->analysers &= ~an_bit;
1934 rep->analyse_exp = TICK_ETERNITY;
1935 return 1;
1936 }
1937 }
1938
1939 /* we need to be called again. */
1940 if (ret == HTTP_RULE_RES_YIELD) {
1941 channel_dont_close(rep);
1942 return 0;
1943 }
1944
1945 /* try headers filters */
1946 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001947 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1948 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001949 }
1950
1951 /* has the response been denied ? */
1952 if (txn->flags & TX_SVDENY) {
1953 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001954 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001955
Olivier Houcharda798bf52019-03-08 18:52:00 +01001956 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1957 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001958 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001959 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001960 goto return_srv_prx_502;
1961 }
1962
1963 /* add response headers from the rule sets in the same order */
1964 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001965 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966 if (txn->status < 200 && txn->status != 101)
1967 break;
1968 if (wl->cond) {
1969 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1970 ret = acl_pass(ret);
1971 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1972 ret = !ret;
1973 if (!ret)
1974 continue;
1975 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001976
1977 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1978 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001979 goto return_bad_resp;
1980 }
1981
1982 /* check whether we're already working on the frontend */
1983 if (cur_proxy == sess->fe)
1984 break;
1985 cur_proxy = sess->fe;
1986 }
1987
1988 /* After this point, this anayzer can't return yield, so we can
1989 * remove the bit corresponding to this analyzer from the list.
1990 *
1991 * Note that the intermediate returns and goto found previously
1992 * reset the analyzers.
1993 */
1994 rep->analysers &= ~an_bit;
1995 rep->analyse_exp = TICK_ETERNITY;
1996
1997 /* OK that's all we can do for 1xx responses */
1998 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001999 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002000
2001 /*
2002 * Now check for a server cookie.
2003 */
2004 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002005 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002006
2007 /*
2008 * Check for cache-control or pragma headers if required.
2009 */
2010 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2011 check_response_for_cacheability(s, rep);
2012
2013 /*
2014 * Add server cookie in the response if needed
2015 */
2016 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2017 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2018 (!(s->flags & SF_DIRECT) ||
2019 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2020 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2021 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2022 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2023 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2024 !(s->flags & SF_IGNORE_PRST)) {
2025 /* the server is known, it's not the one the client requested, or the
2026 * cookie's last seen date needs to be refreshed. We have to
2027 * insert a set-cookie here, except if we want to insert only on POST
2028 * requests and this one isn't. Note that servers which don't have cookies
2029 * (eg: some backup servers) will return a full cookie removal request.
2030 */
2031 if (!objt_server(s->target)->cookie) {
2032 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002033 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002034 s->be->cookie_name);
2035 }
2036 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002037 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002038
2039 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2040 /* emit last_date, which is mandatory */
2041 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2042 s30tob64((date.tv_sec+3) >> 2,
2043 trash.area + trash.data);
2044 trash.data += 5;
2045
2046 if (s->be->cookie_maxlife) {
2047 /* emit first_date, which is either the original one or
2048 * the current date.
2049 */
2050 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2051 s30tob64(txn->cookie_first_date ?
2052 txn->cookie_first_date >> 2 :
2053 (date.tv_sec+3) >> 2,
2054 trash.area + trash.data);
2055 trash.data += 5;
2056 }
2057 }
2058 chunk_appendf(&trash, "; path=/");
2059 }
2060
2061 if (s->be->cookie_domain)
2062 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2063
2064 if (s->be->ck_opts & PR_CK_HTTPONLY)
2065 chunk_appendf(&trash, "; HttpOnly");
2066
2067 if (s->be->ck_opts & PR_CK_SECURE)
2068 chunk_appendf(&trash, "; Secure");
2069
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002070 if (s->be->cookie_attrs)
2071 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2072
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002073 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002074 goto return_bad_resp;
2075
2076 txn->flags &= ~TX_SCK_MASK;
2077 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2078 /* the server did not change, only the date was updated */
2079 txn->flags |= TX_SCK_UPDATED;
2080 else
2081 txn->flags |= TX_SCK_INSERTED;
2082
2083 /* Here, we will tell an eventual cache on the client side that we don't
2084 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2085 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2086 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2087 */
2088 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2089
2090 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2091
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002092 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002093 goto return_bad_resp;
2094 }
2095 }
2096
2097 /*
2098 * Check if result will be cacheable with a cookie.
2099 * We'll block the response if security checks have caught
2100 * nasty things such as a cacheable cookie.
2101 */
2102 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2103 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2104 (s->be->options & PR_O_CHK_CACHE)) {
2105 /* we're in presence of a cacheable response containing
2106 * a set-cookie header. We'll block it as requested by
2107 * the 'checkcache' option, and send an alert.
2108 */
2109 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002110 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002111
Olivier Houcharda798bf52019-03-08 18:52:00 +01002112 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2113 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002114 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002115 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002116
2117 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2118 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2119 send_log(s->be, LOG_ALERT,
2120 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2121 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2122 goto return_srv_prx_502;
2123 }
2124
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002125 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 /* Always enter in the body analyzer */
2127 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2128 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2129
2130 /* if the user wants to log as soon as possible, without counting
2131 * bytes from the server, then this is the right moment. We have
2132 * to temporarily assign bytes_out to log what we currently have.
2133 */
2134 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2135 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002136 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002137 s->do_log(s);
2138 s->logs.bytes_out = 0;
2139 }
2140 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002141
2142 return_bad_resp:
2143 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002144 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002145 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002146 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002147 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002148
2149 return_srv_prx_502:
2150 rep->analysers &= AN_RES_FLT_END;
2151 txn->status = 502;
2152 s->logs.t_data = -1; /* was not a valid response */
2153 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002154 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002155 if (!(s->flags & SF_ERR_MASK))
2156 s->flags |= SF_ERR_PRXCOND;
2157 if (!(s->flags & SF_FINST_MASK))
2158 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002159
2160 s->req.analysers &= AN_REQ_FLT_END;
2161 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002162 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002163}
2164
2165/* This function is an analyser which forwards response body (including chunk
2166 * sizes if any). It is called as soon as we must forward, even if we forward
2167 * zero byte. The only situation where it must not be called is when we're in
2168 * tunnel mode and we want to forward till the close. It's used both to forward
2169 * remaining data and to resync after end of body. It expects the msg_state to
2170 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2171 * read more data, or 1 once we can go on with next request or end the stream.
2172 *
2173 * It is capable of compressing response data both in content-length mode and
2174 * in chunked mode. The state machines follows different flows depending on
2175 * whether content-length and chunked modes are used, since there are no
2176 * trailers in content-length :
2177 *
2178 * chk-mode cl-mode
2179 * ,----- BODY -----.
2180 * / \
2181 * V size > 0 V chk-mode
2182 * .--> SIZE -------------> DATA -------------> CRLF
2183 * | | size == 0 | last byte |
2184 * | v final crlf v inspected |
2185 * | TRAILERS -----------> DONE |
2186 * | |
2187 * `----------------------------------------------'
2188 *
2189 * Compression only happens in the DATA state, and must be flushed in final
2190 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2191 * is performed at once on final states for all bytes parsed, or when leaving
2192 * on missing data.
2193 */
2194int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2195{
2196 struct session *sess = s->sess;
2197 struct http_txn *txn = s->txn;
2198 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002199 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002200 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201
2202 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2203 now_ms, __FUNCTION__,
2204 s,
2205 res,
2206 res->rex, res->wex,
2207 res->flags,
2208 ci_data(res),
2209 res->analysers);
2210
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002211 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212
2213 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002214 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002215 /* Output closed while we were sending data. We must abort and
2216 * wake the other side up.
2217 */
2218 msg->err_state = msg->msg_state;
2219 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002220 htx_end_response(s);
2221 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222 return 1;
2223 }
2224
Christopher Faulet9768c262018-10-22 09:34:31 +02002225 if (msg->msg_state == HTTP_MSG_BODY)
2226 msg->msg_state = HTTP_MSG_DATA;
2227
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228 /* in most states, we should abort in case of early close */
2229 channel_auto_close(res);
2230
Christopher Faulete0768eb2018-10-03 16:38:02 +02002231 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002232 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002233 if (res->flags & CF_EOI)
2234 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002235 }
2236 else {
2237 /* We can't process the buffer's contents yet */
2238 res->flags |= CF_WAKE_WRITE;
2239 goto missing_data_or_waiting;
2240 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 }
2242
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002243 if (msg->msg_state >= HTTP_MSG_ENDING)
2244 goto ending;
2245
2246 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2247 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2248 msg->msg_state = HTTP_MSG_ENDING;
2249 goto ending;
2250 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002251
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002252 /* Forward input data. We get it by removing all outgoing data not
2253 * forwarded yet from HTX data size. If there are some data filters, we
2254 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002255 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002256 if (HAS_RSP_DATA_FILTERS(s)) {
2257 ret = flt_http_payload(s, msg, htx->data);
2258 if (ret < 0)
2259 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002260 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002261 }
2262 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002263 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002264 if (msg->flags & HTTP_MSGF_XFER_LEN)
2265 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002266 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002267
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002268 if (htx->data != co_data(res))
2269 goto missing_data_or_waiting;
2270
2271 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2272 msg->msg_state = HTTP_MSG_ENDING;
2273 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274 }
2275
Christopher Faulet9768c262018-10-22 09:34:31 +02002276 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002277 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2278 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002279 */
2280 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2281 goto missing_data_or_waiting;
2282
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002283 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002284
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002285 ending:
2286 /* other states, ENDING...TUNNEL */
2287 if (msg->msg_state >= HTTP_MSG_DONE)
2288 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002289
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002290 if (HAS_RSP_DATA_FILTERS(s)) {
2291 ret = flt_http_end(s, msg);
2292 if (ret <= 0) {
2293 if (!ret)
2294 goto missing_data_or_waiting;
2295 goto return_bad_res;
2296 }
2297 }
2298
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002299 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2300 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2301 msg->msg_state = HTTP_MSG_TUNNEL;
2302 goto ending;
2303 }
2304 else {
2305 msg->msg_state = HTTP_MSG_DONE;
2306 res->to_forward = 0;
2307 }
2308
2309 done:
2310
2311 channel_dont_close(res);
2312
Christopher Fauletf2824e62018-10-01 12:12:37 +02002313 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002314 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002315 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002316 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2317 if (res->flags & CF_SHUTW) {
2318 /* response errors are most likely due to the
2319 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002320 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002321 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002322 goto return_bad_res;
2323 }
2324 return 1;
2325 }
2326 return 0;
2327
2328 missing_data_or_waiting:
2329 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002330 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331
Christopher Faulet47365272018-10-31 17:40:50 +01002332 if (htx->flags & HTX_FL_PARSING_ERROR)
2333 goto return_bad_res;
2334
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335 /* stop waiting for data if the input is closed before the end. If the
2336 * client side was already closed, it means that the client has aborted,
2337 * so we don't want to count this as a server abort. Otherwise it's a
2338 * server abort.
2339 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002340 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002341 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002342 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002344 if (htx_is_empty(htx))
2345 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002346 }
2347
Christopher Faulete0768eb2018-10-03 16:38:02 +02002348 /* When TE: chunked is used, we need to get there again to parse
2349 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002350 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2351 * are filters registered on the stream, we don't want to forward a
2352 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002353 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002354 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002355 channel_dont_close(res);
2356
2357 /* We know that more data are expected, but we couldn't send more that
2358 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2359 * system knows it must not set a PUSH on this first part. Interactive
2360 * modes are already handled by the stream sock layer. We must not do
2361 * this in content-length mode because it could present the MSG_MORE
2362 * flag with the last block of forwarded data, which would cause an
2363 * additional delay to be observed by the receiver.
2364 */
2365 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2366 res->flags |= CF_EXPECT_MORE;
2367
2368 /* the stream handler will take care of timeouts and errors */
2369 return 0;
2370
Christopher Faulet93e02d82019-03-08 14:18:50 +01002371 return_srv_abort:
2372 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2373 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002374 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002375 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2376 if (!(s->flags & SF_ERR_MASK))
2377 s->flags |= SF_ERR_SRVCL;
2378 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002379
Christopher Faulet93e02d82019-03-08 14:18:50 +01002380 return_cli_abort:
2381 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2382 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002383 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002384 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2385 if (!(s->flags & SF_ERR_MASK))
2386 s->flags |= SF_ERR_CLICL;
2387 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002388
Christopher Faulet93e02d82019-03-08 14:18:50 +01002389 return_bad_res:
2390 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2391 if (objt_server(s->target)) {
2392 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2393 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2394 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002395 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002396 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002397
Christopher Faulet93e02d82019-03-08 14:18:50 +01002398 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002399 txn->rsp.err_state = txn->rsp.msg_state;
2400 txn->rsp.msg_state = HTTP_MSG_ERROR;
2401 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002402 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002403 res->analysers &= AN_RES_FLT_END;
2404 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 +02002405 if (!(s->flags & SF_FINST_MASK))
2406 s->flags |= SF_FINST_D;
2407 return 0;
2408}
2409
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002411 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002412 * as too large a request to build a valid response.
2413 */
2414int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2415{
Christopher Faulet99daf282018-11-28 22:58:13 +01002416 struct channel *req = &s->req;
2417 struct channel *res = &s->res;
2418 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002419 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002421 struct ist status, reason, location;
2422 unsigned int flags;
2423 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002424 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002425
2426 chunk = alloc_trash_chunk();
2427 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002428 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429
Christopher Faulet99daf282018-11-28 22:58:13 +01002430 /*
2431 * Create the location
2432 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002433 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002435 case REDIRECT_TYPE_SCHEME: {
2436 struct http_hdr_ctx ctx;
2437 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438
Christopher Faulet99daf282018-11-28 22:58:13 +01002439 host = ist("");
2440 ctx.blk = NULL;
2441 if (http_find_header(htx, ist("Host"), &ctx, 0))
2442 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002443
Christopher Faulet297fbb42019-05-13 14:41:27 +02002444 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 path = http_get_path(htx_sl_req_uri(sl));
2446 /* build message using path */
2447 if (path.ptr) {
2448 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2449 int qs = 0;
2450 while (qs < path.len) {
2451 if (*(path.ptr + qs) == '?') {
2452 path.len = qs;
2453 break;
2454 }
2455 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002457 }
2458 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002459 else
2460 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002461
Christopher Faulet99daf282018-11-28 22:58:13 +01002462 if (rule->rdr_str) { /* this is an old "redirect" rule */
2463 /* add scheme */
2464 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2465 goto fail;
2466 }
2467 else {
2468 /* add scheme with executing log format */
2469 chunk->data += build_logline(s, chunk->area + chunk->data,
2470 chunk->size - chunk->data,
2471 &rule->rdr_fmt);
2472 }
2473 /* add "://" + host + path */
2474 if (!chunk_memcat(chunk, "://", 3) ||
2475 !chunk_memcat(chunk, host.ptr, host.len) ||
2476 !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 Fauletf2824e62018-10-01 12:12:37 +02002488
Christopher Faulet99daf282018-11-28 22:58:13 +01002489 case REDIRECT_TYPE_PREFIX: {
2490 struct ist path;
2491
Christopher Faulet297fbb42019-05-13 14:41:27 +02002492 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002493 path = http_get_path(htx_sl_req_uri(sl));
2494 /* build message using path */
2495 if (path.ptr) {
2496 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2497 int qs = 0;
2498 while (qs < path.len) {
2499 if (*(path.ptr + qs) == '?') {
2500 path.len = qs;
2501 break;
2502 }
2503 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002504 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002505 }
2506 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002507 else
2508 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002509
Christopher Faulet99daf282018-11-28 22:58:13 +01002510 if (rule->rdr_str) { /* this is an old "redirect" rule */
2511 /* add prefix. Note that if prefix == "/", we don't want to
2512 * add anything, otherwise it makes it hard for the user to
2513 * configure a self-redirection.
2514 */
2515 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2516 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2517 goto fail;
2518 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002519 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 else {
2521 /* add prefix with executing log format */
2522 chunk->data += build_logline(s, chunk->area + chunk->data,
2523 chunk->size - chunk->data,
2524 &rule->rdr_fmt);
2525 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002526
Christopher Faulet99daf282018-11-28 22:58:13 +01002527 /* add path */
2528 if (!chunk_memcat(chunk, path.ptr, path.len))
2529 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002530
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 /* append a slash at the end of the location if needed and missing */
2532 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2533 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2534 if (chunk->data + 1 >= chunk->size)
2535 goto fail;
2536 chunk->area[chunk->data++] = '/';
2537 }
2538 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002540 case REDIRECT_TYPE_LOCATION:
2541 default:
2542 if (rule->rdr_str) { /* this is an old "redirect" rule */
2543 /* add location */
2544 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2545 goto fail;
2546 }
2547 else {
2548 /* add location with executing log format */
2549 chunk->data += build_logline(s, chunk->area + chunk->data,
2550 chunk->size - chunk->data,
2551 &rule->rdr_fmt);
2552 }
2553 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002554 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002555 location = ist2(chunk->area, chunk->data);
2556
2557 /*
2558 * Create the 30x response
2559 */
2560 switch (rule->code) {
2561 case 308:
2562 status = ist("308");
2563 reason = ist("Permanent Redirect");
2564 break;
2565 case 307:
2566 status = ist("307");
2567 reason = ist("Temporary Redirect");
2568 break;
2569 case 303:
2570 status = ist("303");
2571 reason = ist("See Other");
2572 break;
2573 case 301:
2574 status = ist("301");
2575 reason = ist("Moved Permanently");
2576 break;
2577 case 302:
2578 default:
2579 status = ist("302");
2580 reason = ist("Found");
2581 break;
2582 }
2583
Christopher Faulet08e66462019-05-23 16:44:59 +02002584 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2585 close = 1;
2586
Christopher Faulet99daf282018-11-28 22:58:13 +01002587 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002588 /* Trim any possible response */
2589 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002590 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2591 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2592 if (!sl)
2593 goto fail;
2594 sl->info.res.status = rule->code;
2595 s->txn->status = rule->code;
2596
Christopher Faulet08e66462019-05-23 16:44:59 +02002597 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2598 goto fail;
2599
2600 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002601 !htx_add_header(htx, ist("Location"), location))
2602 goto fail;
2603
2604 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2605 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2606 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002607 }
2608
2609 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002610 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2611 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002612 }
2613
Christopher Faulet99daf282018-11-28 22:58:13 +01002614 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2615 goto fail;
2616
Kevin Zhu0fd70882020-01-07 09:42:55 +01002617 htx_to_buf(htx, &res->buf);
2618
Christopher Faulet99daf282018-11-28 22:58:13 +01002619 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002620 c_adv(res, data);
2621 res->total += data;
2622
2623 channel_auto_read(req);
2624 channel_abort(req);
2625 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002626 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002627
2628 res->wex = tick_add_ifset(now_ms, res->wto);
2629 channel_auto_read(res);
2630 channel_auto_close(res);
2631 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002632 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2633 /* let's log the request time */
2634 s->logs.tv_request = now;
2635 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002636
Christopher Faulet7d84db32020-01-28 09:18:10 +01002637 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2638 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2639 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002640
2641 if (!(s->flags & SF_ERR_MASK))
2642 s->flags |= SF_ERR_LOCAL;
2643 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002644 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002645
Christopher Faulet99daf282018-11-28 22:58:13 +01002646 free_trash_chunk(chunk);
2647 return 1;
2648
2649 fail:
2650 /* If an error occurred, remove the incomplete HTTP response from the
2651 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002652 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002653 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002654 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002655}
2656
Christopher Faulet72333522018-10-24 11:25:02 +02002657int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2658 struct ist name, const char *str, struct my_regex *re, int action)
2659{
2660 struct http_hdr_ctx ctx;
2661 struct buffer *output = get_trash_chunk();
2662
2663 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2664 ctx.blk = NULL;
2665 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2666 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2667 continue;
2668
2669 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2670 if (output->data == -1)
2671 return -1;
2672 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2673 return -1;
2674 }
2675 return 0;
2676}
2677
2678static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2679 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2680{
2681 struct buffer *replace;
2682 int ret = -1;
2683
2684 replace = alloc_trash_chunk();
2685 if (!replace)
2686 goto leave;
2687
2688 replace->data = build_logline(s, replace->area, replace->size, fmt);
2689 if (replace->data >= replace->size - 1)
2690 goto leave;
2691
2692 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2693
2694 leave:
2695 free_trash_chunk(replace);
2696 return ret;
2697}
2698
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699
2700/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2701 * on success and -1 on error. The response channel is updated accordingly.
2702 */
2703static int htx_reply_103_early_hints(struct channel *res)
2704{
2705 struct htx *htx = htx_from_buf(&res->buf);
2706 size_t data;
2707
Christopher Faulet9869f932019-06-26 14:23:54 +02002708 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002709 /* If an error occurred during an Early-hint rule,
2710 * remove the incomplete HTTP 103 response from the
2711 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002712 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002713 return -1;
2714 }
2715
2716 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002717 c_adv(res, data);
2718 res->total += data;
2719 return 0;
2720}
2721
Christopher Faulet6eb92892018-11-15 16:39:29 +01002722/*
2723 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2724 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002725 * If <early_hints> is 0, it is starts a new response by adding the start
2726 * line. If an error occurred -1 is returned. On success 0 is returned. The
2727 * channel is not updated here. It must be done calling the function
2728 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002729 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002730static 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 +01002731{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002732 struct channel *res = &s->res;
2733 struct htx *htx = htx_from_buf(&res->buf);
2734 struct buffer *value = alloc_trash_chunk();
2735
Christopher Faulet6eb92892018-11-15 16:39:29 +01002736 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002737 struct htx_sl *sl;
2738 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2739 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2740
2741 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2742 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2743 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002744 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002745 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002746 }
2747
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002748 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2749 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002750 goto fail;
2751
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002752 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002753 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002754
2755 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002756 /* If an error occurred during an Early-hint rule, remove the incomplete
2757 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002758 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002759 free_trash_chunk(value);
2760 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002761}
2762
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002763/* This function executes one of the set-{method,path,query,uri} actions. It
2764 * takes the string from the variable 'replace' with length 'len', then modifies
2765 * the relevant part of the request line accordingly. Then it updates various
2766 * pointers to the next elements which were moved, and the total buffer length.
2767 * It finds the action to be performed in p[2], previously filled by function
2768 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2769 * error, though this can be revisited when this code is finally exploited.
2770 *
2771 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2772 * query string and 3 to replace uri.
2773 *
2774 * In query string case, the mark question '?' must be set at the start of the
2775 * string by the caller, event if the replacement query string is empty.
2776 */
2777int htx_req_replace_stline(int action, const char *replace, int len,
2778 struct proxy *px, struct stream *s)
2779{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002780 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002781
2782 switch (action) {
2783 case 0: // method
2784 if (!http_replace_req_meth(htx, ist2(replace, len)))
2785 return -1;
2786 break;
2787
2788 case 1: // path
2789 if (!http_replace_req_path(htx, ist2(replace, len)))
2790 return -1;
2791 break;
2792
2793 case 2: // query
2794 if (!http_replace_req_query(htx, ist2(replace, len)))
2795 return -1;
2796 break;
2797
2798 case 3: // uri
2799 if (!http_replace_req_uri(htx, ist2(replace, len)))
2800 return -1;
2801 break;
2802
2803 default:
2804 return -1;
2805 }
2806 return 0;
2807}
2808
2809/* This function replace the HTTP status code and the associated message. The
2810 * variable <status> contains the new status code. This function never fails.
2811 */
2812void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2813{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002814 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002815 char *res;
2816
2817 chunk_reset(&trash);
2818 res = ultoa_o(status, trash.area, trash.size);
2819 trash.data = res - trash.area;
2820
2821 /* Do we have a custom reason format string? */
2822 if (reason == NULL)
2823 reason = http_get_reason(status);
2824
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002825 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002826 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2827}
2828
Christopher Faulet3e964192018-10-24 11:39:23 +02002829/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2830 * transaction <txn>. Returns the verdict of the first rule that prevents
2831 * further processing of the request (auth, deny, ...), and defaults to
2832 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2833 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2834 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2835 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2836 * status.
2837 */
2838static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2839 struct stream *s, int *deny_status)
2840{
2841 struct session *sess = strm_sess(s);
2842 struct http_txn *txn = s->txn;
2843 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002844 struct act_rule *rule;
2845 struct http_hdr_ctx ctx;
2846 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002847 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2848 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002849 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002850
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002851 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002852
2853 /* If "the current_rule_list" match the executed rule list, we are in
2854 * resume condition. If a resume is needed it is always in the action
2855 * and never in the ACL or converters. In this case, we initialise the
2856 * current rule, and go to the action execution point.
2857 */
2858 if (s->current_rule) {
2859 rule = s->current_rule;
2860 s->current_rule = NULL;
2861 if (s->current_rule_list == rules)
2862 goto resume_execution;
2863 }
2864 s->current_rule_list = rules;
2865
2866 list_for_each_entry(rule, rules, list) {
2867 /* check optional condition */
2868 if (rule->cond) {
2869 int ret;
2870
2871 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2872 ret = acl_pass(ret);
2873
2874 if (rule->cond->pol == ACL_COND_UNLESS)
2875 ret = !ret;
2876
2877 if (!ret) /* condition not matched */
2878 continue;
2879 }
2880
2881 act_flags |= ACT_FLAG_FIRST;
2882 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002883 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2884 early_hints = 0;
2885 if (htx_reply_103_early_hints(&s->res) == -1) {
2886 rule_ret = HTTP_RULE_RES_BADREQ;
2887 goto end;
2888 }
2889 }
2890
Christopher Faulet3e964192018-10-24 11:39:23 +02002891 switch (rule->action) {
2892 case ACT_ACTION_ALLOW:
2893 rule_ret = HTTP_RULE_RES_STOP;
2894 goto end;
2895
2896 case ACT_ACTION_DENY:
2897 if (deny_status)
2898 *deny_status = rule->deny_status;
2899 rule_ret = HTTP_RULE_RES_DENY;
2900 goto end;
2901
2902 case ACT_HTTP_REQ_TARPIT:
2903 txn->flags |= TX_CLTARPIT;
2904 if (deny_status)
2905 *deny_status = rule->deny_status;
2906 rule_ret = HTTP_RULE_RES_DENY;
2907 goto end;
2908
2909 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002910 /* Auth might be performed on regular http-req rules as well as on stats */
2911 auth_realm = rule->arg.auth.realm;
2912 if (!auth_realm) {
2913 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2914 auth_realm = STATS_DEFAULT_REALM;
2915 else
2916 auth_realm = px->id;
2917 }
2918 /* send 401/407 depending on whether we use a proxy or not. We still
2919 * count one error, because normal browsing won't significantly
2920 * increase the counter but brute force attempts will.
2921 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002922 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002923 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2924 rule_ret = HTTP_RULE_RES_BADREQ;
2925 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002926 goto end;
2927
2928 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002929 rule_ret = HTTP_RULE_RES_DONE;
2930 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2931 rule_ret = HTTP_RULE_RES_BADREQ;
2932 goto end;
2933
2934 case ACT_HTTP_SET_NICE:
2935 s->task->nice = rule->arg.nice;
2936 break;
2937
2938 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002939 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002940 break;
2941
2942 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002943 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 break;
2945
2946 case ACT_HTTP_SET_LOGL:
2947 s->logs.level = rule->arg.loglevel;
2948 break;
2949
2950 case ACT_HTTP_REPLACE_HDR:
2951 case ACT_HTTP_REPLACE_VAL:
2952 if (htx_transform_header(s, &s->req, htx,
2953 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2954 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002955 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002956 rule_ret = HTTP_RULE_RES_BADREQ;
2957 goto end;
2958 }
2959 break;
2960
2961 case ACT_HTTP_DEL_HDR:
2962 /* remove all occurrences of the header */
2963 ctx.blk = NULL;
2964 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2965 http_remove_header(htx, &ctx);
2966 break;
2967
2968 case ACT_HTTP_SET_HDR:
2969 case ACT_HTTP_ADD_HDR: {
2970 /* The scope of the trash buffer must be limited to this function. The
2971 * build_logline() function can execute a lot of other function which
2972 * can use the trash buffer. So for limiting the scope of this global
2973 * buffer, we build first the header value using build_logline, and
2974 * after we store the header name.
2975 */
2976 struct buffer *replace;
2977 struct ist n, v;
2978
2979 replace = alloc_trash_chunk();
2980 if (!replace) {
2981 rule_ret = HTTP_RULE_RES_BADREQ;
2982 goto end;
2983 }
2984
2985 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2986 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2987 v = ist2(replace->area, replace->data);
2988
2989 if (rule->action == ACT_HTTP_SET_HDR) {
2990 /* remove all occurrences of the header */
2991 ctx.blk = NULL;
2992 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2993 http_remove_header(htx, &ctx);
2994 }
2995
2996 if (!http_add_header(htx, n, v)) {
2997 static unsigned char rate_limit = 0;
2998
2999 if ((rate_limit++ & 255) == 0) {
3000 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);
3001 }
3002
Olivier Houcharda798bf52019-03-08 18:52:00 +01003003 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003004 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003005 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003006 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003007 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003008 }
3009 free_trash_chunk(replace);
3010 break;
3011 }
3012
3013 case ACT_HTTP_DEL_ACL:
3014 case ACT_HTTP_DEL_MAP: {
3015 struct pat_ref *ref;
3016 struct buffer *key;
3017
3018 /* collect reference */
3019 ref = pat_ref_lookup(rule->arg.map.ref);
3020 if (!ref)
3021 continue;
3022
3023 /* allocate key */
3024 key = alloc_trash_chunk();
3025 if (!key) {
3026 rule_ret = HTTP_RULE_RES_BADREQ;
3027 goto end;
3028 }
3029
3030 /* collect key */
3031 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3032 key->area[key->data] = '\0';
3033
3034 /* perform update */
3035 /* returned code: 1=ok, 0=ko */
3036 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3037 pat_ref_delete(ref, key->area);
3038 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3039
3040 free_trash_chunk(key);
3041 break;
3042 }
3043
3044 case ACT_HTTP_ADD_ACL: {
3045 struct pat_ref *ref;
3046 struct buffer *key;
3047
3048 /* collect reference */
3049 ref = pat_ref_lookup(rule->arg.map.ref);
3050 if (!ref)
3051 continue;
3052
3053 /* allocate key */
3054 key = alloc_trash_chunk();
3055 if (!key) {
3056 rule_ret = HTTP_RULE_RES_BADREQ;
3057 goto end;
3058 }
3059
3060 /* collect key */
3061 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3062 key->area[key->data] = '\0';
3063
3064 /* perform update */
3065 /* add entry only if it does not already exist */
3066 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3067 if (pat_ref_find_elt(ref, key->area) == NULL)
3068 pat_ref_add(ref, key->area, NULL, NULL);
3069 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3070
3071 free_trash_chunk(key);
3072 break;
3073 }
3074
3075 case ACT_HTTP_SET_MAP: {
3076 struct pat_ref *ref;
3077 struct buffer *key, *value;
3078
3079 /* collect reference */
3080 ref = pat_ref_lookup(rule->arg.map.ref);
3081 if (!ref)
3082 continue;
3083
3084 /* allocate key */
3085 key = alloc_trash_chunk();
3086 if (!key) {
3087 rule_ret = HTTP_RULE_RES_BADREQ;
3088 goto end;
3089 }
3090
3091 /* allocate value */
3092 value = alloc_trash_chunk();
3093 if (!value) {
3094 free_trash_chunk(key);
3095 rule_ret = HTTP_RULE_RES_BADREQ;
3096 goto end;
3097 }
3098
3099 /* collect key */
3100 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3101 key->area[key->data] = '\0';
3102
3103 /* collect value */
3104 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3105 value->area[value->data] = '\0';
3106
3107 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003108 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003109 if (pat_ref_find_elt(ref, key->area) != NULL)
3110 /* update entry if it exists */
3111 pat_ref_set(ref, key->area, value->area, NULL);
3112 else
3113 /* insert a new entry */
3114 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003115 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003116 free_trash_chunk(key);
3117 free_trash_chunk(value);
3118 break;
3119 }
3120
3121 case ACT_HTTP_EARLY_HINT:
3122 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3123 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003124 early_hints = htx_add_early_hint_header(s, early_hints,
3125 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003126 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003127 if (early_hints == -1) {
3128 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003129 goto end;
3130 }
3131 break;
3132
3133 case ACT_CUSTOM:
3134 if ((s->req.flags & CF_READ_ERROR) ||
3135 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003136 (px->options & PR_O_ABRT_CLOSE)))
3137 act_flags |= ACT_FLAG_FINAL;
3138
3139 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3140 case ACT_RET_ERR:
3141 case ACT_RET_CONT:
3142 break;
3143 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003144 rule_ret = HTTP_RULE_RES_STOP;
3145 goto end;
3146 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003147 rule_ret = HTTP_RULE_RES_DONE;
3148 goto end;
3149 case ACT_RET_YIELD:
3150 s->current_rule = rule;
3151 rule_ret = HTTP_RULE_RES_YIELD;
3152 goto end;
3153 }
3154 break;
3155
3156 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3157 /* Note: only the first valid tracking parameter of each
3158 * applies.
3159 */
3160
3161 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3162 struct stktable *t;
3163 struct stksess *ts;
3164 struct stktable_key *key;
3165 void *ptr1, *ptr2;
3166
3167 t = rule->arg.trk_ctr.table.t;
3168 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3169 rule->arg.trk_ctr.expr, NULL);
3170
3171 if (key && (ts = stktable_get_entry(t, key))) {
3172 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3173
3174 /* let's count a new HTTP request as it's the first time we do it */
3175 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3176 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3177 if (ptr1 || ptr2) {
3178 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3179
3180 if (ptr1)
3181 stktable_data_cast(ptr1, http_req_cnt)++;
3182
3183 if (ptr2)
3184 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3185 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3186
3187 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3188
3189 /* If data was modified, we need to touch to re-schedule sync */
3190 stktable_touch_local(t, ts, 0);
3191 }
3192
3193 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3194 if (sess->fe != s->be)
3195 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3196 }
3197 }
3198 break;
3199
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003200 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003201 default:
3202 break;
3203 }
3204 }
3205
3206 end:
3207 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003208 if (htx_reply_103_early_hints(&s->res) == -1)
3209 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003210 }
3211
3212 /* we reached the end of the rules, nothing to report */
3213 return rule_ret;
3214}
3215
3216/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3217 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3218 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3219 * is returned, the process can continue the evaluation of next rule list. If
3220 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3221 * is returned, it means the operation could not be processed and a server error
3222 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3223 * deny rule. If *YIELD is returned, the caller must call again the function
3224 * with the same context.
3225 */
3226static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3227 struct stream *s)
3228{
3229 struct session *sess = strm_sess(s);
3230 struct http_txn *txn = s->txn;
3231 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003232 struct act_rule *rule;
3233 struct http_hdr_ctx ctx;
3234 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3235 int act_flags = 0;
3236
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003237 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003238
3239 /* If "the current_rule_list" match the executed rule list, we are in
3240 * resume condition. If a resume is needed it is always in the action
3241 * and never in the ACL or converters. In this case, we initialise the
3242 * current rule, and go to the action execution point.
3243 */
3244 if (s->current_rule) {
3245 rule = s->current_rule;
3246 s->current_rule = NULL;
3247 if (s->current_rule_list == rules)
3248 goto resume_execution;
3249 }
3250 s->current_rule_list = rules;
3251
3252 list_for_each_entry(rule, rules, list) {
3253 /* check optional condition */
3254 if (rule->cond) {
3255 int ret;
3256
3257 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3258 ret = acl_pass(ret);
3259
3260 if (rule->cond->pol == ACL_COND_UNLESS)
3261 ret = !ret;
3262
3263 if (!ret) /* condition not matched */
3264 continue;
3265 }
3266
3267 act_flags |= ACT_FLAG_FIRST;
3268resume_execution:
3269 switch (rule->action) {
3270 case ACT_ACTION_ALLOW:
3271 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3272 goto end;
3273
3274 case ACT_ACTION_DENY:
3275 txn->flags |= TX_SVDENY;
3276 rule_ret = HTTP_RULE_RES_STOP;
3277 goto end;
3278
3279 case ACT_HTTP_SET_NICE:
3280 s->task->nice = rule->arg.nice;
3281 break;
3282
3283 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003284 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003285 break;
3286
3287 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003288 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003289 break;
3290
3291 case ACT_HTTP_SET_LOGL:
3292 s->logs.level = rule->arg.loglevel;
3293 break;
3294
3295 case ACT_HTTP_REPLACE_HDR:
3296 case ACT_HTTP_REPLACE_VAL:
3297 if (htx_transform_header(s, &s->res, htx,
3298 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3299 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003300 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003301 rule_ret = HTTP_RULE_RES_BADREQ;
3302 goto end;
3303 }
3304 break;
3305
3306 case ACT_HTTP_DEL_HDR:
3307 /* remove all occurrences of the header */
3308 ctx.blk = NULL;
3309 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3310 http_remove_header(htx, &ctx);
3311 break;
3312
3313 case ACT_HTTP_SET_HDR:
3314 case ACT_HTTP_ADD_HDR: {
3315 struct buffer *replace;
3316 struct ist n, v;
3317
3318 replace = alloc_trash_chunk();
3319 if (!replace) {
3320 rule_ret = HTTP_RULE_RES_BADREQ;
3321 goto end;
3322 }
3323
3324 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3325 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3326 v = ist2(replace->area, replace->data);
3327
3328 if (rule->action == ACT_HTTP_SET_HDR) {
3329 /* remove all occurrences of the header */
3330 ctx.blk = NULL;
3331 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3332 http_remove_header(htx, &ctx);
3333 }
3334
3335 if (!http_add_header(htx, n, v)) {
3336 static unsigned char rate_limit = 0;
3337
3338 if ((rate_limit++ & 255) == 0) {
3339 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);
3340 }
3341
Olivier Houcharda798bf52019-03-08 18:52:00 +01003342 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003343 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003344 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003345 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003346 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003347 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003349 }
3350 free_trash_chunk(replace);
3351 break;
3352 }
3353
3354 case ACT_HTTP_DEL_ACL:
3355 case ACT_HTTP_DEL_MAP: {
3356 struct pat_ref *ref;
3357 struct buffer *key;
3358
3359 /* collect reference */
3360 ref = pat_ref_lookup(rule->arg.map.ref);
3361 if (!ref)
3362 continue;
3363
3364 /* allocate key */
3365 key = alloc_trash_chunk();
3366 if (!key) {
3367 rule_ret = HTTP_RULE_RES_BADREQ;
3368 goto end;
3369 }
3370
3371 /* collect key */
3372 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3373 key->area[key->data] = '\0';
3374
3375 /* perform update */
3376 /* returned code: 1=ok, 0=ko */
3377 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3378 pat_ref_delete(ref, key->area);
3379 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3380
3381 free_trash_chunk(key);
3382 break;
3383 }
3384
3385 case ACT_HTTP_ADD_ACL: {
3386 struct pat_ref *ref;
3387 struct buffer *key;
3388
3389 /* collect reference */
3390 ref = pat_ref_lookup(rule->arg.map.ref);
3391 if (!ref)
3392 continue;
3393
3394 /* allocate key */
3395 key = alloc_trash_chunk();
3396 if (!key) {
3397 rule_ret = HTTP_RULE_RES_BADREQ;
3398 goto end;
3399 }
3400
3401 /* collect key */
3402 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3403 key->area[key->data] = '\0';
3404
3405 /* perform update */
3406 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003407 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003408 if (pat_ref_find_elt(ref, key->area) == NULL)
3409 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003410 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003411 free_trash_chunk(key);
3412 break;
3413 }
3414
3415 case ACT_HTTP_SET_MAP: {
3416 struct pat_ref *ref;
3417 struct buffer *key, *value;
3418
3419 /* collect reference */
3420 ref = pat_ref_lookup(rule->arg.map.ref);
3421 if (!ref)
3422 continue;
3423
3424 /* allocate key */
3425 key = alloc_trash_chunk();
3426 if (!key) {
3427 rule_ret = HTTP_RULE_RES_BADREQ;
3428 goto end;
3429 }
3430
3431 /* allocate value */
3432 value = alloc_trash_chunk();
3433 if (!value) {
3434 free_trash_chunk(key);
3435 rule_ret = HTTP_RULE_RES_BADREQ;
3436 goto end;
3437 }
3438
3439 /* collect key */
3440 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3441 key->area[key->data] = '\0';
3442
3443 /* collect value */
3444 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3445 value->area[value->data] = '\0';
3446
3447 /* perform update */
3448 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3449 if (pat_ref_find_elt(ref, key->area) != NULL)
3450 /* update entry if it exists */
3451 pat_ref_set(ref, key->area, value->area, NULL);
3452 else
3453 /* insert a new entry */
3454 pat_ref_add(ref, key->area, value->area, NULL);
3455 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3456 free_trash_chunk(key);
3457 free_trash_chunk(value);
3458 break;
3459 }
3460
3461 case ACT_HTTP_REDIR:
3462 rule_ret = HTTP_RULE_RES_DONE;
3463 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3464 rule_ret = HTTP_RULE_RES_BADREQ;
3465 goto end;
3466
3467 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3468 /* Note: only the first valid tracking parameter of each
3469 * applies.
3470 */
3471 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3472 struct stktable *t;
3473 struct stksess *ts;
3474 struct stktable_key *key;
3475 void *ptr;
3476
3477 t = rule->arg.trk_ctr.table.t;
3478 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3479 rule->arg.trk_ctr.expr, NULL);
3480
3481 if (key && (ts = stktable_get_entry(t, key))) {
3482 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3483
3484 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3485
3486 /* let's count a new HTTP request as it's the first time we do it */
3487 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3488 if (ptr)
3489 stktable_data_cast(ptr, http_req_cnt)++;
3490
3491 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3492 if (ptr)
3493 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3494 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3495
3496 /* When the client triggers a 4xx from the server, it's most often due
3497 * to a missing object or permission. These events should be tracked
3498 * because if they happen often, it may indicate a brute force or a
3499 * vulnerability scan. Normally this is done when receiving the response
3500 * but here we're tracking after this ought to have been done so we have
3501 * to do it on purpose.
3502 */
3503 if ((unsigned)(txn->status - 400) < 100) {
3504 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3505 if (ptr)
3506 stktable_data_cast(ptr, http_err_cnt)++;
3507
3508 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3509 if (ptr)
3510 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3511 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3512 }
3513
3514 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3515
3516 /* If data was modified, we need to touch to re-schedule sync */
3517 stktable_touch_local(t, ts, 0);
3518
3519 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3520 if (sess->fe != s->be)
3521 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3522 }
3523 }
3524 break;
3525
3526 case ACT_CUSTOM:
3527 if ((s->req.flags & CF_READ_ERROR) ||
3528 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003529 (px->options & PR_O_ABRT_CLOSE)))
3530 act_flags |= ACT_FLAG_FINAL;
3531
3532 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3533 case ACT_RET_ERR:
3534 case ACT_RET_CONT:
3535 break;
3536 case ACT_RET_STOP:
3537 rule_ret = HTTP_RULE_RES_STOP;
3538 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003539 case ACT_RET_DONE:
3540 rule_ret = HTTP_RULE_RES_DONE;
3541 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003542 case ACT_RET_YIELD:
3543 s->current_rule = rule;
3544 rule_ret = HTTP_RULE_RES_YIELD;
3545 goto end;
3546 }
3547 break;
3548
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003549 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003550 default:
3551 break;
3552 }
3553 }
3554
3555 end:
3556 /* we reached the end of the rules, nothing to report */
3557 return rule_ret;
3558}
3559
Christopher Faulet33640082018-10-24 11:53:01 +02003560/* Iterate the same filter through all request headers.
3561 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3562 * Since it can manage the switch to another backend, it updates the per-proxy
3563 * DENY stats.
3564 */
3565static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3566{
3567 struct http_txn *txn = s->txn;
3568 struct htx *htx;
3569 struct buffer *hdr = get_trash_chunk();
3570 int32_t pos;
3571
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003572 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003573
Christopher Fauleta3f15502019-05-13 15:27:23 +02003574 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003575 struct htx_blk *blk = htx_get_blk(htx, pos);
3576 enum htx_blk_type type;
3577 struct ist n, v;
3578
3579 next_hdr:
3580 type = htx_get_blk_type(blk);
3581 if (type == HTX_BLK_EOH)
3582 break;
3583 if (type != HTX_BLK_HDR)
3584 continue;
3585
3586 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3587 return 1;
3588 else if (unlikely(txn->flags & TX_CLALLOW) &&
3589 (exp->action == ACT_ALLOW ||
3590 exp->action == ACT_DENY ||
3591 exp->action == ACT_TARPIT))
3592 return 0;
3593
3594 n = htx_get_blk_name(htx, blk);
3595 v = htx_get_blk_value(htx, blk);
3596
Christopher Faulet02e771a2019-02-26 15:36:05 +01003597 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003598 hdr->area[hdr->data++] = ':';
3599 hdr->area[hdr->data++] = ' ';
3600 chunk_memcat(hdr, v.ptr, v.len);
3601
3602 /* Now we have one header in <hdr> */
3603
3604 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3605 struct http_hdr_ctx ctx;
3606 int len;
3607
3608 switch (exp->action) {
3609 case ACT_ALLOW:
3610 txn->flags |= TX_CLALLOW;
3611 goto end;
3612
3613 case ACT_DENY:
3614 txn->flags |= TX_CLDENY;
3615 goto end;
3616
3617 case ACT_TARPIT:
3618 txn->flags |= TX_CLTARPIT;
3619 goto end;
3620
3621 case ACT_REPLACE:
3622 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3623 if (len < 0)
3624 return -1;
3625
3626 http_parse_header(ist2(trash.area, len), &n, &v);
3627 ctx.blk = blk;
3628 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003629 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003630 if (!http_replace_header(htx, &ctx, n, v))
3631 return -1;
3632 if (!ctx.blk)
3633 goto end;
3634 pos = htx_get_blk_pos(htx, blk);
3635 break;
3636
3637 case ACT_REMOVE:
3638 ctx.blk = blk;
3639 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003640 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003641 if (!http_remove_header(htx, &ctx))
3642 return -1;
3643 if (!ctx.blk)
3644 goto end;
3645 pos = htx_get_blk_pos(htx, blk);
3646 goto next_hdr;
3647
3648 }
3649 }
3650 }
3651 end:
3652 return 0;
3653}
3654
3655/* Apply the filter to the request line.
3656 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3657 * or -1 if a replacement resulted in an invalid request line.
3658 * Since it can manage the switch to another backend, it updates the per-proxy
3659 * DENY stats.
3660 */
3661static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3662{
3663 struct http_txn *txn = s->txn;
3664 struct htx *htx;
3665 struct buffer *reqline = get_trash_chunk();
3666 int done;
3667
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003668 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003669
3670 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3671 return 1;
3672 else if (unlikely(txn->flags & TX_CLALLOW) &&
3673 (exp->action == ACT_ALLOW ||
3674 exp->action == ACT_DENY ||
3675 exp->action == ACT_TARPIT))
3676 return 0;
3677 else if (exp->action == ACT_REMOVE)
3678 return 0;
3679
3680 done = 0;
3681
Christopher Faulet297fbb42019-05-13 14:41:27 +02003682 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003683
3684 /* Now we have the request line between cur_ptr and cur_end */
3685 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003686 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003687 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003688 int len;
3689
3690 switch (exp->action) {
3691 case ACT_ALLOW:
3692 txn->flags |= TX_CLALLOW;
3693 done = 1;
3694 break;
3695
3696 case ACT_DENY:
3697 txn->flags |= TX_CLDENY;
3698 done = 1;
3699 break;
3700
3701 case ACT_TARPIT:
3702 txn->flags |= TX_CLTARPIT;
3703 done = 1;
3704 break;
3705
3706 case ACT_REPLACE:
3707 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3708 if (len < 0)
3709 return -1;
3710
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003711 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3712 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3713 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003714 return -1;
3715 done = 1;
3716 break;
3717 }
3718 }
3719 return done;
3720}
3721
3722/*
3723 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3724 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3725 * unparsable request. Since it can manage the switch to another backend, it
3726 * updates the per-proxy DENY stats.
3727 */
3728static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3729{
3730 struct session *sess = s->sess;
3731 struct http_txn *txn = s->txn;
3732 struct hdr_exp *exp;
3733
3734 for (exp = px->req_exp; exp; exp = exp->next) {
3735 int ret;
3736
3737 /*
3738 * The interleaving of transformations and verdicts
3739 * makes it difficult to decide to continue or stop
3740 * the evaluation.
3741 */
3742
3743 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3744 break;
3745
3746 if ((txn->flags & TX_CLALLOW) &&
3747 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3748 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3749 continue;
3750
3751 /* if this filter had a condition, evaluate it now and skip to
3752 * next filter if the condition does not match.
3753 */
3754 if (exp->cond) {
3755 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3756 ret = acl_pass(ret);
3757 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3758 ret = !ret;
3759
3760 if (!ret)
3761 continue;
3762 }
3763
3764 /* Apply the filter to the request line. */
3765 ret = htx_apply_filter_to_req_line(s, req, exp);
3766 if (unlikely(ret < 0))
3767 return -1;
3768
3769 if (likely(ret == 0)) {
3770 /* The filter did not match the request, it can be
3771 * iterated through all headers.
3772 */
3773 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3774 return -1;
3775 }
3776 }
3777 return 0;
3778}
3779
3780/* Iterate the same filter through all response headers contained in <res>.
3781 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3782 */
3783static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3784{
3785 struct http_txn *txn = s->txn;
3786 struct htx *htx;
3787 struct buffer *hdr = get_trash_chunk();
3788 int32_t pos;
3789
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003790 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003791
Christopher Fauleta3f15502019-05-13 15:27:23 +02003792 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003793 struct htx_blk *blk = htx_get_blk(htx, pos);
3794 enum htx_blk_type type;
3795 struct ist n, v;
3796
3797 next_hdr:
3798 type = htx_get_blk_type(blk);
3799 if (type == HTX_BLK_EOH)
3800 break;
3801 if (type != HTX_BLK_HDR)
3802 continue;
3803
3804 if (unlikely(txn->flags & TX_SVDENY))
3805 return 1;
3806 else if (unlikely(txn->flags & TX_SVALLOW) &&
3807 (exp->action == ACT_ALLOW ||
3808 exp->action == ACT_DENY))
3809 return 0;
3810
3811 n = htx_get_blk_name(htx, blk);
3812 v = htx_get_blk_value(htx, blk);
3813
Christopher Faulet02e771a2019-02-26 15:36:05 +01003814 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003815 hdr->area[hdr->data++] = ':';
3816 hdr->area[hdr->data++] = ' ';
3817 chunk_memcat(hdr, v.ptr, v.len);
3818
3819 /* Now we have one header in <hdr> */
3820
3821 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3822 struct http_hdr_ctx ctx;
3823 int len;
3824
3825 switch (exp->action) {
3826 case ACT_ALLOW:
3827 txn->flags |= TX_SVALLOW;
3828 goto end;
3829 break;
3830
3831 case ACT_DENY:
3832 txn->flags |= TX_SVDENY;
3833 goto end;
3834 break;
3835
3836 case ACT_REPLACE:
3837 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3838 if (len < 0)
3839 return -1;
3840
3841 http_parse_header(ist2(trash.area, len), &n, &v);
3842 ctx.blk = blk;
3843 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003844 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003845 if (!http_replace_header(htx, &ctx, n, v))
3846 return -1;
3847 if (!ctx.blk)
3848 goto end;
3849 pos = htx_get_blk_pos(htx, blk);
3850 break;
3851
3852 case ACT_REMOVE:
3853 ctx.blk = blk;
3854 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003855 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003856 if (!http_remove_header(htx, &ctx))
3857 return -1;
3858 if (!ctx.blk)
3859 goto end;
3860 pos = htx_get_blk_pos(htx, blk);
3861 goto next_hdr;
3862 }
3863 }
3864
3865 }
3866 end:
3867 return 0;
3868}
3869
3870/* Apply the filter to the status line in the response buffer <res>.
3871 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3872 * or -1 if a replacement resulted in an invalid status line.
3873 */
3874static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3875{
3876 struct http_txn *txn = s->txn;
3877 struct htx *htx;
3878 struct buffer *resline = get_trash_chunk();
3879 int done;
3880
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003881 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003882
3883 if (unlikely(txn->flags & TX_SVDENY))
3884 return 1;
3885 else if (unlikely(txn->flags & TX_SVALLOW) &&
3886 (exp->action == ACT_ALLOW ||
3887 exp->action == ACT_DENY))
3888 return 0;
3889 else if (exp->action == ACT_REMOVE)
3890 return 0;
3891
3892 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003893 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003894
3895 /* Now we have the status line between cur_ptr and cur_end */
3896 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003897 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003898 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003899 int len;
3900
3901 switch (exp->action) {
3902 case ACT_ALLOW:
3903 txn->flags |= TX_SVALLOW;
3904 done = 1;
3905 break;
3906
3907 case ACT_DENY:
3908 txn->flags |= TX_SVDENY;
3909 done = 1;
3910 break;
3911
3912 case ACT_REPLACE:
3913 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3914 if (len < 0)
3915 return -1;
3916
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003917 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3918 sl->info.res.status = strl2ui(code.ptr, code.len);
3919 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003920 return -1;
3921
3922 done = 1;
3923 return 1;
3924 }
3925 }
3926 return done;
3927}
3928
3929/*
3930 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3931 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3932 * unparsable response.
3933 */
3934static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3935{
3936 struct session *sess = s->sess;
3937 struct http_txn *txn = s->txn;
3938 struct hdr_exp *exp;
3939
3940 for (exp = px->rsp_exp; exp; exp = exp->next) {
3941 int ret;
3942
3943 /*
3944 * The interleaving of transformations and verdicts
3945 * makes it difficult to decide to continue or stop
3946 * the evaluation.
3947 */
3948
3949 if (txn->flags & TX_SVDENY)
3950 break;
3951
3952 if ((txn->flags & TX_SVALLOW) &&
3953 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3954 exp->action == ACT_PASS)) {
3955 exp = exp->next;
3956 continue;
3957 }
3958
3959 /* if this filter had a condition, evaluate it now and skip to
3960 * next filter if the condition does not match.
3961 */
3962 if (exp->cond) {
3963 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3964 ret = acl_pass(ret);
3965 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3966 ret = !ret;
3967 if (!ret)
3968 continue;
3969 }
3970
3971 /* Apply the filter to the status line. */
3972 ret = htx_apply_filter_to_sts_line(s, res, exp);
3973 if (unlikely(ret < 0))
3974 return -1;
3975
3976 if (likely(ret == 0)) {
3977 /* The filter did not match the response, it can be
3978 * iterated through all headers.
3979 */
3980 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3981 return -1;
3982 }
3983 }
3984 return 0;
3985}
3986
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003987/*
3988 * Manage client-side cookie. It can impact performance by about 2% so it is
3989 * desirable to call it only when needed. This code is quite complex because
3990 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3991 * highly recommended not to touch this part without a good reason !
3992 */
3993static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3994{
3995 struct session *sess = s->sess;
3996 struct http_txn *txn = s->txn;
3997 struct htx *htx;
3998 struct http_hdr_ctx ctx;
3999 char *hdr_beg, *hdr_end, *del_from;
4000 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4001 int preserve_hdr;
4002
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004003 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004004 ctx.blk = NULL;
4005 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004006 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004007 del_from = NULL; /* nothing to be deleted */
4008 preserve_hdr = 0; /* assume we may kill the whole header */
4009
4010 /* Now look for cookies. Conforming to RFC2109, we have to support
4011 * attributes whose name begin with a '$', and associate them with
4012 * the right cookie, if we want to delete this cookie.
4013 * So there are 3 cases for each cookie read :
4014 * 1) it's a special attribute, beginning with a '$' : ignore it.
4015 * 2) it's a server id cookie that we *MAY* want to delete : save
4016 * some pointers on it (last semi-colon, beginning of cookie...)
4017 * 3) it's an application cookie : we *MAY* have to delete a previous
4018 * "special" cookie.
4019 * At the end of loop, if a "special" cookie remains, we may have to
4020 * remove it. If no application cookie persists in the header, we
4021 * *MUST* delete it.
4022 *
4023 * Note: RFC2965 is unclear about the processing of spaces around
4024 * the equal sign in the ATTR=VALUE form. A careful inspection of
4025 * the RFC explicitly allows spaces before it, and not within the
4026 * tokens (attrs or values). An inspection of RFC2109 allows that
4027 * too but section 10.1.3 lets one think that spaces may be allowed
4028 * after the equal sign too, resulting in some (rare) buggy
4029 * implementations trying to do that. So let's do what servers do.
4030 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4031 * allowed quoted strings in values, with any possible character
4032 * after a backslash, including control chars and delimitors, which
4033 * causes parsing to become ambiguous. Browsers also allow spaces
4034 * within values even without quotes.
4035 *
4036 * We have to keep multiple pointers in order to support cookie
4037 * removal at the beginning, middle or end of header without
4038 * corrupting the header. All of these headers are valid :
4039 *
4040 * hdr_beg hdr_end
4041 * | |
4042 * v |
4043 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4044 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4045 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4046 * | | | | | | |
4047 * | | | | | | |
4048 * | | | | | | +--> next
4049 * | | | | | +----> val_end
4050 * | | | | +-----------> val_beg
4051 * | | | +--------------> equal
4052 * | | +----------------> att_end
4053 * | +---------------------> att_beg
4054 * +--------------------------> prev
4055 *
4056 */
4057 hdr_beg = ctx.value.ptr;
4058 hdr_end = hdr_beg + ctx.value.len;
4059 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4060 /* Iterate through all cookies on this line */
4061
4062 /* find att_beg */
4063 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004064 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004065 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004066 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004067
4068 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4069 att_beg++;
4070
4071 /* find att_end : this is the first character after the last non
4072 * space before the equal. It may be equal to hdr_end.
4073 */
4074 equal = att_end = att_beg;
4075 while (equal < hdr_end) {
4076 if (*equal == '=' || *equal == ',' || *equal == ';')
4077 break;
4078 if (HTTP_IS_SPHT(*equal++))
4079 continue;
4080 att_end = equal;
4081 }
4082
4083 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4084 * is between <att_beg> and <equal>, both may be identical.
4085 */
4086 /* look for end of cookie if there is an equal sign */
4087 if (equal < hdr_end && *equal == '=') {
4088 /* look for the beginning of the value */
4089 val_beg = equal + 1;
4090 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4091 val_beg++;
4092
4093 /* find the end of the value, respecting quotes */
4094 next = http_find_cookie_value_end(val_beg, hdr_end);
4095
4096 /* make val_end point to the first white space or delimitor after the value */
4097 val_end = next;
4098 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4099 val_end--;
4100 }
4101 else
4102 val_beg = val_end = next = equal;
4103
4104 /* We have nothing to do with attributes beginning with
4105 * '$'. However, they will automatically be removed if a
4106 * header before them is removed, since they're supposed
4107 * to be linked together.
4108 */
4109 if (*att_beg == '$')
4110 continue;
4111
4112 /* Ignore cookies with no equal sign */
4113 if (equal == next) {
4114 /* This is not our cookie, so we must preserve it. But if we already
4115 * scheduled another cookie for removal, we cannot remove the
4116 * complete header, but we can remove the previous block itself.
4117 */
4118 preserve_hdr = 1;
4119 if (del_from != NULL) {
4120 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4121 val_end += delta;
4122 next += delta;
4123 hdr_end += delta;
4124 prev = del_from;
4125 del_from = NULL;
4126 }
4127 continue;
4128 }
4129
4130 /* if there are spaces around the equal sign, we need to
4131 * strip them otherwise we'll get trouble for cookie captures,
4132 * or even for rewrites. Since this happens extremely rarely,
4133 * it does not hurt performance.
4134 */
4135 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4136 int stripped_before = 0;
4137 int stripped_after = 0;
4138
4139 if (att_end != equal) {
4140 memmove(att_end, equal, hdr_end - equal);
4141 stripped_before = (att_end - equal);
4142 equal += stripped_before;
4143 val_beg += stripped_before;
4144 }
4145
4146 if (val_beg > equal + 1) {
4147 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4148 stripped_after = (equal + 1) - val_beg;
4149 val_beg += stripped_after;
4150 stripped_before += stripped_after;
4151 }
4152
4153 val_end += stripped_before;
4154 next += stripped_before;
4155 hdr_end += stripped_before;
4156 }
4157 /* now everything is as on the diagram above */
4158
4159 /* First, let's see if we want to capture this cookie. We check
4160 * that we don't already have a client side cookie, because we
4161 * can only capture one. Also as an optimisation, we ignore
4162 * cookies shorter than the declared name.
4163 */
4164 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4165 (val_end - att_beg >= sess->fe->capture_namelen) &&
4166 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4167 int log_len = val_end - att_beg;
4168
4169 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4170 ha_alert("HTTP logging : out of memory.\n");
4171 } else {
4172 if (log_len > sess->fe->capture_len)
4173 log_len = sess->fe->capture_len;
4174 memcpy(txn->cli_cookie, att_beg, log_len);
4175 txn->cli_cookie[log_len] = 0;
4176 }
4177 }
4178
4179 /* Persistence cookies in passive, rewrite or insert mode have the
4180 * following form :
4181 *
4182 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4183 *
4184 * For cookies in prefix mode, the form is :
4185 *
4186 * Cookie: NAME=SRV~VALUE
4187 */
4188 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4189 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4190 struct server *srv = s->be->srv;
4191 char *delim;
4192
4193 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4194 * have the server ID between val_beg and delim, and the original cookie between
4195 * delim+1 and val_end. Otherwise, delim==val_end :
4196 *
4197 * hdr_beg
4198 * |
4199 * v
4200 * NAME=SRV; # in all but prefix modes
4201 * NAME=SRV~OPAQUE ; # in prefix mode
4202 * || || | |+-> next
4203 * || || | +--> val_end
4204 * || || +---------> delim
4205 * || |+------------> val_beg
4206 * || +-------------> att_end = equal
4207 * |+-----------------> att_beg
4208 * +------------------> prev
4209 *
4210 */
4211 if (s->be->ck_opts & PR_CK_PFX) {
4212 for (delim = val_beg; delim < val_end; delim++)
4213 if (*delim == COOKIE_DELIM)
4214 break;
4215 }
4216 else {
4217 char *vbar1;
4218 delim = val_end;
4219 /* Now check if the cookie contains a date field, which would
4220 * appear after a vertical bar ('|') just after the server name
4221 * and before the delimiter.
4222 */
4223 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4224 if (vbar1) {
4225 /* OK, so left of the bar is the server's cookie and
4226 * right is the last seen date. It is a base64 encoded
4227 * 30-bit value representing the UNIX date since the
4228 * epoch in 4-second quantities.
4229 */
4230 int val;
4231 delim = vbar1++;
4232 if (val_end - vbar1 >= 5) {
4233 val = b64tos30(vbar1);
4234 if (val > 0)
4235 txn->cookie_last_date = val << 2;
4236 }
4237 /* look for a second vertical bar */
4238 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4239 if (vbar1 && (val_end - vbar1 > 5)) {
4240 val = b64tos30(vbar1 + 1);
4241 if (val > 0)
4242 txn->cookie_first_date = val << 2;
4243 }
4244 }
4245 }
4246
4247 /* if the cookie has an expiration date and the proxy wants to check
4248 * it, then we do that now. We first check if the cookie is too old,
4249 * then only if it has expired. We detect strict overflow because the
4250 * time resolution here is not great (4 seconds). Cookies with dates
4251 * in the future are ignored if their offset is beyond one day. This
4252 * allows an admin to fix timezone issues without expiring everyone
4253 * and at the same time avoids keeping unwanted side effects for too
4254 * long.
4255 */
4256 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4257 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4258 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4259 txn->flags &= ~TX_CK_MASK;
4260 txn->flags |= TX_CK_OLD;
4261 delim = val_beg; // let's pretend we have not found the cookie
4262 txn->cookie_first_date = 0;
4263 txn->cookie_last_date = 0;
4264 }
4265 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4266 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4267 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4268 txn->flags &= ~TX_CK_MASK;
4269 txn->flags |= TX_CK_EXPIRED;
4270 delim = val_beg; // let's pretend we have not found the cookie
4271 txn->cookie_first_date = 0;
4272 txn->cookie_last_date = 0;
4273 }
4274
4275 /* Here, we'll look for the first running server which supports the cookie.
4276 * This allows to share a same cookie between several servers, for example
4277 * to dedicate backup servers to specific servers only.
4278 * However, to prevent clients from sticking to cookie-less backup server
4279 * when they have incidentely learned an empty cookie, we simply ignore
4280 * empty cookies and mark them as invalid.
4281 * The same behaviour is applied when persistence must be ignored.
4282 */
4283 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4284 srv = NULL;
4285
4286 while (srv) {
4287 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4288 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4289 if ((srv->cur_state != SRV_ST_STOPPED) ||
4290 (s->be->options & PR_O_PERSIST) ||
4291 (s->flags & SF_FORCE_PRST)) {
4292 /* we found the server and we can use it */
4293 txn->flags &= ~TX_CK_MASK;
4294 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4295 s->flags |= SF_DIRECT | SF_ASSIGNED;
4296 s->target = &srv->obj_type;
4297 break;
4298 } else {
4299 /* we found a server, but it's down,
4300 * mark it as such and go on in case
4301 * another one is available.
4302 */
4303 txn->flags &= ~TX_CK_MASK;
4304 txn->flags |= TX_CK_DOWN;
4305 }
4306 }
4307 srv = srv->next;
4308 }
4309
4310 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4311 /* no server matched this cookie or we deliberately skipped it */
4312 txn->flags &= ~TX_CK_MASK;
4313 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4314 txn->flags |= TX_CK_UNUSED;
4315 else
4316 txn->flags |= TX_CK_INVALID;
4317 }
4318
4319 /* depending on the cookie mode, we may have to either :
4320 * - delete the complete cookie if we're in insert+indirect mode, so that
4321 * the server never sees it ;
4322 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004323 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004324 * if we're in cookie prefix mode
4325 */
4326 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4327 int delta; /* negative */
4328
4329 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4330 delta = val_beg - (delim + 1);
4331 val_end += delta;
4332 next += delta;
4333 hdr_end += delta;
4334 del_from = NULL;
4335 preserve_hdr = 1; /* we want to keep this cookie */
4336 }
4337 else if (del_from == NULL &&
4338 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4339 del_from = prev;
4340 }
4341 }
4342 else {
4343 /* This is not our cookie, so we must preserve it. But if we already
4344 * scheduled another cookie for removal, we cannot remove the
4345 * complete header, but we can remove the previous block itself.
4346 */
4347 preserve_hdr = 1;
4348
4349 if (del_from != NULL) {
4350 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4351 if (att_beg >= del_from)
4352 att_beg += delta;
4353 if (att_end >= del_from)
4354 att_end += delta;
4355 val_beg += delta;
4356 val_end += delta;
4357 next += delta;
4358 hdr_end += delta;
4359 prev = del_from;
4360 del_from = NULL;
4361 }
4362 }
4363
4364 /* continue with next cookie on this header line */
4365 att_beg = next;
4366 } /* for each cookie */
4367
4368
4369 /* There are no more cookies on this line.
4370 * We may still have one (or several) marked for deletion at the
4371 * end of the line. We must do this now in two ways :
4372 * - if some cookies must be preserved, we only delete from the
4373 * mark to the end of line ;
4374 * - if nothing needs to be preserved, simply delete the whole header
4375 */
4376 if (del_from) {
4377 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4378 }
4379 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004380 if (hdr_beg != hdr_end)
4381 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004382 else
4383 http_remove_header(htx, &ctx);
4384 }
4385 } /* for each "Cookie header */
4386}
4387
4388/*
4389 * Manage server-side cookies. It can impact performance by about 2% so it is
4390 * desirable to call it only when needed. This function is also used when we
4391 * just need to know if there is a cookie (eg: for check-cache).
4392 */
4393static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4394{
4395 struct session *sess = s->sess;
4396 struct http_txn *txn = s->txn;
4397 struct htx *htx;
4398 struct http_hdr_ctx ctx;
4399 struct server *srv;
4400 char *hdr_beg, *hdr_end;
4401 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004402 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004403
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004404 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004405
4406 ctx.blk = NULL;
4407 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004408 int is_first = 1;
4409
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004410 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4411 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4412 break;
4413 is_cookie2 = 1;
4414 }
4415
4416 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4417 * <prev> points to the colon.
4418 */
4419 txn->flags |= TX_SCK_PRESENT;
4420
4421 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4422 * check-cache is enabled) and we are not interested in checking
4423 * them. Warning, the cookie capture is declared in the frontend.
4424 */
4425 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4426 break;
4427
4428 /* OK so now we know we have to process this response cookie.
4429 * The format of the Set-Cookie header is slightly different
4430 * from the format of the Cookie header in that it does not
4431 * support the comma as a cookie delimiter (thus the header
4432 * cannot be folded) because the Expires attribute described in
4433 * the original Netscape's spec may contain an unquoted date
4434 * with a comma inside. We have to live with this because
4435 * many browsers don't support Max-Age and some browsers don't
4436 * support quoted strings. However the Set-Cookie2 header is
4437 * clean.
4438 *
4439 * We have to keep multiple pointers in order to support cookie
4440 * removal at the beginning, middle or end of header without
4441 * corrupting the header (in case of set-cookie2). A special
4442 * pointer, <scav> points to the beginning of the set-cookie-av
4443 * fields after the first semi-colon. The <next> pointer points
4444 * either to the end of line (set-cookie) or next unquoted comma
4445 * (set-cookie2). All of these headers are valid :
4446 *
4447 * hdr_beg hdr_end
4448 * | |
4449 * v |
4450 * NAME1 = VALUE 1 ; Secure; Path="/" |
4451 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4452 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4453 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4454 * | | | | | | | |
4455 * | | | | | | | +-> next
4456 * | | | | | | +------------> scav
4457 * | | | | | +--------------> val_end
4458 * | | | | +--------------------> val_beg
4459 * | | | +----------------------> equal
4460 * | | +------------------------> att_end
4461 * | +----------------------------> att_beg
4462 * +------------------------------> prev
4463 * -------------------------------> hdr_beg
4464 */
4465 hdr_beg = ctx.value.ptr;
4466 hdr_end = hdr_beg + ctx.value.len;
4467 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4468
4469 /* Iterate through all cookies on this line */
4470
4471 /* find att_beg */
4472 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004473 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004474 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004475 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004476
4477 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4478 att_beg++;
4479
4480 /* find att_end : this is the first character after the last non
4481 * space before the equal. It may be equal to hdr_end.
4482 */
4483 equal = att_end = att_beg;
4484
4485 while (equal < hdr_end) {
4486 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4487 break;
4488 if (HTTP_IS_SPHT(*equal++))
4489 continue;
4490 att_end = equal;
4491 }
4492
4493 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4494 * is between <att_beg> and <equal>, both may be identical.
4495 */
4496
4497 /* look for end of cookie if there is an equal sign */
4498 if (equal < hdr_end && *equal == '=') {
4499 /* look for the beginning of the value */
4500 val_beg = equal + 1;
4501 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4502 val_beg++;
4503
4504 /* find the end of the value, respecting quotes */
4505 next = http_find_cookie_value_end(val_beg, hdr_end);
4506
4507 /* make val_end point to the first white space or delimitor after the value */
4508 val_end = next;
4509 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4510 val_end--;
4511 }
4512 else {
4513 /* <equal> points to next comma, semi-colon or EOL */
4514 val_beg = val_end = next = equal;
4515 }
4516
4517 if (next < hdr_end) {
4518 /* Set-Cookie2 supports multiple cookies, and <next> points to
4519 * a colon or semi-colon before the end. So skip all attr-value
4520 * pairs and look for the next comma. For Set-Cookie, since
4521 * commas are permitted in values, skip to the end.
4522 */
4523 if (is_cookie2)
4524 next = http_find_hdr_value_end(next, hdr_end);
4525 else
4526 next = hdr_end;
4527 }
4528
4529 /* Now everything is as on the diagram above */
4530
4531 /* Ignore cookies with no equal sign */
4532 if (equal == val_end)
4533 continue;
4534
4535 /* If there are spaces around the equal sign, we need to
4536 * strip them otherwise we'll get trouble for cookie captures,
4537 * or even for rewrites. Since this happens extremely rarely,
4538 * it does not hurt performance.
4539 */
4540 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4541 int stripped_before = 0;
4542 int stripped_after = 0;
4543
4544 if (att_end != equal) {
4545 memmove(att_end, equal, hdr_end - equal);
4546 stripped_before = (att_end - equal);
4547 equal += stripped_before;
4548 val_beg += stripped_before;
4549 }
4550
4551 if (val_beg > equal + 1) {
4552 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4553 stripped_after = (equal + 1) - val_beg;
4554 val_beg += stripped_after;
4555 stripped_before += stripped_after;
4556 }
4557
4558 val_end += stripped_before;
4559 next += stripped_before;
4560 hdr_end += stripped_before;
4561
Christopher Faulet41dc8432019-06-18 09:49:16 +02004562 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004563 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004564 }
4565
4566 /* First, let's see if we want to capture this cookie. We check
4567 * that we don't already have a server side cookie, because we
4568 * can only capture one. Also as an optimisation, we ignore
4569 * cookies shorter than the declared name.
4570 */
4571 if (sess->fe->capture_name != NULL &&
4572 txn->srv_cookie == NULL &&
4573 (val_end - att_beg >= sess->fe->capture_namelen) &&
4574 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4575 int log_len = val_end - att_beg;
4576 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4577 ha_alert("HTTP logging : out of memory.\n");
4578 }
4579 else {
4580 if (log_len > sess->fe->capture_len)
4581 log_len = sess->fe->capture_len;
4582 memcpy(txn->srv_cookie, att_beg, log_len);
4583 txn->srv_cookie[log_len] = 0;
4584 }
4585 }
4586
4587 srv = objt_server(s->target);
4588 /* now check if we need to process it for persistence */
4589 if (!(s->flags & SF_IGNORE_PRST) &&
4590 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4591 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4592 /* assume passive cookie by default */
4593 txn->flags &= ~TX_SCK_MASK;
4594 txn->flags |= TX_SCK_FOUND;
4595
4596 /* If the cookie is in insert mode on a known server, we'll delete
4597 * this occurrence because we'll insert another one later.
4598 * We'll delete it too if the "indirect" option is set and we're in
4599 * a direct access.
4600 */
4601 if (s->be->ck_opts & PR_CK_PSV) {
4602 /* The "preserve" flag was set, we don't want to touch the
4603 * server's cookie.
4604 */
4605 }
4606 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4607 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4608 /* this cookie must be deleted */
4609 if (prev == hdr_beg && next == hdr_end) {
4610 /* whole header */
4611 http_remove_header(htx, &ctx);
4612 /* note: while both invalid now, <next> and <hdr_end>
4613 * are still equal, so the for() will stop as expected.
4614 */
4615 } else {
4616 /* just remove the value */
4617 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4618 next = prev;
4619 hdr_end += delta;
4620 }
4621 txn->flags &= ~TX_SCK_MASK;
4622 txn->flags |= TX_SCK_DELETED;
4623 /* and go on with next cookie */
4624 }
4625 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4626 /* replace bytes val_beg->val_end with the cookie name associated
4627 * with this server since we know it.
4628 */
4629 int sliding, delta;
4630
4631 ctx.value = ist2(val_beg, val_end - val_beg);
4632 ctx.lws_before = ctx.lws_after = 0;
4633 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4634 delta = srv->cklen - (val_end - val_beg);
4635 sliding = (ctx.value.ptr - val_beg);
4636 hdr_beg += sliding;
4637 val_beg += sliding;
4638 next += sliding + delta;
4639 hdr_end += sliding + delta;
4640
4641 txn->flags &= ~TX_SCK_MASK;
4642 txn->flags |= TX_SCK_REPLACED;
4643 }
4644 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4645 /* insert the cookie name associated with this server
4646 * before existing cookie, and insert a delimiter between them..
4647 */
4648 int sliding, delta;
4649 ctx.value = ist2(val_beg, 0);
4650 ctx.lws_before = ctx.lws_after = 0;
4651 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4652 delta = srv->cklen + 1;
4653 sliding = (ctx.value.ptr - val_beg);
4654 hdr_beg += sliding;
4655 val_beg += sliding;
4656 next += sliding + delta;
4657 hdr_end += sliding + delta;
4658
4659 val_beg[srv->cklen] = COOKIE_DELIM;
4660 txn->flags &= ~TX_SCK_MASK;
4661 txn->flags |= TX_SCK_REPLACED;
4662 }
4663 }
4664 /* that's done for this cookie, check the next one on the same
4665 * line when next != hdr_end (only if is_cookie2).
4666 */
4667 }
4668 }
4669}
4670
Christopher Faulet25a02f62018-10-24 12:00:25 +02004671/*
4672 * Parses the Cache-Control and Pragma request header fields to determine if
4673 * the request may be served from the cache and/or if it is cacheable. Updates
4674 * s->txn->flags.
4675 */
4676void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4677{
4678 struct http_txn *txn = s->txn;
4679 struct htx *htx;
4680 int32_t pos;
4681 int pragma_found, cc_found, i;
4682
4683 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4684 return; /* nothing more to do here */
4685
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004686 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004687 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004688 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004689 struct htx_blk *blk = htx_get_blk(htx, pos);
4690 enum htx_blk_type type = htx_get_blk_type(blk);
4691 struct ist n, v;
4692
4693 if (type == HTX_BLK_EOH)
4694 break;
4695 if (type != HTX_BLK_HDR)
4696 continue;
4697
4698 n = htx_get_blk_name(htx, blk);
4699 v = htx_get_blk_value(htx, blk);
4700
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004701 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004702 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4703 pragma_found = 1;
4704 continue;
4705 }
4706 }
4707
4708 /* Don't use the cache and don't try to store if we found the
4709 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004710 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004711 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4712 txn->flags |= TX_CACHE_IGNORE;
4713 continue;
4714 }
4715
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004716 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004717 continue;
4718
4719 /* OK, right now we know we have a cache-control header */
4720 cc_found = 1;
4721 if (!v.len) /* no info */
4722 continue;
4723
4724 i = 0;
4725 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4726 !isspace((unsigned char)*(v.ptr+i)))
4727 i++;
4728
4729 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4730 * values after max-age, max-stale nor min-fresh, we simply don't
4731 * use the cache when they're specified.
4732 */
4733 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4734 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4735 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4736 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4737 txn->flags |= TX_CACHE_IGNORE;
4738 continue;
4739 }
4740
4741 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4742 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4743 continue;
4744 }
4745 }
4746
4747 /* RFC7234#5.4:
4748 * When the Cache-Control header field is also present and
4749 * understood in a request, Pragma is ignored.
4750 * When the Cache-Control header field is not present in a
4751 * request, caches MUST consider the no-cache request
4752 * pragma-directive as having the same effect as if
4753 * "Cache-Control: no-cache" were present.
4754 */
4755 if (!cc_found && pragma_found)
4756 txn->flags |= TX_CACHE_IGNORE;
4757}
4758
4759/*
4760 * Check if response is cacheable or not. Updates s->txn->flags.
4761 */
4762void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4763{
4764 struct http_txn *txn = s->txn;
4765 struct htx *htx;
4766 int32_t pos;
4767 int i;
4768
4769 if (txn->status < 200) {
4770 /* do not try to cache interim responses! */
4771 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4772 return;
4773 }
4774
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004775 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004776 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004777 struct htx_blk *blk = htx_get_blk(htx, pos);
4778 enum htx_blk_type type = htx_get_blk_type(blk);
4779 struct ist n, v;
4780
4781 if (type == HTX_BLK_EOH)
4782 break;
4783 if (type != HTX_BLK_HDR)
4784 continue;
4785
4786 n = htx_get_blk_name(htx, blk);
4787 v = htx_get_blk_value(htx, blk);
4788
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004789 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004790 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4791 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4792 return;
4793 }
4794 }
4795
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004796 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004797 continue;
4798
4799 /* OK, right now we know we have a cache-control header */
4800 if (!v.len) /* no info */
4801 continue;
4802
4803 i = 0;
4804 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4805 !isspace((unsigned char)*(v.ptr+i)))
4806 i++;
4807
4808 /* we have a complete value between v.ptr and (v.ptr+i) */
4809 if (i < v.len && *(v.ptr + i) == '=') {
4810 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4811 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4812 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4813 continue;
4814 }
4815
4816 /* we have something of the form no-cache="set-cookie" */
4817 if ((v.len >= 21) &&
4818 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4819 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4820 txn->flags &= ~TX_CACHE_COOK;
4821 continue;
4822 }
4823
4824 /* OK, so we know that either p2 points to the end of string or to a comma */
4825 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4826 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4827 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4828 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4829 return;
4830 }
4831
4832 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4833 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4834 continue;
4835 }
4836 }
4837}
4838
Christopher Faulet64159df2018-10-24 21:15:35 +02004839/* send a server's name with an outgoing request over an established connection.
4840 * Note: this function is designed to be called once the request has been
4841 * scheduled for being forwarded. This is the reason why the number of forwarded
4842 * bytes have to be adjusted.
4843 */
4844int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4845{
4846 struct htx *htx;
4847 struct http_hdr_ctx ctx;
4848 struct ist hdr;
4849 uint32_t data;
4850
4851 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004852 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004853 data = htx->data;
4854
4855 ctx.blk = NULL;
4856 while (http_find_header(htx, hdr, &ctx, 1))
4857 http_remove_header(htx, &ctx);
4858 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4859
4860 if (co_data(&s->req)) {
4861 if (data >= htx->data)
4862 c_rew(&s->req, data - htx->data);
4863 else
4864 c_adv(&s->req, htx->data - data);
4865 }
4866 return 0;
4867}
4868
Christopher Faulet377c5a52018-10-24 21:21:30 +02004869/*
4870 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4871 * for the current backend.
4872 *
4873 * It is assumed that the request is either a HEAD, GET, or POST and that the
4874 * uri_auth field is valid.
4875 *
4876 * Returns 1 if stats should be provided, otherwise 0.
4877 */
4878static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4879{
4880 struct uri_auth *uri_auth = backend->uri_auth;
4881 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004882 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004883 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004884
4885 if (!uri_auth)
4886 return 0;
4887
4888 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4889 return 0;
4890
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004891 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004892 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004893 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004894
4895 /* check URI size */
4896 if (uri_auth->uri_len > uri.len)
4897 return 0;
4898
4899 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4900 return 0;
4901
4902 return 1;
4903}
4904
4905/* This function prepares an applet to handle the stats. It can deal with the
4906 * "100-continue" expectation, check that admin rules are met for POST requests,
4907 * and program a response message if something was unexpected. It cannot fail
4908 * and always relies on the stats applet to complete the job. It does not touch
4909 * analysers nor counters, which are left to the caller. It does not touch
4910 * s->target which is supposed to already point to the stats applet. The caller
4911 * is expected to have already assigned an appctx to the stream.
4912 */
4913static int htx_handle_stats(struct stream *s, struct channel *req)
4914{
4915 struct stats_admin_rule *stats_admin_rule;
4916 struct stream_interface *si = &s->si[1];
4917 struct session *sess = s->sess;
4918 struct http_txn *txn = s->txn;
4919 struct http_msg *msg = &txn->req;
4920 struct uri_auth *uri_auth = s->be->uri_auth;
4921 const char *h, *lookup, *end;
4922 struct appctx *appctx;
4923 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004924 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004925
4926 appctx = si_appctx(si);
4927 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4928 appctx->st1 = appctx->st2 = 0;
4929 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4930 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4931 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4932 appctx->ctx.stats.flags |= STAT_CHUNKED;
4933
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004934 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004935 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004936 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4937 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004938
4939 for (h = lookup; h <= end - 3; h++) {
4940 if (memcmp(h, ";up", 3) == 0) {
4941 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4942 break;
4943 }
4944 }
4945
4946 if (uri_auth->refresh) {
4947 for (h = lookup; h <= end - 10; h++) {
4948 if (memcmp(h, ";norefresh", 10) == 0) {
4949 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4950 break;
4951 }
4952 }
4953 }
4954
4955 for (h = lookup; h <= end - 4; h++) {
4956 if (memcmp(h, ";csv", 4) == 0) {
4957 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4958 break;
4959 }
4960 }
4961
4962 for (h = lookup; h <= end - 6; h++) {
4963 if (memcmp(h, ";typed", 6) == 0) {
4964 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4965 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4966 break;
4967 }
4968 }
4969
4970 for (h = lookup; h <= end - 8; h++) {
4971 if (memcmp(h, ";st=", 4) == 0) {
4972 int i;
4973 h += 4;
4974 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4975 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4976 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4977 appctx->ctx.stats.st_code = i;
4978 break;
4979 }
4980 }
4981 break;
4982 }
4983 }
4984
4985 appctx->ctx.stats.scope_str = 0;
4986 appctx->ctx.stats.scope_len = 0;
4987 for (h = lookup; h <= end - 8; h++) {
4988 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4989 int itx = 0;
4990 const char *h2;
4991 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4992 const char *err;
4993
4994 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4995 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004996 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4997 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004998 if (*h == ';' || *h == '&' || *h == ' ')
4999 break;
5000 itx++;
5001 h++;
5002 }
5003
5004 if (itx > STAT_SCOPE_TXT_MAXLEN)
5005 itx = STAT_SCOPE_TXT_MAXLEN;
5006 appctx->ctx.stats.scope_len = itx;
5007
5008 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5009 memcpy(scope_txt, h2, itx);
5010 scope_txt[itx] = '\0';
5011 err = invalid_char(scope_txt);
5012 if (err) {
5013 /* bad char in search text => clear scope */
5014 appctx->ctx.stats.scope_str = 0;
5015 appctx->ctx.stats.scope_len = 0;
5016 }
5017 break;
5018 }
5019 }
5020
5021 /* now check whether we have some admin rules for this request */
5022 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5023 int ret = 1;
5024
5025 if (stats_admin_rule->cond) {
5026 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5027 ret = acl_pass(ret);
5028 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5029 ret = !ret;
5030 }
5031
5032 if (ret) {
5033 /* no rule, or the rule matches */
5034 appctx->ctx.stats.flags |= STAT_ADMIN;
5035 break;
5036 }
5037 }
5038
Christopher Faulet5d45e382019-02-27 15:15:23 +01005039 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5040 appctx->st0 = STAT_HTTP_HEAD;
5041 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005042 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005043 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005044 if (msg->msg_state < HTTP_MSG_DATA)
5045 req->analysers |= AN_REQ_HTTP_BODY;
5046 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005047 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005048 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005049 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5050 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5051 appctx->st0 = STAT_HTTP_LAST;
5052 }
5053 }
5054 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005055 /* Unsupported method */
5056 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5057 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5058 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005059 }
5060
5061 s->task->nice = -32; /* small boost for HTTP statistics */
5062 return 1;
5063}
5064
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005065void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5066{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005067 struct channel *req = &s->req;
5068 struct channel *res = &s->res;
5069 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005070 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005071 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005072 struct ist path, location;
5073 unsigned int flags;
5074 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005075
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005076 /*
5077 * Create the location
5078 */
5079 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005081 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005082 /* special prefix "/" means don't change URL */
5083 srv = __objt_server(s->target);
5084 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5085 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5086 return;
5087 }
5088
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005089 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005090 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005091 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005092 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005093 if (!path.ptr)
5094 return;
5095
5096 if (!chunk_memcat(&trash, path.ptr, path.len))
5097 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005098 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005099
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005100 /*
5101 * Create the 302 respone
5102 */
5103 htx = htx_from_buf(&res->buf);
5104 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5105 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5106 ist("HTTP/1.1"), ist("302"), ist("Found"));
5107 if (!sl)
5108 goto fail;
5109 sl->info.res.status = 302;
5110 s->txn->status = 302;
5111
5112 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5113 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5114 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5115 !htx_add_header(htx, ist("Location"), location))
5116 goto fail;
5117
5118 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5119 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005120
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005121 /*
5122 * Send the message
5123 */
5124 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005125 c_adv(res, data);
5126 res->total += data;
5127
5128 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005129 si_shutr(si);
5130 si_shutw(si);
5131 si->err_type = SI_ET_NONE;
5132 si->state = SI_ST_CLO;
5133
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005134 channel_auto_read(req);
5135 channel_abort(req);
5136 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005137 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005138 channel_auto_read(res);
5139 channel_auto_close(res);
5140
5141 if (!(s->flags & SF_ERR_MASK))
5142 s->flags |= SF_ERR_LOCAL;
5143 if (!(s->flags & SF_FINST_MASK))
5144 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005145
5146 /* FIXME: we should increase a counter of redirects per server and per backend. */
5147 srv_inc_sess_ctr(srv);
5148 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005149 return;
5150
5151 fail:
5152 /* If an error occurred, remove the incomplete HTTP response from the
5153 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005154 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005155}
5156
Christopher Fauletf2824e62018-10-01 12:12:37 +02005157/* This function terminates the request because it was completly analyzed or
5158 * because an error was triggered during the body forwarding.
5159 */
5160static void htx_end_request(struct stream *s)
5161{
5162 struct channel *chn = &s->req;
5163 struct http_txn *txn = s->txn;
5164
5165 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5166 now_ms, __FUNCTION__, s,
5167 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5168 s->req.analysers, s->res.analysers);
5169
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005170 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5171 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005173 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005174 goto end;
5175 }
5176
5177 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5178 return;
5179
5180 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005181 /* No need to read anymore, the request was completely parsed.
5182 * We can shut the read side unless we want to abort_on_close,
5183 * or we have a POST request. The issue with POST requests is
5184 * that some browsers still send a CRLF after the request, and
5185 * this CRLF must be read so that it does not remain in the kernel
5186 * buffers, otherwise a close could cause an RST on some systems
5187 * (eg: Linux).
5188 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005189 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 channel_dont_read(chn);
5191
5192 /* if the server closes the connection, we want to immediately react
5193 * and close the socket to save packets and syscalls.
5194 */
5195 s->si[1].flags |= SI_FL_NOHALF;
5196
5197 /* In any case we've finished parsing the request so we must
5198 * disable Nagle when sending data because 1) we're not going
5199 * to shut this side, and 2) the server is waiting for us to
5200 * send pending data.
5201 */
5202 chn->flags |= CF_NEVER_WAIT;
5203
Christopher Fauletd01ce402019-01-02 17:44:13 +01005204 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5205 /* The server has not finished to respond, so we
5206 * don't want to move in order not to upset it.
5207 */
5208 return;
5209 }
5210
Christopher Fauletf2824e62018-10-01 12:12:37 +02005211 /* When we get here, it means that both the request and the
5212 * response have finished receiving. Depending on the connection
5213 * mode, we'll have to wait for the last bytes to leave in either
5214 * direction, and sometimes for a close to be effective.
5215 */
5216 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5217 /* Tunnel mode will not have any analyser so it needs to
5218 * poll for reads.
5219 */
5220 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005221 if (b_data(&chn->buf))
5222 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005223 txn->req.msg_state = HTTP_MSG_TUNNEL;
5224 }
5225 else {
5226 /* we're not expecting any new data to come for this
5227 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005228 *
5229 * However, there is an exception if the response
5230 * length is undefined. In this case, we need to wait
5231 * the close from the server. The response will be
5232 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 */
5234 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5235 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005237
5238 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5239 channel_shutr_now(chn);
5240 channel_shutw_now(chn);
5241 }
5242 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005243 goto check_channel_flags;
5244 }
5245
5246 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5247 http_msg_closing:
5248 /* nothing else to forward, just waiting for the output buffer
5249 * to be empty and for the shutw_now to take effect.
5250 */
5251 if (channel_is_empty(chn)) {
5252 txn->req.msg_state = HTTP_MSG_CLOSED;
5253 goto http_msg_closed;
5254 }
5255 else if (chn->flags & CF_SHUTW) {
5256 txn->req.err_state = txn->req.msg_state;
5257 txn->req.msg_state = HTTP_MSG_ERROR;
5258 goto end;
5259 }
5260 return;
5261 }
5262
5263 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5264 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005265 /* if we don't know whether the server will close, we need to hard close */
5266 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5267 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005268 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005269 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005270 channel_dont_read(chn);
5271 goto end;
5272 }
5273
5274 check_channel_flags:
5275 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5276 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5277 /* if we've just closed an output, let's switch */
5278 txn->req.msg_state = HTTP_MSG_CLOSING;
5279 goto http_msg_closing;
5280 }
5281
5282 end:
5283 chn->analysers &= AN_REQ_FLT_END;
5284 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5285 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5286 channel_auto_close(chn);
5287 channel_auto_read(chn);
5288}
5289
5290
5291/* This function terminates the response because it was completly analyzed or
5292 * because an error was triggered during the body forwarding.
5293 */
5294static void htx_end_response(struct stream *s)
5295{
5296 struct channel *chn = &s->res;
5297 struct http_txn *txn = s->txn;
5298
5299 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5300 now_ms, __FUNCTION__, s,
5301 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5302 s->req.analysers, s->res.analysers);
5303
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005304 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5305 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005306 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005307 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005308 goto end;
5309 }
5310
5311 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5312 return;
5313
5314 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5315 /* In theory, we don't need to read anymore, but we must
5316 * still monitor the server connection for a possible close
5317 * while the request is being uploaded, so we don't disable
5318 * reading.
5319 */
5320 /* channel_dont_read(chn); */
5321
5322 if (txn->req.msg_state < HTTP_MSG_DONE) {
5323 /* The client seems to still be sending data, probably
5324 * because we got an error response during an upload.
5325 * We have the choice of either breaking the connection
5326 * or letting it pass through. Let's do the later.
5327 */
5328 return;
5329 }
5330
5331 /* When we get here, it means that both the request and the
5332 * response have finished receiving. Depending on the connection
5333 * mode, we'll have to wait for the last bytes to leave in either
5334 * direction, and sometimes for a close to be effective.
5335 */
5336 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5337 channel_auto_read(chn);
5338 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005339 if (b_data(&chn->buf))
5340 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005341 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5342 }
5343 else {
5344 /* we're not expecting any new data to come for this
5345 * transaction, so we can close it.
5346 */
5347 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5348 channel_shutr_now(chn);
5349 channel_shutw_now(chn);
5350 }
5351 }
5352 goto check_channel_flags;
5353 }
5354
5355 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5356 http_msg_closing:
5357 /* nothing else to forward, just waiting for the output buffer
5358 * to be empty and for the shutw_now to take effect.
5359 */
5360 if (channel_is_empty(chn)) {
5361 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5362 goto http_msg_closed;
5363 }
5364 else if (chn->flags & CF_SHUTW) {
5365 txn->rsp.err_state = txn->rsp.msg_state;
5366 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005367 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005368 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005369 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005370 goto end;
5371 }
5372 return;
5373 }
5374
5375 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5376 http_msg_closed:
5377 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005378 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005379 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005380 goto end;
5381 }
5382
5383 check_channel_flags:
5384 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5385 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5386 /* if we've just closed an output, let's switch */
5387 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5388 goto http_msg_closing;
5389 }
5390
5391 end:
5392 chn->analysers &= AN_RES_FLT_END;
5393 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5394 chn->analysers |= AN_RES_FLT_XFER_DATA;
5395 channel_auto_close(chn);
5396 channel_auto_read(chn);
5397}
5398
Christopher Faulet0f226952018-10-22 09:29:56 +02005399void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5400 int finst, const struct buffer *msg)
5401{
5402 channel_auto_read(si_oc(si));
5403 channel_abort(si_oc(si));
5404 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005405 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005406 channel_auto_close(si_ic(si));
5407 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005408
5409 /* <msg> is an HTX structure. So we copy it in the response's
5410 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005411 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005412 struct channel *chn = si_ic(si);
5413 struct htx *htx;
5414
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005415 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005416 chn->buf.data = msg->data;
5417 memcpy(chn->buf.area, msg->area, msg->data);
5418 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005419 c_adv(chn, htx->data);
5420 chn->total += htx->data;
5421 }
5422 if (!(s->flags & SF_ERR_MASK))
5423 s->flags |= err;
5424 if (!(s->flags & SF_FINST_MASK))
5425 s->flags |= finst;
5426}
5427
5428void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5429{
5430 channel_auto_read(&s->req);
5431 channel_abort(&s->req);
5432 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005433 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5434 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005435
5436 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005437
5438 /* <msg> is an HTX structure. So we copy it in the response's
5439 * channel */
5440 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005441 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005442 struct channel *chn = &s->res;
5443 struct htx *htx;
5444
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005445 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005446 chn->buf.data = msg->data;
5447 memcpy(chn->buf.area, msg->area, msg->data);
5448 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005449 c_adv(chn, htx->data);
5450 chn->total += htx->data;
5451 }
5452
5453 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5454 channel_auto_read(&s->res);
5455 channel_auto_close(&s->res);
5456 channel_shutr_now(&s->res);
5457}
5458
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005459struct buffer *htx_error_message(struct stream *s)
5460{
5461 const int msgnum = http_get_status_idx(s->txn->status);
5462
5463 if (s->be->errmsg[msgnum].area)
5464 return &s->be->errmsg[msgnum];
5465 else if (strm_fe(s)->errmsg[msgnum].area)
5466 return &strm_fe(s)->errmsg[msgnum];
5467 else
5468 return &htx_err_chunks[msgnum];
5469}
5470
5471
Christopher Faulet4a28a532019-03-01 11:19:40 +01005472/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5473 * on success and -1 on error.
5474 */
5475static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5476{
5477 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5478 * then we must send an HTTP/1.1 100 Continue intermediate response.
5479 */
5480 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5481 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5482 struct ist hdr = { .ptr = "Expect", .len = 6 };
5483 struct http_hdr_ctx ctx;
5484
5485 ctx.blk = NULL;
5486 /* Expect is allowed in 1.1, look for it */
5487 if (http_find_header(htx, hdr, &ctx, 0) &&
5488 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5489 if (htx_reply_100_continue(s) == -1)
5490 return -1;
5491 http_remove_header(htx, &ctx);
5492 }
5493 }
5494 return 0;
5495}
5496
Christopher Faulet23a3c792018-11-28 10:01:23 +01005497/* Send a 100-Continue response to the client. It returns 0 on success and -1
5498 * on error. The response channel is updated accordingly.
5499 */
5500static int htx_reply_100_continue(struct stream *s)
5501{
5502 struct channel *res = &s->res;
5503 struct htx *htx = htx_from_buf(&res->buf);
5504 struct htx_sl *sl;
5505 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5506 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5507 size_t data;
5508
5509 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5510 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5511 if (!sl)
5512 goto fail;
5513 sl->info.res.status = 100;
5514
Christopher Faulet9869f932019-06-26 14:23:54 +02005515 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005516 goto fail;
5517
5518 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005519 c_adv(res, data);
5520 res->total += data;
5521 return 0;
5522
5523 fail:
5524 /* If an error occurred, remove the incomplete HTTP response from the
5525 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005526 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005527 return -1;
5528}
5529
Christopher Faulet12c51e22018-11-28 15:59:42 +01005530
5531/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5532 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5533 * error. The response channel is updated accordingly.
5534 */
5535static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5536{
5537 struct channel *res = &s->res;
5538 struct htx *htx = htx_from_buf(&res->buf);
5539 struct htx_sl *sl;
5540 struct ist code, body;
5541 int status;
5542 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5543 size_t data;
5544
5545 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5546 status = 401;
5547 code = ist("401");
5548 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5549 "You need a valid user and password to access this content.\n"
5550 "</body></html>\n");
5551 }
5552 else {
5553 status = 407;
5554 code = ist("407");
5555 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5556 "You need a valid user and password to access this content.\n"
5557 "</body></html>\n");
5558 }
5559
5560 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5561 ist("HTTP/1.1"), code, ist("Unauthorized"));
5562 if (!sl)
5563 goto fail;
5564 sl->info.res.status = status;
5565 s->txn->status = status;
5566
5567 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5568 goto fail;
5569
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005570 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5571 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005572 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005573 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5574 goto fail;
5575 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5576 goto fail;
5577 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005578 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005579 if (!htx_add_endof(htx, HTX_BLK_EOH))
5580 goto fail;
5581
5582 while (body.len) {
5583 size_t sent = htx_add_data(htx, body);
5584 if (!sent)
5585 goto fail;
5586 body.ptr += sent;
5587 body.len -= sent;
5588 }
5589
5590 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005591 goto fail;
5592
5593 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005594 c_adv(res, data);
5595 res->total += data;
5596
5597 channel_auto_read(&s->req);
5598 channel_abort(&s->req);
5599 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005600 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005601
5602 res->wex = tick_add_ifset(now_ms, res->wto);
5603 channel_auto_read(res);
5604 channel_auto_close(res);
5605 channel_shutr_now(res);
5606 return 0;
5607
5608 fail:
5609 /* If an error occurred, remove the incomplete HTTP response from the
5610 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005611 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005612 return -1;
5613}
5614
Christopher Faulet0f226952018-10-22 09:29:56 +02005615/*
5616 * Capture headers from message <htx> according to header list <cap_hdr>, and
5617 * fill the <cap> pointers appropriately.
5618 */
5619static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5620{
5621 struct cap_hdr *h;
5622 int32_t pos;
5623
Christopher Fauleta3f15502019-05-13 15:27:23 +02005624 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005625 struct htx_blk *blk = htx_get_blk(htx, pos);
5626 enum htx_blk_type type = htx_get_blk_type(blk);
5627 struct ist n, v;
5628
5629 if (type == HTX_BLK_EOH)
5630 break;
5631 if (type != HTX_BLK_HDR)
5632 continue;
5633
5634 n = htx_get_blk_name(htx, blk);
5635
5636 for (h = cap_hdr; h; h = h->next) {
5637 if (h->namelen && (h->namelen == n.len) &&
5638 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5639 if (cap[h->index] == NULL)
5640 cap[h->index] =
5641 pool_alloc(h->pool);
5642
5643 if (cap[h->index] == NULL) {
5644 ha_alert("HTTP capture : out of memory.\n");
5645 break;
5646 }
5647
5648 v = htx_get_blk_value(htx, blk);
5649 if (v.len > h->len)
5650 v.len = h->len;
5651
5652 memcpy(cap[h->index], v.ptr, v.len);
5653 cap[h->index][v.len]=0;
5654 }
5655 }
5656 }
5657}
5658
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005659/* Delete a value in a header between delimiters <from> and <next>. The header
5660 * itself is delimited by <start> and <end> pointers. The number of characters
5661 * displaced is returned, and the pointer to the first delimiter is updated if
5662 * required. The function tries as much as possible to respect the following
5663 * principles :
5664 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5665 * in which case <next> is simply removed
5666 * - set exactly one space character after the new first delimiter, unless there
5667 * are not enough characters in the block being moved to do so.
5668 * - remove unneeded spaces before the previous delimiter and after the new
5669 * one.
5670 *
5671 * It is the caller's responsibility to ensure that :
5672 * - <from> points to a valid delimiter or <start> ;
5673 * - <next> points to a valid delimiter or <end> ;
5674 * - there are non-space chars before <from>.
5675 */
5676static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5677{
5678 char *prev = *from;
5679
5680 if (prev == start) {
5681 /* We're removing the first value. eat the semicolon, if <next>
5682 * is lower than <end> */
5683 if (next < end)
5684 next++;
5685
5686 while (next < end && HTTP_IS_SPHT(*next))
5687 next++;
5688 }
5689 else {
5690 /* Remove useless spaces before the old delimiter. */
5691 while (HTTP_IS_SPHT(*(prev-1)))
5692 prev--;
5693 *from = prev;
5694
5695 /* copy the delimiter and if possible a space if we're
5696 * not at the end of the line.
5697 */
5698 if (next < end) {
5699 *prev++ = *next++;
5700 if (prev + 1 < next)
5701 *prev++ = ' ';
5702 while (next < end && HTTP_IS_SPHT(*next))
5703 next++;
5704 }
5705 }
5706 memmove(prev, next, end - next);
5707 return (prev - next);
5708}
5709
Christopher Faulet0f226952018-10-22 09:29:56 +02005710
5711/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005712 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005713 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005714static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005715{
5716 struct ist dst = ist2(str, 0);
5717
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005718 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005719 goto end;
5720 if (dst.len + 1 > len)
5721 goto end;
5722 dst.ptr[dst.len++] = ' ';
5723
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005724 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005725 goto end;
5726 if (dst.len + 1 > len)
5727 goto end;
5728 dst.ptr[dst.len++] = ' ';
5729
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005730 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005731 end:
5732 return dst.len;
5733}
5734
Christopher Fauletf0523542018-10-24 11:06:58 +02005735/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005736 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005737 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005738static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005739{
5740 struct ist dst = ist2(str, 0);
5741
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005742 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005743 goto end;
5744 if (dst.len + 1 > len)
5745 goto end;
5746 dst.ptr[dst.len++] = ' ';
5747
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005748 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005749 goto end;
5750 if (dst.len + 1 > len)
5751 goto end;
5752 dst.ptr[dst.len++] = ' ';
5753
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005754 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005755 end:
5756 return dst.len;
5757}
5758
5759
Christopher Faulet0f226952018-10-22 09:29:56 +02005760/*
5761 * Print a debug line with a start line.
5762 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005763static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005764{
5765 struct session *sess = strm_sess(s);
5766 int max;
5767
5768 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5769 dir,
5770 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5771 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5772
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005773 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005774 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005775 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005776 trash.area[trash.data++] = ' ';
5777
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005778 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005779 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005780 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005781 trash.area[trash.data++] = ' ';
5782
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005783 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005784 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005785 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005786 trash.area[trash.data++] = '\n';
5787
5788 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5789}
5790
5791/*
5792 * Print a debug line with a header.
5793 */
5794static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5795{
5796 struct session *sess = strm_sess(s);
5797 int max;
5798
5799 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5800 dir,
5801 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5802 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5803
5804 max = n.len;
5805 UBOUND(max, trash.size - trash.data - 3);
5806 chunk_memcat(&trash, n.ptr, max);
5807 trash.area[trash.data++] = ':';
5808 trash.area[trash.data++] = ' ';
5809
5810 max = v.len;
5811 UBOUND(max, trash.size - trash.data - 1);
5812 chunk_memcat(&trash, v.ptr, max);
5813 trash.area[trash.data++] = '\n';
5814
5815 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5816}
5817
5818
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005819__attribute__((constructor))
5820static void __htx_protocol_init(void)
5821{
5822}
5823
5824
5825/*
5826 * Local variables:
5827 * c-indent-level: 8
5828 * c-basic-offset: 8
5829 * End:
5830 */