blob: 1c82bcd18137c024032b9aa4b8faf54534e2433c [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 Houchard530249c2019-07-12 16:16:59 +02001416 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001417 si->exp = TICK_ETERNITY;
1418 res->rex = TICK_ETERNITY;
1419 res->to_forward = 0;
1420 res->analyse_exp = TICK_ETERNITY;
1421 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001422 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001423 si_release_endpoint(&s->si[1]);
1424 b_free(&req->buf);
1425 /* Swap the L7 buffer with the channel buffer */
1426 /* We know we stored the co_data as b_data, so get it there */
1427 co_data = b_data(&si->l7_buffer);
1428 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1429 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1430
1431 co_set_data(req, co_data);
1432 b_reset(&res->buf);
1433 co_set_data(res, 0);
1434 return 0;
1435}
1436
Christopher Faulete0768eb2018-10-03 16:38:02 +02001437/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1438 * processing can continue on next analysers, or zero if it either needs more
1439 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1440 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1441 * when it has nothing left to do, and may remove any analyser when it wants to
1442 * abort.
1443 */
1444int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1445{
Christopher Faulet9768c262018-10-22 09:34:31 +02001446 /*
1447 * We will analyze a complete HTTP response to check the its syntax.
1448 *
1449 * Once the start line and all headers are received, we may perform a
1450 * capture of the error (if any), and we will set a few fields. We also
1451 * logging and finally headers capture.
1452 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001453 struct session *sess = s->sess;
1454 struct http_txn *txn = s->txn;
1455 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001456 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001457 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001458 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001459 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 int n;
1461
1462 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1463 now_ms, __FUNCTION__,
1464 s,
1465 rep,
1466 rep->rex, rep->wex,
1467 rep->flags,
1468 ci_data(rep),
1469 rep->analysers);
1470
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001471 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472
Willy Tarreau4236f032019-03-05 10:43:32 +01001473 /* Parsing errors are caught here */
1474 if (htx->flags & HTX_FL_PARSING_ERROR)
1475 goto return_bad_res;
1476
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477 /*
1478 * Now we quickly check if we have found a full valid response.
1479 * If not so, we check the FD and buffer states before leaving.
1480 * A full response is indicated by the fact that we have seen
1481 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1482 * responses are checked first.
1483 *
1484 * Depending on whether the client is still there or not, we
1485 * may send an error response back or not. Note that normally
1486 * we should only check for HTTP status there, and check I/O
1487 * errors somewhere else.
1488 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001489 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001490 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001491 /* 1: have we encountered a read error ? */
1492 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001493 struct connection *conn = NULL;
1494
Olivier Houchard865d8392019-05-03 22:46:27 +02001495 if (objt_cs(s->si[1].end))
1496 conn = objt_cs(s->si[1].end)->conn;
1497
1498 if (si_b->flags & SI_FL_L7_RETRY &&
1499 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001500 /* If we arrive here, then CF_READ_ERROR was
1501 * set by si_cs_recv() because we matched a
1502 * status, overwise it would have removed
1503 * the SI_FL_L7_RETRY flag, so it's ok not
1504 * to check s->be->retry_type.
1505 */
1506 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1507 return 0;
1508 }
1509
Olivier Houchard6db16992019-05-17 15:40:49 +02001510 if (txn->flags & TX_NOT_FIRST)
1511 goto abort_keep_alive;
1512
Olivier Houcharda798bf52019-03-08 18:52:00 +01001513 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001515 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001516 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001517 }
1518
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 rep->analysers &= AN_RES_FLT_END;
1520 txn->status = 502;
1521
1522 /* Check to see if the server refused the early data.
1523 * If so, just send a 425
1524 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001525 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1526 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001527 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001528 do_l7_retry(s, si_b) == 0)
1529 return 0;
1530 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 }
1532
1533 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001534 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535
1536 if (!(s->flags & SF_ERR_MASK))
1537 s->flags |= SF_ERR_SRVCL;
1538 if (!(s->flags & SF_FINST_MASK))
1539 s->flags |= SF_FINST_H;
1540 return 0;
1541 }
1542
Christopher Faulet9768c262018-10-22 09:34:31 +02001543 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001545 if ((si_b->flags & SI_FL_L7_RETRY) &&
1546 (s->be->retry_type & PR_RE_TIMEOUT)) {
1547 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1548 return 0;
1549 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001550 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001552 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001553 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 }
1555
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 rep->analysers &= AN_RES_FLT_END;
1557 txn->status = 504;
1558 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001559 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560
1561 if (!(s->flags & SF_ERR_MASK))
1562 s->flags |= SF_ERR_SRVTO;
1563 if (!(s->flags & SF_FINST_MASK))
1564 s->flags |= SF_FINST_H;
1565 return 0;
1566 }
1567
Christopher Faulet9768c262018-10-22 09:34:31 +02001568 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001570 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1571 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001573 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574
1575 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001577 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578
1579 if (!(s->flags & SF_ERR_MASK))
1580 s->flags |= SF_ERR_CLICL;
1581 if (!(s->flags & SF_FINST_MASK))
1582 s->flags |= SF_FINST_H;
1583
1584 /* process_stream() will take care of the error */
1585 return 0;
1586 }
1587
Christopher Faulet9768c262018-10-22 09:34:31 +02001588 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001589 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001590 if ((si_b->flags & SI_FL_L7_RETRY) &&
1591 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1592 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1593 return 0;
1594 }
1595
Olivier Houchard6db16992019-05-17 15:40:49 +02001596 if (txn->flags & TX_NOT_FIRST)
1597 goto abort_keep_alive;
1598
Olivier Houcharda798bf52019-03-08 18:52:00 +01001599 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001601 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001602 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 }
1604
Christopher Faulete0768eb2018-10-03 16:38:02 +02001605 rep->analysers &= AN_RES_FLT_END;
1606 txn->status = 502;
1607 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001608 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001609
1610 if (!(s->flags & SF_ERR_MASK))
1611 s->flags |= SF_ERR_SRVCL;
1612 if (!(s->flags & SF_FINST_MASK))
1613 s->flags |= SF_FINST_H;
1614 return 0;
1615 }
1616
Christopher Faulet9768c262018-10-22 09:34:31 +02001617 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001619 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620 goto abort_keep_alive;
1621
Olivier Houcharda798bf52019-03-08 18:52:00 +01001622 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624
1625 if (!(s->flags & SF_ERR_MASK))
1626 s->flags |= SF_ERR_CLICL;
1627 if (!(s->flags & SF_FINST_MASK))
1628 s->flags |= SF_FINST_H;
1629
1630 /* process_stream() will take care of the error */
1631 return 0;
1632 }
1633
1634 channel_dont_close(rep);
1635 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1636 return 0;
1637 }
1638
1639 /* More interesting part now : we know that we have a complete
1640 * response which at least looks like HTTP. We have an indicator
1641 * of each header's length, so we can parse them quickly.
1642 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001643 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001644 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001645 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001646
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 /* 0: we might have to print this header in debug mode */
1648 if (unlikely((global.mode & MODE_DEBUG) &&
1649 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1650 int32_t pos;
1651
Christopher Faulet03599112018-11-27 11:21:21 +01001652 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001653
Christopher Fauleta3f15502019-05-13 15:27:23 +02001654 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001655 struct htx_blk *blk = htx_get_blk(htx, pos);
1656 enum htx_blk_type type = htx_get_blk_type(blk);
1657
1658 if (type == HTX_BLK_EOH)
1659 break;
1660 if (type != HTX_BLK_HDR)
1661 continue;
1662
1663 htx_debug_hdr("srvhdr", s,
1664 htx_get_blk_name(htx, blk),
1665 htx_get_blk_value(htx, blk));
1666 }
1667 }
1668
Christopher Faulet03599112018-11-27 11:21:21 +01001669 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001670 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001671 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001672 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001673 if (sl->flags & HTX_SL_F_XFER_LEN) {
1674 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001675 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001676 if (sl->flags & HTX_SL_F_BODYLESS)
1677 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001678 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001679
1680 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001681 if (n < 1 || n > 5)
1682 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001683
Christopher Faulete0768eb2018-10-03 16:38:02 +02001684 /* when the client triggers a 4xx from the server, it's most often due
1685 * to a missing object or permission. These events should be tracked
1686 * because if they happen often, it may indicate a brute force or a
1687 * vulnerability scan.
1688 */
1689 if (n == 4)
1690 stream_inc_http_err_ctr(s);
1691
1692 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001693 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695 /* Adjust server's health based on status code. Note: status codes 501
1696 * and 505 are triggered on demand by client request, so we must not
1697 * count them as server failures.
1698 */
1699 if (objt_server(s->target)) {
1700 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001701 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001703 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001704 }
1705
1706 /*
1707 * We may be facing a 100-continue response, or any other informational
1708 * 1xx response which is non-final, in which case this is not the right
1709 * response, and we're waiting for the next one. Let's allow this response
1710 * to go to the client and wait for the next one. There's an exception for
1711 * 101 which is used later in the code to switch protocols.
1712 */
1713 if (txn->status < 200 &&
1714 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001715 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001716 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001718 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001719 txn->status = 0;
1720 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001721 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001722 }
1723
1724 /*
1725 * 2: check for cacheability.
1726 */
1727
1728 switch (txn->status) {
1729 case 200:
1730 case 203:
1731 case 204:
1732 case 206:
1733 case 300:
1734 case 301:
1735 case 404:
1736 case 405:
1737 case 410:
1738 case 414:
1739 case 501:
1740 break;
1741 default:
1742 /* RFC7231#6.1:
1743 * Responses with status codes that are defined as
1744 * cacheable by default (e.g., 200, 203, 204, 206,
1745 * 300, 301, 404, 405, 410, 414, and 501 in this
1746 * specification) can be reused by a cache with
1747 * heuristic expiration unless otherwise indicated
1748 * by the method definition or explicit cache
1749 * controls [RFC7234]; all other status codes are
1750 * not cacheable by default.
1751 */
1752 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1753 break;
1754 }
1755
1756 /*
1757 * 3: we may need to capture headers
1758 */
1759 s->logs.logwait &= ~LW_RESP;
1760 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001761 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001762
Christopher Faulet9768c262018-10-22 09:34:31 +02001763 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001764 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1765 txn->status == 101)) {
1766 /* Either we've established an explicit tunnel, or we're
1767 * switching the protocol. In both cases, we're very unlikely
1768 * to understand the next protocols. We have to switch to tunnel
1769 * mode, so that we transfer the request and responses then let
1770 * this protocol pass unmodified. When we later implement specific
1771 * parsers for such protocols, we'll want to check the Upgrade
1772 * header which contains information about that protocol for
1773 * responses with status 101 (eg: see RFC2817 about TLS).
1774 */
1775 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776 }
1777
Christopher Faulet61608322018-11-23 16:23:45 +01001778 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1779 * 407 (Proxy-Authenticate) responses and set the connection to private
1780 */
1781 srv_conn = cs_conn(objt_cs(s->si[1].end));
1782 if (srv_conn) {
1783 struct ist hdr;
1784 struct http_hdr_ctx ctx;
1785
1786 if (txn->status == 401)
1787 hdr = ist("WWW-Authenticate");
1788 else if (txn->status == 407)
1789 hdr = ist("Proxy-Authenticate");
1790 else
1791 goto end;
1792
1793 ctx.blk = NULL;
1794 while (http_find_header(htx, hdr, &ctx, 0)) {
1795 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001796 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1797 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001798 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001799 }
Christopher Faulet61608322018-11-23 16:23:45 +01001800 }
1801 }
1802
1803 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 /* we want to have the response time before we start processing it */
1805 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1806
1807 /* end of job, return OK */
1808 rep->analysers &= ~an_bit;
1809 rep->analyse_exp = TICK_ETERNITY;
1810 channel_auto_close(rep);
1811 return 1;
1812
Christopher Faulet47365272018-10-31 17:40:50 +01001813 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001814 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001815 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001816 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001817 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001818 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001819 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001820 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001821 do_l7_retry(s, si_b) == 0)
1822 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001823 txn->status = 502;
1824 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001825 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001826 rep->analysers &= AN_RES_FLT_END;
1827
1828 if (!(s->flags & SF_ERR_MASK))
1829 s->flags |= SF_ERR_PRXCOND;
1830 if (!(s->flags & SF_FINST_MASK))
1831 s->flags |= SF_FINST_H;
1832 return 0;
1833
Christopher Faulete0768eb2018-10-03 16:38:02 +02001834 abort_keep_alive:
1835 /* A keep-alive request to the server failed on a network error.
1836 * The client is required to retry. We need to close without returning
1837 * any other information so that the client retries.
1838 */
1839 txn->status = 0;
1840 rep->analysers &= AN_RES_FLT_END;
1841 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001842 s->logs.logwait = 0;
1843 s->logs.level = 0;
1844 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001845 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001846 return 0;
1847}
1848
1849/* This function performs all the processing enabled for the current response.
1850 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1851 * and updates s->res.analysers. It might make sense to explode it into several
1852 * other functions. It works like process_request (see indications above).
1853 */
1854int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1855{
1856 struct session *sess = s->sess;
1857 struct http_txn *txn = s->txn;
1858 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001859 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001860 struct proxy *cur_proxy;
1861 struct cond_wordlist *wl;
1862 enum rule_result ret = HTTP_RULE_RES_CONT;
1863
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001864 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1865 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001866
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1868 now_ms, __FUNCTION__,
1869 s,
1870 rep,
1871 rep->rex, rep->wex,
1872 rep->flags,
1873 ci_data(rep),
1874 rep->analysers);
1875
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001876 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001877
1878 /* The stats applet needs to adjust the Connection header but we don't
1879 * apply any filter there.
1880 */
1881 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1882 rep->analysers &= ~an_bit;
1883 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001884 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001885 }
1886
1887 /*
1888 * We will have to evaluate the filters.
1889 * As opposed to version 1.2, now they will be evaluated in the
1890 * filters order and not in the header order. This means that
1891 * each filter has to be validated among all headers.
1892 *
1893 * Filters are tried with ->be first, then with ->fe if it is
1894 * different from ->be.
1895 *
1896 * Maybe we are in resume condiion. In this case I choose the
1897 * "struct proxy" which contains the rule list matching the resume
1898 * pointer. If none of theses "struct proxy" match, I initialise
1899 * the process with the first one.
1900 *
1901 * In fact, I check only correspondance betwwen the current list
1902 * pointer and the ->fe rule list. If it doesn't match, I initialize
1903 * the loop with the ->be.
1904 */
1905 if (s->current_rule_list == &sess->fe->http_res_rules)
1906 cur_proxy = sess->fe;
1907 else
1908 cur_proxy = s->be;
1909 while (1) {
1910 struct proxy *rule_set = cur_proxy;
1911
1912 /* evaluate http-response rules */
1913 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001914 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001915
1916 if (ret == HTTP_RULE_RES_BADREQ)
1917 goto return_srv_prx_502;
1918
1919 if (ret == HTTP_RULE_RES_DONE) {
1920 rep->analysers &= ~an_bit;
1921 rep->analyse_exp = TICK_ETERNITY;
1922 return 1;
1923 }
1924 }
1925
1926 /* we need to be called again. */
1927 if (ret == HTTP_RULE_RES_YIELD) {
1928 channel_dont_close(rep);
1929 return 0;
1930 }
1931
1932 /* try headers filters */
1933 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001934 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1935 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001936 }
1937
1938 /* has the response been denied ? */
1939 if (txn->flags & TX_SVDENY) {
1940 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001941 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001942
Olivier Houcharda798bf52019-03-08 18:52:00 +01001943 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1944 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001946 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001947 goto return_srv_prx_502;
1948 }
1949
1950 /* add response headers from the rule sets in the same order */
1951 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001952 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001953 if (txn->status < 200 && txn->status != 101)
1954 break;
1955 if (wl->cond) {
1956 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1957 ret = acl_pass(ret);
1958 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1959 ret = !ret;
1960 if (!ret)
1961 continue;
1962 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001963
1964 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1965 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966 goto return_bad_resp;
1967 }
1968
1969 /* check whether we're already working on the frontend */
1970 if (cur_proxy == sess->fe)
1971 break;
1972 cur_proxy = sess->fe;
1973 }
1974
1975 /* After this point, this anayzer can't return yield, so we can
1976 * remove the bit corresponding to this analyzer from the list.
1977 *
1978 * Note that the intermediate returns and goto found previously
1979 * reset the analyzers.
1980 */
1981 rep->analysers &= ~an_bit;
1982 rep->analyse_exp = TICK_ETERNITY;
1983
1984 /* OK that's all we can do for 1xx responses */
1985 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001986 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001987
1988 /*
1989 * Now check for a server cookie.
1990 */
1991 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001992 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001993
1994 /*
1995 * Check for cache-control or pragma headers if required.
1996 */
1997 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1998 check_response_for_cacheability(s, rep);
1999
2000 /*
2001 * Add server cookie in the response if needed
2002 */
2003 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2004 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2005 (!(s->flags & SF_DIRECT) ||
2006 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2007 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2008 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2009 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2010 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2011 !(s->flags & SF_IGNORE_PRST)) {
2012 /* the server is known, it's not the one the client requested, or the
2013 * cookie's last seen date needs to be refreshed. We have to
2014 * insert a set-cookie here, except if we want to insert only on POST
2015 * requests and this one isn't. Note that servers which don't have cookies
2016 * (eg: some backup servers) will return a full cookie removal request.
2017 */
2018 if (!objt_server(s->target)->cookie) {
2019 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002020 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002021 s->be->cookie_name);
2022 }
2023 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002024 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002025
2026 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2027 /* emit last_date, which is mandatory */
2028 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2029 s30tob64((date.tv_sec+3) >> 2,
2030 trash.area + trash.data);
2031 trash.data += 5;
2032
2033 if (s->be->cookie_maxlife) {
2034 /* emit first_date, which is either the original one or
2035 * the current date.
2036 */
2037 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2038 s30tob64(txn->cookie_first_date ?
2039 txn->cookie_first_date >> 2 :
2040 (date.tv_sec+3) >> 2,
2041 trash.area + trash.data);
2042 trash.data += 5;
2043 }
2044 }
2045 chunk_appendf(&trash, "; path=/");
2046 }
2047
2048 if (s->be->cookie_domain)
2049 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2050
2051 if (s->be->ck_opts & PR_CK_HTTPONLY)
2052 chunk_appendf(&trash, "; HttpOnly");
2053
2054 if (s->be->ck_opts & PR_CK_SECURE)
2055 chunk_appendf(&trash, "; Secure");
2056
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002057 if (s->be->cookie_attrs)
2058 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2059
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002060 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002061 goto return_bad_resp;
2062
2063 txn->flags &= ~TX_SCK_MASK;
2064 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2065 /* the server did not change, only the date was updated */
2066 txn->flags |= TX_SCK_UPDATED;
2067 else
2068 txn->flags |= TX_SCK_INSERTED;
2069
2070 /* Here, we will tell an eventual cache on the client side that we don't
2071 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2072 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2073 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2074 */
2075 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2076
2077 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2078
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002079 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002080 goto return_bad_resp;
2081 }
2082 }
2083
2084 /*
2085 * Check if result will be cacheable with a cookie.
2086 * We'll block the response if security checks have caught
2087 * nasty things such as a cacheable cookie.
2088 */
2089 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2090 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2091 (s->be->options & PR_O_CHK_CACHE)) {
2092 /* we're in presence of a cacheable response containing
2093 * a set-cookie header. We'll block it as requested by
2094 * the 'checkcache' option, and send an alert.
2095 */
2096 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002097 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002098
Olivier Houcharda798bf52019-03-08 18:52:00 +01002099 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2100 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002102 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002103
2104 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2105 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2106 send_log(s->be, LOG_ALERT,
2107 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2108 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2109 goto return_srv_prx_502;
2110 }
2111
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002113 /* Always enter in the body analyzer */
2114 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2115 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2116
2117 /* if the user wants to log as soon as possible, without counting
2118 * bytes from the server, then this is the right moment. We have
2119 * to temporarily assign bytes_out to log what we currently have.
2120 */
2121 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2122 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002123 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124 s->do_log(s);
2125 s->logs.bytes_out = 0;
2126 }
2127 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002128
2129 return_bad_resp:
2130 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002131 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002132 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002133 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002134 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002135
2136 return_srv_prx_502:
2137 rep->analysers &= AN_RES_FLT_END;
2138 txn->status = 502;
2139 s->logs.t_data = -1; /* was not a valid response */
2140 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002141 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002142 if (!(s->flags & SF_ERR_MASK))
2143 s->flags |= SF_ERR_PRXCOND;
2144 if (!(s->flags & SF_FINST_MASK))
2145 s->flags |= SF_FINST_H;
2146 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002147}
2148
2149/* This function is an analyser which forwards response body (including chunk
2150 * sizes if any). It is called as soon as we must forward, even if we forward
2151 * zero byte. The only situation where it must not be called is when we're in
2152 * tunnel mode and we want to forward till the close. It's used both to forward
2153 * remaining data and to resync after end of body. It expects the msg_state to
2154 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2155 * read more data, or 1 once we can go on with next request or end the stream.
2156 *
2157 * It is capable of compressing response data both in content-length mode and
2158 * in chunked mode. The state machines follows different flows depending on
2159 * whether content-length and chunked modes are used, since there are no
2160 * trailers in content-length :
2161 *
2162 * chk-mode cl-mode
2163 * ,----- BODY -----.
2164 * / \
2165 * V size > 0 V chk-mode
2166 * .--> SIZE -------------> DATA -------------> CRLF
2167 * | | size == 0 | last byte |
2168 * | v final crlf v inspected |
2169 * | TRAILERS -----------> DONE |
2170 * | |
2171 * `----------------------------------------------'
2172 *
2173 * Compression only happens in the DATA state, and must be flushed in final
2174 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2175 * is performed at once on final states for all bytes parsed, or when leaving
2176 * on missing data.
2177 */
2178int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2179{
2180 struct session *sess = s->sess;
2181 struct http_txn *txn = s->txn;
2182 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002183 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002184 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002185
2186 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2187 now_ms, __FUNCTION__,
2188 s,
2189 res,
2190 res->rex, res->wex,
2191 res->flags,
2192 ci_data(res),
2193 res->analysers);
2194
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002195 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196
2197 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002198 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002199 /* Output closed while we were sending data. We must abort and
2200 * wake the other side up.
2201 */
2202 msg->err_state = msg->msg_state;
2203 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002204 htx_end_response(s);
2205 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002206 return 1;
2207 }
2208
Christopher Faulet9768c262018-10-22 09:34:31 +02002209 if (msg->msg_state == HTTP_MSG_BODY)
2210 msg->msg_state = HTTP_MSG_DATA;
2211
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 /* in most states, we should abort in case of early close */
2213 channel_auto_close(res);
2214
Christopher Faulete0768eb2018-10-03 16:38:02 +02002215 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002216 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002217 if (res->flags & CF_EOI)
2218 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002219 }
2220 else {
2221 /* We can't process the buffer's contents yet */
2222 res->flags |= CF_WAKE_WRITE;
2223 goto missing_data_or_waiting;
2224 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 }
2226
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002227 if (msg->msg_state >= HTTP_MSG_ENDING)
2228 goto ending;
2229
2230 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2231 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2232 msg->msg_state = HTTP_MSG_ENDING;
2233 goto ending;
2234 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002235
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002236 /* Forward input data. We get it by removing all outgoing data not
2237 * forwarded yet from HTX data size. If there are some data filters, we
2238 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002240 if (HAS_RSP_DATA_FILTERS(s)) {
2241 ret = flt_http_payload(s, msg, htx->data);
2242 if (ret < 0)
2243 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002244 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002245 }
2246 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002247 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002248 if (msg->flags & HTTP_MSGF_XFER_LEN)
2249 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002250 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002251
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002252 if (htx->data != co_data(res))
2253 goto missing_data_or_waiting;
2254
2255 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2256 msg->msg_state = HTTP_MSG_ENDING;
2257 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258 }
2259
Christopher Faulet9768c262018-10-22 09:34:31 +02002260 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002261 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2262 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002263 */
2264 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2265 goto missing_data_or_waiting;
2266
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002267 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002268
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002269 ending:
2270 /* other states, ENDING...TUNNEL */
2271 if (msg->msg_state >= HTTP_MSG_DONE)
2272 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002273
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002274 if (HAS_RSP_DATA_FILTERS(s)) {
2275 ret = flt_http_end(s, msg);
2276 if (ret <= 0) {
2277 if (!ret)
2278 goto missing_data_or_waiting;
2279 goto return_bad_res;
2280 }
2281 }
2282
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002283 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2284 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2285 msg->msg_state = HTTP_MSG_TUNNEL;
2286 goto ending;
2287 }
2288 else {
2289 msg->msg_state = HTTP_MSG_DONE;
2290 res->to_forward = 0;
2291 }
2292
2293 done:
2294
2295 channel_dont_close(res);
2296
Christopher Fauletf2824e62018-10-01 12:12:37 +02002297 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002299 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2301 if (res->flags & CF_SHUTW) {
2302 /* response errors are most likely due to the
2303 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002304 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002306 goto return_bad_res;
2307 }
2308 return 1;
2309 }
2310 return 0;
2311
2312 missing_data_or_waiting:
2313 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002314 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002315
Christopher Faulet47365272018-10-31 17:40:50 +01002316 if (htx->flags & HTX_FL_PARSING_ERROR)
2317 goto return_bad_res;
2318
Christopher Faulete0768eb2018-10-03 16:38:02 +02002319 /* stop waiting for data if the input is closed before the end. If the
2320 * client side was already closed, it means that the client has aborted,
2321 * so we don't want to count this as a server abort. Otherwise it's a
2322 * server abort.
2323 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002324 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002325 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002326 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002327 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002328 if (htx_is_empty(htx))
2329 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 }
2331
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332 /* When TE: chunked is used, we need to get there again to parse
2333 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002334 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2335 * are filters registered on the stream, we don't want to forward a
2336 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002338 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002339 channel_dont_close(res);
2340
2341 /* We know that more data are expected, but we couldn't send more that
2342 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2343 * system knows it must not set a PUSH on this first part. Interactive
2344 * modes are already handled by the stream sock layer. We must not do
2345 * this in content-length mode because it could present the MSG_MORE
2346 * flag with the last block of forwarded data, which would cause an
2347 * additional delay to be observed by the receiver.
2348 */
2349 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2350 res->flags |= CF_EXPECT_MORE;
2351
2352 /* the stream handler will take care of timeouts and errors */
2353 return 0;
2354
Christopher Faulet93e02d82019-03-08 14:18:50 +01002355 return_srv_abort:
2356 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2357 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002359 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2360 if (!(s->flags & SF_ERR_MASK))
2361 s->flags |= SF_ERR_SRVCL;
2362 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363
Christopher Faulet93e02d82019-03-08 14:18:50 +01002364 return_cli_abort:
2365 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2366 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002367 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002368 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2369 if (!(s->flags & SF_ERR_MASK))
2370 s->flags |= SF_ERR_CLICL;
2371 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002372
Christopher Faulet93e02d82019-03-08 14:18:50 +01002373 return_bad_res:
2374 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2375 if (objt_server(s->target)) {
2376 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2377 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2378 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002379 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002380 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002381
Christopher Faulet93e02d82019-03-08 14:18:50 +01002382 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002383 txn->rsp.err_state = txn->rsp.msg_state;
2384 txn->rsp.msg_state = HTTP_MSG_ERROR;
2385 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002386 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002387 res->analysers &= AN_RES_FLT_END;
2388 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 +02002389 if (!(s->flags & SF_FINST_MASK))
2390 s->flags |= SF_FINST_D;
2391 return 0;
2392}
2393
Christopher Fauletf2824e62018-10-01 12:12:37 +02002394/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002395 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002396 * as too large a request to build a valid response.
2397 */
2398int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2399{
Christopher Faulet99daf282018-11-28 22:58:13 +01002400 struct channel *req = &s->req;
2401 struct channel *res = &s->res;
2402 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002403 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 struct ist status, reason, location;
2406 unsigned int flags;
2407 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002408 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409
2410 chunk = alloc_trash_chunk();
2411 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002413
Christopher Faulet99daf282018-11-28 22:58:13 +01002414 /*
2415 * Create the location
2416 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002417 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 case REDIRECT_TYPE_SCHEME: {
2420 struct http_hdr_ctx ctx;
2421 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 host = ist("");
2424 ctx.blk = NULL;
2425 if (http_find_header(htx, ist("Host"), &ctx, 0))
2426 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427
Christopher Faulet297fbb42019-05-13 14:41:27 +02002428 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002429 path = http_get_path(htx_sl_req_uri(sl));
2430 /* build message using path */
2431 if (path.ptr) {
2432 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2433 int qs = 0;
2434 while (qs < path.len) {
2435 if (*(path.ptr + qs) == '?') {
2436 path.len = qs;
2437 break;
2438 }
2439 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002440 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
2442 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 else
2444 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002445
Christopher Faulet99daf282018-11-28 22:58:13 +01002446 if (rule->rdr_str) { /* this is an old "redirect" rule */
2447 /* add scheme */
2448 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2449 goto fail;
2450 }
2451 else {
2452 /* add scheme with executing log format */
2453 chunk->data += build_logline(s, chunk->area + chunk->data,
2454 chunk->size - chunk->data,
2455 &rule->rdr_fmt);
2456 }
2457 /* add "://" + host + path */
2458 if (!chunk_memcat(chunk, "://", 3) ||
2459 !chunk_memcat(chunk, host.ptr, host.len) ||
2460 !chunk_memcat(chunk, path.ptr, path.len))
2461 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002462
Christopher Faulet99daf282018-11-28 22:58:13 +01002463 /* append a slash at the end of the location if needed and missing */
2464 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2465 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2466 if (chunk->data + 1 >= chunk->size)
2467 goto fail;
2468 chunk->area[chunk->data++] = '/';
2469 }
2470 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472
Christopher Faulet99daf282018-11-28 22:58:13 +01002473 case REDIRECT_TYPE_PREFIX: {
2474 struct ist path;
2475
Christopher Faulet297fbb42019-05-13 14:41:27 +02002476 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002477 path = http_get_path(htx_sl_req_uri(sl));
2478 /* build message using path */
2479 if (path.ptr) {
2480 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2481 int qs = 0;
2482 while (qs < path.len) {
2483 if (*(path.ptr + qs) == '?') {
2484 path.len = qs;
2485 break;
2486 }
2487 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002488 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489 }
2490 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002491 else
2492 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493
Christopher Faulet99daf282018-11-28 22:58:13 +01002494 if (rule->rdr_str) { /* this is an old "redirect" rule */
2495 /* add prefix. Note that if prefix == "/", we don't want to
2496 * add anything, otherwise it makes it hard for the user to
2497 * configure a self-redirection.
2498 */
2499 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2500 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2501 goto fail;
2502 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002503 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002504 else {
2505 /* add prefix with executing log format */
2506 chunk->data += build_logline(s, chunk->area + chunk->data,
2507 chunk->size - chunk->data,
2508 &rule->rdr_fmt);
2509 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002510
Christopher Faulet99daf282018-11-28 22:58:13 +01002511 /* add path */
2512 if (!chunk_memcat(chunk, path.ptr, path.len))
2513 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002514
Christopher Faulet99daf282018-11-28 22:58:13 +01002515 /* append a slash at the end of the location if needed and missing */
2516 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2517 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2518 if (chunk->data + 1 >= chunk->size)
2519 goto fail;
2520 chunk->area[chunk->data++] = '/';
2521 }
2522 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002523 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002524 case REDIRECT_TYPE_LOCATION:
2525 default:
2526 if (rule->rdr_str) { /* this is an old "redirect" rule */
2527 /* add location */
2528 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2529 goto fail;
2530 }
2531 else {
2532 /* add location with executing log format */
2533 chunk->data += build_logline(s, chunk->area + chunk->data,
2534 chunk->size - chunk->data,
2535 &rule->rdr_fmt);
2536 }
2537 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002538 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 location = ist2(chunk->area, chunk->data);
2540
2541 /*
2542 * Create the 30x response
2543 */
2544 switch (rule->code) {
2545 case 308:
2546 status = ist("308");
2547 reason = ist("Permanent Redirect");
2548 break;
2549 case 307:
2550 status = ist("307");
2551 reason = ist("Temporary Redirect");
2552 break;
2553 case 303:
2554 status = ist("303");
2555 reason = ist("See Other");
2556 break;
2557 case 301:
2558 status = ist("301");
2559 reason = ist("Moved Permanently");
2560 break;
2561 case 302:
2562 default:
2563 status = ist("302");
2564 reason = ist("Found");
2565 break;
2566 }
2567
Christopher Faulet08e66462019-05-23 16:44:59 +02002568 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2569 close = 1;
2570
Christopher Faulet99daf282018-11-28 22:58:13 +01002571 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002572 /* Trim any possible response */
2573 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002574 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2575 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2576 if (!sl)
2577 goto fail;
2578 sl->info.res.status = rule->code;
2579 s->txn->status = rule->code;
2580
Christopher Faulet08e66462019-05-23 16:44:59 +02002581 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2582 goto fail;
2583
2584 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002585 !htx_add_header(htx, ist("Location"), location))
2586 goto fail;
2587
2588 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2589 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2590 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591 }
2592
2593 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002594 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2595 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002596 }
2597
Christopher Faulet99daf282018-11-28 22:58:13 +01002598 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2599 goto fail;
2600
Kevin Zhu0fd70882020-01-07 09:42:55 +01002601 htx_to_buf(htx, &res->buf);
2602
Christopher Fauletf2824e62018-10-01 12:12:37 +02002603 /* let's log the request time */
2604 s->logs.tv_request = now;
2605
Christopher Faulet99daf282018-11-28 22:58:13 +01002606 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002607 c_adv(res, data);
2608 res->total += data;
2609
2610 channel_auto_read(req);
2611 channel_abort(req);
2612 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002613 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002614
2615 res->wex = tick_add_ifset(now_ms, res->wto);
2616 channel_auto_read(res);
2617 channel_auto_close(res);
2618 channel_shutr_now(res);
2619
2620 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002621
2622 if (!(s->flags & SF_ERR_MASK))
2623 s->flags |= SF_ERR_LOCAL;
2624 if (!(s->flags & SF_FINST_MASK))
2625 s->flags |= SF_FINST_R;
2626
Christopher Faulet99daf282018-11-28 22:58:13 +01002627 free_trash_chunk(chunk);
2628 return 1;
2629
2630 fail:
2631 /* If an error occurred, remove the incomplete HTTP response from the
2632 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002633 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002634 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002635 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002636}
2637
Christopher Faulet72333522018-10-24 11:25:02 +02002638int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2639 struct ist name, const char *str, struct my_regex *re, int action)
2640{
2641 struct http_hdr_ctx ctx;
2642 struct buffer *output = get_trash_chunk();
2643
2644 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2645 ctx.blk = NULL;
2646 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2647 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2648 continue;
2649
2650 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2651 if (output->data == -1)
2652 return -1;
2653 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2654 return -1;
2655 }
2656 return 0;
2657}
2658
2659static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2660 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2661{
2662 struct buffer *replace;
2663 int ret = -1;
2664
2665 replace = alloc_trash_chunk();
2666 if (!replace)
2667 goto leave;
2668
2669 replace->data = build_logline(s, replace->area, replace->size, fmt);
2670 if (replace->data >= replace->size - 1)
2671 goto leave;
2672
2673 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2674
2675 leave:
2676 free_trash_chunk(replace);
2677 return ret;
2678}
2679
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002680
2681/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2682 * on success and -1 on error. The response channel is updated accordingly.
2683 */
2684static int htx_reply_103_early_hints(struct channel *res)
2685{
2686 struct htx *htx = htx_from_buf(&res->buf);
2687 size_t data;
2688
Christopher Faulet9869f932019-06-26 14:23:54 +02002689 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 /* If an error occurred during an Early-hint rule,
2691 * remove the incomplete HTTP 103 response from the
2692 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002693 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002694 return -1;
2695 }
2696
2697 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002698 c_adv(res, data);
2699 res->total += data;
2700 return 0;
2701}
2702
Christopher Faulet6eb92892018-11-15 16:39:29 +01002703/*
2704 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2705 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002706 * If <early_hints> is 0, it is starts a new response by adding the start
2707 * line. If an error occurred -1 is returned. On success 0 is returned. The
2708 * channel is not updated here. It must be done calling the function
2709 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002710 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002711static 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 +01002712{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002713 struct channel *res = &s->res;
2714 struct htx *htx = htx_from_buf(&res->buf);
2715 struct buffer *value = alloc_trash_chunk();
2716
Christopher Faulet6eb92892018-11-15 16:39:29 +01002717 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002718 struct htx_sl *sl;
2719 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2720 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2721
2722 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2723 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2724 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002725 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002726 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002727 }
2728
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002729 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2730 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002731 goto fail;
2732
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002733 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002734 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002735
2736 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002737 /* If an error occurred during an Early-hint rule, remove the incomplete
2738 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002739 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002740 free_trash_chunk(value);
2741 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002742}
2743
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002744/* This function executes one of the set-{method,path,query,uri} actions. It
2745 * takes the string from the variable 'replace' with length 'len', then modifies
2746 * the relevant part of the request line accordingly. Then it updates various
2747 * pointers to the next elements which were moved, and the total buffer length.
2748 * It finds the action to be performed in p[2], previously filled by function
2749 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2750 * error, though this can be revisited when this code is finally exploited.
2751 *
2752 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2753 * query string and 3 to replace uri.
2754 *
2755 * In query string case, the mark question '?' must be set at the start of the
2756 * string by the caller, event if the replacement query string is empty.
2757 */
2758int htx_req_replace_stline(int action, const char *replace, int len,
2759 struct proxy *px, struct stream *s)
2760{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002761 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002762
2763 switch (action) {
2764 case 0: // method
2765 if (!http_replace_req_meth(htx, ist2(replace, len)))
2766 return -1;
2767 break;
2768
2769 case 1: // path
2770 if (!http_replace_req_path(htx, ist2(replace, len)))
2771 return -1;
2772 break;
2773
2774 case 2: // query
2775 if (!http_replace_req_query(htx, ist2(replace, len)))
2776 return -1;
2777 break;
2778
2779 case 3: // uri
2780 if (!http_replace_req_uri(htx, ist2(replace, len)))
2781 return -1;
2782 break;
2783
2784 default:
2785 return -1;
2786 }
2787 return 0;
2788}
2789
2790/* This function replace the HTTP status code and the associated message. The
2791 * variable <status> contains the new status code. This function never fails.
2792 */
2793void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2794{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002795 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002796 char *res;
2797
2798 chunk_reset(&trash);
2799 res = ultoa_o(status, trash.area, trash.size);
2800 trash.data = res - trash.area;
2801
2802 /* Do we have a custom reason format string? */
2803 if (reason == NULL)
2804 reason = http_get_reason(status);
2805
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002806 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002807 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2808}
2809
Christopher Faulet3e964192018-10-24 11:39:23 +02002810/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2811 * transaction <txn>. Returns the verdict of the first rule that prevents
2812 * further processing of the request (auth, deny, ...), and defaults to
2813 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2814 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2815 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2816 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2817 * status.
2818 */
2819static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2820 struct stream *s, int *deny_status)
2821{
2822 struct session *sess = strm_sess(s);
2823 struct http_txn *txn = s->txn;
2824 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002825 struct act_rule *rule;
2826 struct http_hdr_ctx ctx;
2827 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2829 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002830 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002831
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002832 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002833
2834 /* If "the current_rule_list" match the executed rule list, we are in
2835 * resume condition. If a resume is needed it is always in the action
2836 * and never in the ACL or converters. In this case, we initialise the
2837 * current rule, and go to the action execution point.
2838 */
2839 if (s->current_rule) {
2840 rule = s->current_rule;
2841 s->current_rule = NULL;
2842 if (s->current_rule_list == rules)
2843 goto resume_execution;
2844 }
2845 s->current_rule_list = rules;
2846
2847 list_for_each_entry(rule, rules, list) {
2848 /* check optional condition */
2849 if (rule->cond) {
2850 int ret;
2851
2852 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2853 ret = acl_pass(ret);
2854
2855 if (rule->cond->pol == ACL_COND_UNLESS)
2856 ret = !ret;
2857
2858 if (!ret) /* condition not matched */
2859 continue;
2860 }
2861
2862 act_flags |= ACT_FLAG_FIRST;
2863 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002864 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2865 early_hints = 0;
2866 if (htx_reply_103_early_hints(&s->res) == -1) {
2867 rule_ret = HTTP_RULE_RES_BADREQ;
2868 goto end;
2869 }
2870 }
2871
Christopher Faulet3e964192018-10-24 11:39:23 +02002872 switch (rule->action) {
2873 case ACT_ACTION_ALLOW:
2874 rule_ret = HTTP_RULE_RES_STOP;
2875 goto end;
2876
2877 case ACT_ACTION_DENY:
2878 if (deny_status)
2879 *deny_status = rule->deny_status;
2880 rule_ret = HTTP_RULE_RES_DENY;
2881 goto end;
2882
2883 case ACT_HTTP_REQ_TARPIT:
2884 txn->flags |= TX_CLTARPIT;
2885 if (deny_status)
2886 *deny_status = rule->deny_status;
2887 rule_ret = HTTP_RULE_RES_DENY;
2888 goto end;
2889
2890 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002891 /* Auth might be performed on regular http-req rules as well as on stats */
2892 auth_realm = rule->arg.auth.realm;
2893 if (!auth_realm) {
2894 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2895 auth_realm = STATS_DEFAULT_REALM;
2896 else
2897 auth_realm = px->id;
2898 }
2899 /* send 401/407 depending on whether we use a proxy or not. We still
2900 * count one error, because normal browsing won't significantly
2901 * increase the counter but brute force attempts will.
2902 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002903 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002904 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2905 rule_ret = HTTP_RULE_RES_BADREQ;
2906 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002907 goto end;
2908
2909 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002910 rule_ret = HTTP_RULE_RES_DONE;
2911 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2912 rule_ret = HTTP_RULE_RES_BADREQ;
2913 goto end;
2914
2915 case ACT_HTTP_SET_NICE:
2916 s->task->nice = rule->arg.nice;
2917 break;
2918
2919 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002920 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002921 break;
2922
2923 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002924 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002925 break;
2926
2927 case ACT_HTTP_SET_LOGL:
2928 s->logs.level = rule->arg.loglevel;
2929 break;
2930
2931 case ACT_HTTP_REPLACE_HDR:
2932 case ACT_HTTP_REPLACE_VAL:
2933 if (htx_transform_header(s, &s->req, htx,
2934 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2935 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002936 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002937 rule_ret = HTTP_RULE_RES_BADREQ;
2938 goto end;
2939 }
2940 break;
2941
2942 case ACT_HTTP_DEL_HDR:
2943 /* remove all occurrences of the header */
2944 ctx.blk = NULL;
2945 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2946 http_remove_header(htx, &ctx);
2947 break;
2948
2949 case ACT_HTTP_SET_HDR:
2950 case ACT_HTTP_ADD_HDR: {
2951 /* The scope of the trash buffer must be limited to this function. The
2952 * build_logline() function can execute a lot of other function which
2953 * can use the trash buffer. So for limiting the scope of this global
2954 * buffer, we build first the header value using build_logline, and
2955 * after we store the header name.
2956 */
2957 struct buffer *replace;
2958 struct ist n, v;
2959
2960 replace = alloc_trash_chunk();
2961 if (!replace) {
2962 rule_ret = HTTP_RULE_RES_BADREQ;
2963 goto end;
2964 }
2965
2966 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2967 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2968 v = ist2(replace->area, replace->data);
2969
2970 if (rule->action == ACT_HTTP_SET_HDR) {
2971 /* remove all occurrences of the header */
2972 ctx.blk = NULL;
2973 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2974 http_remove_header(htx, &ctx);
2975 }
2976
2977 if (!http_add_header(htx, n, v)) {
2978 static unsigned char rate_limit = 0;
2979
2980 if ((rate_limit++ & 255) == 0) {
2981 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);
2982 }
2983
Olivier Houcharda798bf52019-03-08 18:52:00 +01002984 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002985 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002986 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002987 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002988 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002989 }
2990 free_trash_chunk(replace);
2991 break;
2992 }
2993
2994 case ACT_HTTP_DEL_ACL:
2995 case ACT_HTTP_DEL_MAP: {
2996 struct pat_ref *ref;
2997 struct buffer *key;
2998
2999 /* collect reference */
3000 ref = pat_ref_lookup(rule->arg.map.ref);
3001 if (!ref)
3002 continue;
3003
3004 /* allocate key */
3005 key = alloc_trash_chunk();
3006 if (!key) {
3007 rule_ret = HTTP_RULE_RES_BADREQ;
3008 goto end;
3009 }
3010
3011 /* collect key */
3012 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3013 key->area[key->data] = '\0';
3014
3015 /* perform update */
3016 /* returned code: 1=ok, 0=ko */
3017 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3018 pat_ref_delete(ref, key->area);
3019 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3020
3021 free_trash_chunk(key);
3022 break;
3023 }
3024
3025 case ACT_HTTP_ADD_ACL: {
3026 struct pat_ref *ref;
3027 struct buffer *key;
3028
3029 /* collect reference */
3030 ref = pat_ref_lookup(rule->arg.map.ref);
3031 if (!ref)
3032 continue;
3033
3034 /* allocate key */
3035 key = alloc_trash_chunk();
3036 if (!key) {
3037 rule_ret = HTTP_RULE_RES_BADREQ;
3038 goto end;
3039 }
3040
3041 /* collect key */
3042 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3043 key->area[key->data] = '\0';
3044
3045 /* perform update */
3046 /* add entry only if it does not already exist */
3047 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3048 if (pat_ref_find_elt(ref, key->area) == NULL)
3049 pat_ref_add(ref, key->area, NULL, NULL);
3050 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3051
3052 free_trash_chunk(key);
3053 break;
3054 }
3055
3056 case ACT_HTTP_SET_MAP: {
3057 struct pat_ref *ref;
3058 struct buffer *key, *value;
3059
3060 /* collect reference */
3061 ref = pat_ref_lookup(rule->arg.map.ref);
3062 if (!ref)
3063 continue;
3064
3065 /* allocate key */
3066 key = alloc_trash_chunk();
3067 if (!key) {
3068 rule_ret = HTTP_RULE_RES_BADREQ;
3069 goto end;
3070 }
3071
3072 /* allocate value */
3073 value = alloc_trash_chunk();
3074 if (!value) {
3075 free_trash_chunk(key);
3076 rule_ret = HTTP_RULE_RES_BADREQ;
3077 goto end;
3078 }
3079
3080 /* collect key */
3081 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3082 key->area[key->data] = '\0';
3083
3084 /* collect value */
3085 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3086 value->area[value->data] = '\0';
3087
3088 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003089 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003090 if (pat_ref_find_elt(ref, key->area) != NULL)
3091 /* update entry if it exists */
3092 pat_ref_set(ref, key->area, value->area, NULL);
3093 else
3094 /* insert a new entry */
3095 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003096 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003097 free_trash_chunk(key);
3098 free_trash_chunk(value);
3099 break;
3100 }
3101
3102 case ACT_HTTP_EARLY_HINT:
3103 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3104 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003105 early_hints = htx_add_early_hint_header(s, early_hints,
3106 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003107 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003108 if (early_hints == -1) {
3109 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003110 goto end;
3111 }
3112 break;
3113
3114 case ACT_CUSTOM:
3115 if ((s->req.flags & CF_READ_ERROR) ||
3116 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003117 (px->options & PR_O_ABRT_CLOSE)))
3118 act_flags |= ACT_FLAG_FINAL;
3119
3120 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3121 case ACT_RET_ERR:
3122 case ACT_RET_CONT:
3123 break;
3124 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003125 rule_ret = HTTP_RULE_RES_STOP;
3126 goto end;
3127 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003128 rule_ret = HTTP_RULE_RES_DONE;
3129 goto end;
3130 case ACT_RET_YIELD:
3131 s->current_rule = rule;
3132 rule_ret = HTTP_RULE_RES_YIELD;
3133 goto end;
3134 }
3135 break;
3136
3137 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3138 /* Note: only the first valid tracking parameter of each
3139 * applies.
3140 */
3141
3142 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3143 struct stktable *t;
3144 struct stksess *ts;
3145 struct stktable_key *key;
3146 void *ptr1, *ptr2;
3147
3148 t = rule->arg.trk_ctr.table.t;
3149 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3150 rule->arg.trk_ctr.expr, NULL);
3151
3152 if (key && (ts = stktable_get_entry(t, key))) {
3153 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3154
3155 /* let's count a new HTTP request as it's the first time we do it */
3156 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3157 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3158 if (ptr1 || ptr2) {
3159 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3160
3161 if (ptr1)
3162 stktable_data_cast(ptr1, http_req_cnt)++;
3163
3164 if (ptr2)
3165 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3166 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3167
3168 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3169
3170 /* If data was modified, we need to touch to re-schedule sync */
3171 stktable_touch_local(t, ts, 0);
3172 }
3173
3174 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3175 if (sess->fe != s->be)
3176 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3177 }
3178 }
3179 break;
3180
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003181 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003182 default:
3183 break;
3184 }
3185 }
3186
3187 end:
3188 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003189 if (htx_reply_103_early_hints(&s->res) == -1)
3190 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003191 }
3192
3193 /* we reached the end of the rules, nothing to report */
3194 return rule_ret;
3195}
3196
3197/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3198 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3199 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3200 * is returned, the process can continue the evaluation of next rule list. If
3201 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3202 * is returned, it means the operation could not be processed and a server error
3203 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3204 * deny rule. If *YIELD is returned, the caller must call again the function
3205 * with the same context.
3206 */
3207static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3208 struct stream *s)
3209{
3210 struct session *sess = strm_sess(s);
3211 struct http_txn *txn = s->txn;
3212 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003213 struct act_rule *rule;
3214 struct http_hdr_ctx ctx;
3215 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3216 int act_flags = 0;
3217
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003218 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003219
3220 /* If "the current_rule_list" match the executed rule list, we are in
3221 * resume condition. If a resume is needed it is always in the action
3222 * and never in the ACL or converters. In this case, we initialise the
3223 * current rule, and go to the action execution point.
3224 */
3225 if (s->current_rule) {
3226 rule = s->current_rule;
3227 s->current_rule = NULL;
3228 if (s->current_rule_list == rules)
3229 goto resume_execution;
3230 }
3231 s->current_rule_list = rules;
3232
3233 list_for_each_entry(rule, rules, list) {
3234 /* check optional condition */
3235 if (rule->cond) {
3236 int ret;
3237
3238 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3239 ret = acl_pass(ret);
3240
3241 if (rule->cond->pol == ACL_COND_UNLESS)
3242 ret = !ret;
3243
3244 if (!ret) /* condition not matched */
3245 continue;
3246 }
3247
3248 act_flags |= ACT_FLAG_FIRST;
3249resume_execution:
3250 switch (rule->action) {
3251 case ACT_ACTION_ALLOW:
3252 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3253 goto end;
3254
3255 case ACT_ACTION_DENY:
3256 txn->flags |= TX_SVDENY;
3257 rule_ret = HTTP_RULE_RES_STOP;
3258 goto end;
3259
3260 case ACT_HTTP_SET_NICE:
3261 s->task->nice = rule->arg.nice;
3262 break;
3263
3264 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003265 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003266 break;
3267
3268 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003269 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003270 break;
3271
3272 case ACT_HTTP_SET_LOGL:
3273 s->logs.level = rule->arg.loglevel;
3274 break;
3275
3276 case ACT_HTTP_REPLACE_HDR:
3277 case ACT_HTTP_REPLACE_VAL:
3278 if (htx_transform_header(s, &s->res, htx,
3279 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3280 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003281 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 rule_ret = HTTP_RULE_RES_BADREQ;
3283 goto end;
3284 }
3285 break;
3286
3287 case ACT_HTTP_DEL_HDR:
3288 /* remove all occurrences of the header */
3289 ctx.blk = NULL;
3290 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3291 http_remove_header(htx, &ctx);
3292 break;
3293
3294 case ACT_HTTP_SET_HDR:
3295 case ACT_HTTP_ADD_HDR: {
3296 struct buffer *replace;
3297 struct ist n, v;
3298
3299 replace = alloc_trash_chunk();
3300 if (!replace) {
3301 rule_ret = HTTP_RULE_RES_BADREQ;
3302 goto end;
3303 }
3304
3305 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3306 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3307 v = ist2(replace->area, replace->data);
3308
3309 if (rule->action == ACT_HTTP_SET_HDR) {
3310 /* remove all occurrences of the header */
3311 ctx.blk = NULL;
3312 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3313 http_remove_header(htx, &ctx);
3314 }
3315
3316 if (!http_add_header(htx, n, v)) {
3317 static unsigned char rate_limit = 0;
3318
3319 if ((rate_limit++ & 255) == 0) {
3320 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);
3321 }
3322
Olivier Houcharda798bf52019-03-08 18:52:00 +01003323 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003324 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003325 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003326 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003327 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003328 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003329 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003330 }
3331 free_trash_chunk(replace);
3332 break;
3333 }
3334
3335 case ACT_HTTP_DEL_ACL:
3336 case ACT_HTTP_DEL_MAP: {
3337 struct pat_ref *ref;
3338 struct buffer *key;
3339
3340 /* collect reference */
3341 ref = pat_ref_lookup(rule->arg.map.ref);
3342 if (!ref)
3343 continue;
3344
3345 /* allocate key */
3346 key = alloc_trash_chunk();
3347 if (!key) {
3348 rule_ret = HTTP_RULE_RES_BADREQ;
3349 goto end;
3350 }
3351
3352 /* collect key */
3353 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3354 key->area[key->data] = '\0';
3355
3356 /* perform update */
3357 /* returned code: 1=ok, 0=ko */
3358 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3359 pat_ref_delete(ref, key->area);
3360 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3361
3362 free_trash_chunk(key);
3363 break;
3364 }
3365
3366 case ACT_HTTP_ADD_ACL: {
3367 struct pat_ref *ref;
3368 struct buffer *key;
3369
3370 /* collect reference */
3371 ref = pat_ref_lookup(rule->arg.map.ref);
3372 if (!ref)
3373 continue;
3374
3375 /* allocate key */
3376 key = alloc_trash_chunk();
3377 if (!key) {
3378 rule_ret = HTTP_RULE_RES_BADREQ;
3379 goto end;
3380 }
3381
3382 /* collect key */
3383 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3384 key->area[key->data] = '\0';
3385
3386 /* perform update */
3387 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003388 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003389 if (pat_ref_find_elt(ref, key->area) == NULL)
3390 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003391 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003392 free_trash_chunk(key);
3393 break;
3394 }
3395
3396 case ACT_HTTP_SET_MAP: {
3397 struct pat_ref *ref;
3398 struct buffer *key, *value;
3399
3400 /* collect reference */
3401 ref = pat_ref_lookup(rule->arg.map.ref);
3402 if (!ref)
3403 continue;
3404
3405 /* allocate key */
3406 key = alloc_trash_chunk();
3407 if (!key) {
3408 rule_ret = HTTP_RULE_RES_BADREQ;
3409 goto end;
3410 }
3411
3412 /* allocate value */
3413 value = alloc_trash_chunk();
3414 if (!value) {
3415 free_trash_chunk(key);
3416 rule_ret = HTTP_RULE_RES_BADREQ;
3417 goto end;
3418 }
3419
3420 /* collect key */
3421 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3422 key->area[key->data] = '\0';
3423
3424 /* collect value */
3425 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3426 value->area[value->data] = '\0';
3427
3428 /* perform update */
3429 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3430 if (pat_ref_find_elt(ref, key->area) != NULL)
3431 /* update entry if it exists */
3432 pat_ref_set(ref, key->area, value->area, NULL);
3433 else
3434 /* insert a new entry */
3435 pat_ref_add(ref, key->area, value->area, NULL);
3436 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3437 free_trash_chunk(key);
3438 free_trash_chunk(value);
3439 break;
3440 }
3441
3442 case ACT_HTTP_REDIR:
3443 rule_ret = HTTP_RULE_RES_DONE;
3444 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3445 rule_ret = HTTP_RULE_RES_BADREQ;
3446 goto end;
3447
3448 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3449 /* Note: only the first valid tracking parameter of each
3450 * applies.
3451 */
3452 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3453 struct stktable *t;
3454 struct stksess *ts;
3455 struct stktable_key *key;
3456 void *ptr;
3457
3458 t = rule->arg.trk_ctr.table.t;
3459 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3460 rule->arg.trk_ctr.expr, NULL);
3461
3462 if (key && (ts = stktable_get_entry(t, key))) {
3463 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3464
3465 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3466
3467 /* let's count a new HTTP request as it's the first time we do it */
3468 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3469 if (ptr)
3470 stktable_data_cast(ptr, http_req_cnt)++;
3471
3472 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3473 if (ptr)
3474 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3475 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3476
3477 /* When the client triggers a 4xx from the server, it's most often due
3478 * to a missing object or permission. These events should be tracked
3479 * because if they happen often, it may indicate a brute force or a
3480 * vulnerability scan. Normally this is done when receiving the response
3481 * but here we're tracking after this ought to have been done so we have
3482 * to do it on purpose.
3483 */
3484 if ((unsigned)(txn->status - 400) < 100) {
3485 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3486 if (ptr)
3487 stktable_data_cast(ptr, http_err_cnt)++;
3488
3489 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3490 if (ptr)
3491 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3492 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3493 }
3494
3495 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3496
3497 /* If data was modified, we need to touch to re-schedule sync */
3498 stktable_touch_local(t, ts, 0);
3499
3500 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3501 if (sess->fe != s->be)
3502 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3503 }
3504 }
3505 break;
3506
3507 case ACT_CUSTOM:
3508 if ((s->req.flags & CF_READ_ERROR) ||
3509 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003510 (px->options & PR_O_ABRT_CLOSE)))
3511 act_flags |= ACT_FLAG_FINAL;
3512
3513 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3514 case ACT_RET_ERR:
3515 case ACT_RET_CONT:
3516 break;
3517 case ACT_RET_STOP:
3518 rule_ret = HTTP_RULE_RES_STOP;
3519 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003520 case ACT_RET_DONE:
3521 rule_ret = HTTP_RULE_RES_DONE;
3522 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003523 case ACT_RET_YIELD:
3524 s->current_rule = rule;
3525 rule_ret = HTTP_RULE_RES_YIELD;
3526 goto end;
3527 }
3528 break;
3529
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003530 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003531 default:
3532 break;
3533 }
3534 }
3535
3536 end:
3537 /* we reached the end of the rules, nothing to report */
3538 return rule_ret;
3539}
3540
Christopher Faulet33640082018-10-24 11:53:01 +02003541/* Iterate the same filter through all request headers.
3542 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3543 * Since it can manage the switch to another backend, it updates the per-proxy
3544 * DENY stats.
3545 */
3546static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3547{
3548 struct http_txn *txn = s->txn;
3549 struct htx *htx;
3550 struct buffer *hdr = get_trash_chunk();
3551 int32_t pos;
3552
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003553 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003554
Christopher Fauleta3f15502019-05-13 15:27:23 +02003555 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003556 struct htx_blk *blk = htx_get_blk(htx, pos);
3557 enum htx_blk_type type;
3558 struct ist n, v;
3559
3560 next_hdr:
3561 type = htx_get_blk_type(blk);
3562 if (type == HTX_BLK_EOH)
3563 break;
3564 if (type != HTX_BLK_HDR)
3565 continue;
3566
3567 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3568 return 1;
3569 else if (unlikely(txn->flags & TX_CLALLOW) &&
3570 (exp->action == ACT_ALLOW ||
3571 exp->action == ACT_DENY ||
3572 exp->action == ACT_TARPIT))
3573 return 0;
3574
3575 n = htx_get_blk_name(htx, blk);
3576 v = htx_get_blk_value(htx, blk);
3577
Christopher Faulet02e771a2019-02-26 15:36:05 +01003578 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003579 hdr->area[hdr->data++] = ':';
3580 hdr->area[hdr->data++] = ' ';
3581 chunk_memcat(hdr, v.ptr, v.len);
3582
3583 /* Now we have one header in <hdr> */
3584
3585 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3586 struct http_hdr_ctx ctx;
3587 int len;
3588
3589 switch (exp->action) {
3590 case ACT_ALLOW:
3591 txn->flags |= TX_CLALLOW;
3592 goto end;
3593
3594 case ACT_DENY:
3595 txn->flags |= TX_CLDENY;
3596 goto end;
3597
3598 case ACT_TARPIT:
3599 txn->flags |= TX_CLTARPIT;
3600 goto end;
3601
3602 case ACT_REPLACE:
3603 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3604 if (len < 0)
3605 return -1;
3606
3607 http_parse_header(ist2(trash.area, len), &n, &v);
3608 ctx.blk = blk;
3609 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003610 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003611 if (!http_replace_header(htx, &ctx, n, v))
3612 return -1;
3613 if (!ctx.blk)
3614 goto end;
3615 pos = htx_get_blk_pos(htx, blk);
3616 break;
3617
3618 case ACT_REMOVE:
3619 ctx.blk = blk;
3620 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003621 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003622 if (!http_remove_header(htx, &ctx))
3623 return -1;
3624 if (!ctx.blk)
3625 goto end;
3626 pos = htx_get_blk_pos(htx, blk);
3627 goto next_hdr;
3628
3629 }
3630 }
3631 }
3632 end:
3633 return 0;
3634}
3635
3636/* Apply the filter to the request line.
3637 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3638 * or -1 if a replacement resulted in an invalid request line.
3639 * Since it can manage the switch to another backend, it updates the per-proxy
3640 * DENY stats.
3641 */
3642static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3643{
3644 struct http_txn *txn = s->txn;
3645 struct htx *htx;
3646 struct buffer *reqline = get_trash_chunk();
3647 int done;
3648
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003649 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003650
3651 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3652 return 1;
3653 else if (unlikely(txn->flags & TX_CLALLOW) &&
3654 (exp->action == ACT_ALLOW ||
3655 exp->action == ACT_DENY ||
3656 exp->action == ACT_TARPIT))
3657 return 0;
3658 else if (exp->action == ACT_REMOVE)
3659 return 0;
3660
3661 done = 0;
3662
Christopher Faulet297fbb42019-05-13 14:41:27 +02003663 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003664
3665 /* Now we have the request line between cur_ptr and cur_end */
3666 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003667 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003668 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003669 int len;
3670
3671 switch (exp->action) {
3672 case ACT_ALLOW:
3673 txn->flags |= TX_CLALLOW;
3674 done = 1;
3675 break;
3676
3677 case ACT_DENY:
3678 txn->flags |= TX_CLDENY;
3679 done = 1;
3680 break;
3681
3682 case ACT_TARPIT:
3683 txn->flags |= TX_CLTARPIT;
3684 done = 1;
3685 break;
3686
3687 case ACT_REPLACE:
3688 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3689 if (len < 0)
3690 return -1;
3691
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003692 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3693 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3694 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003695 return -1;
3696 done = 1;
3697 break;
3698 }
3699 }
3700 return done;
3701}
3702
3703/*
3704 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3705 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3706 * unparsable request. Since it can manage the switch to another backend, it
3707 * updates the per-proxy DENY stats.
3708 */
3709static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3710{
3711 struct session *sess = s->sess;
3712 struct http_txn *txn = s->txn;
3713 struct hdr_exp *exp;
3714
3715 for (exp = px->req_exp; exp; exp = exp->next) {
3716 int ret;
3717
3718 /*
3719 * The interleaving of transformations and verdicts
3720 * makes it difficult to decide to continue or stop
3721 * the evaluation.
3722 */
3723
3724 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3725 break;
3726
3727 if ((txn->flags & TX_CLALLOW) &&
3728 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3729 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3730 continue;
3731
3732 /* if this filter had a condition, evaluate it now and skip to
3733 * next filter if the condition does not match.
3734 */
3735 if (exp->cond) {
3736 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3737 ret = acl_pass(ret);
3738 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3739 ret = !ret;
3740
3741 if (!ret)
3742 continue;
3743 }
3744
3745 /* Apply the filter to the request line. */
3746 ret = htx_apply_filter_to_req_line(s, req, exp);
3747 if (unlikely(ret < 0))
3748 return -1;
3749
3750 if (likely(ret == 0)) {
3751 /* The filter did not match the request, it can be
3752 * iterated through all headers.
3753 */
3754 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3755 return -1;
3756 }
3757 }
3758 return 0;
3759}
3760
3761/* Iterate the same filter through all response headers contained in <res>.
3762 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3763 */
3764static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3765{
3766 struct http_txn *txn = s->txn;
3767 struct htx *htx;
3768 struct buffer *hdr = get_trash_chunk();
3769 int32_t pos;
3770
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003771 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003772
Christopher Fauleta3f15502019-05-13 15:27:23 +02003773 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003774 struct htx_blk *blk = htx_get_blk(htx, pos);
3775 enum htx_blk_type type;
3776 struct ist n, v;
3777
3778 next_hdr:
3779 type = htx_get_blk_type(blk);
3780 if (type == HTX_BLK_EOH)
3781 break;
3782 if (type != HTX_BLK_HDR)
3783 continue;
3784
3785 if (unlikely(txn->flags & TX_SVDENY))
3786 return 1;
3787 else if (unlikely(txn->flags & TX_SVALLOW) &&
3788 (exp->action == ACT_ALLOW ||
3789 exp->action == ACT_DENY))
3790 return 0;
3791
3792 n = htx_get_blk_name(htx, blk);
3793 v = htx_get_blk_value(htx, blk);
3794
Christopher Faulet02e771a2019-02-26 15:36:05 +01003795 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003796 hdr->area[hdr->data++] = ':';
3797 hdr->area[hdr->data++] = ' ';
3798 chunk_memcat(hdr, v.ptr, v.len);
3799
3800 /* Now we have one header in <hdr> */
3801
3802 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3803 struct http_hdr_ctx ctx;
3804 int len;
3805
3806 switch (exp->action) {
3807 case ACT_ALLOW:
3808 txn->flags |= TX_SVALLOW;
3809 goto end;
3810 break;
3811
3812 case ACT_DENY:
3813 txn->flags |= TX_SVDENY;
3814 goto end;
3815 break;
3816
3817 case ACT_REPLACE:
3818 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3819 if (len < 0)
3820 return -1;
3821
3822 http_parse_header(ist2(trash.area, len), &n, &v);
3823 ctx.blk = blk;
3824 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003825 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003826 if (!http_replace_header(htx, &ctx, n, v))
3827 return -1;
3828 if (!ctx.blk)
3829 goto end;
3830 pos = htx_get_blk_pos(htx, blk);
3831 break;
3832
3833 case ACT_REMOVE:
3834 ctx.blk = blk;
3835 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003836 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003837 if (!http_remove_header(htx, &ctx))
3838 return -1;
3839 if (!ctx.blk)
3840 goto end;
3841 pos = htx_get_blk_pos(htx, blk);
3842 goto next_hdr;
3843 }
3844 }
3845
3846 }
3847 end:
3848 return 0;
3849}
3850
3851/* Apply the filter to the status line in the response buffer <res>.
3852 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3853 * or -1 if a replacement resulted in an invalid status line.
3854 */
3855static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3856{
3857 struct http_txn *txn = s->txn;
3858 struct htx *htx;
3859 struct buffer *resline = get_trash_chunk();
3860 int done;
3861
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003862 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003863
3864 if (unlikely(txn->flags & TX_SVDENY))
3865 return 1;
3866 else if (unlikely(txn->flags & TX_SVALLOW) &&
3867 (exp->action == ACT_ALLOW ||
3868 exp->action == ACT_DENY))
3869 return 0;
3870 else if (exp->action == ACT_REMOVE)
3871 return 0;
3872
3873 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003874 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003875
3876 /* Now we have the status line between cur_ptr and cur_end */
3877 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003878 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003879 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003880 int len;
3881
3882 switch (exp->action) {
3883 case ACT_ALLOW:
3884 txn->flags |= TX_SVALLOW;
3885 done = 1;
3886 break;
3887
3888 case ACT_DENY:
3889 txn->flags |= TX_SVDENY;
3890 done = 1;
3891 break;
3892
3893 case ACT_REPLACE:
3894 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3895 if (len < 0)
3896 return -1;
3897
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003898 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3899 sl->info.res.status = strl2ui(code.ptr, code.len);
3900 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003901 return -1;
3902
3903 done = 1;
3904 return 1;
3905 }
3906 }
3907 return done;
3908}
3909
3910/*
3911 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3912 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3913 * unparsable response.
3914 */
3915static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3916{
3917 struct session *sess = s->sess;
3918 struct http_txn *txn = s->txn;
3919 struct hdr_exp *exp;
3920
3921 for (exp = px->rsp_exp; exp; exp = exp->next) {
3922 int ret;
3923
3924 /*
3925 * The interleaving of transformations and verdicts
3926 * makes it difficult to decide to continue or stop
3927 * the evaluation.
3928 */
3929
3930 if (txn->flags & TX_SVDENY)
3931 break;
3932
3933 if ((txn->flags & TX_SVALLOW) &&
3934 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3935 exp->action == ACT_PASS)) {
3936 exp = exp->next;
3937 continue;
3938 }
3939
3940 /* if this filter had a condition, evaluate it now and skip to
3941 * next filter if the condition does not match.
3942 */
3943 if (exp->cond) {
3944 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3945 ret = acl_pass(ret);
3946 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3947 ret = !ret;
3948 if (!ret)
3949 continue;
3950 }
3951
3952 /* Apply the filter to the status line. */
3953 ret = htx_apply_filter_to_sts_line(s, res, exp);
3954 if (unlikely(ret < 0))
3955 return -1;
3956
3957 if (likely(ret == 0)) {
3958 /* The filter did not match the response, it can be
3959 * iterated through all headers.
3960 */
3961 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3962 return -1;
3963 }
3964 }
3965 return 0;
3966}
3967
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003968/*
3969 * Manage client-side cookie. It can impact performance by about 2% so it is
3970 * desirable to call it only when needed. This code is quite complex because
3971 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3972 * highly recommended not to touch this part without a good reason !
3973 */
3974static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3975{
3976 struct session *sess = s->sess;
3977 struct http_txn *txn = s->txn;
3978 struct htx *htx;
3979 struct http_hdr_ctx ctx;
3980 char *hdr_beg, *hdr_end, *del_from;
3981 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3982 int preserve_hdr;
3983
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003984 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003985 ctx.blk = NULL;
3986 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02003987 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003988 del_from = NULL; /* nothing to be deleted */
3989 preserve_hdr = 0; /* assume we may kill the whole header */
3990
3991 /* Now look for cookies. Conforming to RFC2109, we have to support
3992 * attributes whose name begin with a '$', and associate them with
3993 * the right cookie, if we want to delete this cookie.
3994 * So there are 3 cases for each cookie read :
3995 * 1) it's a special attribute, beginning with a '$' : ignore it.
3996 * 2) it's a server id cookie that we *MAY* want to delete : save
3997 * some pointers on it (last semi-colon, beginning of cookie...)
3998 * 3) it's an application cookie : we *MAY* have to delete a previous
3999 * "special" cookie.
4000 * At the end of loop, if a "special" cookie remains, we may have to
4001 * remove it. If no application cookie persists in the header, we
4002 * *MUST* delete it.
4003 *
4004 * Note: RFC2965 is unclear about the processing of spaces around
4005 * the equal sign in the ATTR=VALUE form. A careful inspection of
4006 * the RFC explicitly allows spaces before it, and not within the
4007 * tokens (attrs or values). An inspection of RFC2109 allows that
4008 * too but section 10.1.3 lets one think that spaces may be allowed
4009 * after the equal sign too, resulting in some (rare) buggy
4010 * implementations trying to do that. So let's do what servers do.
4011 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4012 * allowed quoted strings in values, with any possible character
4013 * after a backslash, including control chars and delimitors, which
4014 * causes parsing to become ambiguous. Browsers also allow spaces
4015 * within values even without quotes.
4016 *
4017 * We have to keep multiple pointers in order to support cookie
4018 * removal at the beginning, middle or end of header without
4019 * corrupting the header. All of these headers are valid :
4020 *
4021 * hdr_beg hdr_end
4022 * | |
4023 * v |
4024 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4025 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4026 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4027 * | | | | | | |
4028 * | | | | | | |
4029 * | | | | | | +--> next
4030 * | | | | | +----> val_end
4031 * | | | | +-----------> val_beg
4032 * | | | +--------------> equal
4033 * | | +----------------> att_end
4034 * | +---------------------> att_beg
4035 * +--------------------------> prev
4036 *
4037 */
4038 hdr_beg = ctx.value.ptr;
4039 hdr_end = hdr_beg + ctx.value.len;
4040 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4041 /* Iterate through all cookies on this line */
4042
4043 /* find att_beg */
4044 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004045 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004046 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004047 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004048
4049 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4050 att_beg++;
4051
4052 /* find att_end : this is the first character after the last non
4053 * space before the equal. It may be equal to hdr_end.
4054 */
4055 equal = att_end = att_beg;
4056 while (equal < hdr_end) {
4057 if (*equal == '=' || *equal == ',' || *equal == ';')
4058 break;
4059 if (HTTP_IS_SPHT(*equal++))
4060 continue;
4061 att_end = equal;
4062 }
4063
4064 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4065 * is between <att_beg> and <equal>, both may be identical.
4066 */
4067 /* look for end of cookie if there is an equal sign */
4068 if (equal < hdr_end && *equal == '=') {
4069 /* look for the beginning of the value */
4070 val_beg = equal + 1;
4071 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4072 val_beg++;
4073
4074 /* find the end of the value, respecting quotes */
4075 next = http_find_cookie_value_end(val_beg, hdr_end);
4076
4077 /* make val_end point to the first white space or delimitor after the value */
4078 val_end = next;
4079 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4080 val_end--;
4081 }
4082 else
4083 val_beg = val_end = next = equal;
4084
4085 /* We have nothing to do with attributes beginning with
4086 * '$'. However, they will automatically be removed if a
4087 * header before them is removed, since they're supposed
4088 * to be linked together.
4089 */
4090 if (*att_beg == '$')
4091 continue;
4092
4093 /* Ignore cookies with no equal sign */
4094 if (equal == next) {
4095 /* This is not our cookie, so we must preserve it. But if we already
4096 * scheduled another cookie for removal, we cannot remove the
4097 * complete header, but we can remove the previous block itself.
4098 */
4099 preserve_hdr = 1;
4100 if (del_from != NULL) {
4101 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4102 val_end += delta;
4103 next += delta;
4104 hdr_end += delta;
4105 prev = del_from;
4106 del_from = NULL;
4107 }
4108 continue;
4109 }
4110
4111 /* if there are spaces around the equal sign, we need to
4112 * strip them otherwise we'll get trouble for cookie captures,
4113 * or even for rewrites. Since this happens extremely rarely,
4114 * it does not hurt performance.
4115 */
4116 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4117 int stripped_before = 0;
4118 int stripped_after = 0;
4119
4120 if (att_end != equal) {
4121 memmove(att_end, equal, hdr_end - equal);
4122 stripped_before = (att_end - equal);
4123 equal += stripped_before;
4124 val_beg += stripped_before;
4125 }
4126
4127 if (val_beg > equal + 1) {
4128 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4129 stripped_after = (equal + 1) - val_beg;
4130 val_beg += stripped_after;
4131 stripped_before += stripped_after;
4132 }
4133
4134 val_end += stripped_before;
4135 next += stripped_before;
4136 hdr_end += stripped_before;
4137 }
4138 /* now everything is as on the diagram above */
4139
4140 /* First, let's see if we want to capture this cookie. We check
4141 * that we don't already have a client side cookie, because we
4142 * can only capture one. Also as an optimisation, we ignore
4143 * cookies shorter than the declared name.
4144 */
4145 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4146 (val_end - att_beg >= sess->fe->capture_namelen) &&
4147 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4148 int log_len = val_end - att_beg;
4149
4150 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4151 ha_alert("HTTP logging : out of memory.\n");
4152 } else {
4153 if (log_len > sess->fe->capture_len)
4154 log_len = sess->fe->capture_len;
4155 memcpy(txn->cli_cookie, att_beg, log_len);
4156 txn->cli_cookie[log_len] = 0;
4157 }
4158 }
4159
4160 /* Persistence cookies in passive, rewrite or insert mode have the
4161 * following form :
4162 *
4163 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4164 *
4165 * For cookies in prefix mode, the form is :
4166 *
4167 * Cookie: NAME=SRV~VALUE
4168 */
4169 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4170 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4171 struct server *srv = s->be->srv;
4172 char *delim;
4173
4174 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4175 * have the server ID between val_beg and delim, and the original cookie between
4176 * delim+1 and val_end. Otherwise, delim==val_end :
4177 *
4178 * hdr_beg
4179 * |
4180 * v
4181 * NAME=SRV; # in all but prefix modes
4182 * NAME=SRV~OPAQUE ; # in prefix mode
4183 * || || | |+-> next
4184 * || || | +--> val_end
4185 * || || +---------> delim
4186 * || |+------------> val_beg
4187 * || +-------------> att_end = equal
4188 * |+-----------------> att_beg
4189 * +------------------> prev
4190 *
4191 */
4192 if (s->be->ck_opts & PR_CK_PFX) {
4193 for (delim = val_beg; delim < val_end; delim++)
4194 if (*delim == COOKIE_DELIM)
4195 break;
4196 }
4197 else {
4198 char *vbar1;
4199 delim = val_end;
4200 /* Now check if the cookie contains a date field, which would
4201 * appear after a vertical bar ('|') just after the server name
4202 * and before the delimiter.
4203 */
4204 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4205 if (vbar1) {
4206 /* OK, so left of the bar is the server's cookie and
4207 * right is the last seen date. It is a base64 encoded
4208 * 30-bit value representing the UNIX date since the
4209 * epoch in 4-second quantities.
4210 */
4211 int val;
4212 delim = vbar1++;
4213 if (val_end - vbar1 >= 5) {
4214 val = b64tos30(vbar1);
4215 if (val > 0)
4216 txn->cookie_last_date = val << 2;
4217 }
4218 /* look for a second vertical bar */
4219 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4220 if (vbar1 && (val_end - vbar1 > 5)) {
4221 val = b64tos30(vbar1 + 1);
4222 if (val > 0)
4223 txn->cookie_first_date = val << 2;
4224 }
4225 }
4226 }
4227
4228 /* if the cookie has an expiration date and the proxy wants to check
4229 * it, then we do that now. We first check if the cookie is too old,
4230 * then only if it has expired. We detect strict overflow because the
4231 * time resolution here is not great (4 seconds). Cookies with dates
4232 * in the future are ignored if their offset is beyond one day. This
4233 * allows an admin to fix timezone issues without expiring everyone
4234 * and at the same time avoids keeping unwanted side effects for too
4235 * long.
4236 */
4237 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4238 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4239 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4240 txn->flags &= ~TX_CK_MASK;
4241 txn->flags |= TX_CK_OLD;
4242 delim = val_beg; // let's pretend we have not found the cookie
4243 txn->cookie_first_date = 0;
4244 txn->cookie_last_date = 0;
4245 }
4246 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4247 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4248 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4249 txn->flags &= ~TX_CK_MASK;
4250 txn->flags |= TX_CK_EXPIRED;
4251 delim = val_beg; // let's pretend we have not found the cookie
4252 txn->cookie_first_date = 0;
4253 txn->cookie_last_date = 0;
4254 }
4255
4256 /* Here, we'll look for the first running server which supports the cookie.
4257 * This allows to share a same cookie between several servers, for example
4258 * to dedicate backup servers to specific servers only.
4259 * However, to prevent clients from sticking to cookie-less backup server
4260 * when they have incidentely learned an empty cookie, we simply ignore
4261 * empty cookies and mark them as invalid.
4262 * The same behaviour is applied when persistence must be ignored.
4263 */
4264 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4265 srv = NULL;
4266
4267 while (srv) {
4268 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4269 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4270 if ((srv->cur_state != SRV_ST_STOPPED) ||
4271 (s->be->options & PR_O_PERSIST) ||
4272 (s->flags & SF_FORCE_PRST)) {
4273 /* we found the server and we can use it */
4274 txn->flags &= ~TX_CK_MASK;
4275 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4276 s->flags |= SF_DIRECT | SF_ASSIGNED;
4277 s->target = &srv->obj_type;
4278 break;
4279 } else {
4280 /* we found a server, but it's down,
4281 * mark it as such and go on in case
4282 * another one is available.
4283 */
4284 txn->flags &= ~TX_CK_MASK;
4285 txn->flags |= TX_CK_DOWN;
4286 }
4287 }
4288 srv = srv->next;
4289 }
4290
4291 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4292 /* no server matched this cookie or we deliberately skipped it */
4293 txn->flags &= ~TX_CK_MASK;
4294 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4295 txn->flags |= TX_CK_UNUSED;
4296 else
4297 txn->flags |= TX_CK_INVALID;
4298 }
4299
4300 /* depending on the cookie mode, we may have to either :
4301 * - delete the complete cookie if we're in insert+indirect mode, so that
4302 * the server never sees it ;
4303 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004304 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004305 * if we're in cookie prefix mode
4306 */
4307 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4308 int delta; /* negative */
4309
4310 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4311 delta = val_beg - (delim + 1);
4312 val_end += delta;
4313 next += delta;
4314 hdr_end += delta;
4315 del_from = NULL;
4316 preserve_hdr = 1; /* we want to keep this cookie */
4317 }
4318 else if (del_from == NULL &&
4319 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4320 del_from = prev;
4321 }
4322 }
4323 else {
4324 /* This is not our cookie, so we must preserve it. But if we already
4325 * scheduled another cookie for removal, we cannot remove the
4326 * complete header, but we can remove the previous block itself.
4327 */
4328 preserve_hdr = 1;
4329
4330 if (del_from != NULL) {
4331 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4332 if (att_beg >= del_from)
4333 att_beg += delta;
4334 if (att_end >= del_from)
4335 att_end += delta;
4336 val_beg += delta;
4337 val_end += delta;
4338 next += delta;
4339 hdr_end += delta;
4340 prev = del_from;
4341 del_from = NULL;
4342 }
4343 }
4344
4345 /* continue with next cookie on this header line */
4346 att_beg = next;
4347 } /* for each cookie */
4348
4349
4350 /* There are no more cookies on this line.
4351 * We may still have one (or several) marked for deletion at the
4352 * end of the line. We must do this now in two ways :
4353 * - if some cookies must be preserved, we only delete from the
4354 * mark to the end of line ;
4355 * - if nothing needs to be preserved, simply delete the whole header
4356 */
4357 if (del_from) {
4358 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4359 }
4360 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004361 if (hdr_beg != hdr_end)
4362 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004363 else
4364 http_remove_header(htx, &ctx);
4365 }
4366 } /* for each "Cookie header */
4367}
4368
4369/*
4370 * Manage server-side cookies. It can impact performance by about 2% so it is
4371 * desirable to call it only when needed. This function is also used when we
4372 * just need to know if there is a cookie (eg: for check-cache).
4373 */
4374static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4375{
4376 struct session *sess = s->sess;
4377 struct http_txn *txn = s->txn;
4378 struct htx *htx;
4379 struct http_hdr_ctx ctx;
4380 struct server *srv;
4381 char *hdr_beg, *hdr_end;
4382 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004383 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004384
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004385 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004386
4387 ctx.blk = NULL;
4388 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004389 int is_first = 1;
4390
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004391 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4392 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4393 break;
4394 is_cookie2 = 1;
4395 }
4396
4397 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4398 * <prev> points to the colon.
4399 */
4400 txn->flags |= TX_SCK_PRESENT;
4401
4402 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4403 * check-cache is enabled) and we are not interested in checking
4404 * them. Warning, the cookie capture is declared in the frontend.
4405 */
4406 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4407 break;
4408
4409 /* OK so now we know we have to process this response cookie.
4410 * The format of the Set-Cookie header is slightly different
4411 * from the format of the Cookie header in that it does not
4412 * support the comma as a cookie delimiter (thus the header
4413 * cannot be folded) because the Expires attribute described in
4414 * the original Netscape's spec may contain an unquoted date
4415 * with a comma inside. We have to live with this because
4416 * many browsers don't support Max-Age and some browsers don't
4417 * support quoted strings. However the Set-Cookie2 header is
4418 * clean.
4419 *
4420 * We have to keep multiple pointers in order to support cookie
4421 * removal at the beginning, middle or end of header without
4422 * corrupting the header (in case of set-cookie2). A special
4423 * pointer, <scav> points to the beginning of the set-cookie-av
4424 * fields after the first semi-colon. The <next> pointer points
4425 * either to the end of line (set-cookie) or next unquoted comma
4426 * (set-cookie2). All of these headers are valid :
4427 *
4428 * hdr_beg hdr_end
4429 * | |
4430 * v |
4431 * NAME1 = VALUE 1 ; Secure; Path="/" |
4432 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4433 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4434 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4435 * | | | | | | | |
4436 * | | | | | | | +-> next
4437 * | | | | | | +------------> scav
4438 * | | | | | +--------------> val_end
4439 * | | | | +--------------------> val_beg
4440 * | | | +----------------------> equal
4441 * | | +------------------------> att_end
4442 * | +----------------------------> att_beg
4443 * +------------------------------> prev
4444 * -------------------------------> hdr_beg
4445 */
4446 hdr_beg = ctx.value.ptr;
4447 hdr_end = hdr_beg + ctx.value.len;
4448 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4449
4450 /* Iterate through all cookies on this line */
4451
4452 /* find att_beg */
4453 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004454 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004455 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004456 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004457
4458 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4459 att_beg++;
4460
4461 /* find att_end : this is the first character after the last non
4462 * space before the equal. It may be equal to hdr_end.
4463 */
4464 equal = att_end = att_beg;
4465
4466 while (equal < hdr_end) {
4467 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4468 break;
4469 if (HTTP_IS_SPHT(*equal++))
4470 continue;
4471 att_end = equal;
4472 }
4473
4474 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4475 * is between <att_beg> and <equal>, both may be identical.
4476 */
4477
4478 /* look for end of cookie if there is an equal sign */
4479 if (equal < hdr_end && *equal == '=') {
4480 /* look for the beginning of the value */
4481 val_beg = equal + 1;
4482 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4483 val_beg++;
4484
4485 /* find the end of the value, respecting quotes */
4486 next = http_find_cookie_value_end(val_beg, hdr_end);
4487
4488 /* make val_end point to the first white space or delimitor after the value */
4489 val_end = next;
4490 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4491 val_end--;
4492 }
4493 else {
4494 /* <equal> points to next comma, semi-colon or EOL */
4495 val_beg = val_end = next = equal;
4496 }
4497
4498 if (next < hdr_end) {
4499 /* Set-Cookie2 supports multiple cookies, and <next> points to
4500 * a colon or semi-colon before the end. So skip all attr-value
4501 * pairs and look for the next comma. For Set-Cookie, since
4502 * commas are permitted in values, skip to the end.
4503 */
4504 if (is_cookie2)
4505 next = http_find_hdr_value_end(next, hdr_end);
4506 else
4507 next = hdr_end;
4508 }
4509
4510 /* Now everything is as on the diagram above */
4511
4512 /* Ignore cookies with no equal sign */
4513 if (equal == val_end)
4514 continue;
4515
4516 /* If there are spaces around the equal sign, we need to
4517 * strip them otherwise we'll get trouble for cookie captures,
4518 * or even for rewrites. Since this happens extremely rarely,
4519 * it does not hurt performance.
4520 */
4521 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4522 int stripped_before = 0;
4523 int stripped_after = 0;
4524
4525 if (att_end != equal) {
4526 memmove(att_end, equal, hdr_end - equal);
4527 stripped_before = (att_end - equal);
4528 equal += stripped_before;
4529 val_beg += stripped_before;
4530 }
4531
4532 if (val_beg > equal + 1) {
4533 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4534 stripped_after = (equal + 1) - val_beg;
4535 val_beg += stripped_after;
4536 stripped_before += stripped_after;
4537 }
4538
4539 val_end += stripped_before;
4540 next += stripped_before;
4541 hdr_end += stripped_before;
4542
Christopher Faulet41dc8432019-06-18 09:49:16 +02004543 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004544 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004545 }
4546
4547 /* First, let's see if we want to capture this cookie. We check
4548 * that we don't already have a server side cookie, because we
4549 * can only capture one. Also as an optimisation, we ignore
4550 * cookies shorter than the declared name.
4551 */
4552 if (sess->fe->capture_name != NULL &&
4553 txn->srv_cookie == NULL &&
4554 (val_end - att_beg >= sess->fe->capture_namelen) &&
4555 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4556 int log_len = val_end - att_beg;
4557 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4558 ha_alert("HTTP logging : out of memory.\n");
4559 }
4560 else {
4561 if (log_len > sess->fe->capture_len)
4562 log_len = sess->fe->capture_len;
4563 memcpy(txn->srv_cookie, att_beg, log_len);
4564 txn->srv_cookie[log_len] = 0;
4565 }
4566 }
4567
4568 srv = objt_server(s->target);
4569 /* now check if we need to process it for persistence */
4570 if (!(s->flags & SF_IGNORE_PRST) &&
4571 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4572 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4573 /* assume passive cookie by default */
4574 txn->flags &= ~TX_SCK_MASK;
4575 txn->flags |= TX_SCK_FOUND;
4576
4577 /* If the cookie is in insert mode on a known server, we'll delete
4578 * this occurrence because we'll insert another one later.
4579 * We'll delete it too if the "indirect" option is set and we're in
4580 * a direct access.
4581 */
4582 if (s->be->ck_opts & PR_CK_PSV) {
4583 /* The "preserve" flag was set, we don't want to touch the
4584 * server's cookie.
4585 */
4586 }
4587 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4588 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4589 /* this cookie must be deleted */
4590 if (prev == hdr_beg && next == hdr_end) {
4591 /* whole header */
4592 http_remove_header(htx, &ctx);
4593 /* note: while both invalid now, <next> and <hdr_end>
4594 * are still equal, so the for() will stop as expected.
4595 */
4596 } else {
4597 /* just remove the value */
4598 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4599 next = prev;
4600 hdr_end += delta;
4601 }
4602 txn->flags &= ~TX_SCK_MASK;
4603 txn->flags |= TX_SCK_DELETED;
4604 /* and go on with next cookie */
4605 }
4606 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4607 /* replace bytes val_beg->val_end with the cookie name associated
4608 * with this server since we know it.
4609 */
4610 int sliding, delta;
4611
4612 ctx.value = ist2(val_beg, val_end - val_beg);
4613 ctx.lws_before = ctx.lws_after = 0;
4614 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4615 delta = srv->cklen - (val_end - val_beg);
4616 sliding = (ctx.value.ptr - val_beg);
4617 hdr_beg += sliding;
4618 val_beg += sliding;
4619 next += sliding + delta;
4620 hdr_end += sliding + delta;
4621
4622 txn->flags &= ~TX_SCK_MASK;
4623 txn->flags |= TX_SCK_REPLACED;
4624 }
4625 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4626 /* insert the cookie name associated with this server
4627 * before existing cookie, and insert a delimiter between them..
4628 */
4629 int sliding, delta;
4630 ctx.value = ist2(val_beg, 0);
4631 ctx.lws_before = ctx.lws_after = 0;
4632 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4633 delta = srv->cklen + 1;
4634 sliding = (ctx.value.ptr - val_beg);
4635 hdr_beg += sliding;
4636 val_beg += sliding;
4637 next += sliding + delta;
4638 hdr_end += sliding + delta;
4639
4640 val_beg[srv->cklen] = COOKIE_DELIM;
4641 txn->flags &= ~TX_SCK_MASK;
4642 txn->flags |= TX_SCK_REPLACED;
4643 }
4644 }
4645 /* that's done for this cookie, check the next one on the same
4646 * line when next != hdr_end (only if is_cookie2).
4647 */
4648 }
4649 }
4650}
4651
Christopher Faulet25a02f62018-10-24 12:00:25 +02004652/*
4653 * Parses the Cache-Control and Pragma request header fields to determine if
4654 * the request may be served from the cache and/or if it is cacheable. Updates
4655 * s->txn->flags.
4656 */
4657void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4658{
4659 struct http_txn *txn = s->txn;
4660 struct htx *htx;
4661 int32_t pos;
4662 int pragma_found, cc_found, i;
4663
4664 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4665 return; /* nothing more to do here */
4666
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004667 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004668 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004669 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004670 struct htx_blk *blk = htx_get_blk(htx, pos);
4671 enum htx_blk_type type = htx_get_blk_type(blk);
4672 struct ist n, v;
4673
4674 if (type == HTX_BLK_EOH)
4675 break;
4676 if (type != HTX_BLK_HDR)
4677 continue;
4678
4679 n = htx_get_blk_name(htx, blk);
4680 v = htx_get_blk_value(htx, blk);
4681
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004682 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004683 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4684 pragma_found = 1;
4685 continue;
4686 }
4687 }
4688
4689 /* Don't use the cache and don't try to store if we found the
4690 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004691 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004692 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4693 txn->flags |= TX_CACHE_IGNORE;
4694 continue;
4695 }
4696
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004697 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004698 continue;
4699
4700 /* OK, right now we know we have a cache-control header */
4701 cc_found = 1;
4702 if (!v.len) /* no info */
4703 continue;
4704
4705 i = 0;
4706 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4707 !isspace((unsigned char)*(v.ptr+i)))
4708 i++;
4709
4710 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4711 * values after max-age, max-stale nor min-fresh, we simply don't
4712 * use the cache when they're specified.
4713 */
4714 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4715 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4716 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4717 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4718 txn->flags |= TX_CACHE_IGNORE;
4719 continue;
4720 }
4721
4722 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 continue;
4725 }
4726 }
4727
4728 /* RFC7234#5.4:
4729 * When the Cache-Control header field is also present and
4730 * understood in a request, Pragma is ignored.
4731 * When the Cache-Control header field is not present in a
4732 * request, caches MUST consider the no-cache request
4733 * pragma-directive as having the same effect as if
4734 * "Cache-Control: no-cache" were present.
4735 */
4736 if (!cc_found && pragma_found)
4737 txn->flags |= TX_CACHE_IGNORE;
4738}
4739
4740/*
4741 * Check if response is cacheable or not. Updates s->txn->flags.
4742 */
4743void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4744{
4745 struct http_txn *txn = s->txn;
4746 struct htx *htx;
4747 int32_t pos;
4748 int i;
4749
4750 if (txn->status < 200) {
4751 /* do not try to cache interim responses! */
4752 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4753 return;
4754 }
4755
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004756 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004757 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004758 struct htx_blk *blk = htx_get_blk(htx, pos);
4759 enum htx_blk_type type = htx_get_blk_type(blk);
4760 struct ist n, v;
4761
4762 if (type == HTX_BLK_EOH)
4763 break;
4764 if (type != HTX_BLK_HDR)
4765 continue;
4766
4767 n = htx_get_blk_name(htx, blk);
4768 v = htx_get_blk_value(htx, blk);
4769
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004770 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004771 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4772 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4773 return;
4774 }
4775 }
4776
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004777 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004778 continue;
4779
4780 /* OK, right now we know we have a cache-control header */
4781 if (!v.len) /* no info */
4782 continue;
4783
4784 i = 0;
4785 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4786 !isspace((unsigned char)*(v.ptr+i)))
4787 i++;
4788
4789 /* we have a complete value between v.ptr and (v.ptr+i) */
4790 if (i < v.len && *(v.ptr + i) == '=') {
4791 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4792 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4793 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4794 continue;
4795 }
4796
4797 /* we have something of the form no-cache="set-cookie" */
4798 if ((v.len >= 21) &&
4799 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4800 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4801 txn->flags &= ~TX_CACHE_COOK;
4802 continue;
4803 }
4804
4805 /* OK, so we know that either p2 points to the end of string or to a comma */
4806 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4807 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4808 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4809 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4810 return;
4811 }
4812
4813 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4814 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4815 continue;
4816 }
4817 }
4818}
4819
Christopher Faulet64159df2018-10-24 21:15:35 +02004820/* send a server's name with an outgoing request over an established connection.
4821 * Note: this function is designed to be called once the request has been
4822 * scheduled for being forwarded. This is the reason why the number of forwarded
4823 * bytes have to be adjusted.
4824 */
4825int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4826{
4827 struct htx *htx;
4828 struct http_hdr_ctx ctx;
4829 struct ist hdr;
4830 uint32_t data;
4831
4832 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004833 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004834 data = htx->data;
4835
4836 ctx.blk = NULL;
4837 while (http_find_header(htx, hdr, &ctx, 1))
4838 http_remove_header(htx, &ctx);
4839 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4840
4841 if (co_data(&s->req)) {
4842 if (data >= htx->data)
4843 c_rew(&s->req, data - htx->data);
4844 else
4845 c_adv(&s->req, htx->data - data);
4846 }
4847 return 0;
4848}
4849
Christopher Faulet377c5a52018-10-24 21:21:30 +02004850/*
4851 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4852 * for the current backend.
4853 *
4854 * It is assumed that the request is either a HEAD, GET, or POST and that the
4855 * uri_auth field is valid.
4856 *
4857 * Returns 1 if stats should be provided, otherwise 0.
4858 */
4859static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4860{
4861 struct uri_auth *uri_auth = backend->uri_auth;
4862 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004863 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004864 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004865
4866 if (!uri_auth)
4867 return 0;
4868
4869 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4870 return 0;
4871
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004872 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004873 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004874 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004875
4876 /* check URI size */
4877 if (uri_auth->uri_len > uri.len)
4878 return 0;
4879
4880 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4881 return 0;
4882
4883 return 1;
4884}
4885
4886/* This function prepares an applet to handle the stats. It can deal with the
4887 * "100-continue" expectation, check that admin rules are met for POST requests,
4888 * and program a response message if something was unexpected. It cannot fail
4889 * and always relies on the stats applet to complete the job. It does not touch
4890 * analysers nor counters, which are left to the caller. It does not touch
4891 * s->target which is supposed to already point to the stats applet. The caller
4892 * is expected to have already assigned an appctx to the stream.
4893 */
4894static int htx_handle_stats(struct stream *s, struct channel *req)
4895{
4896 struct stats_admin_rule *stats_admin_rule;
4897 struct stream_interface *si = &s->si[1];
4898 struct session *sess = s->sess;
4899 struct http_txn *txn = s->txn;
4900 struct http_msg *msg = &txn->req;
4901 struct uri_auth *uri_auth = s->be->uri_auth;
4902 const char *h, *lookup, *end;
4903 struct appctx *appctx;
4904 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004905 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004906
4907 appctx = si_appctx(si);
4908 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4909 appctx->st1 = appctx->st2 = 0;
4910 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4911 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4912 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4913 appctx->ctx.stats.flags |= STAT_CHUNKED;
4914
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004915 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004916 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004917 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4918 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004919
4920 for (h = lookup; h <= end - 3; h++) {
4921 if (memcmp(h, ";up", 3) == 0) {
4922 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4923 break;
4924 }
4925 }
4926
4927 if (uri_auth->refresh) {
4928 for (h = lookup; h <= end - 10; h++) {
4929 if (memcmp(h, ";norefresh", 10) == 0) {
4930 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4931 break;
4932 }
4933 }
4934 }
4935
4936 for (h = lookup; h <= end - 4; h++) {
4937 if (memcmp(h, ";csv", 4) == 0) {
4938 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4939 break;
4940 }
4941 }
4942
4943 for (h = lookup; h <= end - 6; h++) {
4944 if (memcmp(h, ";typed", 6) == 0) {
4945 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4946 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4947 break;
4948 }
4949 }
4950
4951 for (h = lookup; h <= end - 8; h++) {
4952 if (memcmp(h, ";st=", 4) == 0) {
4953 int i;
4954 h += 4;
4955 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4956 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4957 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4958 appctx->ctx.stats.st_code = i;
4959 break;
4960 }
4961 }
4962 break;
4963 }
4964 }
4965
4966 appctx->ctx.stats.scope_str = 0;
4967 appctx->ctx.stats.scope_len = 0;
4968 for (h = lookup; h <= end - 8; h++) {
4969 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4970 int itx = 0;
4971 const char *h2;
4972 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4973 const char *err;
4974
4975 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4976 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004977 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4978 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004979 if (*h == ';' || *h == '&' || *h == ' ')
4980 break;
4981 itx++;
4982 h++;
4983 }
4984
4985 if (itx > STAT_SCOPE_TXT_MAXLEN)
4986 itx = STAT_SCOPE_TXT_MAXLEN;
4987 appctx->ctx.stats.scope_len = itx;
4988
4989 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4990 memcpy(scope_txt, h2, itx);
4991 scope_txt[itx] = '\0';
4992 err = invalid_char(scope_txt);
4993 if (err) {
4994 /* bad char in search text => clear scope */
4995 appctx->ctx.stats.scope_str = 0;
4996 appctx->ctx.stats.scope_len = 0;
4997 }
4998 break;
4999 }
5000 }
5001
5002 /* now check whether we have some admin rules for this request */
5003 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5004 int ret = 1;
5005
5006 if (stats_admin_rule->cond) {
5007 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5008 ret = acl_pass(ret);
5009 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5010 ret = !ret;
5011 }
5012
5013 if (ret) {
5014 /* no rule, or the rule matches */
5015 appctx->ctx.stats.flags |= STAT_ADMIN;
5016 break;
5017 }
5018 }
5019
Christopher Faulet5d45e382019-02-27 15:15:23 +01005020 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5021 appctx->st0 = STAT_HTTP_HEAD;
5022 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005023 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005024 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005025 if (msg->msg_state < HTTP_MSG_DATA)
5026 req->analysers |= AN_REQ_HTTP_BODY;
5027 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005028 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005029 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005030 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5031 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5032 appctx->st0 = STAT_HTTP_LAST;
5033 }
5034 }
5035 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005036 /* Unsupported method */
5037 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5038 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5039 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005040 }
5041
5042 s->task->nice = -32; /* small boost for HTTP statistics */
5043 return 1;
5044}
5045
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005046void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5047{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005048 struct channel *req = &s->req;
5049 struct channel *res = &s->res;
5050 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005052 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005053 struct ist path, location;
5054 unsigned int flags;
5055 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005056
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005057 /*
5058 * Create the location
5059 */
5060 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005061
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005062 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005063 /* special prefix "/" means don't change URL */
5064 srv = __objt_server(s->target);
5065 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5066 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5067 return;
5068 }
5069
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005070 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005071 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005072 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005073 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005074 if (!path.ptr)
5075 return;
5076
5077 if (!chunk_memcat(&trash, path.ptr, path.len))
5078 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005079 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005081 /*
5082 * Create the 302 respone
5083 */
5084 htx = htx_from_buf(&res->buf);
5085 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5086 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5087 ist("HTTP/1.1"), ist("302"), ist("Found"));
5088 if (!sl)
5089 goto fail;
5090 sl->info.res.status = 302;
5091 s->txn->status = 302;
5092
5093 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5094 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5095 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5096 !htx_add_header(htx, ist("Location"), location))
5097 goto fail;
5098
5099 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5100 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005101
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005102 /*
5103 * Send the message
5104 */
5105 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005106 c_adv(res, data);
5107 res->total += data;
5108
5109 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005110 si_shutr(si);
5111 si_shutw(si);
5112 si->err_type = SI_ET_NONE;
5113 si->state = SI_ST_CLO;
5114
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005115 channel_auto_read(req);
5116 channel_abort(req);
5117 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005118 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005119 channel_auto_read(res);
5120 channel_auto_close(res);
5121
5122 if (!(s->flags & SF_ERR_MASK))
5123 s->flags |= SF_ERR_LOCAL;
5124 if (!(s->flags & SF_FINST_MASK))
5125 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005126
5127 /* FIXME: we should increase a counter of redirects per server and per backend. */
5128 srv_inc_sess_ctr(srv);
5129 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005130 return;
5131
5132 fail:
5133 /* If an error occurred, remove the incomplete HTTP response from the
5134 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005135 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005136}
5137
Christopher Fauletf2824e62018-10-01 12:12:37 +02005138/* This function terminates the request because it was completly analyzed or
5139 * because an error was triggered during the body forwarding.
5140 */
5141static void htx_end_request(struct stream *s)
5142{
5143 struct channel *chn = &s->req;
5144 struct http_txn *txn = s->txn;
5145
5146 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5147 now_ms, __FUNCTION__, s,
5148 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5149 s->req.analysers, s->res.analysers);
5150
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005151 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5152 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005153 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005154 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005155 goto end;
5156 }
5157
5158 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5159 return;
5160
5161 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162 /* No need to read anymore, the request was completely parsed.
5163 * We can shut the read side unless we want to abort_on_close,
5164 * or we have a POST request. The issue with POST requests is
5165 * that some browsers still send a CRLF after the request, and
5166 * this CRLF must be read so that it does not remain in the kernel
5167 * buffers, otherwise a close could cause an RST on some systems
5168 * (eg: Linux).
5169 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005170 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005171 channel_dont_read(chn);
5172
5173 /* if the server closes the connection, we want to immediately react
5174 * and close the socket to save packets and syscalls.
5175 */
5176 s->si[1].flags |= SI_FL_NOHALF;
5177
5178 /* In any case we've finished parsing the request so we must
5179 * disable Nagle when sending data because 1) we're not going
5180 * to shut this side, and 2) the server is waiting for us to
5181 * send pending data.
5182 */
5183 chn->flags |= CF_NEVER_WAIT;
5184
Christopher Fauletd01ce402019-01-02 17:44:13 +01005185 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5186 /* The server has not finished to respond, so we
5187 * don't want to move in order not to upset it.
5188 */
5189 return;
5190 }
5191
Christopher Fauletf2824e62018-10-01 12:12:37 +02005192 /* When we get here, it means that both the request and the
5193 * response have finished receiving. Depending on the connection
5194 * mode, we'll have to wait for the last bytes to leave in either
5195 * direction, and sometimes for a close to be effective.
5196 */
5197 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5198 /* Tunnel mode will not have any analyser so it needs to
5199 * poll for reads.
5200 */
5201 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005202 if (b_data(&chn->buf))
5203 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005204 txn->req.msg_state = HTTP_MSG_TUNNEL;
5205 }
5206 else {
5207 /* we're not expecting any new data to come for this
5208 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005209 *
5210 * However, there is an exception if the response
5211 * length is undefined. In this case, we need to wait
5212 * the close from the server. The response will be
5213 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005214 */
5215 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5216 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005217 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005218
5219 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5220 channel_shutr_now(chn);
5221 channel_shutw_now(chn);
5222 }
5223 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005224 goto check_channel_flags;
5225 }
5226
5227 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5228 http_msg_closing:
5229 /* nothing else to forward, just waiting for the output buffer
5230 * to be empty and for the shutw_now to take effect.
5231 */
5232 if (channel_is_empty(chn)) {
5233 txn->req.msg_state = HTTP_MSG_CLOSED;
5234 goto http_msg_closed;
5235 }
5236 else if (chn->flags & CF_SHUTW) {
5237 txn->req.err_state = txn->req.msg_state;
5238 txn->req.msg_state = HTTP_MSG_ERROR;
5239 goto end;
5240 }
5241 return;
5242 }
5243
5244 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5245 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005246 /* if we don't know whether the server will close, we need to hard close */
5247 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5248 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005249 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005250 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005251 channel_dont_read(chn);
5252 goto end;
5253 }
5254
5255 check_channel_flags:
5256 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5257 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5258 /* if we've just closed an output, let's switch */
5259 txn->req.msg_state = HTTP_MSG_CLOSING;
5260 goto http_msg_closing;
5261 }
5262
5263 end:
5264 chn->analysers &= AN_REQ_FLT_END;
5265 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5266 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5267 channel_auto_close(chn);
5268 channel_auto_read(chn);
5269}
5270
5271
5272/* This function terminates the response because it was completly analyzed or
5273 * because an error was triggered during the body forwarding.
5274 */
5275static void htx_end_response(struct stream *s)
5276{
5277 struct channel *chn = &s->res;
5278 struct http_txn *txn = s->txn;
5279
5280 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5281 now_ms, __FUNCTION__, s,
5282 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5283 s->req.analysers, s->res.analysers);
5284
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005285 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5286 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005287 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005288 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005289 goto end;
5290 }
5291
5292 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5293 return;
5294
5295 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5296 /* In theory, we don't need to read anymore, but we must
5297 * still monitor the server connection for a possible close
5298 * while the request is being uploaded, so we don't disable
5299 * reading.
5300 */
5301 /* channel_dont_read(chn); */
5302
5303 if (txn->req.msg_state < HTTP_MSG_DONE) {
5304 /* The client seems to still be sending data, probably
5305 * because we got an error response during an upload.
5306 * We have the choice of either breaking the connection
5307 * or letting it pass through. Let's do the later.
5308 */
5309 return;
5310 }
5311
5312 /* When we get here, it means that both the request and the
5313 * response have finished receiving. Depending on the connection
5314 * mode, we'll have to wait for the last bytes to leave in either
5315 * direction, and sometimes for a close to be effective.
5316 */
5317 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5318 channel_auto_read(chn);
5319 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005320 if (b_data(&chn->buf))
5321 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005322 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5323 }
5324 else {
5325 /* we're not expecting any new data to come for this
5326 * transaction, so we can close it.
5327 */
5328 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5329 channel_shutr_now(chn);
5330 channel_shutw_now(chn);
5331 }
5332 }
5333 goto check_channel_flags;
5334 }
5335
5336 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5337 http_msg_closing:
5338 /* nothing else to forward, just waiting for the output buffer
5339 * to be empty and for the shutw_now to take effect.
5340 */
5341 if (channel_is_empty(chn)) {
5342 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5343 goto http_msg_closed;
5344 }
5345 else if (chn->flags & CF_SHUTW) {
5346 txn->rsp.err_state = txn->rsp.msg_state;
5347 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005348 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005349 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005350 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005351 goto end;
5352 }
5353 return;
5354 }
5355
5356 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5357 http_msg_closed:
5358 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005359 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005360 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005361 goto end;
5362 }
5363
5364 check_channel_flags:
5365 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5366 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5367 /* if we've just closed an output, let's switch */
5368 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5369 goto http_msg_closing;
5370 }
5371
5372 end:
5373 chn->analysers &= AN_RES_FLT_END;
5374 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5375 chn->analysers |= AN_RES_FLT_XFER_DATA;
5376 channel_auto_close(chn);
5377 channel_auto_read(chn);
5378}
5379
Christopher Faulet0f226952018-10-22 09:29:56 +02005380void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5381 int finst, const struct buffer *msg)
5382{
5383 channel_auto_read(si_oc(si));
5384 channel_abort(si_oc(si));
5385 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005386 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005387 channel_auto_close(si_ic(si));
5388 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005389
5390 /* <msg> is an HTX structure. So we copy it in the response's
5391 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005392 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005393 struct channel *chn = si_ic(si);
5394 struct htx *htx;
5395
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005396 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005397 chn->buf.data = msg->data;
5398 memcpy(chn->buf.area, msg->area, msg->data);
5399 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005400 c_adv(chn, htx->data);
5401 chn->total += htx->data;
5402 }
5403 if (!(s->flags & SF_ERR_MASK))
5404 s->flags |= err;
5405 if (!(s->flags & SF_FINST_MASK))
5406 s->flags |= finst;
5407}
5408
5409void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5410{
5411 channel_auto_read(&s->req);
5412 channel_abort(&s->req);
5413 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005414 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5415 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005416
5417 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005418
5419 /* <msg> is an HTX structure. So we copy it in the response's
5420 * channel */
5421 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005422 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005423 struct channel *chn = &s->res;
5424 struct htx *htx;
5425
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005426 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005427 chn->buf.data = msg->data;
5428 memcpy(chn->buf.area, msg->area, msg->data);
5429 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005430 c_adv(chn, htx->data);
5431 chn->total += htx->data;
5432 }
5433
5434 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5435 channel_auto_read(&s->res);
5436 channel_auto_close(&s->res);
5437 channel_shutr_now(&s->res);
5438}
5439
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005440struct buffer *htx_error_message(struct stream *s)
5441{
5442 const int msgnum = http_get_status_idx(s->txn->status);
5443
5444 if (s->be->errmsg[msgnum].area)
5445 return &s->be->errmsg[msgnum];
5446 else if (strm_fe(s)->errmsg[msgnum].area)
5447 return &strm_fe(s)->errmsg[msgnum];
5448 else
5449 return &htx_err_chunks[msgnum];
5450}
5451
5452
Christopher Faulet4a28a532019-03-01 11:19:40 +01005453/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5454 * on success and -1 on error.
5455 */
5456static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5457{
5458 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5459 * then we must send an HTTP/1.1 100 Continue intermediate response.
5460 */
5461 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5462 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5463 struct ist hdr = { .ptr = "Expect", .len = 6 };
5464 struct http_hdr_ctx ctx;
5465
5466 ctx.blk = NULL;
5467 /* Expect is allowed in 1.1, look for it */
5468 if (http_find_header(htx, hdr, &ctx, 0) &&
5469 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5470 if (htx_reply_100_continue(s) == -1)
5471 return -1;
5472 http_remove_header(htx, &ctx);
5473 }
5474 }
5475 return 0;
5476}
5477
Christopher Faulet23a3c792018-11-28 10:01:23 +01005478/* Send a 100-Continue response to the client. It returns 0 on success and -1
5479 * on error. The response channel is updated accordingly.
5480 */
5481static int htx_reply_100_continue(struct stream *s)
5482{
5483 struct channel *res = &s->res;
5484 struct htx *htx = htx_from_buf(&res->buf);
5485 struct htx_sl *sl;
5486 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5487 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5488 size_t data;
5489
5490 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5491 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5492 if (!sl)
5493 goto fail;
5494 sl->info.res.status = 100;
5495
Christopher Faulet9869f932019-06-26 14:23:54 +02005496 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005497 goto fail;
5498
5499 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005500 c_adv(res, data);
5501 res->total += data;
5502 return 0;
5503
5504 fail:
5505 /* If an error occurred, remove the incomplete HTTP response from the
5506 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005507 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005508 return -1;
5509}
5510
Christopher Faulet12c51e22018-11-28 15:59:42 +01005511
5512/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5513 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5514 * error. The response channel is updated accordingly.
5515 */
5516static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5517{
5518 struct channel *res = &s->res;
5519 struct htx *htx = htx_from_buf(&res->buf);
5520 struct htx_sl *sl;
5521 struct ist code, body;
5522 int status;
5523 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5524 size_t data;
5525
5526 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5527 status = 401;
5528 code = ist("401");
5529 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5530 "You need a valid user and password to access this content.\n"
5531 "</body></html>\n");
5532 }
5533 else {
5534 status = 407;
5535 code = ist("407");
5536 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5537 "You need a valid user and password to access this content.\n"
5538 "</body></html>\n");
5539 }
5540
5541 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5542 ist("HTTP/1.1"), code, ist("Unauthorized"));
5543 if (!sl)
5544 goto fail;
5545 sl->info.res.status = status;
5546 s->txn->status = status;
5547
5548 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5549 goto fail;
5550
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005551 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5552 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005553 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005554 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5555 goto fail;
5556 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5557 goto fail;
5558 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005559 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005560 if (!htx_add_endof(htx, HTX_BLK_EOH))
5561 goto fail;
5562
5563 while (body.len) {
5564 size_t sent = htx_add_data(htx, body);
5565 if (!sent)
5566 goto fail;
5567 body.ptr += sent;
5568 body.len -= sent;
5569 }
5570
5571 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005572 goto fail;
5573
5574 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005575 c_adv(res, data);
5576 res->total += data;
5577
5578 channel_auto_read(&s->req);
5579 channel_abort(&s->req);
5580 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005581 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005582
5583 res->wex = tick_add_ifset(now_ms, res->wto);
5584 channel_auto_read(res);
5585 channel_auto_close(res);
5586 channel_shutr_now(res);
5587 return 0;
5588
5589 fail:
5590 /* If an error occurred, remove the incomplete HTTP response from the
5591 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005592 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005593 return -1;
5594}
5595
Christopher Faulet0f226952018-10-22 09:29:56 +02005596/*
5597 * Capture headers from message <htx> according to header list <cap_hdr>, and
5598 * fill the <cap> pointers appropriately.
5599 */
5600static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5601{
5602 struct cap_hdr *h;
5603 int32_t pos;
5604
Christopher Fauleta3f15502019-05-13 15:27:23 +02005605 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005606 struct htx_blk *blk = htx_get_blk(htx, pos);
5607 enum htx_blk_type type = htx_get_blk_type(blk);
5608 struct ist n, v;
5609
5610 if (type == HTX_BLK_EOH)
5611 break;
5612 if (type != HTX_BLK_HDR)
5613 continue;
5614
5615 n = htx_get_blk_name(htx, blk);
5616
5617 for (h = cap_hdr; h; h = h->next) {
5618 if (h->namelen && (h->namelen == n.len) &&
5619 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5620 if (cap[h->index] == NULL)
5621 cap[h->index] =
5622 pool_alloc(h->pool);
5623
5624 if (cap[h->index] == NULL) {
5625 ha_alert("HTTP capture : out of memory.\n");
5626 break;
5627 }
5628
5629 v = htx_get_blk_value(htx, blk);
5630 if (v.len > h->len)
5631 v.len = h->len;
5632
5633 memcpy(cap[h->index], v.ptr, v.len);
5634 cap[h->index][v.len]=0;
5635 }
5636 }
5637 }
5638}
5639
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005640/* Delete a value in a header between delimiters <from> and <next>. The header
5641 * itself is delimited by <start> and <end> pointers. The number of characters
5642 * displaced is returned, and the pointer to the first delimiter is updated if
5643 * required. The function tries as much as possible to respect the following
5644 * principles :
5645 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5646 * in which case <next> is simply removed
5647 * - set exactly one space character after the new first delimiter, unless there
5648 * are not enough characters in the block being moved to do so.
5649 * - remove unneeded spaces before the previous delimiter and after the new
5650 * one.
5651 *
5652 * It is the caller's responsibility to ensure that :
5653 * - <from> points to a valid delimiter or <start> ;
5654 * - <next> points to a valid delimiter or <end> ;
5655 * - there are non-space chars before <from>.
5656 */
5657static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5658{
5659 char *prev = *from;
5660
5661 if (prev == start) {
5662 /* We're removing the first value. eat the semicolon, if <next>
5663 * is lower than <end> */
5664 if (next < end)
5665 next++;
5666
5667 while (next < end && HTTP_IS_SPHT(*next))
5668 next++;
5669 }
5670 else {
5671 /* Remove useless spaces before the old delimiter. */
5672 while (HTTP_IS_SPHT(*(prev-1)))
5673 prev--;
5674 *from = prev;
5675
5676 /* copy the delimiter and if possible a space if we're
5677 * not at the end of the line.
5678 */
5679 if (next < end) {
5680 *prev++ = *next++;
5681 if (prev + 1 < next)
5682 *prev++ = ' ';
5683 while (next < end && HTTP_IS_SPHT(*next))
5684 next++;
5685 }
5686 }
5687 memmove(prev, next, end - next);
5688 return (prev - next);
5689}
5690
Christopher Faulet0f226952018-10-22 09:29:56 +02005691
5692/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005693 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005694 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005695static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005696{
5697 struct ist dst = ist2(str, 0);
5698
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 goto end;
5701 if (dst.len + 1 > len)
5702 goto end;
5703 dst.ptr[dst.len++] = ' ';
5704
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005705 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005706 goto end;
5707 if (dst.len + 1 > len)
5708 goto end;
5709 dst.ptr[dst.len++] = ' ';
5710
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 end:
5713 return dst.len;
5714}
5715
Christopher Fauletf0523542018-10-24 11:06:58 +02005716/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005717 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005718 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005719static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005720{
5721 struct ist dst = ist2(str, 0);
5722
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005723 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005724 goto end;
5725 if (dst.len + 1 > len)
5726 goto end;
5727 dst.ptr[dst.len++] = ' ';
5728
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005729 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005730 goto end;
5731 if (dst.len + 1 > len)
5732 goto end;
5733 dst.ptr[dst.len++] = ' ';
5734
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005735 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005736 end:
5737 return dst.len;
5738}
5739
5740
Christopher Faulet0f226952018-10-22 09:29:56 +02005741/*
5742 * Print a debug line with a start line.
5743 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005744static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005745{
5746 struct session *sess = strm_sess(s);
5747 int max;
5748
5749 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5750 dir,
5751 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5752 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5753
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005754 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005755 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005756 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005757 trash.area[trash.data++] = ' ';
5758
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005759 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005760 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005761 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005762 trash.area[trash.data++] = ' ';
5763
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005764 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005765 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005766 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005767 trash.area[trash.data++] = '\n';
5768
5769 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5770}
5771
5772/*
5773 * Print a debug line with a header.
5774 */
5775static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5776{
5777 struct session *sess = strm_sess(s);
5778 int max;
5779
5780 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5781 dir,
5782 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5783 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5784
5785 max = n.len;
5786 UBOUND(max, trash.size - trash.data - 3);
5787 chunk_memcat(&trash, n.ptr, max);
5788 trash.area[trash.data++] = ':';
5789 trash.area[trash.data++] = ' ';
5790
5791 max = v.len;
5792 UBOUND(max, trash.size - trash.data - 1);
5793 chunk_memcat(&trash, v.ptr, max);
5794 trash.area[trash.data++] = '\n';
5795
5796 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5797}
5798
5799
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005800__attribute__((constructor))
5801static void __htx_protocol_init(void)
5802{
5803}
5804
5805
5806/*
5807 * Local variables:
5808 * c-indent-level: 8
5809 * c-basic-offset: 8
5810 * End:
5811 */