blob: 979217b0567e0e8c63181340802accdf0b00e4eb [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 Fauletf1ba18d2018-11-26 21:37:08 +0100332 isteqi(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
1013 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001014 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001015
1016 req->analysers &= AN_REQ_FLT_END;
1017 req->analyse_exp = TICK_ETERNITY;
1018
1019 if (!(s->flags & SF_ERR_MASK))
1020 s->flags |= SF_ERR_PRXCOND;
1021 if (!(s->flags & SF_FINST_MASK))
1022 s->flags |= SF_FINST_T;
1023 return 0;
1024}
1025
1026/* This function is an analyser which waits for the HTTP request body. It waits
1027 * for either the buffer to be full, or the full advertised contents to have
1028 * reached the buffer. It must only be called after the standard HTTP request
1029 * processing has occurred, because it expects the request to be parsed and will
1030 * look for the Expect header. It may send a 100-Continue interim response. It
1031 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1032 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1033 * needs to read more data, or 1 once it has completed its analysis.
1034 */
1035int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1036{
1037 struct session *sess = s->sess;
1038 struct http_txn *txn = s->txn;
1039 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001040 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001041
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001042
1043 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1044 now_ms, __FUNCTION__,
1045 s,
1046 req,
1047 req->rex, req->wex,
1048 req->flags,
1049 ci_data(req),
1050 req->analysers);
1051
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001052 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053
Willy Tarreau4236f032019-03-05 10:43:32 +01001054 if (htx->flags & HTX_FL_PARSING_ERROR)
1055 goto return_bad_req;
1056
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057 if (msg->msg_state < HTTP_MSG_BODY)
1058 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001059
Christopher Faulete0768eb2018-10-03 16:38:02 +02001060 /* We have to parse the HTTP request body to find any required data.
1061 * "balance url_param check_post" should have been the only way to get
1062 * into this. We were brought here after HTTP header analysis, so all
1063 * related structures are ready.
1064 */
1065
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001066 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001067 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1068 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001069 }
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001073 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1074 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001076 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001077 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001078 goto http_end;
1079
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001080 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001081 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1082 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001083 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
1085 if (!(s->flags & SF_ERR_MASK))
1086 s->flags |= SF_ERR_CLITO;
1087 if (!(s->flags & SF_FINST_MASK))
1088 s->flags |= SF_FINST_D;
1089 goto return_err_msg;
1090 }
1091
1092 /* we get here if we need to wait for more data */
1093 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1094 /* Not enough data. We'll re-use the http-request
1095 * timeout here. Ideally, we should set the timeout
1096 * relative to the accept() date. We just set the
1097 * request timeout once at the beginning of the
1098 * request.
1099 */
1100 channel_dont_connect(req);
1101 if (!tick_isset(req->analyse_exp))
1102 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1103 return 0;
1104 }
1105
1106 http_end:
1107 /* The situation will not evolve, so let's give up on the analysis. */
1108 s->logs.tv_request = now; /* update the request timer to reflect full request */
1109 req->analysers &= ~an_bit;
1110 req->analyse_exp = TICK_ETERNITY;
1111 return 1;
1112
1113 return_bad_req: /* let's centralize all bad requests */
1114 txn->req.err_state = txn->req.msg_state;
1115 txn->req.msg_state = HTTP_MSG_ERROR;
1116 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001117 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001118
1119 if (!(s->flags & SF_ERR_MASK))
1120 s->flags |= SF_ERR_PRXCOND;
1121 if (!(s->flags & SF_FINST_MASK))
1122 s->flags |= SF_FINST_R;
1123
1124 return_err_msg:
1125 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001126 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001127 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001128 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001129 return 0;
1130}
1131
1132/* This function is an analyser which forwards request body (including chunk
1133 * sizes if any). It is called as soon as we must forward, even if we forward
1134 * zero byte. The only situation where it must not be called is when we're in
1135 * tunnel mode and we want to forward till the close. It's used both to forward
1136 * remaining data and to resync after end of body. It expects the msg_state to
1137 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1138 * read more data, or 1 once we can go on with next request or end the stream.
1139 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1140 * bytes of pending data + the headers if not already done.
1141 */
1142int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1143{
1144 struct session *sess = s->sess;
1145 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001146 struct http_msg *msg = &txn->req;
1147 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001148 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001149 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001150
1151 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1152 now_ms, __FUNCTION__,
1153 s,
1154 req,
1155 req->rex, req->wex,
1156 req->flags,
1157 ci_data(req),
1158 req->analysers);
1159
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001160 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001161
1162 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1163 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1164 /* Output closed while we were sending data. We must abort and
1165 * wake the other side up.
1166 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001167 /* Don't abort yet if we had L7 retries activated and it
1168 * was a write error, we may recover.
1169 */
1170 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1171 (s->si[1].flags & SI_FL_L7_RETRY))
1172 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001173 msg->err_state = msg->msg_state;
1174 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001175 htx_end_request(s);
1176 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001177 return 1;
1178 }
1179
1180 /* Note that we don't have to send 100-continue back because we don't
1181 * need the data to complete our job, and it's up to the server to
1182 * decide whether to return 100, 417 or anything else in return of
1183 * an "Expect: 100-continue" header.
1184 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001185 if (msg->msg_state == HTTP_MSG_BODY)
1186 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001187
1188 /* Some post-connect processing might want us to refrain from starting to
1189 * forward data. Currently, the only reason for this is "balance url_param"
1190 * whichs need to parse/process the request after we've enabled forwarding.
1191 */
1192 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1193 if (!(s->res.flags & CF_READ_ATTACHED)) {
1194 channel_auto_connect(req);
1195 req->flags |= CF_WAKE_CONNECT;
1196 channel_dont_close(req); /* don't fail on early shutr */
1197 goto waiting;
1198 }
1199 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1200 }
1201
1202 /* in most states, we should abort in case of early close */
1203 channel_auto_close(req);
1204
1205 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001206 if (req->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001207 if (req->flags & CF_EOI)
1208 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01001209 }
1210 else {
1211 /* We can't process the buffer's contents yet */
1212 req->flags |= CF_WAKE_WRITE;
1213 goto missing_data_or_waiting;
1214 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001215 }
1216
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001217 if (msg->msg_state >= HTTP_MSG_ENDING)
1218 goto ending;
1219
1220 if (txn->meth == HTTP_METH_CONNECT) {
1221 msg->msg_state = HTTP_MSG_ENDING;
1222 goto ending;
1223 }
1224
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001225 /* Forward input data. We get it by removing all outgoing data not
1226 * forwarded yet from HTX data size. If there are some data filters, we
1227 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001228 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001229 if (HAS_REQ_DATA_FILTERS(s)) {
1230 ret = flt_http_payload(s, msg, htx->data);
1231 if (ret < 0)
1232 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001233 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001234 }
1235 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001236 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001237 if (msg->flags & HTTP_MSGF_XFER_LEN)
1238 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001239 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001240
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001241 if (htx->data != co_data(req))
1242 goto missing_data_or_waiting;
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001243
Christopher Faulet9768c262018-10-22 09:34:31 +02001244 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001245 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1246 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001247 */
1248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1249 goto missing_data_or_waiting;
1250
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001251 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02001252
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001253 ending:
1254 /* other states, ENDING...TUNNEL */
1255 if (msg->msg_state >= HTTP_MSG_DONE)
1256 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001257
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001258 if (HAS_REQ_DATA_FILTERS(s)) {
1259 ret = flt_http_end(s, msg);
1260 if (ret <= 0) {
1261 if (!ret)
1262 goto missing_data_or_waiting;
1263 goto return_bad_req;
1264 }
1265 }
1266
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001267 if (txn->meth == HTTP_METH_CONNECT)
1268 msg->msg_state = HTTP_MSG_TUNNEL;
1269 else {
1270 msg->msg_state = HTTP_MSG_DONE;
1271 req->to_forward = 0;
1272 }
1273
1274 done:
1275 /* we don't want to forward closes on DONE except in tunnel mode. */
1276 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1277 channel_dont_close(req);
1278
Christopher Fauletf2824e62018-10-01 12:12:37 +02001279 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001281 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1283 if (req->flags & CF_SHUTW) {
1284 /* request errors are most likely due to the
1285 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001286 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001287 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001288 goto return_bad_req;
1289 }
1290 return 1;
1291 }
1292
1293 /* If "option abortonclose" is set on the backend, we want to monitor
1294 * the client's connection and forward any shutdown notification to the
1295 * server, which will decide whether to close or to go on processing the
1296 * request. We only do that in tunnel mode, and not in other modes since
1297 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001298 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001299 channel_auto_read(req);
1300 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1301 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1302 s->si[1].flags |= SI_FL_NOLINGER;
1303 channel_auto_close(req);
1304 }
1305 else if (s->txn->meth == HTTP_METH_POST) {
1306 /* POST requests may require to read extra CRLF sent by broken
1307 * browsers and which could cause an RST to be sent upon close
1308 * on some systems (eg: Linux). */
1309 channel_auto_read(req);
1310 }
1311 return 0;
1312
1313 missing_data_or_waiting:
1314 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001315 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001316 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001317
1318 waiting:
1319 /* waiting for the last bits to leave the buffer */
1320 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001321 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001322
Christopher Faulet47365272018-10-31 17:40:50 +01001323 if (htx->flags & HTX_FL_PARSING_ERROR)
1324 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001325
Christopher Faulete0768eb2018-10-03 16:38:02 +02001326 /* When TE: chunked is used, we need to get there again to parse remaining
1327 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1328 * And when content-length is used, we never want to let the possible
1329 * shutdown be forwarded to the other side, as the state machine will
1330 * take care of it once the client responds. It's also important to
1331 * prevent TIME_WAITs from accumulating on the backend side, and for
1332 * HTTP/2 where the last frame comes with a shutdown.
1333 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001334 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001335 channel_dont_close(req);
1336
1337 /* We know that more data are expected, but we couldn't send more that
1338 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1339 * system knows it must not set a PUSH on this first part. Interactive
1340 * modes are already handled by the stream sock layer. We must not do
1341 * this in content-length mode because it could present the MSG_MORE
1342 * flag with the last block of forwarded data, which would cause an
1343 * additional delay to be observed by the receiver.
1344 */
1345 if (msg->flags & HTTP_MSGF_TE_CHNK)
1346 req->flags |= CF_EXPECT_MORE;
1347
1348 return 0;
1349
Christopher Faulet93e02d82019-03-08 14:18:50 +01001350 return_cli_abort:
1351 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1352 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1353 if (objt_server(s->target))
1354 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1355 if (!(s->flags & SF_ERR_MASK))
1356 s->flags |= SF_ERR_CLICL;
1357 status = 400;
1358 goto return_error;
1359
1360 return_srv_abort:
1361 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1362 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1363 if (objt_server(s->target))
1364 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1365 if (!(s->flags & SF_ERR_MASK))
1366 s->flags |= SF_ERR_SRVCL;
1367 status = 502;
1368 goto return_error;
1369
1370 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001371 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001373 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001375 s->flags |= SF_ERR_CLICL;
1376 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377
Christopher Faulet93e02d82019-03-08 14:18:50 +01001378 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001379 txn->req.err_state = txn->req.msg_state;
1380 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001381 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001382 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001383 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001384 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001385 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001386 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001387 }
1388 req->analysers &= AN_REQ_FLT_END;
1389 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 +01001390 if (!(s->flags & SF_FINST_MASK))
1391 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001392 return 0;
1393}
1394
Olivier Houcharda254a372019-04-05 15:30:12 +02001395/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1396/* Returns 0 if we can attempt to retry, -1 otherwise */
1397static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1398{
1399 struct channel *req, *res;
1400 int co_data;
1401
1402 si->conn_retries--;
1403 if (si->conn_retries < 0)
1404 return -1;
1405
Willy Tarreau223995e2019-05-04 10:38:31 +02001406 if (objt_server(s->target))
1407 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1408 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1409
Olivier Houcharda254a372019-04-05 15:30:12 +02001410 req = &s->req;
1411 res = &s->res;
1412 /* Remove any write error from the request, and read error from the response */
1413 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1414 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1415 res->analysers = 0;
1416 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard530249c2019-07-12 16:16:59 +02001417 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001418 si->exp = TICK_ETERNITY;
1419 res->rex = TICK_ETERNITY;
1420 res->to_forward = 0;
1421 res->analyse_exp = TICK_ETERNITY;
1422 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001423 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001424 si_release_endpoint(&s->si[1]);
1425 b_free(&req->buf);
1426 /* Swap the L7 buffer with the channel buffer */
1427 /* We know we stored the co_data as b_data, so get it there */
1428 co_data = b_data(&si->l7_buffer);
1429 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1430 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1431
1432 co_set_data(req, co_data);
1433 b_reset(&res->buf);
1434 co_set_data(res, 0);
1435 return 0;
1436}
1437
Christopher Faulete0768eb2018-10-03 16:38:02 +02001438/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1439 * processing can continue on next analysers, or zero if it either needs more
1440 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1441 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1442 * when it has nothing left to do, and may remove any analyser when it wants to
1443 * abort.
1444 */
1445int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1446{
Christopher Faulet9768c262018-10-22 09:34:31 +02001447 /*
1448 * We will analyze a complete HTTP response to check the its syntax.
1449 *
1450 * Once the start line and all headers are received, we may perform a
1451 * capture of the error (if any), and we will set a few fields. We also
1452 * logging and finally headers capture.
1453 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 struct session *sess = s->sess;
1455 struct http_txn *txn = s->txn;
1456 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001457 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001458 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001459 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001460 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 int n;
1462
1463 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1464 now_ms, __FUNCTION__,
1465 s,
1466 rep,
1467 rep->rex, rep->wex,
1468 rep->flags,
1469 ci_data(rep),
1470 rep->analysers);
1471
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001472 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473
Willy Tarreau4236f032019-03-05 10:43:32 +01001474 /* Parsing errors are caught here */
1475 if (htx->flags & HTX_FL_PARSING_ERROR)
1476 goto return_bad_res;
1477
Christopher Faulete0768eb2018-10-03 16:38:02 +02001478 /*
1479 * Now we quickly check if we have found a full valid response.
1480 * If not so, we check the FD and buffer states before leaving.
1481 * A full response is indicated by the fact that we have seen
1482 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1483 * responses are checked first.
1484 *
1485 * Depending on whether the client is still there or not, we
1486 * may send an error response back or not. Note that normally
1487 * we should only check for HTTP status there, and check I/O
1488 * errors somewhere else.
1489 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001490 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001491 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001492 /* 1: have we encountered a read error ? */
1493 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001494 struct connection *conn = NULL;
1495
Olivier Houchard865d8392019-05-03 22:46:27 +02001496 if (objt_cs(s->si[1].end))
1497 conn = objt_cs(s->si[1].end)->conn;
1498
1499 if (si_b->flags & SI_FL_L7_RETRY &&
1500 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001501 /* If we arrive here, then CF_READ_ERROR was
1502 * set by si_cs_recv() because we matched a
1503 * status, overwise it would have removed
1504 * the SI_FL_L7_RETRY flag, so it's ok not
1505 * to check s->be->retry_type.
1506 */
1507 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1508 return 0;
1509 }
1510
Olivier Houchard6db16992019-05-17 15:40:49 +02001511 if (txn->flags & TX_NOT_FIRST)
1512 goto abort_keep_alive;
1513
Olivier Houcharda798bf52019-03-08 18:52:00 +01001514 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001516 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001517 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 }
1519
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520 rep->analysers &= AN_RES_FLT_END;
1521 txn->status = 502;
1522
1523 /* Check to see if the server refused the early data.
1524 * If so, just send a 425
1525 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001526 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1527 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001528 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001529 do_l7_retry(s, si_b) == 0)
1530 return 0;
1531 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532 }
1533
1534 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001535 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536
1537 if (!(s->flags & SF_ERR_MASK))
1538 s->flags |= SF_ERR_SRVCL;
1539 if (!(s->flags & SF_FINST_MASK))
1540 s->flags |= SF_FINST_H;
1541 return 0;
1542 }
1543
Christopher Faulet9768c262018-10-22 09:34:31 +02001544 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001546 if ((si_b->flags & SI_FL_L7_RETRY) &&
1547 (s->be->retry_type & PR_RE_TIMEOUT)) {
1548 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1549 return 0;
1550 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001551 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001552 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001554 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 }
1556
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 rep->analysers &= AN_RES_FLT_END;
1558 txn->status = 504;
1559 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001560 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561
1562 if (!(s->flags & SF_ERR_MASK))
1563 s->flags |= SF_ERR_SRVTO;
1564 if (!(s->flags & SF_FINST_MASK))
1565 s->flags |= SF_FINST_H;
1566 return 0;
1567 }
1568
Christopher Faulet9768c262018-10-22 09:34:31 +02001569 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001570 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001571 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1572 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001574 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001575
1576 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001578 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579
1580 if (!(s->flags & SF_ERR_MASK))
1581 s->flags |= SF_ERR_CLICL;
1582 if (!(s->flags & SF_FINST_MASK))
1583 s->flags |= SF_FINST_H;
1584
1585 /* process_stream() will take care of the error */
1586 return 0;
1587 }
1588
Christopher Faulet9768c262018-10-22 09:34:31 +02001589 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001590 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001591 if ((si_b->flags & SI_FL_L7_RETRY) &&
1592 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1593 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1594 return 0;
1595 }
1596
Olivier Houchard6db16992019-05-17 15:40:49 +02001597 if (txn->flags & TX_NOT_FIRST)
1598 goto abort_keep_alive;
1599
Olivier Houcharda798bf52019-03-08 18:52:00 +01001600 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001601 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001602 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001603 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 }
1605
Christopher Faulete0768eb2018-10-03 16:38:02 +02001606 rep->analysers &= AN_RES_FLT_END;
1607 txn->status = 502;
1608 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001609 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610
1611 if (!(s->flags & SF_ERR_MASK))
1612 s->flags |= SF_ERR_SRVCL;
1613 if (!(s->flags & SF_FINST_MASK))
1614 s->flags |= SF_FINST_H;
1615 return 0;
1616 }
1617
Christopher Faulet9768c262018-10-22 09:34:31 +02001618 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001619 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001620 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621 goto abort_keep_alive;
1622
Olivier Houcharda798bf52019-03-08 18:52:00 +01001623 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625
1626 if (!(s->flags & SF_ERR_MASK))
1627 s->flags |= SF_ERR_CLICL;
1628 if (!(s->flags & SF_FINST_MASK))
1629 s->flags |= SF_FINST_H;
1630
1631 /* process_stream() will take care of the error */
1632 return 0;
1633 }
1634
1635 channel_dont_close(rep);
1636 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1637 return 0;
1638 }
1639
1640 /* More interesting part now : we know that we have a complete
1641 * response which at least looks like HTTP. We have an indicator
1642 * of each header's length, so we can parse them quickly.
1643 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001644 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001645 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001646 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647
Christopher Faulet9768c262018-10-22 09:34:31 +02001648 /* 0: we might have to print this header in debug mode */
1649 if (unlikely((global.mode & MODE_DEBUG) &&
1650 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1651 int32_t pos;
1652
Christopher Faulet03599112018-11-27 11:21:21 +01001653 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001654
Christopher Fauleta3f15502019-05-13 15:27:23 +02001655 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001656 struct htx_blk *blk = htx_get_blk(htx, pos);
1657 enum htx_blk_type type = htx_get_blk_type(blk);
1658
1659 if (type == HTX_BLK_EOH)
1660 break;
1661 if (type != HTX_BLK_HDR)
1662 continue;
1663
1664 htx_debug_hdr("srvhdr", s,
1665 htx_get_blk_name(htx, blk),
1666 htx_get_blk_value(htx, blk));
1667 }
1668 }
1669
Christopher Faulet03599112018-11-27 11:21:21 +01001670 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001671 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001672 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001673 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001674 if (sl->flags & HTX_SL_F_XFER_LEN) {
1675 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001676 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001677 if (sl->flags & HTX_SL_F_BODYLESS)
1678 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001679 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001680
1681 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001682 if (n < 1 || n > 5)
1683 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001684
Christopher Faulete0768eb2018-10-03 16:38:02 +02001685 /* when the client triggers a 4xx from the server, it's most often due
1686 * to a missing object or permission. These events should be tracked
1687 * because if they happen often, it may indicate a brute force or a
1688 * vulnerability scan.
1689 */
1690 if (n == 4)
1691 stream_inc_http_err_ctr(s);
1692
1693 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001694 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695
Christopher Faulete0768eb2018-10-03 16:38:02 +02001696 /* Adjust server's health based on status code. Note: status codes 501
1697 * and 505 are triggered on demand by client request, so we must not
1698 * count them as server failures.
1699 */
1700 if (objt_server(s->target)) {
1701 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001702 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001703 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001704 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705 }
1706
1707 /*
1708 * We may be facing a 100-continue response, or any other informational
1709 * 1xx response which is non-final, in which case this is not the right
1710 * response, and we're waiting for the next one. Let's allow this response
1711 * to go to the client and wait for the next one. There's an exception for
1712 * 101 which is used later in the code to switch protocols.
1713 */
1714 if (txn->status < 200 &&
1715 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001716 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001717 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001718 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001719 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720 txn->status = 0;
1721 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001722 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001723 }
1724
1725 /*
1726 * 2: check for cacheability.
1727 */
1728
1729 switch (txn->status) {
1730 case 200:
1731 case 203:
1732 case 204:
1733 case 206:
1734 case 300:
1735 case 301:
1736 case 404:
1737 case 405:
1738 case 410:
1739 case 414:
1740 case 501:
1741 break;
1742 default:
1743 /* RFC7231#6.1:
1744 * Responses with status codes that are defined as
1745 * cacheable by default (e.g., 200, 203, 204, 206,
1746 * 300, 301, 404, 405, 410, 414, and 501 in this
1747 * specification) can be reused by a cache with
1748 * heuristic expiration unless otherwise indicated
1749 * by the method definition or explicit cache
1750 * controls [RFC7234]; all other status codes are
1751 * not cacheable by default.
1752 */
1753 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1754 break;
1755 }
1756
1757 /*
1758 * 3: we may need to capture headers
1759 */
1760 s->logs.logwait &= ~LW_RESP;
1761 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001762 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001763
Christopher Faulet9768c262018-10-22 09:34:31 +02001764 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001765 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1766 txn->status == 101)) {
1767 /* Either we've established an explicit tunnel, or we're
1768 * switching the protocol. In both cases, we're very unlikely
1769 * to understand the next protocols. We have to switch to tunnel
1770 * mode, so that we transfer the request and responses then let
1771 * this protocol pass unmodified. When we later implement specific
1772 * parsers for such protocols, we'll want to check the Upgrade
1773 * header which contains information about that protocol for
1774 * responses with status 101 (eg: see RFC2817 about TLS).
1775 */
1776 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001777 }
1778
Christopher Faulet61608322018-11-23 16:23:45 +01001779 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1780 * 407 (Proxy-Authenticate) responses and set the connection to private
1781 */
1782 srv_conn = cs_conn(objt_cs(s->si[1].end));
1783 if (srv_conn) {
1784 struct ist hdr;
1785 struct http_hdr_ctx ctx;
1786
1787 if (txn->status == 401)
1788 hdr = ist("WWW-Authenticate");
1789 else if (txn->status == 407)
1790 hdr = ist("Proxy-Authenticate");
1791 else
1792 goto end;
1793
1794 ctx.blk = NULL;
1795 while (http_find_header(htx, hdr, &ctx, 0)) {
1796 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001797 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1798 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001799 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001800 }
Christopher Faulet61608322018-11-23 16:23:45 +01001801 }
1802 }
1803
1804 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 /* we want to have the response time before we start processing it */
1806 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1807
1808 /* end of job, return OK */
1809 rep->analysers &= ~an_bit;
1810 rep->analyse_exp = TICK_ETERNITY;
1811 channel_auto_close(rep);
1812 return 1;
1813
Christopher Faulet47365272018-10-31 17:40:50 +01001814 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001815 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001816 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001817 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001818 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001819 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001820 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001821 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001822 do_l7_retry(s, si_b) == 0)
1823 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001824 txn->status = 502;
1825 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001826 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001827 rep->analysers &= AN_RES_FLT_END;
1828
1829 if (!(s->flags & SF_ERR_MASK))
1830 s->flags |= SF_ERR_PRXCOND;
1831 if (!(s->flags & SF_FINST_MASK))
1832 s->flags |= SF_FINST_H;
1833 return 0;
1834
Christopher Faulete0768eb2018-10-03 16:38:02 +02001835 abort_keep_alive:
1836 /* A keep-alive request to the server failed on a network error.
1837 * The client is required to retry. We need to close without returning
1838 * any other information so that the client retries.
1839 */
1840 txn->status = 0;
1841 rep->analysers &= AN_RES_FLT_END;
1842 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001843 s->logs.logwait = 0;
1844 s->logs.level = 0;
1845 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001846 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 return 0;
1848}
1849
1850/* This function performs all the processing enabled for the current response.
1851 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1852 * and updates s->res.analysers. It might make sense to explode it into several
1853 * other functions. It works like process_request (see indications above).
1854 */
1855int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1856{
1857 struct session *sess = s->sess;
1858 struct http_txn *txn = s->txn;
1859 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001860 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861 struct proxy *cur_proxy;
1862 struct cond_wordlist *wl;
1863 enum rule_result ret = HTTP_RULE_RES_CONT;
1864
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001865 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1866 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001867
Christopher Faulete0768eb2018-10-03 16:38:02 +02001868 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1869 now_ms, __FUNCTION__,
1870 s,
1871 rep,
1872 rep->rex, rep->wex,
1873 rep->flags,
1874 ci_data(rep),
1875 rep->analysers);
1876
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001877 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001878
1879 /* The stats applet needs to adjust the Connection header but we don't
1880 * apply any filter there.
1881 */
1882 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1883 rep->analysers &= ~an_bit;
1884 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001885 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001886 }
1887
1888 /*
1889 * We will have to evaluate the filters.
1890 * As opposed to version 1.2, now they will be evaluated in the
1891 * filters order and not in the header order. This means that
1892 * each filter has to be validated among all headers.
1893 *
1894 * Filters are tried with ->be first, then with ->fe if it is
1895 * different from ->be.
1896 *
1897 * Maybe we are in resume condiion. In this case I choose the
1898 * "struct proxy" which contains the rule list matching the resume
1899 * pointer. If none of theses "struct proxy" match, I initialise
1900 * the process with the first one.
1901 *
1902 * In fact, I check only correspondance betwwen the current list
1903 * pointer and the ->fe rule list. If it doesn't match, I initialize
1904 * the loop with the ->be.
1905 */
1906 if (s->current_rule_list == &sess->fe->http_res_rules)
1907 cur_proxy = sess->fe;
1908 else
1909 cur_proxy = s->be;
1910 while (1) {
1911 struct proxy *rule_set = cur_proxy;
1912
1913 /* evaluate http-response rules */
1914 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001915 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001916
1917 if (ret == HTTP_RULE_RES_BADREQ)
1918 goto return_srv_prx_502;
1919
1920 if (ret == HTTP_RULE_RES_DONE) {
1921 rep->analysers &= ~an_bit;
1922 rep->analyse_exp = TICK_ETERNITY;
1923 return 1;
1924 }
1925 }
1926
1927 /* we need to be called again. */
1928 if (ret == HTTP_RULE_RES_YIELD) {
1929 channel_dont_close(rep);
1930 return 0;
1931 }
1932
1933 /* try headers filters */
1934 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001935 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1936 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001937 }
1938
1939 /* has the response been denied ? */
1940 if (txn->flags & TX_SVDENY) {
1941 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001942 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001943
Olivier Houcharda798bf52019-03-08 18:52:00 +01001944 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1945 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001947 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001948 goto return_srv_prx_502;
1949 }
1950
1951 /* add response headers from the rule sets in the same order */
1952 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001953 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001954 if (txn->status < 200 && txn->status != 101)
1955 break;
1956 if (wl->cond) {
1957 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1958 ret = acl_pass(ret);
1959 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1960 ret = !ret;
1961 if (!ret)
1962 continue;
1963 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001964
1965 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1966 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967 goto return_bad_resp;
1968 }
1969
1970 /* check whether we're already working on the frontend */
1971 if (cur_proxy == sess->fe)
1972 break;
1973 cur_proxy = sess->fe;
1974 }
1975
1976 /* After this point, this anayzer can't return yield, so we can
1977 * remove the bit corresponding to this analyzer from the list.
1978 *
1979 * Note that the intermediate returns and goto found previously
1980 * reset the analyzers.
1981 */
1982 rep->analysers &= ~an_bit;
1983 rep->analyse_exp = TICK_ETERNITY;
1984
1985 /* OK that's all we can do for 1xx responses */
1986 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001987 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001988
1989 /*
1990 * Now check for a server cookie.
1991 */
1992 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001993 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001994
1995 /*
1996 * Check for cache-control or pragma headers if required.
1997 */
1998 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1999 check_response_for_cacheability(s, rep);
2000
2001 /*
2002 * Add server cookie in the response if needed
2003 */
2004 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2005 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2006 (!(s->flags & SF_DIRECT) ||
2007 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2008 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2009 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2010 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2011 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2012 !(s->flags & SF_IGNORE_PRST)) {
2013 /* the server is known, it's not the one the client requested, or the
2014 * cookie's last seen date needs to be refreshed. We have to
2015 * insert a set-cookie here, except if we want to insert only on POST
2016 * requests and this one isn't. Note that servers which don't have cookies
2017 * (eg: some backup servers) will return a full cookie removal request.
2018 */
2019 if (!objt_server(s->target)->cookie) {
2020 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002021 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022 s->be->cookie_name);
2023 }
2024 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002025 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002026
2027 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2028 /* emit last_date, which is mandatory */
2029 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2030 s30tob64((date.tv_sec+3) >> 2,
2031 trash.area + trash.data);
2032 trash.data += 5;
2033
2034 if (s->be->cookie_maxlife) {
2035 /* emit first_date, which is either the original one or
2036 * the current date.
2037 */
2038 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2039 s30tob64(txn->cookie_first_date ?
2040 txn->cookie_first_date >> 2 :
2041 (date.tv_sec+3) >> 2,
2042 trash.area + trash.data);
2043 trash.data += 5;
2044 }
2045 }
2046 chunk_appendf(&trash, "; path=/");
2047 }
2048
2049 if (s->be->cookie_domain)
2050 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2051
2052 if (s->be->ck_opts & PR_CK_HTTPONLY)
2053 chunk_appendf(&trash, "; HttpOnly");
2054
2055 if (s->be->ck_opts & PR_CK_SECURE)
2056 chunk_appendf(&trash, "; Secure");
2057
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002058 if (s->be->cookie_attrs)
2059 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2060
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002061 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002062 goto return_bad_resp;
2063
2064 txn->flags &= ~TX_SCK_MASK;
2065 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2066 /* the server did not change, only the date was updated */
2067 txn->flags |= TX_SCK_UPDATED;
2068 else
2069 txn->flags |= TX_SCK_INSERTED;
2070
2071 /* Here, we will tell an eventual cache on the client side that we don't
2072 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2073 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2074 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2075 */
2076 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2077
2078 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2079
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002080 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002081 goto return_bad_resp;
2082 }
2083 }
2084
2085 /*
2086 * Check if result will be cacheable with a cookie.
2087 * We'll block the response if security checks have caught
2088 * nasty things such as a cacheable cookie.
2089 */
2090 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2091 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2092 (s->be->options & PR_O_CHK_CACHE)) {
2093 /* we're in presence of a cacheable response containing
2094 * a set-cookie header. We'll block it as requested by
2095 * the 'checkcache' option, and send an alert.
2096 */
2097 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002098 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002099
Olivier Houcharda798bf52019-03-08 18:52:00 +01002100 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2101 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002102 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002103 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002104
2105 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2106 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2107 send_log(s->be, LOG_ALERT,
2108 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2109 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2110 goto return_srv_prx_502;
2111 }
2112
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002113 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002114 /* Always enter in the body analyzer */
2115 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2116 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2117
2118 /* if the user wants to log as soon as possible, without counting
2119 * bytes from the server, then this is the right moment. We have
2120 * to temporarily assign bytes_out to log what we currently have.
2121 */
2122 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2123 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002124 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002125 s->do_log(s);
2126 s->logs.bytes_out = 0;
2127 }
2128 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002129
2130 return_bad_resp:
2131 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002132 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002133 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002134 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002135 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002136
2137 return_srv_prx_502:
2138 rep->analysers &= AN_RES_FLT_END;
2139 txn->status = 502;
2140 s->logs.t_data = -1; /* was not a valid response */
2141 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002142 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002143 if (!(s->flags & SF_ERR_MASK))
2144 s->flags |= SF_ERR_PRXCOND;
2145 if (!(s->flags & SF_FINST_MASK))
2146 s->flags |= SF_FINST_H;
2147 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002148}
2149
2150/* This function is an analyser which forwards response body (including chunk
2151 * sizes if any). It is called as soon as we must forward, even if we forward
2152 * zero byte. The only situation where it must not be called is when we're in
2153 * tunnel mode and we want to forward till the close. It's used both to forward
2154 * remaining data and to resync after end of body. It expects the msg_state to
2155 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2156 * read more data, or 1 once we can go on with next request or end the stream.
2157 *
2158 * It is capable of compressing response data both in content-length mode and
2159 * in chunked mode. The state machines follows different flows depending on
2160 * whether content-length and chunked modes are used, since there are no
2161 * trailers in content-length :
2162 *
2163 * chk-mode cl-mode
2164 * ,----- BODY -----.
2165 * / \
2166 * V size > 0 V chk-mode
2167 * .--> SIZE -------------> DATA -------------> CRLF
2168 * | | size == 0 | last byte |
2169 * | v final crlf v inspected |
2170 * | TRAILERS -----------> DONE |
2171 * | |
2172 * `----------------------------------------------'
2173 *
2174 * Compression only happens in the DATA state, and must be flushed in final
2175 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2176 * is performed at once on final states for all bytes parsed, or when leaving
2177 * on missing data.
2178 */
2179int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2180{
2181 struct session *sess = s->sess;
2182 struct http_txn *txn = s->txn;
2183 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002184 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002185 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002186
2187 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2188 now_ms, __FUNCTION__,
2189 s,
2190 res,
2191 res->rex, res->wex,
2192 res->flags,
2193 ci_data(res),
2194 res->analysers);
2195
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002196 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197
2198 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002199 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 /* Output closed while we were sending data. We must abort and
2201 * wake the other side up.
2202 */
2203 msg->err_state = msg->msg_state;
2204 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002205 htx_end_response(s);
2206 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 return 1;
2208 }
2209
Christopher Faulet9768c262018-10-22 09:34:31 +02002210 if (msg->msg_state == HTTP_MSG_BODY)
2211 msg->msg_state = HTTP_MSG_DATA;
2212
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 /* in most states, we should abort in case of early close */
2214 channel_auto_close(res);
2215
Christopher Faulete0768eb2018-10-03 16:38:02 +02002216 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002217 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002218 if (res->flags & CF_EOI)
2219 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002220 }
2221 else {
2222 /* We can't process the buffer's contents yet */
2223 res->flags |= CF_WAKE_WRITE;
2224 goto missing_data_or_waiting;
2225 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 }
2227
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002228 if (msg->msg_state >= HTTP_MSG_ENDING)
2229 goto ending;
2230
2231 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2232 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2233 msg->msg_state = HTTP_MSG_ENDING;
2234 goto ending;
2235 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002236
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002237 /* Forward input data. We get it by removing all outgoing data not
2238 * forwarded yet from HTX data size. If there are some data filters, we
2239 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002240 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002241 if (HAS_RSP_DATA_FILTERS(s)) {
2242 ret = flt_http_payload(s, msg, htx->data);
2243 if (ret < 0)
2244 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002245 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002246 }
2247 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002248 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002249 if (msg->flags & HTTP_MSGF_XFER_LEN)
2250 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002251 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002252
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002253 if (htx->data != co_data(res))
2254 goto missing_data_or_waiting;
2255
2256 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2257 msg->msg_state = HTTP_MSG_ENDING;
2258 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 }
2260
Christopher Faulet9768c262018-10-22 09:34:31 +02002261 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002262 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2263 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002264 */
2265 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2266 goto missing_data_or_waiting;
2267
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002268 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002269
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002270 ending:
2271 /* other states, ENDING...TUNNEL */
2272 if (msg->msg_state >= HTTP_MSG_DONE)
2273 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002274
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002275 if (HAS_RSP_DATA_FILTERS(s)) {
2276 ret = flt_http_end(s, msg);
2277 if (ret <= 0) {
2278 if (!ret)
2279 goto missing_data_or_waiting;
2280 goto return_bad_res;
2281 }
2282 }
2283
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002284 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2285 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2286 msg->msg_state = HTTP_MSG_TUNNEL;
2287 goto ending;
2288 }
2289 else {
2290 msg->msg_state = HTTP_MSG_DONE;
2291 res->to_forward = 0;
2292 }
2293
2294 done:
2295
2296 channel_dont_close(res);
2297
Christopher Fauletf2824e62018-10-01 12:12:37 +02002298 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002299 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002300 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2302 if (res->flags & CF_SHUTW) {
2303 /* response errors are most likely due to the
2304 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002305 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002306 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 goto return_bad_res;
2308 }
2309 return 1;
2310 }
2311 return 0;
2312
2313 missing_data_or_waiting:
2314 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002315 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002316
Christopher Faulet47365272018-10-31 17:40:50 +01002317 if (htx->flags & HTX_FL_PARSING_ERROR)
2318 goto return_bad_res;
2319
Christopher Faulete0768eb2018-10-03 16:38:02 +02002320 /* stop waiting for data if the input is closed before the end. If the
2321 * client side was already closed, it means that the client has aborted,
2322 * so we don't want to count this as a server abort. Otherwise it's a
2323 * server abort.
2324 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002325 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002327 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 if (htx_is_empty(htx))
2330 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331 }
2332
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333 /* When TE: chunked is used, we need to get there again to parse
2334 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002335 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2336 * are filters registered on the stream, we don't want to forward a
2337 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002339 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002340 channel_dont_close(res);
2341
2342 /* We know that more data are expected, but we couldn't send more that
2343 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2344 * system knows it must not set a PUSH on this first part. Interactive
2345 * modes are already handled by the stream sock layer. We must not do
2346 * this in content-length mode because it could present the MSG_MORE
2347 * flag with the last block of forwarded data, which would cause an
2348 * additional delay to be observed by the receiver.
2349 */
2350 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2351 res->flags |= CF_EXPECT_MORE;
2352
2353 /* the stream handler will take care of timeouts and errors */
2354 return 0;
2355
Christopher Faulet93e02d82019-03-08 14:18:50 +01002356 return_srv_abort:
2357 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2358 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002359 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002360 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2361 if (!(s->flags & SF_ERR_MASK))
2362 s->flags |= SF_ERR_SRVCL;
2363 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002364
Christopher Faulet93e02d82019-03-08 14:18:50 +01002365 return_cli_abort:
2366 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2367 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002368 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002369 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2370 if (!(s->flags & SF_ERR_MASK))
2371 s->flags |= SF_ERR_CLICL;
2372 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002373
Christopher Faulet93e02d82019-03-08 14:18:50 +01002374 return_bad_res:
2375 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2376 if (objt_server(s->target)) {
2377 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2378 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2379 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002380 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002381 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002382
Christopher Faulet93e02d82019-03-08 14:18:50 +01002383 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002384 txn->rsp.err_state = txn->rsp.msg_state;
2385 txn->rsp.msg_state = HTTP_MSG_ERROR;
2386 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002387 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002388 res->analysers &= AN_RES_FLT_END;
2389 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 +02002390 if (!(s->flags & SF_FINST_MASK))
2391 s->flags |= SF_FINST_D;
2392 return 0;
2393}
2394
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002396 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 * as too large a request to build a valid response.
2398 */
2399int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2400{
Christopher Faulet99daf282018-11-28 22:58:13 +01002401 struct channel *req = &s->req;
2402 struct channel *res = &s->res;
2403 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002404 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002406 struct ist status, reason, location;
2407 unsigned int flags;
2408 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002409 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410
2411 chunk = alloc_trash_chunk();
2412 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002413 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414
Christopher Faulet99daf282018-11-28 22:58:13 +01002415 /*
2416 * Create the location
2417 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002418 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002419 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002420 case REDIRECT_TYPE_SCHEME: {
2421 struct http_hdr_ctx ctx;
2422 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 host = ist("");
2425 ctx.blk = NULL;
2426 if (http_find_header(htx, ist("Host"), &ctx, 0))
2427 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428
Christopher Faulet297fbb42019-05-13 14:41:27 +02002429 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002430 path = http_get_path(htx_sl_req_uri(sl));
2431 /* build message using path */
2432 if (path.ptr) {
2433 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2434 int qs = 0;
2435 while (qs < path.len) {
2436 if (*(path.ptr + qs) == '?') {
2437 path.len = qs;
2438 break;
2439 }
2440 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442 }
2443 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002444 else
2445 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 if (rule->rdr_str) { /* this is an old "redirect" rule */
2448 /* add scheme */
2449 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2450 goto fail;
2451 }
2452 else {
2453 /* add scheme with executing log format */
2454 chunk->data += build_logline(s, chunk->area + chunk->data,
2455 chunk->size - chunk->data,
2456 &rule->rdr_fmt);
2457 }
2458 /* add "://" + host + path */
2459 if (!chunk_memcat(chunk, "://", 3) ||
2460 !chunk_memcat(chunk, host.ptr, host.len) ||
2461 !chunk_memcat(chunk, path.ptr, path.len))
2462 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463
Christopher Faulet99daf282018-11-28 22:58:13 +01002464 /* append a slash at the end of the location if needed and missing */
2465 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2466 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2467 if (chunk->data + 1 >= chunk->size)
2468 goto fail;
2469 chunk->area[chunk->data++] = '/';
2470 }
2471 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 case REDIRECT_TYPE_PREFIX: {
2475 struct ist path;
2476
Christopher Faulet297fbb42019-05-13 14:41:27 +02002477 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002478 path = http_get_path(htx_sl_req_uri(sl));
2479 /* build message using path */
2480 if (path.ptr) {
2481 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2482 int qs = 0;
2483 while (qs < path.len) {
2484 if (*(path.ptr + qs) == '?') {
2485 path.len = qs;
2486 break;
2487 }
2488 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002490 }
2491 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002492 else
2493 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002494
Christopher Faulet99daf282018-11-28 22:58:13 +01002495 if (rule->rdr_str) { /* this is an old "redirect" rule */
2496 /* add prefix. Note that if prefix == "/", we don't want to
2497 * add anything, otherwise it makes it hard for the user to
2498 * configure a self-redirection.
2499 */
2500 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2501 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2502 goto fail;
2503 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002504 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 else {
2506 /* add prefix with executing log format */
2507 chunk->data += build_logline(s, chunk->area + chunk->data,
2508 chunk->size - chunk->data,
2509 &rule->rdr_fmt);
2510 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002511
Christopher Faulet99daf282018-11-28 22:58:13 +01002512 /* add path */
2513 if (!chunk_memcat(chunk, path.ptr, path.len))
2514 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002515
Christopher Faulet99daf282018-11-28 22:58:13 +01002516 /* append a slash at the end of the location if needed and missing */
2517 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2518 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2519 if (chunk->data + 1 >= chunk->size)
2520 goto fail;
2521 chunk->area[chunk->data++] = '/';
2522 }
2523 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002524 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002525 case REDIRECT_TYPE_LOCATION:
2526 default:
2527 if (rule->rdr_str) { /* this is an old "redirect" rule */
2528 /* add location */
2529 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2530 goto fail;
2531 }
2532 else {
2533 /* add location with executing log format */
2534 chunk->data += build_logline(s, chunk->area + chunk->data,
2535 chunk->size - chunk->data,
2536 &rule->rdr_fmt);
2537 }
2538 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002540 location = ist2(chunk->area, chunk->data);
2541
2542 /*
2543 * Create the 30x response
2544 */
2545 switch (rule->code) {
2546 case 308:
2547 status = ist("308");
2548 reason = ist("Permanent Redirect");
2549 break;
2550 case 307:
2551 status = ist("307");
2552 reason = ist("Temporary Redirect");
2553 break;
2554 case 303:
2555 status = ist("303");
2556 reason = ist("See Other");
2557 break;
2558 case 301:
2559 status = ist("301");
2560 reason = ist("Moved Permanently");
2561 break;
2562 case 302:
2563 default:
2564 status = ist("302");
2565 reason = ist("Found");
2566 break;
2567 }
2568
Christopher Faulet08e66462019-05-23 16:44:59 +02002569 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2570 close = 1;
2571
Christopher Faulet99daf282018-11-28 22:58:13 +01002572 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002573 /* Trim any possible response */
2574 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002575 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2576 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2577 if (!sl)
2578 goto fail;
2579 sl->info.res.status = rule->code;
2580 s->txn->status = rule->code;
2581
Christopher Faulet08e66462019-05-23 16:44:59 +02002582 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2583 goto fail;
2584
2585 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002586 !htx_add_header(htx, ist("Location"), location))
2587 goto fail;
2588
2589 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2590 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2591 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002592 }
2593
2594 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002595 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2596 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002597 }
2598
Christopher Faulet99daf282018-11-28 22:58:13 +01002599 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2600 goto fail;
2601
Kevin Zhu0fd70882020-01-07 09:42:55 +01002602 htx_to_buf(htx, &res->buf);
2603
Christopher Fauletf2824e62018-10-01 12:12:37 +02002604 /* let's log the request time */
2605 s->logs.tv_request = now;
2606
Christopher Faulet99daf282018-11-28 22:58:13 +01002607 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002608 c_adv(res, data);
2609 res->total += data;
2610
2611 channel_auto_read(req);
2612 channel_abort(req);
2613 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002614 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002615
2616 res->wex = tick_add_ifset(now_ms, res->wto);
2617 channel_auto_read(res);
2618 channel_auto_close(res);
2619 channel_shutr_now(res);
2620
2621 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002622
2623 if (!(s->flags & SF_ERR_MASK))
2624 s->flags |= SF_ERR_LOCAL;
2625 if (!(s->flags & SF_FINST_MASK))
2626 s->flags |= SF_FINST_R;
2627
Christopher Faulet99daf282018-11-28 22:58:13 +01002628 free_trash_chunk(chunk);
2629 return 1;
2630
2631 fail:
2632 /* If an error occurred, remove the incomplete HTTP response from the
2633 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002634 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002635 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002636 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002637}
2638
Christopher Faulet72333522018-10-24 11:25:02 +02002639int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2640 struct ist name, const char *str, struct my_regex *re, int action)
2641{
2642 struct http_hdr_ctx ctx;
2643 struct buffer *output = get_trash_chunk();
2644
2645 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2646 ctx.blk = NULL;
2647 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2648 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2649 continue;
2650
2651 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2652 if (output->data == -1)
2653 return -1;
2654 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2655 return -1;
2656 }
2657 return 0;
2658}
2659
2660static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2661 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2662{
2663 struct buffer *replace;
2664 int ret = -1;
2665
2666 replace = alloc_trash_chunk();
2667 if (!replace)
2668 goto leave;
2669
2670 replace->data = build_logline(s, replace->area, replace->size, fmt);
2671 if (replace->data >= replace->size - 1)
2672 goto leave;
2673
2674 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2675
2676 leave:
2677 free_trash_chunk(replace);
2678 return ret;
2679}
2680
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681
2682/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2683 * on success and -1 on error. The response channel is updated accordingly.
2684 */
2685static int htx_reply_103_early_hints(struct channel *res)
2686{
2687 struct htx *htx = htx_from_buf(&res->buf);
2688 size_t data;
2689
Christopher Faulet9869f932019-06-26 14:23:54 +02002690 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002691 /* If an error occurred during an Early-hint rule,
2692 * remove the incomplete HTTP 103 response from the
2693 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002694 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 return -1;
2696 }
2697
2698 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699 c_adv(res, data);
2700 res->total += data;
2701 return 0;
2702}
2703
Christopher Faulet6eb92892018-11-15 16:39:29 +01002704/*
2705 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2706 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002707 * If <early_hints> is 0, it is starts a new response by adding the start
2708 * line. If an error occurred -1 is returned. On success 0 is returned. The
2709 * channel is not updated here. It must be done calling the function
2710 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002711 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002712static 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 +01002713{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002714 struct channel *res = &s->res;
2715 struct htx *htx = htx_from_buf(&res->buf);
2716 struct buffer *value = alloc_trash_chunk();
2717
Christopher Faulet6eb92892018-11-15 16:39:29 +01002718 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002719 struct htx_sl *sl;
2720 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2721 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2722
2723 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2724 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2725 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002726 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002727 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002728 }
2729
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002730 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2731 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002732 goto fail;
2733
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002734 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002735 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002736
2737 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002738 /* If an error occurred during an Early-hint rule, remove the incomplete
2739 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002740 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002741 free_trash_chunk(value);
2742 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002743}
2744
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002745/* This function executes one of the set-{method,path,query,uri} actions. It
2746 * takes the string from the variable 'replace' with length 'len', then modifies
2747 * the relevant part of the request line accordingly. Then it updates various
2748 * pointers to the next elements which were moved, and the total buffer length.
2749 * It finds the action to be performed in p[2], previously filled by function
2750 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2751 * error, though this can be revisited when this code is finally exploited.
2752 *
2753 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2754 * query string and 3 to replace uri.
2755 *
2756 * In query string case, the mark question '?' must be set at the start of the
2757 * string by the caller, event if the replacement query string is empty.
2758 */
2759int htx_req_replace_stline(int action, const char *replace, int len,
2760 struct proxy *px, struct stream *s)
2761{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002762 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002763
2764 switch (action) {
2765 case 0: // method
2766 if (!http_replace_req_meth(htx, ist2(replace, len)))
2767 return -1;
2768 break;
2769
2770 case 1: // path
2771 if (!http_replace_req_path(htx, ist2(replace, len)))
2772 return -1;
2773 break;
2774
2775 case 2: // query
2776 if (!http_replace_req_query(htx, ist2(replace, len)))
2777 return -1;
2778 break;
2779
2780 case 3: // uri
2781 if (!http_replace_req_uri(htx, ist2(replace, len)))
2782 return -1;
2783 break;
2784
2785 default:
2786 return -1;
2787 }
2788 return 0;
2789}
2790
2791/* This function replace the HTTP status code and the associated message. The
2792 * variable <status> contains the new status code. This function never fails.
2793 */
2794void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2795{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002796 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002797 char *res;
2798
2799 chunk_reset(&trash);
2800 res = ultoa_o(status, trash.area, trash.size);
2801 trash.data = res - trash.area;
2802
2803 /* Do we have a custom reason format string? */
2804 if (reason == NULL)
2805 reason = http_get_reason(status);
2806
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002807 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002808 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2809}
2810
Christopher Faulet3e964192018-10-24 11:39:23 +02002811/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2812 * transaction <txn>. Returns the verdict of the first rule that prevents
2813 * further processing of the request (auth, deny, ...), and defaults to
2814 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2815 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2816 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2817 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2818 * status.
2819 */
2820static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2821 struct stream *s, int *deny_status)
2822{
2823 struct session *sess = strm_sess(s);
2824 struct http_txn *txn = s->txn;
2825 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002826 struct act_rule *rule;
2827 struct http_hdr_ctx ctx;
2828 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002829 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2830 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002831 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002832
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002833 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002834
2835 /* If "the current_rule_list" match the executed rule list, we are in
2836 * resume condition. If a resume is needed it is always in the action
2837 * and never in the ACL or converters. In this case, we initialise the
2838 * current rule, and go to the action execution point.
2839 */
2840 if (s->current_rule) {
2841 rule = s->current_rule;
2842 s->current_rule = NULL;
2843 if (s->current_rule_list == rules)
2844 goto resume_execution;
2845 }
2846 s->current_rule_list = rules;
2847
2848 list_for_each_entry(rule, rules, list) {
2849 /* check optional condition */
2850 if (rule->cond) {
2851 int ret;
2852
2853 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2854 ret = acl_pass(ret);
2855
2856 if (rule->cond->pol == ACL_COND_UNLESS)
2857 ret = !ret;
2858
2859 if (!ret) /* condition not matched */
2860 continue;
2861 }
2862
2863 act_flags |= ACT_FLAG_FIRST;
2864 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002865 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2866 early_hints = 0;
2867 if (htx_reply_103_early_hints(&s->res) == -1) {
2868 rule_ret = HTTP_RULE_RES_BADREQ;
2869 goto end;
2870 }
2871 }
2872
Christopher Faulet3e964192018-10-24 11:39:23 +02002873 switch (rule->action) {
2874 case ACT_ACTION_ALLOW:
2875 rule_ret = HTTP_RULE_RES_STOP;
2876 goto end;
2877
2878 case ACT_ACTION_DENY:
2879 if (deny_status)
2880 *deny_status = rule->deny_status;
2881 rule_ret = HTTP_RULE_RES_DENY;
2882 goto end;
2883
2884 case ACT_HTTP_REQ_TARPIT:
2885 txn->flags |= TX_CLTARPIT;
2886 if (deny_status)
2887 *deny_status = rule->deny_status;
2888 rule_ret = HTTP_RULE_RES_DENY;
2889 goto end;
2890
2891 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 /* Auth might be performed on regular http-req rules as well as on stats */
2893 auth_realm = rule->arg.auth.realm;
2894 if (!auth_realm) {
2895 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2896 auth_realm = STATS_DEFAULT_REALM;
2897 else
2898 auth_realm = px->id;
2899 }
2900 /* send 401/407 depending on whether we use a proxy or not. We still
2901 * count one error, because normal browsing won't significantly
2902 * increase the counter but brute force attempts will.
2903 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002904 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002905 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2906 rule_ret = HTTP_RULE_RES_BADREQ;
2907 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002908 goto end;
2909
2910 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002911 rule_ret = HTTP_RULE_RES_DONE;
2912 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2913 rule_ret = HTTP_RULE_RES_BADREQ;
2914 goto end;
2915
2916 case ACT_HTTP_SET_NICE:
2917 s->task->nice = rule->arg.nice;
2918 break;
2919
2920 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002921 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002922 break;
2923
2924 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002925 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002926 break;
2927
2928 case ACT_HTTP_SET_LOGL:
2929 s->logs.level = rule->arg.loglevel;
2930 break;
2931
2932 case ACT_HTTP_REPLACE_HDR:
2933 case ACT_HTTP_REPLACE_VAL:
2934 if (htx_transform_header(s, &s->req, htx,
2935 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2936 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002937 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002938 rule_ret = HTTP_RULE_RES_BADREQ;
2939 goto end;
2940 }
2941 break;
2942
2943 case ACT_HTTP_DEL_HDR:
2944 /* remove all occurrences of the header */
2945 ctx.blk = NULL;
2946 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2947 http_remove_header(htx, &ctx);
2948 break;
2949
2950 case ACT_HTTP_SET_HDR:
2951 case ACT_HTTP_ADD_HDR: {
2952 /* The scope of the trash buffer must be limited to this function. The
2953 * build_logline() function can execute a lot of other function which
2954 * can use the trash buffer. So for limiting the scope of this global
2955 * buffer, we build first the header value using build_logline, and
2956 * after we store the header name.
2957 */
2958 struct buffer *replace;
2959 struct ist n, v;
2960
2961 replace = alloc_trash_chunk();
2962 if (!replace) {
2963 rule_ret = HTTP_RULE_RES_BADREQ;
2964 goto end;
2965 }
2966
2967 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2968 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2969 v = ist2(replace->area, replace->data);
2970
2971 if (rule->action == ACT_HTTP_SET_HDR) {
2972 /* remove all occurrences of the header */
2973 ctx.blk = NULL;
2974 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2975 http_remove_header(htx, &ctx);
2976 }
2977
2978 if (!http_add_header(htx, n, v)) {
2979 static unsigned char rate_limit = 0;
2980
2981 if ((rate_limit++ & 255) == 0) {
2982 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);
2983 }
2984
Olivier Houcharda798bf52019-03-08 18:52:00 +01002985 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002986 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002987 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002988 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002989 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002990 }
2991 free_trash_chunk(replace);
2992 break;
2993 }
2994
2995 case ACT_HTTP_DEL_ACL:
2996 case ACT_HTTP_DEL_MAP: {
2997 struct pat_ref *ref;
2998 struct buffer *key;
2999
3000 /* collect reference */
3001 ref = pat_ref_lookup(rule->arg.map.ref);
3002 if (!ref)
3003 continue;
3004
3005 /* allocate key */
3006 key = alloc_trash_chunk();
3007 if (!key) {
3008 rule_ret = HTTP_RULE_RES_BADREQ;
3009 goto end;
3010 }
3011
3012 /* collect key */
3013 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3014 key->area[key->data] = '\0';
3015
3016 /* perform update */
3017 /* returned code: 1=ok, 0=ko */
3018 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3019 pat_ref_delete(ref, key->area);
3020 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3021
3022 free_trash_chunk(key);
3023 break;
3024 }
3025
3026 case ACT_HTTP_ADD_ACL: {
3027 struct pat_ref *ref;
3028 struct buffer *key;
3029
3030 /* collect reference */
3031 ref = pat_ref_lookup(rule->arg.map.ref);
3032 if (!ref)
3033 continue;
3034
3035 /* allocate key */
3036 key = alloc_trash_chunk();
3037 if (!key) {
3038 rule_ret = HTTP_RULE_RES_BADREQ;
3039 goto end;
3040 }
3041
3042 /* collect key */
3043 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3044 key->area[key->data] = '\0';
3045
3046 /* perform update */
3047 /* add entry only if it does not already exist */
3048 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3049 if (pat_ref_find_elt(ref, key->area) == NULL)
3050 pat_ref_add(ref, key->area, NULL, NULL);
3051 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3052
3053 free_trash_chunk(key);
3054 break;
3055 }
3056
3057 case ACT_HTTP_SET_MAP: {
3058 struct pat_ref *ref;
3059 struct buffer *key, *value;
3060
3061 /* collect reference */
3062 ref = pat_ref_lookup(rule->arg.map.ref);
3063 if (!ref)
3064 continue;
3065
3066 /* allocate key */
3067 key = alloc_trash_chunk();
3068 if (!key) {
3069 rule_ret = HTTP_RULE_RES_BADREQ;
3070 goto end;
3071 }
3072
3073 /* allocate value */
3074 value = alloc_trash_chunk();
3075 if (!value) {
3076 free_trash_chunk(key);
3077 rule_ret = HTTP_RULE_RES_BADREQ;
3078 goto end;
3079 }
3080
3081 /* collect key */
3082 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3083 key->area[key->data] = '\0';
3084
3085 /* collect value */
3086 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3087 value->area[value->data] = '\0';
3088
3089 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003090 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003091 if (pat_ref_find_elt(ref, key->area) != NULL)
3092 /* update entry if it exists */
3093 pat_ref_set(ref, key->area, value->area, NULL);
3094 else
3095 /* insert a new entry */
3096 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003097 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003098 free_trash_chunk(key);
3099 free_trash_chunk(value);
3100 break;
3101 }
3102
3103 case ACT_HTTP_EARLY_HINT:
3104 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3105 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003106 early_hints = htx_add_early_hint_header(s, early_hints,
3107 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003108 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003109 if (early_hints == -1) {
3110 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003111 goto end;
3112 }
3113 break;
3114
3115 case ACT_CUSTOM:
3116 if ((s->req.flags & CF_READ_ERROR) ||
3117 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003118 (px->options & PR_O_ABRT_CLOSE)))
3119 act_flags |= ACT_FLAG_FINAL;
3120
3121 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3122 case ACT_RET_ERR:
3123 case ACT_RET_CONT:
3124 break;
3125 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003126 rule_ret = HTTP_RULE_RES_STOP;
3127 goto end;
3128 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003129 rule_ret = HTTP_RULE_RES_DONE;
3130 goto end;
3131 case ACT_RET_YIELD:
3132 s->current_rule = rule;
3133 rule_ret = HTTP_RULE_RES_YIELD;
3134 goto end;
3135 }
3136 break;
3137
3138 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3139 /* Note: only the first valid tracking parameter of each
3140 * applies.
3141 */
3142
3143 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3144 struct stktable *t;
3145 struct stksess *ts;
3146 struct stktable_key *key;
3147 void *ptr1, *ptr2;
3148
3149 t = rule->arg.trk_ctr.table.t;
3150 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3151 rule->arg.trk_ctr.expr, NULL);
3152
3153 if (key && (ts = stktable_get_entry(t, key))) {
3154 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3155
3156 /* let's count a new HTTP request as it's the first time we do it */
3157 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3158 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3159 if (ptr1 || ptr2) {
3160 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3161
3162 if (ptr1)
3163 stktable_data_cast(ptr1, http_req_cnt)++;
3164
3165 if (ptr2)
3166 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3167 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3168
3169 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3170
3171 /* If data was modified, we need to touch to re-schedule sync */
3172 stktable_touch_local(t, ts, 0);
3173 }
3174
3175 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3176 if (sess->fe != s->be)
3177 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3178 }
3179 }
3180 break;
3181
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003182 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003183 default:
3184 break;
3185 }
3186 }
3187
3188 end:
3189 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003190 if (htx_reply_103_early_hints(&s->res) == -1)
3191 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003192 }
3193
3194 /* we reached the end of the rules, nothing to report */
3195 return rule_ret;
3196}
3197
3198/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3199 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3200 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3201 * is returned, the process can continue the evaluation of next rule list. If
3202 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3203 * is returned, it means the operation could not be processed and a server error
3204 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3205 * deny rule. If *YIELD is returned, the caller must call again the function
3206 * with the same context.
3207 */
3208static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3209 struct stream *s)
3210{
3211 struct session *sess = strm_sess(s);
3212 struct http_txn *txn = s->txn;
3213 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003214 struct act_rule *rule;
3215 struct http_hdr_ctx ctx;
3216 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3217 int act_flags = 0;
3218
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003219 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003220
3221 /* If "the current_rule_list" match the executed rule list, we are in
3222 * resume condition. If a resume is needed it is always in the action
3223 * and never in the ACL or converters. In this case, we initialise the
3224 * current rule, and go to the action execution point.
3225 */
3226 if (s->current_rule) {
3227 rule = s->current_rule;
3228 s->current_rule = NULL;
3229 if (s->current_rule_list == rules)
3230 goto resume_execution;
3231 }
3232 s->current_rule_list = rules;
3233
3234 list_for_each_entry(rule, rules, list) {
3235 /* check optional condition */
3236 if (rule->cond) {
3237 int ret;
3238
3239 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3240 ret = acl_pass(ret);
3241
3242 if (rule->cond->pol == ACL_COND_UNLESS)
3243 ret = !ret;
3244
3245 if (!ret) /* condition not matched */
3246 continue;
3247 }
3248
3249 act_flags |= ACT_FLAG_FIRST;
3250resume_execution:
3251 switch (rule->action) {
3252 case ACT_ACTION_ALLOW:
3253 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3254 goto end;
3255
3256 case ACT_ACTION_DENY:
3257 txn->flags |= TX_SVDENY;
3258 rule_ret = HTTP_RULE_RES_STOP;
3259 goto end;
3260
3261 case ACT_HTTP_SET_NICE:
3262 s->task->nice = rule->arg.nice;
3263 break;
3264
3265 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003266 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003267 break;
3268
3269 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003270 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003271 break;
3272
3273 case ACT_HTTP_SET_LOGL:
3274 s->logs.level = rule->arg.loglevel;
3275 break;
3276
3277 case ACT_HTTP_REPLACE_HDR:
3278 case ACT_HTTP_REPLACE_VAL:
3279 if (htx_transform_header(s, &s->res, htx,
3280 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3281 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003282 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003283 rule_ret = HTTP_RULE_RES_BADREQ;
3284 goto end;
3285 }
3286 break;
3287
3288 case ACT_HTTP_DEL_HDR:
3289 /* remove all occurrences of the header */
3290 ctx.blk = NULL;
3291 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3292 http_remove_header(htx, &ctx);
3293 break;
3294
3295 case ACT_HTTP_SET_HDR:
3296 case ACT_HTTP_ADD_HDR: {
3297 struct buffer *replace;
3298 struct ist n, v;
3299
3300 replace = alloc_trash_chunk();
3301 if (!replace) {
3302 rule_ret = HTTP_RULE_RES_BADREQ;
3303 goto end;
3304 }
3305
3306 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3307 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3308 v = ist2(replace->area, replace->data);
3309
3310 if (rule->action == ACT_HTTP_SET_HDR) {
3311 /* remove all occurrences of the header */
3312 ctx.blk = NULL;
3313 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3314 http_remove_header(htx, &ctx);
3315 }
3316
3317 if (!http_add_header(htx, n, v)) {
3318 static unsigned char rate_limit = 0;
3319
3320 if ((rate_limit++ & 255) == 0) {
3321 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);
3322 }
3323
Olivier Houcharda798bf52019-03-08 18:52:00 +01003324 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003325 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003326 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003327 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003328 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003329 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003330 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003331 }
3332 free_trash_chunk(replace);
3333 break;
3334 }
3335
3336 case ACT_HTTP_DEL_ACL:
3337 case ACT_HTTP_DEL_MAP: {
3338 struct pat_ref *ref;
3339 struct buffer *key;
3340
3341 /* collect reference */
3342 ref = pat_ref_lookup(rule->arg.map.ref);
3343 if (!ref)
3344 continue;
3345
3346 /* allocate key */
3347 key = alloc_trash_chunk();
3348 if (!key) {
3349 rule_ret = HTTP_RULE_RES_BADREQ;
3350 goto end;
3351 }
3352
3353 /* collect key */
3354 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3355 key->area[key->data] = '\0';
3356
3357 /* perform update */
3358 /* returned code: 1=ok, 0=ko */
3359 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3360 pat_ref_delete(ref, key->area);
3361 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3362
3363 free_trash_chunk(key);
3364 break;
3365 }
3366
3367 case ACT_HTTP_ADD_ACL: {
3368 struct pat_ref *ref;
3369 struct buffer *key;
3370
3371 /* collect reference */
3372 ref = pat_ref_lookup(rule->arg.map.ref);
3373 if (!ref)
3374 continue;
3375
3376 /* allocate key */
3377 key = alloc_trash_chunk();
3378 if (!key) {
3379 rule_ret = HTTP_RULE_RES_BADREQ;
3380 goto end;
3381 }
3382
3383 /* collect key */
3384 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3385 key->area[key->data] = '\0';
3386
3387 /* perform update */
3388 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003389 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003390 if (pat_ref_find_elt(ref, key->area) == NULL)
3391 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003392 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003393 free_trash_chunk(key);
3394 break;
3395 }
3396
3397 case ACT_HTTP_SET_MAP: {
3398 struct pat_ref *ref;
3399 struct buffer *key, *value;
3400
3401 /* collect reference */
3402 ref = pat_ref_lookup(rule->arg.map.ref);
3403 if (!ref)
3404 continue;
3405
3406 /* allocate key */
3407 key = alloc_trash_chunk();
3408 if (!key) {
3409 rule_ret = HTTP_RULE_RES_BADREQ;
3410 goto end;
3411 }
3412
3413 /* allocate value */
3414 value = alloc_trash_chunk();
3415 if (!value) {
3416 free_trash_chunk(key);
3417 rule_ret = HTTP_RULE_RES_BADREQ;
3418 goto end;
3419 }
3420
3421 /* collect key */
3422 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3423 key->area[key->data] = '\0';
3424
3425 /* collect value */
3426 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3427 value->area[value->data] = '\0';
3428
3429 /* perform update */
3430 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3431 if (pat_ref_find_elt(ref, key->area) != NULL)
3432 /* update entry if it exists */
3433 pat_ref_set(ref, key->area, value->area, NULL);
3434 else
3435 /* insert a new entry */
3436 pat_ref_add(ref, key->area, value->area, NULL);
3437 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3438 free_trash_chunk(key);
3439 free_trash_chunk(value);
3440 break;
3441 }
3442
3443 case ACT_HTTP_REDIR:
3444 rule_ret = HTTP_RULE_RES_DONE;
3445 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3446 rule_ret = HTTP_RULE_RES_BADREQ;
3447 goto end;
3448
3449 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3450 /* Note: only the first valid tracking parameter of each
3451 * applies.
3452 */
3453 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3454 struct stktable *t;
3455 struct stksess *ts;
3456 struct stktable_key *key;
3457 void *ptr;
3458
3459 t = rule->arg.trk_ctr.table.t;
3460 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3461 rule->arg.trk_ctr.expr, NULL);
3462
3463 if (key && (ts = stktable_get_entry(t, key))) {
3464 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3465
3466 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3467
3468 /* let's count a new HTTP request as it's the first time we do it */
3469 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3470 if (ptr)
3471 stktable_data_cast(ptr, http_req_cnt)++;
3472
3473 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3474 if (ptr)
3475 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3476 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3477
3478 /* When the client triggers a 4xx from the server, it's most often due
3479 * to a missing object or permission. These events should be tracked
3480 * because if they happen often, it may indicate a brute force or a
3481 * vulnerability scan. Normally this is done when receiving the response
3482 * but here we're tracking after this ought to have been done so we have
3483 * to do it on purpose.
3484 */
3485 if ((unsigned)(txn->status - 400) < 100) {
3486 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3487 if (ptr)
3488 stktable_data_cast(ptr, http_err_cnt)++;
3489
3490 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3491 if (ptr)
3492 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3493 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3494 }
3495
3496 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3497
3498 /* If data was modified, we need to touch to re-schedule sync */
3499 stktable_touch_local(t, ts, 0);
3500
3501 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3502 if (sess->fe != s->be)
3503 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3504 }
3505 }
3506 break;
3507
3508 case ACT_CUSTOM:
3509 if ((s->req.flags & CF_READ_ERROR) ||
3510 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003511 (px->options & PR_O_ABRT_CLOSE)))
3512 act_flags |= ACT_FLAG_FINAL;
3513
3514 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3515 case ACT_RET_ERR:
3516 case ACT_RET_CONT:
3517 break;
3518 case ACT_RET_STOP:
3519 rule_ret = HTTP_RULE_RES_STOP;
3520 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003521 case ACT_RET_DONE:
3522 rule_ret = HTTP_RULE_RES_DONE;
3523 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003524 case ACT_RET_YIELD:
3525 s->current_rule = rule;
3526 rule_ret = HTTP_RULE_RES_YIELD;
3527 goto end;
3528 }
3529 break;
3530
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003531 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003532 default:
3533 break;
3534 }
3535 }
3536
3537 end:
3538 /* we reached the end of the rules, nothing to report */
3539 return rule_ret;
3540}
3541
Christopher Faulet33640082018-10-24 11:53:01 +02003542/* Iterate the same filter through all request headers.
3543 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3544 * Since it can manage the switch to another backend, it updates the per-proxy
3545 * DENY stats.
3546 */
3547static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3548{
3549 struct http_txn *txn = s->txn;
3550 struct htx *htx;
3551 struct buffer *hdr = get_trash_chunk();
3552 int32_t pos;
3553
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003554 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003555
Christopher Fauleta3f15502019-05-13 15:27:23 +02003556 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003557 struct htx_blk *blk = htx_get_blk(htx, pos);
3558 enum htx_blk_type type;
3559 struct ist n, v;
3560
3561 next_hdr:
3562 type = htx_get_blk_type(blk);
3563 if (type == HTX_BLK_EOH)
3564 break;
3565 if (type != HTX_BLK_HDR)
3566 continue;
3567
3568 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3569 return 1;
3570 else if (unlikely(txn->flags & TX_CLALLOW) &&
3571 (exp->action == ACT_ALLOW ||
3572 exp->action == ACT_DENY ||
3573 exp->action == ACT_TARPIT))
3574 return 0;
3575
3576 n = htx_get_blk_name(htx, blk);
3577 v = htx_get_blk_value(htx, blk);
3578
Christopher Faulet02e771a2019-02-26 15:36:05 +01003579 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003580 hdr->area[hdr->data++] = ':';
3581 hdr->area[hdr->data++] = ' ';
3582 chunk_memcat(hdr, v.ptr, v.len);
3583
3584 /* Now we have one header in <hdr> */
3585
3586 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3587 struct http_hdr_ctx ctx;
3588 int len;
3589
3590 switch (exp->action) {
3591 case ACT_ALLOW:
3592 txn->flags |= TX_CLALLOW;
3593 goto end;
3594
3595 case ACT_DENY:
3596 txn->flags |= TX_CLDENY;
3597 goto end;
3598
3599 case ACT_TARPIT:
3600 txn->flags |= TX_CLTARPIT;
3601 goto end;
3602
3603 case ACT_REPLACE:
3604 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3605 if (len < 0)
3606 return -1;
3607
3608 http_parse_header(ist2(trash.area, len), &n, &v);
3609 ctx.blk = blk;
3610 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003611 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003612 if (!http_replace_header(htx, &ctx, n, v))
3613 return -1;
3614 if (!ctx.blk)
3615 goto end;
3616 pos = htx_get_blk_pos(htx, blk);
3617 break;
3618
3619 case ACT_REMOVE:
3620 ctx.blk = blk;
3621 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003622 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003623 if (!http_remove_header(htx, &ctx))
3624 return -1;
3625 if (!ctx.blk)
3626 goto end;
3627 pos = htx_get_blk_pos(htx, blk);
3628 goto next_hdr;
3629
3630 }
3631 }
3632 }
3633 end:
3634 return 0;
3635}
3636
3637/* Apply the filter to the request line.
3638 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3639 * or -1 if a replacement resulted in an invalid request line.
3640 * Since it can manage the switch to another backend, it updates the per-proxy
3641 * DENY stats.
3642 */
3643static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3644{
3645 struct http_txn *txn = s->txn;
3646 struct htx *htx;
3647 struct buffer *reqline = get_trash_chunk();
3648 int done;
3649
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003650 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003651
3652 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3653 return 1;
3654 else if (unlikely(txn->flags & TX_CLALLOW) &&
3655 (exp->action == ACT_ALLOW ||
3656 exp->action == ACT_DENY ||
3657 exp->action == ACT_TARPIT))
3658 return 0;
3659 else if (exp->action == ACT_REMOVE)
3660 return 0;
3661
3662 done = 0;
3663
Christopher Faulet297fbb42019-05-13 14:41:27 +02003664 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003665
3666 /* Now we have the request line between cur_ptr and cur_end */
3667 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003668 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003669 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003670 int len;
3671
3672 switch (exp->action) {
3673 case ACT_ALLOW:
3674 txn->flags |= TX_CLALLOW;
3675 done = 1;
3676 break;
3677
3678 case ACT_DENY:
3679 txn->flags |= TX_CLDENY;
3680 done = 1;
3681 break;
3682
3683 case ACT_TARPIT:
3684 txn->flags |= TX_CLTARPIT;
3685 done = 1;
3686 break;
3687
3688 case ACT_REPLACE:
3689 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3690 if (len < 0)
3691 return -1;
3692
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003693 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3694 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3695 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003696 return -1;
3697 done = 1;
3698 break;
3699 }
3700 }
3701 return done;
3702}
3703
3704/*
3705 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3706 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3707 * unparsable request. Since it can manage the switch to another backend, it
3708 * updates the per-proxy DENY stats.
3709 */
3710static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3711{
3712 struct session *sess = s->sess;
3713 struct http_txn *txn = s->txn;
3714 struct hdr_exp *exp;
3715
3716 for (exp = px->req_exp; exp; exp = exp->next) {
3717 int ret;
3718
3719 /*
3720 * The interleaving of transformations and verdicts
3721 * makes it difficult to decide to continue or stop
3722 * the evaluation.
3723 */
3724
3725 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3726 break;
3727
3728 if ((txn->flags & TX_CLALLOW) &&
3729 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3730 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3731 continue;
3732
3733 /* if this filter had a condition, evaluate it now and skip to
3734 * next filter if the condition does not match.
3735 */
3736 if (exp->cond) {
3737 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3738 ret = acl_pass(ret);
3739 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3740 ret = !ret;
3741
3742 if (!ret)
3743 continue;
3744 }
3745
3746 /* Apply the filter to the request line. */
3747 ret = htx_apply_filter_to_req_line(s, req, exp);
3748 if (unlikely(ret < 0))
3749 return -1;
3750
3751 if (likely(ret == 0)) {
3752 /* The filter did not match the request, it can be
3753 * iterated through all headers.
3754 */
3755 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3756 return -1;
3757 }
3758 }
3759 return 0;
3760}
3761
3762/* Iterate the same filter through all response headers contained in <res>.
3763 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3764 */
3765static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3766{
3767 struct http_txn *txn = s->txn;
3768 struct htx *htx;
3769 struct buffer *hdr = get_trash_chunk();
3770 int32_t pos;
3771
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003772 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003773
Christopher Fauleta3f15502019-05-13 15:27:23 +02003774 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003775 struct htx_blk *blk = htx_get_blk(htx, pos);
3776 enum htx_blk_type type;
3777 struct ist n, v;
3778
3779 next_hdr:
3780 type = htx_get_blk_type(blk);
3781 if (type == HTX_BLK_EOH)
3782 break;
3783 if (type != HTX_BLK_HDR)
3784 continue;
3785
3786 if (unlikely(txn->flags & TX_SVDENY))
3787 return 1;
3788 else if (unlikely(txn->flags & TX_SVALLOW) &&
3789 (exp->action == ACT_ALLOW ||
3790 exp->action == ACT_DENY))
3791 return 0;
3792
3793 n = htx_get_blk_name(htx, blk);
3794 v = htx_get_blk_value(htx, blk);
3795
Christopher Faulet02e771a2019-02-26 15:36:05 +01003796 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003797 hdr->area[hdr->data++] = ':';
3798 hdr->area[hdr->data++] = ' ';
3799 chunk_memcat(hdr, v.ptr, v.len);
3800
3801 /* Now we have one header in <hdr> */
3802
3803 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3804 struct http_hdr_ctx ctx;
3805 int len;
3806
3807 switch (exp->action) {
3808 case ACT_ALLOW:
3809 txn->flags |= TX_SVALLOW;
3810 goto end;
3811 break;
3812
3813 case ACT_DENY:
3814 txn->flags |= TX_SVDENY;
3815 goto end;
3816 break;
3817
3818 case ACT_REPLACE:
3819 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3820 if (len < 0)
3821 return -1;
3822
3823 http_parse_header(ist2(trash.area, len), &n, &v);
3824 ctx.blk = blk;
3825 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003826 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003827 if (!http_replace_header(htx, &ctx, n, v))
3828 return -1;
3829 if (!ctx.blk)
3830 goto end;
3831 pos = htx_get_blk_pos(htx, blk);
3832 break;
3833
3834 case ACT_REMOVE:
3835 ctx.blk = blk;
3836 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003837 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003838 if (!http_remove_header(htx, &ctx))
3839 return -1;
3840 if (!ctx.blk)
3841 goto end;
3842 pos = htx_get_blk_pos(htx, blk);
3843 goto next_hdr;
3844 }
3845 }
3846
3847 }
3848 end:
3849 return 0;
3850}
3851
3852/* Apply the filter to the status line in the response buffer <res>.
3853 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3854 * or -1 if a replacement resulted in an invalid status line.
3855 */
3856static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3857{
3858 struct http_txn *txn = s->txn;
3859 struct htx *htx;
3860 struct buffer *resline = get_trash_chunk();
3861 int done;
3862
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003863 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003864
3865 if (unlikely(txn->flags & TX_SVDENY))
3866 return 1;
3867 else if (unlikely(txn->flags & TX_SVALLOW) &&
3868 (exp->action == ACT_ALLOW ||
3869 exp->action == ACT_DENY))
3870 return 0;
3871 else if (exp->action == ACT_REMOVE)
3872 return 0;
3873
3874 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003875 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003876
3877 /* Now we have the status line between cur_ptr and cur_end */
3878 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003879 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003880 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003881 int len;
3882
3883 switch (exp->action) {
3884 case ACT_ALLOW:
3885 txn->flags |= TX_SVALLOW;
3886 done = 1;
3887 break;
3888
3889 case ACT_DENY:
3890 txn->flags |= TX_SVDENY;
3891 done = 1;
3892 break;
3893
3894 case ACT_REPLACE:
3895 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3896 if (len < 0)
3897 return -1;
3898
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003899 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3900 sl->info.res.status = strl2ui(code.ptr, code.len);
3901 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003902 return -1;
3903
3904 done = 1;
3905 return 1;
3906 }
3907 }
3908 return done;
3909}
3910
3911/*
3912 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3913 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3914 * unparsable response.
3915 */
3916static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3917{
3918 struct session *sess = s->sess;
3919 struct http_txn *txn = s->txn;
3920 struct hdr_exp *exp;
3921
3922 for (exp = px->rsp_exp; exp; exp = exp->next) {
3923 int ret;
3924
3925 /*
3926 * The interleaving of transformations and verdicts
3927 * makes it difficult to decide to continue or stop
3928 * the evaluation.
3929 */
3930
3931 if (txn->flags & TX_SVDENY)
3932 break;
3933
3934 if ((txn->flags & TX_SVALLOW) &&
3935 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3936 exp->action == ACT_PASS)) {
3937 exp = exp->next;
3938 continue;
3939 }
3940
3941 /* if this filter had a condition, evaluate it now and skip to
3942 * next filter if the condition does not match.
3943 */
3944 if (exp->cond) {
3945 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3946 ret = acl_pass(ret);
3947 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3948 ret = !ret;
3949 if (!ret)
3950 continue;
3951 }
3952
3953 /* Apply the filter to the status line. */
3954 ret = htx_apply_filter_to_sts_line(s, res, exp);
3955 if (unlikely(ret < 0))
3956 return -1;
3957
3958 if (likely(ret == 0)) {
3959 /* The filter did not match the response, it can be
3960 * iterated through all headers.
3961 */
3962 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3963 return -1;
3964 }
3965 }
3966 return 0;
3967}
3968
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003969/*
3970 * Manage client-side cookie. It can impact performance by about 2% so it is
3971 * desirable to call it only when needed. This code is quite complex because
3972 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3973 * highly recommended not to touch this part without a good reason !
3974 */
3975static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3976{
3977 struct session *sess = s->sess;
3978 struct http_txn *txn = s->txn;
3979 struct htx *htx;
3980 struct http_hdr_ctx ctx;
3981 char *hdr_beg, *hdr_end, *del_from;
3982 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3983 int preserve_hdr;
3984
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003985 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003986 ctx.blk = NULL;
3987 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02003988 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003989 del_from = NULL; /* nothing to be deleted */
3990 preserve_hdr = 0; /* assume we may kill the whole header */
3991
3992 /* Now look for cookies. Conforming to RFC2109, we have to support
3993 * attributes whose name begin with a '$', and associate them with
3994 * the right cookie, if we want to delete this cookie.
3995 * So there are 3 cases for each cookie read :
3996 * 1) it's a special attribute, beginning with a '$' : ignore it.
3997 * 2) it's a server id cookie that we *MAY* want to delete : save
3998 * some pointers on it (last semi-colon, beginning of cookie...)
3999 * 3) it's an application cookie : we *MAY* have to delete a previous
4000 * "special" cookie.
4001 * At the end of loop, if a "special" cookie remains, we may have to
4002 * remove it. If no application cookie persists in the header, we
4003 * *MUST* delete it.
4004 *
4005 * Note: RFC2965 is unclear about the processing of spaces around
4006 * the equal sign in the ATTR=VALUE form. A careful inspection of
4007 * the RFC explicitly allows spaces before it, and not within the
4008 * tokens (attrs or values). An inspection of RFC2109 allows that
4009 * too but section 10.1.3 lets one think that spaces may be allowed
4010 * after the equal sign too, resulting in some (rare) buggy
4011 * implementations trying to do that. So let's do what servers do.
4012 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4013 * allowed quoted strings in values, with any possible character
4014 * after a backslash, including control chars and delimitors, which
4015 * causes parsing to become ambiguous. Browsers also allow spaces
4016 * within values even without quotes.
4017 *
4018 * We have to keep multiple pointers in order to support cookie
4019 * removal at the beginning, middle or end of header without
4020 * corrupting the header. All of these headers are valid :
4021 *
4022 * hdr_beg hdr_end
4023 * | |
4024 * v |
4025 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4026 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4027 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4028 * | | | | | | |
4029 * | | | | | | |
4030 * | | | | | | +--> next
4031 * | | | | | +----> val_end
4032 * | | | | +-----------> val_beg
4033 * | | | +--------------> equal
4034 * | | +----------------> att_end
4035 * | +---------------------> att_beg
4036 * +--------------------------> prev
4037 *
4038 */
4039 hdr_beg = ctx.value.ptr;
4040 hdr_end = hdr_beg + ctx.value.len;
4041 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4042 /* Iterate through all cookies on this line */
4043
4044 /* find att_beg */
4045 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004046 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004047 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004048 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004049
4050 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4051 att_beg++;
4052
4053 /* find att_end : this is the first character after the last non
4054 * space before the equal. It may be equal to hdr_end.
4055 */
4056 equal = att_end = att_beg;
4057 while (equal < hdr_end) {
4058 if (*equal == '=' || *equal == ',' || *equal == ';')
4059 break;
4060 if (HTTP_IS_SPHT(*equal++))
4061 continue;
4062 att_end = equal;
4063 }
4064
4065 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4066 * is between <att_beg> and <equal>, both may be identical.
4067 */
4068 /* look for end of cookie if there is an equal sign */
4069 if (equal < hdr_end && *equal == '=') {
4070 /* look for the beginning of the value */
4071 val_beg = equal + 1;
4072 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4073 val_beg++;
4074
4075 /* find the end of the value, respecting quotes */
4076 next = http_find_cookie_value_end(val_beg, hdr_end);
4077
4078 /* make val_end point to the first white space or delimitor after the value */
4079 val_end = next;
4080 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4081 val_end--;
4082 }
4083 else
4084 val_beg = val_end = next = equal;
4085
4086 /* We have nothing to do with attributes beginning with
4087 * '$'. However, they will automatically be removed if a
4088 * header before them is removed, since they're supposed
4089 * to be linked together.
4090 */
4091 if (*att_beg == '$')
4092 continue;
4093
4094 /* Ignore cookies with no equal sign */
4095 if (equal == next) {
4096 /* This is not our cookie, so we must preserve it. But if we already
4097 * scheduled another cookie for removal, we cannot remove the
4098 * complete header, but we can remove the previous block itself.
4099 */
4100 preserve_hdr = 1;
4101 if (del_from != NULL) {
4102 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4103 val_end += delta;
4104 next += delta;
4105 hdr_end += delta;
4106 prev = del_from;
4107 del_from = NULL;
4108 }
4109 continue;
4110 }
4111
4112 /* if there are spaces around the equal sign, we need to
4113 * strip them otherwise we'll get trouble for cookie captures,
4114 * or even for rewrites. Since this happens extremely rarely,
4115 * it does not hurt performance.
4116 */
4117 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4118 int stripped_before = 0;
4119 int stripped_after = 0;
4120
4121 if (att_end != equal) {
4122 memmove(att_end, equal, hdr_end - equal);
4123 stripped_before = (att_end - equal);
4124 equal += stripped_before;
4125 val_beg += stripped_before;
4126 }
4127
4128 if (val_beg > equal + 1) {
4129 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4130 stripped_after = (equal + 1) - val_beg;
4131 val_beg += stripped_after;
4132 stripped_before += stripped_after;
4133 }
4134
4135 val_end += stripped_before;
4136 next += stripped_before;
4137 hdr_end += stripped_before;
4138 }
4139 /* now everything is as on the diagram above */
4140
4141 /* First, let's see if we want to capture this cookie. We check
4142 * that we don't already have a client side cookie, because we
4143 * can only capture one. Also as an optimisation, we ignore
4144 * cookies shorter than the declared name.
4145 */
4146 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4147 (val_end - att_beg >= sess->fe->capture_namelen) &&
4148 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4149 int log_len = val_end - att_beg;
4150
4151 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4152 ha_alert("HTTP logging : out of memory.\n");
4153 } else {
4154 if (log_len > sess->fe->capture_len)
4155 log_len = sess->fe->capture_len;
4156 memcpy(txn->cli_cookie, att_beg, log_len);
4157 txn->cli_cookie[log_len] = 0;
4158 }
4159 }
4160
4161 /* Persistence cookies in passive, rewrite or insert mode have the
4162 * following form :
4163 *
4164 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4165 *
4166 * For cookies in prefix mode, the form is :
4167 *
4168 * Cookie: NAME=SRV~VALUE
4169 */
4170 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4171 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4172 struct server *srv = s->be->srv;
4173 char *delim;
4174
4175 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4176 * have the server ID between val_beg and delim, and the original cookie between
4177 * delim+1 and val_end. Otherwise, delim==val_end :
4178 *
4179 * hdr_beg
4180 * |
4181 * v
4182 * NAME=SRV; # in all but prefix modes
4183 * NAME=SRV~OPAQUE ; # in prefix mode
4184 * || || | |+-> next
4185 * || || | +--> val_end
4186 * || || +---------> delim
4187 * || |+------------> val_beg
4188 * || +-------------> att_end = equal
4189 * |+-----------------> att_beg
4190 * +------------------> prev
4191 *
4192 */
4193 if (s->be->ck_opts & PR_CK_PFX) {
4194 for (delim = val_beg; delim < val_end; delim++)
4195 if (*delim == COOKIE_DELIM)
4196 break;
4197 }
4198 else {
4199 char *vbar1;
4200 delim = val_end;
4201 /* Now check if the cookie contains a date field, which would
4202 * appear after a vertical bar ('|') just after the server name
4203 * and before the delimiter.
4204 */
4205 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4206 if (vbar1) {
4207 /* OK, so left of the bar is the server's cookie and
4208 * right is the last seen date. It is a base64 encoded
4209 * 30-bit value representing the UNIX date since the
4210 * epoch in 4-second quantities.
4211 */
4212 int val;
4213 delim = vbar1++;
4214 if (val_end - vbar1 >= 5) {
4215 val = b64tos30(vbar1);
4216 if (val > 0)
4217 txn->cookie_last_date = val << 2;
4218 }
4219 /* look for a second vertical bar */
4220 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4221 if (vbar1 && (val_end - vbar1 > 5)) {
4222 val = b64tos30(vbar1 + 1);
4223 if (val > 0)
4224 txn->cookie_first_date = val << 2;
4225 }
4226 }
4227 }
4228
4229 /* if the cookie has an expiration date and the proxy wants to check
4230 * it, then we do that now. We first check if the cookie is too old,
4231 * then only if it has expired. We detect strict overflow because the
4232 * time resolution here is not great (4 seconds). Cookies with dates
4233 * in the future are ignored if their offset is beyond one day. This
4234 * allows an admin to fix timezone issues without expiring everyone
4235 * and at the same time avoids keeping unwanted side effects for too
4236 * long.
4237 */
4238 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4239 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4240 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4241 txn->flags &= ~TX_CK_MASK;
4242 txn->flags |= TX_CK_OLD;
4243 delim = val_beg; // let's pretend we have not found the cookie
4244 txn->cookie_first_date = 0;
4245 txn->cookie_last_date = 0;
4246 }
4247 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4248 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4249 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4250 txn->flags &= ~TX_CK_MASK;
4251 txn->flags |= TX_CK_EXPIRED;
4252 delim = val_beg; // let's pretend we have not found the cookie
4253 txn->cookie_first_date = 0;
4254 txn->cookie_last_date = 0;
4255 }
4256
4257 /* Here, we'll look for the first running server which supports the cookie.
4258 * This allows to share a same cookie between several servers, for example
4259 * to dedicate backup servers to specific servers only.
4260 * However, to prevent clients from sticking to cookie-less backup server
4261 * when they have incidentely learned an empty cookie, we simply ignore
4262 * empty cookies and mark them as invalid.
4263 * The same behaviour is applied when persistence must be ignored.
4264 */
4265 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4266 srv = NULL;
4267
4268 while (srv) {
4269 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4270 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4271 if ((srv->cur_state != SRV_ST_STOPPED) ||
4272 (s->be->options & PR_O_PERSIST) ||
4273 (s->flags & SF_FORCE_PRST)) {
4274 /* we found the server and we can use it */
4275 txn->flags &= ~TX_CK_MASK;
4276 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4277 s->flags |= SF_DIRECT | SF_ASSIGNED;
4278 s->target = &srv->obj_type;
4279 break;
4280 } else {
4281 /* we found a server, but it's down,
4282 * mark it as such and go on in case
4283 * another one is available.
4284 */
4285 txn->flags &= ~TX_CK_MASK;
4286 txn->flags |= TX_CK_DOWN;
4287 }
4288 }
4289 srv = srv->next;
4290 }
4291
4292 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4293 /* no server matched this cookie or we deliberately skipped it */
4294 txn->flags &= ~TX_CK_MASK;
4295 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4296 txn->flags |= TX_CK_UNUSED;
4297 else
4298 txn->flags |= TX_CK_INVALID;
4299 }
4300
4301 /* depending on the cookie mode, we may have to either :
4302 * - delete the complete cookie if we're in insert+indirect mode, so that
4303 * the server never sees it ;
4304 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004305 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004306 * if we're in cookie prefix mode
4307 */
4308 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4309 int delta; /* negative */
4310
4311 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4312 delta = val_beg - (delim + 1);
4313 val_end += delta;
4314 next += delta;
4315 hdr_end += delta;
4316 del_from = NULL;
4317 preserve_hdr = 1; /* we want to keep this cookie */
4318 }
4319 else if (del_from == NULL &&
4320 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4321 del_from = prev;
4322 }
4323 }
4324 else {
4325 /* This is not our cookie, so we must preserve it. But if we already
4326 * scheduled another cookie for removal, we cannot remove the
4327 * complete header, but we can remove the previous block itself.
4328 */
4329 preserve_hdr = 1;
4330
4331 if (del_from != NULL) {
4332 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4333 if (att_beg >= del_from)
4334 att_beg += delta;
4335 if (att_end >= del_from)
4336 att_end += delta;
4337 val_beg += delta;
4338 val_end += delta;
4339 next += delta;
4340 hdr_end += delta;
4341 prev = del_from;
4342 del_from = NULL;
4343 }
4344 }
4345
4346 /* continue with next cookie on this header line */
4347 att_beg = next;
4348 } /* for each cookie */
4349
4350
4351 /* There are no more cookies on this line.
4352 * We may still have one (or several) marked for deletion at the
4353 * end of the line. We must do this now in two ways :
4354 * - if some cookies must be preserved, we only delete from the
4355 * mark to the end of line ;
4356 * - if nothing needs to be preserved, simply delete the whole header
4357 */
4358 if (del_from) {
4359 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4360 }
4361 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004362 if (hdr_beg != hdr_end)
4363 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004364 else
4365 http_remove_header(htx, &ctx);
4366 }
4367 } /* for each "Cookie header */
4368}
4369
4370/*
4371 * Manage server-side cookies. It can impact performance by about 2% so it is
4372 * desirable to call it only when needed. This function is also used when we
4373 * just need to know if there is a cookie (eg: for check-cache).
4374 */
4375static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4376{
4377 struct session *sess = s->sess;
4378 struct http_txn *txn = s->txn;
4379 struct htx *htx;
4380 struct http_hdr_ctx ctx;
4381 struct server *srv;
4382 char *hdr_beg, *hdr_end;
4383 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004384 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004385
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004386 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004387
4388 ctx.blk = NULL;
4389 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004390 int is_first = 1;
4391
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004392 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4393 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4394 break;
4395 is_cookie2 = 1;
4396 }
4397
4398 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4399 * <prev> points to the colon.
4400 */
4401 txn->flags |= TX_SCK_PRESENT;
4402
4403 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4404 * check-cache is enabled) and we are not interested in checking
4405 * them. Warning, the cookie capture is declared in the frontend.
4406 */
4407 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4408 break;
4409
4410 /* OK so now we know we have to process this response cookie.
4411 * The format of the Set-Cookie header is slightly different
4412 * from the format of the Cookie header in that it does not
4413 * support the comma as a cookie delimiter (thus the header
4414 * cannot be folded) because the Expires attribute described in
4415 * the original Netscape's spec may contain an unquoted date
4416 * with a comma inside. We have to live with this because
4417 * many browsers don't support Max-Age and some browsers don't
4418 * support quoted strings. However the Set-Cookie2 header is
4419 * clean.
4420 *
4421 * We have to keep multiple pointers in order to support cookie
4422 * removal at the beginning, middle or end of header without
4423 * corrupting the header (in case of set-cookie2). A special
4424 * pointer, <scav> points to the beginning of the set-cookie-av
4425 * fields after the first semi-colon. The <next> pointer points
4426 * either to the end of line (set-cookie) or next unquoted comma
4427 * (set-cookie2). All of these headers are valid :
4428 *
4429 * hdr_beg hdr_end
4430 * | |
4431 * v |
4432 * NAME1 = VALUE 1 ; Secure; Path="/" |
4433 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4434 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4435 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4436 * | | | | | | | |
4437 * | | | | | | | +-> next
4438 * | | | | | | +------------> scav
4439 * | | | | | +--------------> val_end
4440 * | | | | +--------------------> val_beg
4441 * | | | +----------------------> equal
4442 * | | +------------------------> att_end
4443 * | +----------------------------> att_beg
4444 * +------------------------------> prev
4445 * -------------------------------> hdr_beg
4446 */
4447 hdr_beg = ctx.value.ptr;
4448 hdr_end = hdr_beg + ctx.value.len;
4449 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4450
4451 /* Iterate through all cookies on this line */
4452
4453 /* find att_beg */
4454 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004455 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004456 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004457 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004458
4459 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4460 att_beg++;
4461
4462 /* find att_end : this is the first character after the last non
4463 * space before the equal. It may be equal to hdr_end.
4464 */
4465 equal = att_end = att_beg;
4466
4467 while (equal < hdr_end) {
4468 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4469 break;
4470 if (HTTP_IS_SPHT(*equal++))
4471 continue;
4472 att_end = equal;
4473 }
4474
4475 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4476 * is between <att_beg> and <equal>, both may be identical.
4477 */
4478
4479 /* look for end of cookie if there is an equal sign */
4480 if (equal < hdr_end && *equal == '=') {
4481 /* look for the beginning of the value */
4482 val_beg = equal + 1;
4483 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4484 val_beg++;
4485
4486 /* find the end of the value, respecting quotes */
4487 next = http_find_cookie_value_end(val_beg, hdr_end);
4488
4489 /* make val_end point to the first white space or delimitor after the value */
4490 val_end = next;
4491 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4492 val_end--;
4493 }
4494 else {
4495 /* <equal> points to next comma, semi-colon or EOL */
4496 val_beg = val_end = next = equal;
4497 }
4498
4499 if (next < hdr_end) {
4500 /* Set-Cookie2 supports multiple cookies, and <next> points to
4501 * a colon or semi-colon before the end. So skip all attr-value
4502 * pairs and look for the next comma. For Set-Cookie, since
4503 * commas are permitted in values, skip to the end.
4504 */
4505 if (is_cookie2)
4506 next = http_find_hdr_value_end(next, hdr_end);
4507 else
4508 next = hdr_end;
4509 }
4510
4511 /* Now everything is as on the diagram above */
4512
4513 /* Ignore cookies with no equal sign */
4514 if (equal == val_end)
4515 continue;
4516
4517 /* If there are spaces around the equal sign, we need to
4518 * strip them otherwise we'll get trouble for cookie captures,
4519 * or even for rewrites. Since this happens extremely rarely,
4520 * it does not hurt performance.
4521 */
4522 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4523 int stripped_before = 0;
4524 int stripped_after = 0;
4525
4526 if (att_end != equal) {
4527 memmove(att_end, equal, hdr_end - equal);
4528 stripped_before = (att_end - equal);
4529 equal += stripped_before;
4530 val_beg += stripped_before;
4531 }
4532
4533 if (val_beg > equal + 1) {
4534 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4535 stripped_after = (equal + 1) - val_beg;
4536 val_beg += stripped_after;
4537 stripped_before += stripped_after;
4538 }
4539
4540 val_end += stripped_before;
4541 next += stripped_before;
4542 hdr_end += stripped_before;
4543
Christopher Faulet41dc8432019-06-18 09:49:16 +02004544 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004545 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004546 }
4547
4548 /* First, let's see if we want to capture this cookie. We check
4549 * that we don't already have a server side cookie, because we
4550 * can only capture one. Also as an optimisation, we ignore
4551 * cookies shorter than the declared name.
4552 */
4553 if (sess->fe->capture_name != NULL &&
4554 txn->srv_cookie == NULL &&
4555 (val_end - att_beg >= sess->fe->capture_namelen) &&
4556 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4557 int log_len = val_end - att_beg;
4558 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4559 ha_alert("HTTP logging : out of memory.\n");
4560 }
4561 else {
4562 if (log_len > sess->fe->capture_len)
4563 log_len = sess->fe->capture_len;
4564 memcpy(txn->srv_cookie, att_beg, log_len);
4565 txn->srv_cookie[log_len] = 0;
4566 }
4567 }
4568
4569 srv = objt_server(s->target);
4570 /* now check if we need to process it for persistence */
4571 if (!(s->flags & SF_IGNORE_PRST) &&
4572 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4573 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4574 /* assume passive cookie by default */
4575 txn->flags &= ~TX_SCK_MASK;
4576 txn->flags |= TX_SCK_FOUND;
4577
4578 /* If the cookie is in insert mode on a known server, we'll delete
4579 * this occurrence because we'll insert another one later.
4580 * We'll delete it too if the "indirect" option is set and we're in
4581 * a direct access.
4582 */
4583 if (s->be->ck_opts & PR_CK_PSV) {
4584 /* The "preserve" flag was set, we don't want to touch the
4585 * server's cookie.
4586 */
4587 }
4588 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4589 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4590 /* this cookie must be deleted */
4591 if (prev == hdr_beg && next == hdr_end) {
4592 /* whole header */
4593 http_remove_header(htx, &ctx);
4594 /* note: while both invalid now, <next> and <hdr_end>
4595 * are still equal, so the for() will stop as expected.
4596 */
4597 } else {
4598 /* just remove the value */
4599 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4600 next = prev;
4601 hdr_end += delta;
4602 }
4603 txn->flags &= ~TX_SCK_MASK;
4604 txn->flags |= TX_SCK_DELETED;
4605 /* and go on with next cookie */
4606 }
4607 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4608 /* replace bytes val_beg->val_end with the cookie name associated
4609 * with this server since we know it.
4610 */
4611 int sliding, delta;
4612
4613 ctx.value = ist2(val_beg, val_end - val_beg);
4614 ctx.lws_before = ctx.lws_after = 0;
4615 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4616 delta = srv->cklen - (val_end - val_beg);
4617 sliding = (ctx.value.ptr - val_beg);
4618 hdr_beg += sliding;
4619 val_beg += sliding;
4620 next += sliding + delta;
4621 hdr_end += sliding + delta;
4622
4623 txn->flags &= ~TX_SCK_MASK;
4624 txn->flags |= TX_SCK_REPLACED;
4625 }
4626 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4627 /* insert the cookie name associated with this server
4628 * before existing cookie, and insert a delimiter between them..
4629 */
4630 int sliding, delta;
4631 ctx.value = ist2(val_beg, 0);
4632 ctx.lws_before = ctx.lws_after = 0;
4633 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4634 delta = srv->cklen + 1;
4635 sliding = (ctx.value.ptr - val_beg);
4636 hdr_beg += sliding;
4637 val_beg += sliding;
4638 next += sliding + delta;
4639 hdr_end += sliding + delta;
4640
4641 val_beg[srv->cklen] = COOKIE_DELIM;
4642 txn->flags &= ~TX_SCK_MASK;
4643 txn->flags |= TX_SCK_REPLACED;
4644 }
4645 }
4646 /* that's done for this cookie, check the next one on the same
4647 * line when next != hdr_end (only if is_cookie2).
4648 */
4649 }
4650 }
4651}
4652
Christopher Faulet25a02f62018-10-24 12:00:25 +02004653/*
4654 * Parses the Cache-Control and Pragma request header fields to determine if
4655 * the request may be served from the cache and/or if it is cacheable. Updates
4656 * s->txn->flags.
4657 */
4658void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4659{
4660 struct http_txn *txn = s->txn;
4661 struct htx *htx;
4662 int32_t pos;
4663 int pragma_found, cc_found, i;
4664
4665 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4666 return; /* nothing more to do here */
4667
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004668 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004669 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004670 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004671 struct htx_blk *blk = htx_get_blk(htx, pos);
4672 enum htx_blk_type type = htx_get_blk_type(blk);
4673 struct ist n, v;
4674
4675 if (type == HTX_BLK_EOH)
4676 break;
4677 if (type != HTX_BLK_HDR)
4678 continue;
4679
4680 n = htx_get_blk_name(htx, blk);
4681 v = htx_get_blk_value(htx, blk);
4682
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004683 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004684 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4685 pragma_found = 1;
4686 continue;
4687 }
4688 }
4689
4690 /* Don't use the cache and don't try to store if we found the
4691 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004692 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004693 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4694 txn->flags |= TX_CACHE_IGNORE;
4695 continue;
4696 }
4697
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004698 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004699 continue;
4700
4701 /* OK, right now we know we have a cache-control header */
4702 cc_found = 1;
4703 if (!v.len) /* no info */
4704 continue;
4705
4706 i = 0;
4707 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4708 !isspace((unsigned char)*(v.ptr+i)))
4709 i++;
4710
4711 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4712 * values after max-age, max-stale nor min-fresh, we simply don't
4713 * use the cache when they're specified.
4714 */
4715 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4716 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4717 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4718 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4719 txn->flags |= TX_CACHE_IGNORE;
4720 continue;
4721 }
4722
4723 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4724 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4725 continue;
4726 }
4727 }
4728
4729 /* RFC7234#5.4:
4730 * When the Cache-Control header field is also present and
4731 * understood in a request, Pragma is ignored.
4732 * When the Cache-Control header field is not present in a
4733 * request, caches MUST consider the no-cache request
4734 * pragma-directive as having the same effect as if
4735 * "Cache-Control: no-cache" were present.
4736 */
4737 if (!cc_found && pragma_found)
4738 txn->flags |= TX_CACHE_IGNORE;
4739}
4740
4741/*
4742 * Check if response is cacheable or not. Updates s->txn->flags.
4743 */
4744void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4745{
4746 struct http_txn *txn = s->txn;
4747 struct htx *htx;
4748 int32_t pos;
4749 int i;
4750
4751 if (txn->status < 200) {
4752 /* do not try to cache interim responses! */
4753 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4754 return;
4755 }
4756
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004757 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004758 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004759 struct htx_blk *blk = htx_get_blk(htx, pos);
4760 enum htx_blk_type type = htx_get_blk_type(blk);
4761 struct ist n, v;
4762
4763 if (type == HTX_BLK_EOH)
4764 break;
4765 if (type != HTX_BLK_HDR)
4766 continue;
4767
4768 n = htx_get_blk_name(htx, blk);
4769 v = htx_get_blk_value(htx, blk);
4770
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004771 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004772 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4773 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4774 return;
4775 }
4776 }
4777
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004778 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004779 continue;
4780
4781 /* OK, right now we know we have a cache-control header */
4782 if (!v.len) /* no info */
4783 continue;
4784
4785 i = 0;
4786 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4787 !isspace((unsigned char)*(v.ptr+i)))
4788 i++;
4789
4790 /* we have a complete value between v.ptr and (v.ptr+i) */
4791 if (i < v.len && *(v.ptr + i) == '=') {
4792 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4793 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4794 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4795 continue;
4796 }
4797
4798 /* we have something of the form no-cache="set-cookie" */
4799 if ((v.len >= 21) &&
4800 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4801 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4802 txn->flags &= ~TX_CACHE_COOK;
4803 continue;
4804 }
4805
4806 /* OK, so we know that either p2 points to the end of string or to a comma */
4807 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4808 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4809 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4810 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4811 return;
4812 }
4813
4814 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4815 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4816 continue;
4817 }
4818 }
4819}
4820
Christopher Faulet64159df2018-10-24 21:15:35 +02004821/* send a server's name with an outgoing request over an established connection.
4822 * Note: this function is designed to be called once the request has been
4823 * scheduled for being forwarded. This is the reason why the number of forwarded
4824 * bytes have to be adjusted.
4825 */
4826int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4827{
4828 struct htx *htx;
4829 struct http_hdr_ctx ctx;
4830 struct ist hdr;
4831 uint32_t data;
4832
4833 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004834 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004835 data = htx->data;
4836
4837 ctx.blk = NULL;
4838 while (http_find_header(htx, hdr, &ctx, 1))
4839 http_remove_header(htx, &ctx);
4840 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4841
4842 if (co_data(&s->req)) {
4843 if (data >= htx->data)
4844 c_rew(&s->req, data - htx->data);
4845 else
4846 c_adv(&s->req, htx->data - data);
4847 }
4848 return 0;
4849}
4850
Christopher Faulet377c5a52018-10-24 21:21:30 +02004851/*
4852 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4853 * for the current backend.
4854 *
4855 * It is assumed that the request is either a HEAD, GET, or POST and that the
4856 * uri_auth field is valid.
4857 *
4858 * Returns 1 if stats should be provided, otherwise 0.
4859 */
4860static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4861{
4862 struct uri_auth *uri_auth = backend->uri_auth;
4863 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004864 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004865 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004866
4867 if (!uri_auth)
4868 return 0;
4869
4870 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4871 return 0;
4872
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004873 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004874 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004875 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004876
4877 /* check URI size */
4878 if (uri_auth->uri_len > uri.len)
4879 return 0;
4880
4881 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4882 return 0;
4883
4884 return 1;
4885}
4886
4887/* This function prepares an applet to handle the stats. It can deal with the
4888 * "100-continue" expectation, check that admin rules are met for POST requests,
4889 * and program a response message if something was unexpected. It cannot fail
4890 * and always relies on the stats applet to complete the job. It does not touch
4891 * analysers nor counters, which are left to the caller. It does not touch
4892 * s->target which is supposed to already point to the stats applet. The caller
4893 * is expected to have already assigned an appctx to the stream.
4894 */
4895static int htx_handle_stats(struct stream *s, struct channel *req)
4896{
4897 struct stats_admin_rule *stats_admin_rule;
4898 struct stream_interface *si = &s->si[1];
4899 struct session *sess = s->sess;
4900 struct http_txn *txn = s->txn;
4901 struct http_msg *msg = &txn->req;
4902 struct uri_auth *uri_auth = s->be->uri_auth;
4903 const char *h, *lookup, *end;
4904 struct appctx *appctx;
4905 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004906 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004907
4908 appctx = si_appctx(si);
4909 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4910 appctx->st1 = appctx->st2 = 0;
4911 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4912 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4913 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4914 appctx->ctx.stats.flags |= STAT_CHUNKED;
4915
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004916 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004917 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004918 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4919 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004920
4921 for (h = lookup; h <= end - 3; h++) {
4922 if (memcmp(h, ";up", 3) == 0) {
4923 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4924 break;
4925 }
4926 }
4927
4928 if (uri_auth->refresh) {
4929 for (h = lookup; h <= end - 10; h++) {
4930 if (memcmp(h, ";norefresh", 10) == 0) {
4931 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4932 break;
4933 }
4934 }
4935 }
4936
4937 for (h = lookup; h <= end - 4; h++) {
4938 if (memcmp(h, ";csv", 4) == 0) {
4939 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4940 break;
4941 }
4942 }
4943
4944 for (h = lookup; h <= end - 6; h++) {
4945 if (memcmp(h, ";typed", 6) == 0) {
4946 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4947 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4948 break;
4949 }
4950 }
4951
4952 for (h = lookup; h <= end - 8; h++) {
4953 if (memcmp(h, ";st=", 4) == 0) {
4954 int i;
4955 h += 4;
4956 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4957 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4958 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4959 appctx->ctx.stats.st_code = i;
4960 break;
4961 }
4962 }
4963 break;
4964 }
4965 }
4966
4967 appctx->ctx.stats.scope_str = 0;
4968 appctx->ctx.stats.scope_len = 0;
4969 for (h = lookup; h <= end - 8; h++) {
4970 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4971 int itx = 0;
4972 const char *h2;
4973 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4974 const char *err;
4975
4976 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4977 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004978 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4979 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004980 if (*h == ';' || *h == '&' || *h == ' ')
4981 break;
4982 itx++;
4983 h++;
4984 }
4985
4986 if (itx > STAT_SCOPE_TXT_MAXLEN)
4987 itx = STAT_SCOPE_TXT_MAXLEN;
4988 appctx->ctx.stats.scope_len = itx;
4989
4990 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4991 memcpy(scope_txt, h2, itx);
4992 scope_txt[itx] = '\0';
4993 err = invalid_char(scope_txt);
4994 if (err) {
4995 /* bad char in search text => clear scope */
4996 appctx->ctx.stats.scope_str = 0;
4997 appctx->ctx.stats.scope_len = 0;
4998 }
4999 break;
5000 }
5001 }
5002
5003 /* now check whether we have some admin rules for this request */
5004 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5005 int ret = 1;
5006
5007 if (stats_admin_rule->cond) {
5008 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5009 ret = acl_pass(ret);
5010 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5011 ret = !ret;
5012 }
5013
5014 if (ret) {
5015 /* no rule, or the rule matches */
5016 appctx->ctx.stats.flags |= STAT_ADMIN;
5017 break;
5018 }
5019 }
5020
Christopher Faulet5d45e382019-02-27 15:15:23 +01005021 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5022 appctx->st0 = STAT_HTTP_HEAD;
5023 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005024 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005025 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005026 if (msg->msg_state < HTTP_MSG_DATA)
5027 req->analysers |= AN_REQ_HTTP_BODY;
5028 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005029 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005030 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005031 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5032 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5033 appctx->st0 = STAT_HTTP_LAST;
5034 }
5035 }
5036 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005037 /* Unsupported method */
5038 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5039 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5040 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005041 }
5042
5043 s->task->nice = -32; /* small boost for HTTP statistics */
5044 return 1;
5045}
5046
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005047void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5048{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005049 struct channel *req = &s->req;
5050 struct channel *res = &s->res;
5051 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005052 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005053 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005054 struct ist path, location;
5055 unsigned int flags;
5056 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005057
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005058 /*
5059 * Create the location
5060 */
5061 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005062
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005064 /* special prefix "/" means don't change URL */
5065 srv = __objt_server(s->target);
5066 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5067 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5068 return;
5069 }
5070
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005071 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005072 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005073 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005074 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005075 if (!path.ptr)
5076 return;
5077
5078 if (!chunk_memcat(&trash, path.ptr, path.len))
5079 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005080 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005081
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005082 /*
5083 * Create the 302 respone
5084 */
5085 htx = htx_from_buf(&res->buf);
5086 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5087 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5088 ist("HTTP/1.1"), ist("302"), ist("Found"));
5089 if (!sl)
5090 goto fail;
5091 sl->info.res.status = 302;
5092 s->txn->status = 302;
5093
5094 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5095 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5096 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5097 !htx_add_header(htx, ist("Location"), location))
5098 goto fail;
5099
5100 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5101 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005102
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005103 /*
5104 * Send the message
5105 */
5106 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005107 c_adv(res, data);
5108 res->total += data;
5109
5110 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005111 si_shutr(si);
5112 si_shutw(si);
5113 si->err_type = SI_ET_NONE;
5114 si->state = SI_ST_CLO;
5115
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005116 channel_auto_read(req);
5117 channel_abort(req);
5118 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005119 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005120 channel_auto_read(res);
5121 channel_auto_close(res);
5122
5123 if (!(s->flags & SF_ERR_MASK))
5124 s->flags |= SF_ERR_LOCAL;
5125 if (!(s->flags & SF_FINST_MASK))
5126 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005127
5128 /* FIXME: we should increase a counter of redirects per server and per backend. */
5129 srv_inc_sess_ctr(srv);
5130 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005131 return;
5132
5133 fail:
5134 /* If an error occurred, remove the incomplete HTTP response from the
5135 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005136 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005137}
5138
Christopher Fauletf2824e62018-10-01 12:12:37 +02005139/* This function terminates the request because it was completly analyzed or
5140 * because an error was triggered during the body forwarding.
5141 */
5142static void htx_end_request(struct stream *s)
5143{
5144 struct channel *chn = &s->req;
5145 struct http_txn *txn = s->txn;
5146
5147 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5148 now_ms, __FUNCTION__, s,
5149 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5150 s->req.analysers, s->res.analysers);
5151
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005152 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5153 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005154 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005155 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005156 goto end;
5157 }
5158
5159 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5160 return;
5161
5162 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005163 /* No need to read anymore, the request was completely parsed.
5164 * We can shut the read side unless we want to abort_on_close,
5165 * or we have a POST request. The issue with POST requests is
5166 * that some browsers still send a CRLF after the request, and
5167 * this CRLF must be read so that it does not remain in the kernel
5168 * buffers, otherwise a close could cause an RST on some systems
5169 * (eg: Linux).
5170 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005171 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172 channel_dont_read(chn);
5173
5174 /* if the server closes the connection, we want to immediately react
5175 * and close the socket to save packets and syscalls.
5176 */
5177 s->si[1].flags |= SI_FL_NOHALF;
5178
5179 /* In any case we've finished parsing the request so we must
5180 * disable Nagle when sending data because 1) we're not going
5181 * to shut this side, and 2) the server is waiting for us to
5182 * send pending data.
5183 */
5184 chn->flags |= CF_NEVER_WAIT;
5185
Christopher Fauletd01ce402019-01-02 17:44:13 +01005186 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5187 /* The server has not finished to respond, so we
5188 * don't want to move in order not to upset it.
5189 */
5190 return;
5191 }
5192
Christopher Fauletf2824e62018-10-01 12:12:37 +02005193 /* When we get here, it means that both the request and the
5194 * response have finished receiving. Depending on the connection
5195 * mode, we'll have to wait for the last bytes to leave in either
5196 * direction, and sometimes for a close to be effective.
5197 */
5198 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5199 /* Tunnel mode will not have any analyser so it needs to
5200 * poll for reads.
5201 */
5202 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005203 if (b_data(&chn->buf))
5204 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005205 txn->req.msg_state = HTTP_MSG_TUNNEL;
5206 }
5207 else {
5208 /* we're not expecting any new data to come for this
5209 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005210 *
5211 * However, there is an exception if the response
5212 * length is undefined. In this case, we need to wait
5213 * the close from the server. The response will be
5214 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005215 */
5216 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5217 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005218 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005219
5220 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5221 channel_shutr_now(chn);
5222 channel_shutw_now(chn);
5223 }
5224 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005225 goto check_channel_flags;
5226 }
5227
5228 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5229 http_msg_closing:
5230 /* nothing else to forward, just waiting for the output buffer
5231 * to be empty and for the shutw_now to take effect.
5232 */
5233 if (channel_is_empty(chn)) {
5234 txn->req.msg_state = HTTP_MSG_CLOSED;
5235 goto http_msg_closed;
5236 }
5237 else if (chn->flags & CF_SHUTW) {
5238 txn->req.err_state = txn->req.msg_state;
5239 txn->req.msg_state = HTTP_MSG_ERROR;
5240 goto end;
5241 }
5242 return;
5243 }
5244
5245 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5246 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005247 /* if we don't know whether the server will close, we need to hard close */
5248 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5249 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005250 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005251 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005252 channel_dont_read(chn);
5253 goto end;
5254 }
5255
5256 check_channel_flags:
5257 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5258 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5259 /* if we've just closed an output, let's switch */
5260 txn->req.msg_state = HTTP_MSG_CLOSING;
5261 goto http_msg_closing;
5262 }
5263
5264 end:
5265 chn->analysers &= AN_REQ_FLT_END;
5266 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5267 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5268 channel_auto_close(chn);
5269 channel_auto_read(chn);
5270}
5271
5272
5273/* This function terminates the response because it was completly analyzed or
5274 * because an error was triggered during the body forwarding.
5275 */
5276static void htx_end_response(struct stream *s)
5277{
5278 struct channel *chn = &s->res;
5279 struct http_txn *txn = s->txn;
5280
5281 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5282 now_ms, __FUNCTION__, s,
5283 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5284 s->req.analysers, s->res.analysers);
5285
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005286 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5287 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005288 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005289 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005290 goto end;
5291 }
5292
5293 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5294 return;
5295
5296 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5297 /* In theory, we don't need to read anymore, but we must
5298 * still monitor the server connection for a possible close
5299 * while the request is being uploaded, so we don't disable
5300 * reading.
5301 */
5302 /* channel_dont_read(chn); */
5303
5304 if (txn->req.msg_state < HTTP_MSG_DONE) {
5305 /* The client seems to still be sending data, probably
5306 * because we got an error response during an upload.
5307 * We have the choice of either breaking the connection
5308 * or letting it pass through. Let's do the later.
5309 */
5310 return;
5311 }
5312
5313 /* When we get here, it means that both the request and the
5314 * response have finished receiving. Depending on the connection
5315 * mode, we'll have to wait for the last bytes to leave in either
5316 * direction, and sometimes for a close to be effective.
5317 */
5318 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5319 channel_auto_read(chn);
5320 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005321 if (b_data(&chn->buf))
5322 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005323 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5324 }
5325 else {
5326 /* we're not expecting any new data to come for this
5327 * transaction, so we can close it.
5328 */
5329 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5330 channel_shutr_now(chn);
5331 channel_shutw_now(chn);
5332 }
5333 }
5334 goto check_channel_flags;
5335 }
5336
5337 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5338 http_msg_closing:
5339 /* nothing else to forward, just waiting for the output buffer
5340 * to be empty and for the shutw_now to take effect.
5341 */
5342 if (channel_is_empty(chn)) {
5343 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5344 goto http_msg_closed;
5345 }
5346 else if (chn->flags & CF_SHUTW) {
5347 txn->rsp.err_state = txn->rsp.msg_state;
5348 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005349 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005350 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005351 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005352 goto end;
5353 }
5354 return;
5355 }
5356
5357 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5358 http_msg_closed:
5359 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005360 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005361 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005362 goto end;
5363 }
5364
5365 check_channel_flags:
5366 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5367 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5368 /* if we've just closed an output, let's switch */
5369 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5370 goto http_msg_closing;
5371 }
5372
5373 end:
5374 chn->analysers &= AN_RES_FLT_END;
5375 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5376 chn->analysers |= AN_RES_FLT_XFER_DATA;
5377 channel_auto_close(chn);
5378 channel_auto_read(chn);
5379}
5380
Christopher Faulet0f226952018-10-22 09:29:56 +02005381void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5382 int finst, const struct buffer *msg)
5383{
5384 channel_auto_read(si_oc(si));
5385 channel_abort(si_oc(si));
5386 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005387 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005388 channel_auto_close(si_ic(si));
5389 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005390
5391 /* <msg> is an HTX structure. So we copy it in the response's
5392 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005393 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005394 struct channel *chn = si_ic(si);
5395 struct htx *htx;
5396
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005397 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005398 chn->buf.data = msg->data;
5399 memcpy(chn->buf.area, msg->area, msg->data);
5400 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005401 c_adv(chn, htx->data);
5402 chn->total += htx->data;
5403 }
5404 if (!(s->flags & SF_ERR_MASK))
5405 s->flags |= err;
5406 if (!(s->flags & SF_FINST_MASK))
5407 s->flags |= finst;
5408}
5409
5410void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5411{
5412 channel_auto_read(&s->req);
5413 channel_abort(&s->req);
5414 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005415 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5416 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005417
5418 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005419
5420 /* <msg> is an HTX structure. So we copy it in the response's
5421 * channel */
5422 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005423 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005424 struct channel *chn = &s->res;
5425 struct htx *htx;
5426
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005427 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005428 chn->buf.data = msg->data;
5429 memcpy(chn->buf.area, msg->area, msg->data);
5430 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005431 c_adv(chn, htx->data);
5432 chn->total += htx->data;
5433 }
5434
5435 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5436 channel_auto_read(&s->res);
5437 channel_auto_close(&s->res);
5438 channel_shutr_now(&s->res);
5439}
5440
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005441struct buffer *htx_error_message(struct stream *s)
5442{
5443 const int msgnum = http_get_status_idx(s->txn->status);
5444
5445 if (s->be->errmsg[msgnum].area)
5446 return &s->be->errmsg[msgnum];
5447 else if (strm_fe(s)->errmsg[msgnum].area)
5448 return &strm_fe(s)->errmsg[msgnum];
5449 else
5450 return &htx_err_chunks[msgnum];
5451}
5452
5453
Christopher Faulet4a28a532019-03-01 11:19:40 +01005454/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5455 * on success and -1 on error.
5456 */
5457static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5458{
5459 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5460 * then we must send an HTTP/1.1 100 Continue intermediate response.
5461 */
5462 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5463 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5464 struct ist hdr = { .ptr = "Expect", .len = 6 };
5465 struct http_hdr_ctx ctx;
5466
5467 ctx.blk = NULL;
5468 /* Expect is allowed in 1.1, look for it */
5469 if (http_find_header(htx, hdr, &ctx, 0) &&
5470 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5471 if (htx_reply_100_continue(s) == -1)
5472 return -1;
5473 http_remove_header(htx, &ctx);
5474 }
5475 }
5476 return 0;
5477}
5478
Christopher Faulet23a3c792018-11-28 10:01:23 +01005479/* Send a 100-Continue response to the client. It returns 0 on success and -1
5480 * on error. The response channel is updated accordingly.
5481 */
5482static int htx_reply_100_continue(struct stream *s)
5483{
5484 struct channel *res = &s->res;
5485 struct htx *htx = htx_from_buf(&res->buf);
5486 struct htx_sl *sl;
5487 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5488 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5489 size_t data;
5490
5491 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5492 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5493 if (!sl)
5494 goto fail;
5495 sl->info.res.status = 100;
5496
Christopher Faulet9869f932019-06-26 14:23:54 +02005497 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005498 goto fail;
5499
5500 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005501 c_adv(res, data);
5502 res->total += data;
5503 return 0;
5504
5505 fail:
5506 /* If an error occurred, remove the incomplete HTTP response from the
5507 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005508 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005509 return -1;
5510}
5511
Christopher Faulet12c51e22018-11-28 15:59:42 +01005512
5513/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5514 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5515 * error. The response channel is updated accordingly.
5516 */
5517static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5518{
5519 struct channel *res = &s->res;
5520 struct htx *htx = htx_from_buf(&res->buf);
5521 struct htx_sl *sl;
5522 struct ist code, body;
5523 int status;
5524 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5525 size_t data;
5526
5527 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5528 status = 401;
5529 code = ist("401");
5530 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5531 "You need a valid user and password to access this content.\n"
5532 "</body></html>\n");
5533 }
5534 else {
5535 status = 407;
5536 code = ist("407");
5537 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5538 "You need a valid user and password to access this content.\n"
5539 "</body></html>\n");
5540 }
5541
5542 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5543 ist("HTTP/1.1"), code, ist("Unauthorized"));
5544 if (!sl)
5545 goto fail;
5546 sl->info.res.status = status;
5547 s->txn->status = status;
5548
5549 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5550 goto fail;
5551
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005552 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5553 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005554 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005555 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5556 goto fail;
5557 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5558 goto fail;
5559 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005560 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005561 if (!htx_add_endof(htx, HTX_BLK_EOH))
5562 goto fail;
5563
5564 while (body.len) {
5565 size_t sent = htx_add_data(htx, body);
5566 if (!sent)
5567 goto fail;
5568 body.ptr += sent;
5569 body.len -= sent;
5570 }
5571
5572 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005573 goto fail;
5574
5575 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005576 c_adv(res, data);
5577 res->total += data;
5578
5579 channel_auto_read(&s->req);
5580 channel_abort(&s->req);
5581 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005582 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005583
5584 res->wex = tick_add_ifset(now_ms, res->wto);
5585 channel_auto_read(res);
5586 channel_auto_close(res);
5587 channel_shutr_now(res);
5588 return 0;
5589
5590 fail:
5591 /* If an error occurred, remove the incomplete HTTP response from the
5592 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005593 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005594 return -1;
5595}
5596
Christopher Faulet0f226952018-10-22 09:29:56 +02005597/*
5598 * Capture headers from message <htx> according to header list <cap_hdr>, and
5599 * fill the <cap> pointers appropriately.
5600 */
5601static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5602{
5603 struct cap_hdr *h;
5604 int32_t pos;
5605
Christopher Fauleta3f15502019-05-13 15:27:23 +02005606 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005607 struct htx_blk *blk = htx_get_blk(htx, pos);
5608 enum htx_blk_type type = htx_get_blk_type(blk);
5609 struct ist n, v;
5610
5611 if (type == HTX_BLK_EOH)
5612 break;
5613 if (type != HTX_BLK_HDR)
5614 continue;
5615
5616 n = htx_get_blk_name(htx, blk);
5617
5618 for (h = cap_hdr; h; h = h->next) {
5619 if (h->namelen && (h->namelen == n.len) &&
5620 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5621 if (cap[h->index] == NULL)
5622 cap[h->index] =
5623 pool_alloc(h->pool);
5624
5625 if (cap[h->index] == NULL) {
5626 ha_alert("HTTP capture : out of memory.\n");
5627 break;
5628 }
5629
5630 v = htx_get_blk_value(htx, blk);
5631 if (v.len > h->len)
5632 v.len = h->len;
5633
5634 memcpy(cap[h->index], v.ptr, v.len);
5635 cap[h->index][v.len]=0;
5636 }
5637 }
5638 }
5639}
5640
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005641/* Delete a value in a header between delimiters <from> and <next>. The header
5642 * itself is delimited by <start> and <end> pointers. The number of characters
5643 * displaced is returned, and the pointer to the first delimiter is updated if
5644 * required. The function tries as much as possible to respect the following
5645 * principles :
5646 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5647 * in which case <next> is simply removed
5648 * - set exactly one space character after the new first delimiter, unless there
5649 * are not enough characters in the block being moved to do so.
5650 * - remove unneeded spaces before the previous delimiter and after the new
5651 * one.
5652 *
5653 * It is the caller's responsibility to ensure that :
5654 * - <from> points to a valid delimiter or <start> ;
5655 * - <next> points to a valid delimiter or <end> ;
5656 * - there are non-space chars before <from>.
5657 */
5658static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5659{
5660 char *prev = *from;
5661
5662 if (prev == start) {
5663 /* We're removing the first value. eat the semicolon, if <next>
5664 * is lower than <end> */
5665 if (next < end)
5666 next++;
5667
5668 while (next < end && HTTP_IS_SPHT(*next))
5669 next++;
5670 }
5671 else {
5672 /* Remove useless spaces before the old delimiter. */
5673 while (HTTP_IS_SPHT(*(prev-1)))
5674 prev--;
5675 *from = prev;
5676
5677 /* copy the delimiter and if possible a space if we're
5678 * not at the end of the line.
5679 */
5680 if (next < end) {
5681 *prev++ = *next++;
5682 if (prev + 1 < next)
5683 *prev++ = ' ';
5684 while (next < end && HTTP_IS_SPHT(*next))
5685 next++;
5686 }
5687 }
5688 memmove(prev, next, end - next);
5689 return (prev - next);
5690}
5691
Christopher Faulet0f226952018-10-22 09:29:56 +02005692
5693/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005694 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005695 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005696static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005697{
5698 struct ist dst = ist2(str, 0);
5699
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005700 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005701 goto end;
5702 if (dst.len + 1 > len)
5703 goto end;
5704 dst.ptr[dst.len++] = ' ';
5705
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005707 goto end;
5708 if (dst.len + 1 > len)
5709 goto end;
5710 dst.ptr[dst.len++] = ' ';
5711
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005712 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005713 end:
5714 return dst.len;
5715}
5716
Christopher Fauletf0523542018-10-24 11:06:58 +02005717/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005718 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005719 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005720static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005721{
5722 struct ist dst = ist2(str, 0);
5723
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005724 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005725 goto end;
5726 if (dst.len + 1 > len)
5727 goto end;
5728 dst.ptr[dst.len++] = ' ';
5729
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005730 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005731 goto end;
5732 if (dst.len + 1 > len)
5733 goto end;
5734 dst.ptr[dst.len++] = ' ';
5735
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005736 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005737 end:
5738 return dst.len;
5739}
5740
5741
Christopher Faulet0f226952018-10-22 09:29:56 +02005742/*
5743 * Print a debug line with a start line.
5744 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005745static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005746{
5747 struct session *sess = strm_sess(s);
5748 int max;
5749
5750 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5751 dir,
5752 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5753 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5754
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005755 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005756 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005757 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005758 trash.area[trash.data++] = ' ';
5759
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005760 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005761 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005762 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005763 trash.area[trash.data++] = ' ';
5764
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005765 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005766 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005767 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005768 trash.area[trash.data++] = '\n';
5769
5770 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5771}
5772
5773/*
5774 * Print a debug line with a header.
5775 */
5776static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5777{
5778 struct session *sess = strm_sess(s);
5779 int max;
5780
5781 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5782 dir,
5783 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5784 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5785
5786 max = n.len;
5787 UBOUND(max, trash.size - trash.data - 3);
5788 chunk_memcat(&trash, n.ptr, max);
5789 trash.area[trash.data++] = ':';
5790 trash.area[trash.data++] = ' ';
5791
5792 max = v.len;
5793 UBOUND(max, trash.size - trash.data - 1);
5794 chunk_memcat(&trash, v.ptr, max);
5795 trash.area[trash.data++] = '\n';
5796
5797 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5798}
5799
5800
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005801__attribute__((constructor))
5802static void __htx_protocol_init(void)
5803{
5804}
5805
5806
5807/*
5808 * Local variables:
5809 * c-indent-level: 8
5810 * c-basic-offset: 8
5811 * End:
5812 */