blob: 1ad4aa86c7e2ede1aaa7e70ccf2f2b59e1864bb4 [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) &&
527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
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 Fauletfec7bd12018-10-24 11:17:50 +02002058 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002059 goto return_bad_resp;
2060
2061 txn->flags &= ~TX_SCK_MASK;
2062 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2063 /* the server did not change, only the date was updated */
2064 txn->flags |= TX_SCK_UPDATED;
2065 else
2066 txn->flags |= TX_SCK_INSERTED;
2067
2068 /* Here, we will tell an eventual cache on the client side that we don't
2069 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2070 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2071 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2072 */
2073 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2074
2075 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2076
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002077 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002078 goto return_bad_resp;
2079 }
2080 }
2081
2082 /*
2083 * Check if result will be cacheable with a cookie.
2084 * We'll block the response if security checks have caught
2085 * nasty things such as a cacheable cookie.
2086 */
2087 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2088 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2089 (s->be->options & PR_O_CHK_CACHE)) {
2090 /* we're in presence of a cacheable response containing
2091 * a set-cookie header. We'll block it as requested by
2092 * the 'checkcache' option, and send an alert.
2093 */
2094 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002095 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002096
Olivier Houcharda798bf52019-03-08 18:52:00 +01002097 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2098 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002099 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002100 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101
2102 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2103 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2104 send_log(s->be, LOG_ALERT,
2105 "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 goto return_srv_prx_502;
2108 }
2109
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002110 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002111 /* Always enter in the body analyzer */
2112 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2113 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2114
2115 /* if the user wants to log as soon as possible, without counting
2116 * bytes from the server, then this is the right moment. We have
2117 * to temporarily assign bytes_out to log what we currently have.
2118 */
2119 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2120 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002121 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002122 s->do_log(s);
2123 s->logs.bytes_out = 0;
2124 }
2125 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002126
2127 return_bad_resp:
2128 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002129 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002130 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002131 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002132 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002133
2134 return_srv_prx_502:
2135 rep->analysers &= AN_RES_FLT_END;
2136 txn->status = 502;
2137 s->logs.t_data = -1; /* was not a valid response */
2138 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002139 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002140 if (!(s->flags & SF_ERR_MASK))
2141 s->flags |= SF_ERR_PRXCOND;
2142 if (!(s->flags & SF_FINST_MASK))
2143 s->flags |= SF_FINST_H;
2144 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002145}
2146
2147/* This function is an analyser which forwards response body (including chunk
2148 * sizes if any). It is called as soon as we must forward, even if we forward
2149 * zero byte. The only situation where it must not be called is when we're in
2150 * tunnel mode and we want to forward till the close. It's used both to forward
2151 * remaining data and to resync after end of body. It expects the msg_state to
2152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2153 * read more data, or 1 once we can go on with next request or end the stream.
2154 *
2155 * It is capable of compressing response data both in content-length mode and
2156 * in chunked mode. The state machines follows different flows depending on
2157 * whether content-length and chunked modes are used, since there are no
2158 * trailers in content-length :
2159 *
2160 * chk-mode cl-mode
2161 * ,----- BODY -----.
2162 * / \
2163 * V size > 0 V chk-mode
2164 * .--> SIZE -------------> DATA -------------> CRLF
2165 * | | size == 0 | last byte |
2166 * | v final crlf v inspected |
2167 * | TRAILERS -----------> DONE |
2168 * | |
2169 * `----------------------------------------------'
2170 *
2171 * Compression only happens in the DATA state, and must be flushed in final
2172 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2173 * is performed at once on final states for all bytes parsed, or when leaving
2174 * on missing data.
2175 */
2176int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2177{
2178 struct session *sess = s->sess;
2179 struct http_txn *txn = s->txn;
2180 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002181 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002182 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183
2184 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2185 now_ms, __FUNCTION__,
2186 s,
2187 res,
2188 res->rex, res->wex,
2189 res->flags,
2190 ci_data(res),
2191 res->analysers);
2192
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002193 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002194
2195 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002196 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197 /* Output closed while we were sending data. We must abort and
2198 * wake the other side up.
2199 */
2200 msg->err_state = msg->msg_state;
2201 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002202 htx_end_response(s);
2203 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 return 1;
2205 }
2206
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 if (msg->msg_state == HTTP_MSG_BODY)
2208 msg->msg_state = HTTP_MSG_DATA;
2209
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210 /* in most states, we should abort in case of early close */
2211 channel_auto_close(res);
2212
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002214 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002215 if (res->flags & CF_EOI)
2216 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002217 }
2218 else {
2219 /* We can't process the buffer's contents yet */
2220 res->flags |= CF_WAKE_WRITE;
2221 goto missing_data_or_waiting;
2222 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002223 }
2224
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002225 if (msg->msg_state >= HTTP_MSG_ENDING)
2226 goto ending;
2227
2228 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2229 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2230 msg->msg_state = HTTP_MSG_ENDING;
2231 goto ending;
2232 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002233
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002234 /* Forward input data. We get it by removing all outgoing data not
2235 * forwarded yet from HTX data size. If there are some data filters, we
2236 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002237 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002238 if (HAS_RSP_DATA_FILTERS(s)) {
2239 ret = flt_http_payload(s, msg, htx->data);
2240 if (ret < 0)
2241 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002242 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002243 }
2244 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002245 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002246 if (msg->flags & HTTP_MSGF_XFER_LEN)
2247 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002248 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002249
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002250 if (htx->data != co_data(res))
2251 goto missing_data_or_waiting;
2252
2253 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2254 msg->msg_state = HTTP_MSG_ENDING;
2255 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 }
2257
Christopher Faulet9768c262018-10-22 09:34:31 +02002258 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002259 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2260 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002261 */
2262 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2263 goto missing_data_or_waiting;
2264
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002265 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002266
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002267 ending:
2268 /* other states, ENDING...TUNNEL */
2269 if (msg->msg_state >= HTTP_MSG_DONE)
2270 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002271
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002272 if (HAS_RSP_DATA_FILTERS(s)) {
2273 ret = flt_http_end(s, msg);
2274 if (ret <= 0) {
2275 if (!ret)
2276 goto missing_data_or_waiting;
2277 goto return_bad_res;
2278 }
2279 }
2280
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002281 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2282 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2283 msg->msg_state = HTTP_MSG_TUNNEL;
2284 goto ending;
2285 }
2286 else {
2287 msg->msg_state = HTTP_MSG_DONE;
2288 res->to_forward = 0;
2289 }
2290
2291 done:
2292
2293 channel_dont_close(res);
2294
Christopher Fauletf2824e62018-10-01 12:12:37 +02002295 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002297 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2299 if (res->flags & CF_SHUTW) {
2300 /* response errors are most likely due to the
2301 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002302 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002303 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002304 goto return_bad_res;
2305 }
2306 return 1;
2307 }
2308 return 0;
2309
2310 missing_data_or_waiting:
2311 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002312 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002313
Christopher Faulet47365272018-10-31 17:40:50 +01002314 if (htx->flags & HTX_FL_PARSING_ERROR)
2315 goto return_bad_res;
2316
Christopher Faulete0768eb2018-10-03 16:38:02 +02002317 /* stop waiting for data if the input is closed before the end. If the
2318 * client side was already closed, it means that the client has aborted,
2319 * so we don't want to count this as a server abort. Otherwise it's a
2320 * server abort.
2321 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002322 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002323 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002324 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002325 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002326 if (htx_is_empty(htx))
2327 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 }
2329
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 /* When TE: chunked is used, we need to get there again to parse
2331 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002332 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2333 * are filters registered on the stream, we don't want to forward a
2334 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002336 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 channel_dont_close(res);
2338
2339 /* We know that more data are expected, but we couldn't send more that
2340 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2341 * system knows it must not set a PUSH on this first part. Interactive
2342 * modes are already handled by the stream sock layer. We must not do
2343 * this in content-length mode because it could present the MSG_MORE
2344 * flag with the last block of forwarded data, which would cause an
2345 * additional delay to be observed by the receiver.
2346 */
2347 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2348 res->flags |= CF_EXPECT_MORE;
2349
2350 /* the stream handler will take care of timeouts and errors */
2351 return 0;
2352
Christopher Faulet93e02d82019-03-08 14:18:50 +01002353 return_srv_abort:
2354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2355 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002356 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002357 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2358 if (!(s->flags & SF_ERR_MASK))
2359 s->flags |= SF_ERR_SRVCL;
2360 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002361
Christopher Faulet93e02d82019-03-08 14:18:50 +01002362 return_cli_abort:
2363 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2364 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002365 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002366 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2367 if (!(s->flags & SF_ERR_MASK))
2368 s->flags |= SF_ERR_CLICL;
2369 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002370
Christopher Faulet93e02d82019-03-08 14:18:50 +01002371 return_bad_res:
2372 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2373 if (objt_server(s->target)) {
2374 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2375 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2376 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002377 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002378 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002379
Christopher Faulet93e02d82019-03-08 14:18:50 +01002380 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002381 txn->rsp.err_state = txn->rsp.msg_state;
2382 txn->rsp.msg_state = HTTP_MSG_ERROR;
2383 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002384 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002385 res->analysers &= AN_RES_FLT_END;
2386 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 +02002387 if (!(s->flags & SF_FINST_MASK))
2388 s->flags |= SF_FINST_D;
2389 return 0;
2390}
2391
Christopher Fauletf2824e62018-10-01 12:12:37 +02002392/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002393 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002394 * as too large a request to build a valid response.
2395 */
2396int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2397{
Christopher Faulet99daf282018-11-28 22:58:13 +01002398 struct channel *req = &s->req;
2399 struct channel *res = &s->res;
2400 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002401 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002403 struct ist status, reason, location;
2404 unsigned int flags;
2405 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002406 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407
2408 chunk = alloc_trash_chunk();
2409 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002410 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 /*
2413 * Create the location
2414 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002415 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002417 case REDIRECT_TYPE_SCHEME: {
2418 struct http_hdr_ctx ctx;
2419 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420
Christopher Faulet99daf282018-11-28 22:58:13 +01002421 host = ist("");
2422 ctx.blk = NULL;
2423 if (http_find_header(htx, ist("Host"), &ctx, 0))
2424 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002425
Christopher Faulet297fbb42019-05-13 14:41:27 +02002426 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 path = http_get_path(htx_sl_req_uri(sl));
2428 /* build message using path */
2429 if (path.ptr) {
2430 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2431 int qs = 0;
2432 while (qs < path.len) {
2433 if (*(path.ptr + qs) == '?') {
2434 path.len = qs;
2435 break;
2436 }
2437 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439 }
2440 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002441 else
2442 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002443
Christopher Faulet99daf282018-11-28 22:58:13 +01002444 if (rule->rdr_str) { /* this is an old "redirect" rule */
2445 /* add scheme */
2446 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2447 goto fail;
2448 }
2449 else {
2450 /* add scheme with executing log format */
2451 chunk->data += build_logline(s, chunk->area + chunk->data,
2452 chunk->size - chunk->data,
2453 &rule->rdr_fmt);
2454 }
2455 /* add "://" + host + path */
2456 if (!chunk_memcat(chunk, "://", 3) ||
2457 !chunk_memcat(chunk, host.ptr, host.len) ||
2458 !chunk_memcat(chunk, path.ptr, path.len))
2459 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002460
Christopher Faulet99daf282018-11-28 22:58:13 +01002461 /* append a slash at the end of the location if needed and missing */
2462 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2463 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2464 if (chunk->data + 1 >= chunk->size)
2465 goto fail;
2466 chunk->area[chunk->data++] = '/';
2467 }
2468 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002469 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002470
Christopher Faulet99daf282018-11-28 22:58:13 +01002471 case REDIRECT_TYPE_PREFIX: {
2472 struct ist path;
2473
Christopher Faulet297fbb42019-05-13 14:41:27 +02002474 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002475 path = http_get_path(htx_sl_req_uri(sl));
2476 /* build message using path */
2477 if (path.ptr) {
2478 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2479 int qs = 0;
2480 while (qs < path.len) {
2481 if (*(path.ptr + qs) == '?') {
2482 path.len = qs;
2483 break;
2484 }
2485 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002486 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002487 }
2488 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002489 else
2490 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002491
Christopher Faulet99daf282018-11-28 22:58:13 +01002492 if (rule->rdr_str) { /* this is an old "redirect" rule */
2493 /* add prefix. Note that if prefix == "/", we don't want to
2494 * add anything, otherwise it makes it hard for the user to
2495 * configure a self-redirection.
2496 */
2497 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2498 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2499 goto fail;
2500 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002501 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002502 else {
2503 /* add prefix with executing log format */
2504 chunk->data += build_logline(s, chunk->area + chunk->data,
2505 chunk->size - chunk->data,
2506 &rule->rdr_fmt);
2507 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 /* add path */
2510 if (!chunk_memcat(chunk, path.ptr, path.len))
2511 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002512
Christopher Faulet99daf282018-11-28 22:58:13 +01002513 /* append a slash at the end of the location if needed and missing */
2514 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2515 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2516 if (chunk->data + 1 >= chunk->size)
2517 goto fail;
2518 chunk->area[chunk->data++] = '/';
2519 }
2520 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002521 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002522 case REDIRECT_TYPE_LOCATION:
2523 default:
2524 if (rule->rdr_str) { /* this is an old "redirect" rule */
2525 /* add location */
2526 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2527 goto fail;
2528 }
2529 else {
2530 /* add location with executing log format */
2531 chunk->data += build_logline(s, chunk->area + chunk->data,
2532 chunk->size - chunk->data,
2533 &rule->rdr_fmt);
2534 }
2535 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002536 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002537 location = ist2(chunk->area, chunk->data);
2538
2539 /*
2540 * Create the 30x response
2541 */
2542 switch (rule->code) {
2543 case 308:
2544 status = ist("308");
2545 reason = ist("Permanent Redirect");
2546 break;
2547 case 307:
2548 status = ist("307");
2549 reason = ist("Temporary Redirect");
2550 break;
2551 case 303:
2552 status = ist("303");
2553 reason = ist("See Other");
2554 break;
2555 case 301:
2556 status = ist("301");
2557 reason = ist("Moved Permanently");
2558 break;
2559 case 302:
2560 default:
2561 status = ist("302");
2562 reason = ist("Found");
2563 break;
2564 }
2565
Christopher Faulet08e66462019-05-23 16:44:59 +02002566 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2567 close = 1;
2568
Christopher Faulet99daf282018-11-28 22:58:13 +01002569 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002570 /* Trim any possible response */
2571 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002572 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2573 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2574 if (!sl)
2575 goto fail;
2576 sl->info.res.status = rule->code;
2577 s->txn->status = rule->code;
2578
Christopher Faulet08e66462019-05-23 16:44:59 +02002579 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2580 goto fail;
2581
2582 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002583 !htx_add_header(htx, ist("Location"), location))
2584 goto fail;
2585
2586 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2587 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2588 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002589 }
2590
2591 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002592 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2593 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002594 }
2595
Christopher Faulet99daf282018-11-28 22:58:13 +01002596 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2597 goto fail;
2598
Kevin Zhu0fd70882020-01-07 09:42:55 +01002599 htx_to_buf(htx, &res->buf);
2600
Christopher Fauletf2824e62018-10-01 12:12:37 +02002601 /* let's log the request time */
2602 s->logs.tv_request = now;
2603
Christopher Faulet99daf282018-11-28 22:58:13 +01002604 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002605 c_adv(res, data);
2606 res->total += data;
2607
2608 channel_auto_read(req);
2609 channel_abort(req);
2610 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002611 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002612
2613 res->wex = tick_add_ifset(now_ms, res->wto);
2614 channel_auto_read(res);
2615 channel_auto_close(res);
2616 channel_shutr_now(res);
2617
2618 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002619
2620 if (!(s->flags & SF_ERR_MASK))
2621 s->flags |= SF_ERR_LOCAL;
2622 if (!(s->flags & SF_FINST_MASK))
2623 s->flags |= SF_FINST_R;
2624
Christopher Faulet99daf282018-11-28 22:58:13 +01002625 free_trash_chunk(chunk);
2626 return 1;
2627
2628 fail:
2629 /* If an error occurred, remove the incomplete HTTP response from the
2630 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002631 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002632 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002633 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002634}
2635
Christopher Faulet72333522018-10-24 11:25:02 +02002636int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2637 struct ist name, const char *str, struct my_regex *re, int action)
2638{
2639 struct http_hdr_ctx ctx;
2640 struct buffer *output = get_trash_chunk();
2641
2642 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2643 ctx.blk = NULL;
2644 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2645 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2646 continue;
2647
2648 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2649 if (output->data == -1)
2650 return -1;
2651 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2652 return -1;
2653 }
2654 return 0;
2655}
2656
2657static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2658 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2659{
2660 struct buffer *replace;
2661 int ret = -1;
2662
2663 replace = alloc_trash_chunk();
2664 if (!replace)
2665 goto leave;
2666
2667 replace->data = build_logline(s, replace->area, replace->size, fmt);
2668 if (replace->data >= replace->size - 1)
2669 goto leave;
2670
2671 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2672
2673 leave:
2674 free_trash_chunk(replace);
2675 return ret;
2676}
2677
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002678
2679/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2680 * on success and -1 on error. The response channel is updated accordingly.
2681 */
2682static int htx_reply_103_early_hints(struct channel *res)
2683{
2684 struct htx *htx = htx_from_buf(&res->buf);
2685 size_t data;
2686
Christopher Faulet9869f932019-06-26 14:23:54 +02002687 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002688 /* If an error occurred during an Early-hint rule,
2689 * remove the incomplete HTTP 103 response from the
2690 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002691 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 return -1;
2693 }
2694
2695 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002696 c_adv(res, data);
2697 res->total += data;
2698 return 0;
2699}
2700
Christopher Faulet6eb92892018-11-15 16:39:29 +01002701/*
2702 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2703 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002704 * If <early_hints> is 0, it is starts a new response by adding the start
2705 * line. If an error occurred -1 is returned. On success 0 is returned. The
2706 * channel is not updated here. It must be done calling the function
2707 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002708 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002709static 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 +01002710{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002711 struct channel *res = &s->res;
2712 struct htx *htx = htx_from_buf(&res->buf);
2713 struct buffer *value = alloc_trash_chunk();
2714
Christopher Faulet6eb92892018-11-15 16:39:29 +01002715 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002716 struct htx_sl *sl;
2717 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2718 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2719
2720 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2721 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2722 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002723 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002724 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002725 }
2726
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002727 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2728 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002729 goto fail;
2730
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002731 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002732 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002733
2734 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002735 /* If an error occurred during an Early-hint rule, remove the incomplete
2736 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002737 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002738 free_trash_chunk(value);
2739 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002740}
2741
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002742/* This function executes one of the set-{method,path,query,uri} actions. It
2743 * takes the string from the variable 'replace' with length 'len', then modifies
2744 * the relevant part of the request line accordingly. Then it updates various
2745 * pointers to the next elements which were moved, and the total buffer length.
2746 * It finds the action to be performed in p[2], previously filled by function
2747 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2748 * error, though this can be revisited when this code is finally exploited.
2749 *
2750 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2751 * query string and 3 to replace uri.
2752 *
2753 * In query string case, the mark question '?' must be set at the start of the
2754 * string by the caller, event if the replacement query string is empty.
2755 */
2756int htx_req_replace_stline(int action, const char *replace, int len,
2757 struct proxy *px, struct stream *s)
2758{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002759 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002760
2761 switch (action) {
2762 case 0: // method
2763 if (!http_replace_req_meth(htx, ist2(replace, len)))
2764 return -1;
2765 break;
2766
2767 case 1: // path
2768 if (!http_replace_req_path(htx, ist2(replace, len)))
2769 return -1;
2770 break;
2771
2772 case 2: // query
2773 if (!http_replace_req_query(htx, ist2(replace, len)))
2774 return -1;
2775 break;
2776
2777 case 3: // uri
2778 if (!http_replace_req_uri(htx, ist2(replace, len)))
2779 return -1;
2780 break;
2781
2782 default:
2783 return -1;
2784 }
2785 return 0;
2786}
2787
2788/* This function replace the HTTP status code and the associated message. The
2789 * variable <status> contains the new status code. This function never fails.
2790 */
2791void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2792{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002793 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002794 char *res;
2795
2796 chunk_reset(&trash);
2797 res = ultoa_o(status, trash.area, trash.size);
2798 trash.data = res - trash.area;
2799
2800 /* Do we have a custom reason format string? */
2801 if (reason == NULL)
2802 reason = http_get_reason(status);
2803
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002804 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002805 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2806}
2807
Christopher Faulet3e964192018-10-24 11:39:23 +02002808/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2809 * transaction <txn>. Returns the verdict of the first rule that prevents
2810 * further processing of the request (auth, deny, ...), and defaults to
2811 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2812 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2813 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2814 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2815 * status.
2816 */
2817static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2818 struct stream *s, int *deny_status)
2819{
2820 struct session *sess = strm_sess(s);
2821 struct http_txn *txn = s->txn;
2822 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002823 struct act_rule *rule;
2824 struct http_hdr_ctx ctx;
2825 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002826 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2827 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002828 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002829
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002830 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002831
2832 /* If "the current_rule_list" match the executed rule list, we are in
2833 * resume condition. If a resume is needed it is always in the action
2834 * and never in the ACL or converters. In this case, we initialise the
2835 * current rule, and go to the action execution point.
2836 */
2837 if (s->current_rule) {
2838 rule = s->current_rule;
2839 s->current_rule = NULL;
2840 if (s->current_rule_list == rules)
2841 goto resume_execution;
2842 }
2843 s->current_rule_list = rules;
2844
2845 list_for_each_entry(rule, rules, list) {
2846 /* check optional condition */
2847 if (rule->cond) {
2848 int ret;
2849
2850 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2851 ret = acl_pass(ret);
2852
2853 if (rule->cond->pol == ACL_COND_UNLESS)
2854 ret = !ret;
2855
2856 if (!ret) /* condition not matched */
2857 continue;
2858 }
2859
2860 act_flags |= ACT_FLAG_FIRST;
2861 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002862 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2863 early_hints = 0;
2864 if (htx_reply_103_early_hints(&s->res) == -1) {
2865 rule_ret = HTTP_RULE_RES_BADREQ;
2866 goto end;
2867 }
2868 }
2869
Christopher Faulet3e964192018-10-24 11:39:23 +02002870 switch (rule->action) {
2871 case ACT_ACTION_ALLOW:
2872 rule_ret = HTTP_RULE_RES_STOP;
2873 goto end;
2874
2875 case ACT_ACTION_DENY:
2876 if (deny_status)
2877 *deny_status = rule->deny_status;
2878 rule_ret = HTTP_RULE_RES_DENY;
2879 goto end;
2880
2881 case ACT_HTTP_REQ_TARPIT:
2882 txn->flags |= TX_CLTARPIT;
2883 if (deny_status)
2884 *deny_status = rule->deny_status;
2885 rule_ret = HTTP_RULE_RES_DENY;
2886 goto end;
2887
2888 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002889 /* Auth might be performed on regular http-req rules as well as on stats */
2890 auth_realm = rule->arg.auth.realm;
2891 if (!auth_realm) {
2892 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2893 auth_realm = STATS_DEFAULT_REALM;
2894 else
2895 auth_realm = px->id;
2896 }
2897 /* send 401/407 depending on whether we use a proxy or not. We still
2898 * count one error, because normal browsing won't significantly
2899 * increase the counter but brute force attempts will.
2900 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002901 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002902 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2903 rule_ret = HTTP_RULE_RES_BADREQ;
2904 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002905 goto end;
2906
2907 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002908 rule_ret = HTTP_RULE_RES_DONE;
2909 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2910 rule_ret = HTTP_RULE_RES_BADREQ;
2911 goto end;
2912
2913 case ACT_HTTP_SET_NICE:
2914 s->task->nice = rule->arg.nice;
2915 break;
2916
2917 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002918 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002919 break;
2920
2921 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002922 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002923 break;
2924
2925 case ACT_HTTP_SET_LOGL:
2926 s->logs.level = rule->arg.loglevel;
2927 break;
2928
2929 case ACT_HTTP_REPLACE_HDR:
2930 case ACT_HTTP_REPLACE_VAL:
2931 if (htx_transform_header(s, &s->req, htx,
2932 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2933 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002934 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002935 rule_ret = HTTP_RULE_RES_BADREQ;
2936 goto end;
2937 }
2938 break;
2939
2940 case ACT_HTTP_DEL_HDR:
2941 /* remove all occurrences of the header */
2942 ctx.blk = NULL;
2943 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2944 http_remove_header(htx, &ctx);
2945 break;
2946
2947 case ACT_HTTP_SET_HDR:
2948 case ACT_HTTP_ADD_HDR: {
2949 /* The scope of the trash buffer must be limited to this function. The
2950 * build_logline() function can execute a lot of other function which
2951 * can use the trash buffer. So for limiting the scope of this global
2952 * buffer, we build first the header value using build_logline, and
2953 * after we store the header name.
2954 */
2955 struct buffer *replace;
2956 struct ist n, v;
2957
2958 replace = alloc_trash_chunk();
2959 if (!replace) {
2960 rule_ret = HTTP_RULE_RES_BADREQ;
2961 goto end;
2962 }
2963
2964 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2965 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2966 v = ist2(replace->area, replace->data);
2967
2968 if (rule->action == ACT_HTTP_SET_HDR) {
2969 /* remove all occurrences of the header */
2970 ctx.blk = NULL;
2971 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2972 http_remove_header(htx, &ctx);
2973 }
2974
2975 if (!http_add_header(htx, n, v)) {
2976 static unsigned char rate_limit = 0;
2977
2978 if ((rate_limit++ & 255) == 0) {
2979 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);
2980 }
2981
Olivier Houcharda798bf52019-03-08 18:52:00 +01002982 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002983 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002984 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002985 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002986 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002987 }
2988 free_trash_chunk(replace);
2989 break;
2990 }
2991
2992 case ACT_HTTP_DEL_ACL:
2993 case ACT_HTTP_DEL_MAP: {
2994 struct pat_ref *ref;
2995 struct buffer *key;
2996
2997 /* collect reference */
2998 ref = pat_ref_lookup(rule->arg.map.ref);
2999 if (!ref)
3000 continue;
3001
3002 /* allocate key */
3003 key = alloc_trash_chunk();
3004 if (!key) {
3005 rule_ret = HTTP_RULE_RES_BADREQ;
3006 goto end;
3007 }
3008
3009 /* collect key */
3010 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3011 key->area[key->data] = '\0';
3012
3013 /* perform update */
3014 /* returned code: 1=ok, 0=ko */
3015 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3016 pat_ref_delete(ref, key->area);
3017 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3018
3019 free_trash_chunk(key);
3020 break;
3021 }
3022
3023 case ACT_HTTP_ADD_ACL: {
3024 struct pat_ref *ref;
3025 struct buffer *key;
3026
3027 /* collect reference */
3028 ref = pat_ref_lookup(rule->arg.map.ref);
3029 if (!ref)
3030 continue;
3031
3032 /* allocate key */
3033 key = alloc_trash_chunk();
3034 if (!key) {
3035 rule_ret = HTTP_RULE_RES_BADREQ;
3036 goto end;
3037 }
3038
3039 /* collect key */
3040 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3041 key->area[key->data] = '\0';
3042
3043 /* perform update */
3044 /* add entry only if it does not already exist */
3045 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3046 if (pat_ref_find_elt(ref, key->area) == NULL)
3047 pat_ref_add(ref, key->area, NULL, NULL);
3048 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3049
3050 free_trash_chunk(key);
3051 break;
3052 }
3053
3054 case ACT_HTTP_SET_MAP: {
3055 struct pat_ref *ref;
3056 struct buffer *key, *value;
3057
3058 /* collect reference */
3059 ref = pat_ref_lookup(rule->arg.map.ref);
3060 if (!ref)
3061 continue;
3062
3063 /* allocate key */
3064 key = alloc_trash_chunk();
3065 if (!key) {
3066 rule_ret = HTTP_RULE_RES_BADREQ;
3067 goto end;
3068 }
3069
3070 /* allocate value */
3071 value = alloc_trash_chunk();
3072 if (!value) {
3073 free_trash_chunk(key);
3074 rule_ret = HTTP_RULE_RES_BADREQ;
3075 goto end;
3076 }
3077
3078 /* collect key */
3079 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3080 key->area[key->data] = '\0';
3081
3082 /* collect value */
3083 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3084 value->area[value->data] = '\0';
3085
3086 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003087 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003088 if (pat_ref_find_elt(ref, key->area) != NULL)
3089 /* update entry if it exists */
3090 pat_ref_set(ref, key->area, value->area, NULL);
3091 else
3092 /* insert a new entry */
3093 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003094 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003095 free_trash_chunk(key);
3096 free_trash_chunk(value);
3097 break;
3098 }
3099
3100 case ACT_HTTP_EARLY_HINT:
3101 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3102 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003103 early_hints = htx_add_early_hint_header(s, early_hints,
3104 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003105 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003106 if (early_hints == -1) {
3107 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003108 goto end;
3109 }
3110 break;
3111
3112 case ACT_CUSTOM:
3113 if ((s->req.flags & CF_READ_ERROR) ||
3114 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003115 (px->options & PR_O_ABRT_CLOSE)))
3116 act_flags |= ACT_FLAG_FINAL;
3117
3118 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3119 case ACT_RET_ERR:
3120 case ACT_RET_CONT:
3121 break;
3122 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003123 rule_ret = HTTP_RULE_RES_STOP;
3124 goto end;
3125 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003126 rule_ret = HTTP_RULE_RES_DONE;
3127 goto end;
3128 case ACT_RET_YIELD:
3129 s->current_rule = rule;
3130 rule_ret = HTTP_RULE_RES_YIELD;
3131 goto end;
3132 }
3133 break;
3134
3135 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3136 /* Note: only the first valid tracking parameter of each
3137 * applies.
3138 */
3139
3140 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3141 struct stktable *t;
3142 struct stksess *ts;
3143 struct stktable_key *key;
3144 void *ptr1, *ptr2;
3145
3146 t = rule->arg.trk_ctr.table.t;
3147 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3148 rule->arg.trk_ctr.expr, NULL);
3149
3150 if (key && (ts = stktable_get_entry(t, key))) {
3151 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3152
3153 /* let's count a new HTTP request as it's the first time we do it */
3154 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3155 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3156 if (ptr1 || ptr2) {
3157 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3158
3159 if (ptr1)
3160 stktable_data_cast(ptr1, http_req_cnt)++;
3161
3162 if (ptr2)
3163 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3164 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3165
3166 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3167
3168 /* If data was modified, we need to touch to re-schedule sync */
3169 stktable_touch_local(t, ts, 0);
3170 }
3171
3172 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3173 if (sess->fe != s->be)
3174 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3175 }
3176 }
3177 break;
3178
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003179 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003180 default:
3181 break;
3182 }
3183 }
3184
3185 end:
3186 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003187 if (htx_reply_103_early_hints(&s->res) == -1)
3188 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003189 }
3190
3191 /* we reached the end of the rules, nothing to report */
3192 return rule_ret;
3193}
3194
3195/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3196 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3197 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3198 * is returned, the process can continue the evaluation of next rule list. If
3199 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3200 * is returned, it means the operation could not be processed and a server error
3201 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3202 * deny rule. If *YIELD is returned, the caller must call again the function
3203 * with the same context.
3204 */
3205static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3206 struct stream *s)
3207{
3208 struct session *sess = strm_sess(s);
3209 struct http_txn *txn = s->txn;
3210 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003211 struct act_rule *rule;
3212 struct http_hdr_ctx ctx;
3213 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3214 int act_flags = 0;
3215
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003216 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003217
3218 /* If "the current_rule_list" match the executed rule list, we are in
3219 * resume condition. If a resume is needed it is always in the action
3220 * and never in the ACL or converters. In this case, we initialise the
3221 * current rule, and go to the action execution point.
3222 */
3223 if (s->current_rule) {
3224 rule = s->current_rule;
3225 s->current_rule = NULL;
3226 if (s->current_rule_list == rules)
3227 goto resume_execution;
3228 }
3229 s->current_rule_list = rules;
3230
3231 list_for_each_entry(rule, rules, list) {
3232 /* check optional condition */
3233 if (rule->cond) {
3234 int ret;
3235
3236 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3237 ret = acl_pass(ret);
3238
3239 if (rule->cond->pol == ACL_COND_UNLESS)
3240 ret = !ret;
3241
3242 if (!ret) /* condition not matched */
3243 continue;
3244 }
3245
3246 act_flags |= ACT_FLAG_FIRST;
3247resume_execution:
3248 switch (rule->action) {
3249 case ACT_ACTION_ALLOW:
3250 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3251 goto end;
3252
3253 case ACT_ACTION_DENY:
3254 txn->flags |= TX_SVDENY;
3255 rule_ret = HTTP_RULE_RES_STOP;
3256 goto end;
3257
3258 case ACT_HTTP_SET_NICE:
3259 s->task->nice = rule->arg.nice;
3260 break;
3261
3262 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003263 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003264 break;
3265
3266 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003267 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003268 break;
3269
3270 case ACT_HTTP_SET_LOGL:
3271 s->logs.level = rule->arg.loglevel;
3272 break;
3273
3274 case ACT_HTTP_REPLACE_HDR:
3275 case ACT_HTTP_REPLACE_VAL:
3276 if (htx_transform_header(s, &s->res, htx,
3277 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3278 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003279 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 rule_ret = HTTP_RULE_RES_BADREQ;
3281 goto end;
3282 }
3283 break;
3284
3285 case ACT_HTTP_DEL_HDR:
3286 /* remove all occurrences of the header */
3287 ctx.blk = NULL;
3288 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3289 http_remove_header(htx, &ctx);
3290 break;
3291
3292 case ACT_HTTP_SET_HDR:
3293 case ACT_HTTP_ADD_HDR: {
3294 struct buffer *replace;
3295 struct ist n, v;
3296
3297 replace = alloc_trash_chunk();
3298 if (!replace) {
3299 rule_ret = HTTP_RULE_RES_BADREQ;
3300 goto end;
3301 }
3302
3303 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3304 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3305 v = ist2(replace->area, replace->data);
3306
3307 if (rule->action == ACT_HTTP_SET_HDR) {
3308 /* remove all occurrences of the header */
3309 ctx.blk = NULL;
3310 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3311 http_remove_header(htx, &ctx);
3312 }
3313
3314 if (!http_add_header(htx, n, v)) {
3315 static unsigned char rate_limit = 0;
3316
3317 if ((rate_limit++ & 255) == 0) {
3318 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);
3319 }
3320
Olivier Houcharda798bf52019-03-08 18:52:00 +01003321 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003322 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003323 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003324 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003325 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003326 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003327 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003328 }
3329 free_trash_chunk(replace);
3330 break;
3331 }
3332
3333 case ACT_HTTP_DEL_ACL:
3334 case ACT_HTTP_DEL_MAP: {
3335 struct pat_ref *ref;
3336 struct buffer *key;
3337
3338 /* collect reference */
3339 ref = pat_ref_lookup(rule->arg.map.ref);
3340 if (!ref)
3341 continue;
3342
3343 /* allocate key */
3344 key = alloc_trash_chunk();
3345 if (!key) {
3346 rule_ret = HTTP_RULE_RES_BADREQ;
3347 goto end;
3348 }
3349
3350 /* collect key */
3351 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3352 key->area[key->data] = '\0';
3353
3354 /* perform update */
3355 /* returned code: 1=ok, 0=ko */
3356 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3357 pat_ref_delete(ref, key->area);
3358 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3359
3360 free_trash_chunk(key);
3361 break;
3362 }
3363
3364 case ACT_HTTP_ADD_ACL: {
3365 struct pat_ref *ref;
3366 struct buffer *key;
3367
3368 /* collect reference */
3369 ref = pat_ref_lookup(rule->arg.map.ref);
3370 if (!ref)
3371 continue;
3372
3373 /* allocate key */
3374 key = alloc_trash_chunk();
3375 if (!key) {
3376 rule_ret = HTTP_RULE_RES_BADREQ;
3377 goto end;
3378 }
3379
3380 /* collect key */
3381 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3382 key->area[key->data] = '\0';
3383
3384 /* perform update */
3385 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003386 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003387 if (pat_ref_find_elt(ref, key->area) == NULL)
3388 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003389 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003390 free_trash_chunk(key);
3391 break;
3392 }
3393
3394 case ACT_HTTP_SET_MAP: {
3395 struct pat_ref *ref;
3396 struct buffer *key, *value;
3397
3398 /* collect reference */
3399 ref = pat_ref_lookup(rule->arg.map.ref);
3400 if (!ref)
3401 continue;
3402
3403 /* allocate key */
3404 key = alloc_trash_chunk();
3405 if (!key) {
3406 rule_ret = HTTP_RULE_RES_BADREQ;
3407 goto end;
3408 }
3409
3410 /* allocate value */
3411 value = alloc_trash_chunk();
3412 if (!value) {
3413 free_trash_chunk(key);
3414 rule_ret = HTTP_RULE_RES_BADREQ;
3415 goto end;
3416 }
3417
3418 /* collect key */
3419 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3420 key->area[key->data] = '\0';
3421
3422 /* collect value */
3423 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3424 value->area[value->data] = '\0';
3425
3426 /* perform update */
3427 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3428 if (pat_ref_find_elt(ref, key->area) != NULL)
3429 /* update entry if it exists */
3430 pat_ref_set(ref, key->area, value->area, NULL);
3431 else
3432 /* insert a new entry */
3433 pat_ref_add(ref, key->area, value->area, NULL);
3434 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3435 free_trash_chunk(key);
3436 free_trash_chunk(value);
3437 break;
3438 }
3439
3440 case ACT_HTTP_REDIR:
3441 rule_ret = HTTP_RULE_RES_DONE;
3442 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3443 rule_ret = HTTP_RULE_RES_BADREQ;
3444 goto end;
3445
3446 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3447 /* Note: only the first valid tracking parameter of each
3448 * applies.
3449 */
3450 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3451 struct stktable *t;
3452 struct stksess *ts;
3453 struct stktable_key *key;
3454 void *ptr;
3455
3456 t = rule->arg.trk_ctr.table.t;
3457 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3458 rule->arg.trk_ctr.expr, NULL);
3459
3460 if (key && (ts = stktable_get_entry(t, key))) {
3461 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3462
3463 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3464
3465 /* let's count a new HTTP request as it's the first time we do it */
3466 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3467 if (ptr)
3468 stktable_data_cast(ptr, http_req_cnt)++;
3469
3470 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3471 if (ptr)
3472 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3473 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3474
3475 /* When the client triggers a 4xx from the server, it's most often due
3476 * to a missing object or permission. These events should be tracked
3477 * because if they happen often, it may indicate a brute force or a
3478 * vulnerability scan. Normally this is done when receiving the response
3479 * but here we're tracking after this ought to have been done so we have
3480 * to do it on purpose.
3481 */
3482 if ((unsigned)(txn->status - 400) < 100) {
3483 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3484 if (ptr)
3485 stktable_data_cast(ptr, http_err_cnt)++;
3486
3487 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3488 if (ptr)
3489 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3490 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3491 }
3492
3493 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3494
3495 /* If data was modified, we need to touch to re-schedule sync */
3496 stktable_touch_local(t, ts, 0);
3497
3498 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3499 if (sess->fe != s->be)
3500 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3501 }
3502 }
3503 break;
3504
3505 case ACT_CUSTOM:
3506 if ((s->req.flags & CF_READ_ERROR) ||
3507 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003508 (px->options & PR_O_ABRT_CLOSE)))
3509 act_flags |= ACT_FLAG_FINAL;
3510
3511 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3512 case ACT_RET_ERR:
3513 case ACT_RET_CONT:
3514 break;
3515 case ACT_RET_STOP:
3516 rule_ret = HTTP_RULE_RES_STOP;
3517 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003518 case ACT_RET_DONE:
3519 rule_ret = HTTP_RULE_RES_DONE;
3520 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003521 case ACT_RET_YIELD:
3522 s->current_rule = rule;
3523 rule_ret = HTTP_RULE_RES_YIELD;
3524 goto end;
3525 }
3526 break;
3527
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003528 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003529 default:
3530 break;
3531 }
3532 }
3533
3534 end:
3535 /* we reached the end of the rules, nothing to report */
3536 return rule_ret;
3537}
3538
Christopher Faulet33640082018-10-24 11:53:01 +02003539/* Iterate the same filter through all request headers.
3540 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3541 * Since it can manage the switch to another backend, it updates the per-proxy
3542 * DENY stats.
3543 */
3544static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3545{
3546 struct http_txn *txn = s->txn;
3547 struct htx *htx;
3548 struct buffer *hdr = get_trash_chunk();
3549 int32_t pos;
3550
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003551 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003552
Christopher Fauleta3f15502019-05-13 15:27:23 +02003553 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003554 struct htx_blk *blk = htx_get_blk(htx, pos);
3555 enum htx_blk_type type;
3556 struct ist n, v;
3557
3558 next_hdr:
3559 type = htx_get_blk_type(blk);
3560 if (type == HTX_BLK_EOH)
3561 break;
3562 if (type != HTX_BLK_HDR)
3563 continue;
3564
3565 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3566 return 1;
3567 else if (unlikely(txn->flags & TX_CLALLOW) &&
3568 (exp->action == ACT_ALLOW ||
3569 exp->action == ACT_DENY ||
3570 exp->action == ACT_TARPIT))
3571 return 0;
3572
3573 n = htx_get_blk_name(htx, blk);
3574 v = htx_get_blk_value(htx, blk);
3575
Christopher Faulet02e771a2019-02-26 15:36:05 +01003576 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003577 hdr->area[hdr->data++] = ':';
3578 hdr->area[hdr->data++] = ' ';
3579 chunk_memcat(hdr, v.ptr, v.len);
3580
3581 /* Now we have one header in <hdr> */
3582
3583 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3584 struct http_hdr_ctx ctx;
3585 int len;
3586
3587 switch (exp->action) {
3588 case ACT_ALLOW:
3589 txn->flags |= TX_CLALLOW;
3590 goto end;
3591
3592 case ACT_DENY:
3593 txn->flags |= TX_CLDENY;
3594 goto end;
3595
3596 case ACT_TARPIT:
3597 txn->flags |= TX_CLTARPIT;
3598 goto end;
3599
3600 case ACT_REPLACE:
3601 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3602 if (len < 0)
3603 return -1;
3604
3605 http_parse_header(ist2(trash.area, len), &n, &v);
3606 ctx.blk = blk;
3607 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003608 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003609 if (!http_replace_header(htx, &ctx, n, v))
3610 return -1;
3611 if (!ctx.blk)
3612 goto end;
3613 pos = htx_get_blk_pos(htx, blk);
3614 break;
3615
3616 case ACT_REMOVE:
3617 ctx.blk = blk;
3618 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003619 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003620 if (!http_remove_header(htx, &ctx))
3621 return -1;
3622 if (!ctx.blk)
3623 goto end;
3624 pos = htx_get_blk_pos(htx, blk);
3625 goto next_hdr;
3626
3627 }
3628 }
3629 }
3630 end:
3631 return 0;
3632}
3633
3634/* Apply the filter to the request line.
3635 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3636 * or -1 if a replacement resulted in an invalid request line.
3637 * Since it can manage the switch to another backend, it updates the per-proxy
3638 * DENY stats.
3639 */
3640static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3641{
3642 struct http_txn *txn = s->txn;
3643 struct htx *htx;
3644 struct buffer *reqline = get_trash_chunk();
3645 int done;
3646
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003647 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003648
3649 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3650 return 1;
3651 else if (unlikely(txn->flags & TX_CLALLOW) &&
3652 (exp->action == ACT_ALLOW ||
3653 exp->action == ACT_DENY ||
3654 exp->action == ACT_TARPIT))
3655 return 0;
3656 else if (exp->action == ACT_REMOVE)
3657 return 0;
3658
3659 done = 0;
3660
Christopher Faulet297fbb42019-05-13 14:41:27 +02003661 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003662
3663 /* Now we have the request line between cur_ptr and cur_end */
3664 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003665 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003666 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003667 int len;
3668
3669 switch (exp->action) {
3670 case ACT_ALLOW:
3671 txn->flags |= TX_CLALLOW;
3672 done = 1;
3673 break;
3674
3675 case ACT_DENY:
3676 txn->flags |= TX_CLDENY;
3677 done = 1;
3678 break;
3679
3680 case ACT_TARPIT:
3681 txn->flags |= TX_CLTARPIT;
3682 done = 1;
3683 break;
3684
3685 case ACT_REPLACE:
3686 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3687 if (len < 0)
3688 return -1;
3689
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003690 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3691 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3692 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003693 return -1;
3694 done = 1;
3695 break;
3696 }
3697 }
3698 return done;
3699}
3700
3701/*
3702 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3703 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3704 * unparsable request. Since it can manage the switch to another backend, it
3705 * updates the per-proxy DENY stats.
3706 */
3707static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3708{
3709 struct session *sess = s->sess;
3710 struct http_txn *txn = s->txn;
3711 struct hdr_exp *exp;
3712
3713 for (exp = px->req_exp; exp; exp = exp->next) {
3714 int ret;
3715
3716 /*
3717 * The interleaving of transformations and verdicts
3718 * makes it difficult to decide to continue or stop
3719 * the evaluation.
3720 */
3721
3722 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3723 break;
3724
3725 if ((txn->flags & TX_CLALLOW) &&
3726 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3727 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3728 continue;
3729
3730 /* if this filter had a condition, evaluate it now and skip to
3731 * next filter if the condition does not match.
3732 */
3733 if (exp->cond) {
3734 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3735 ret = acl_pass(ret);
3736 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3737 ret = !ret;
3738
3739 if (!ret)
3740 continue;
3741 }
3742
3743 /* Apply the filter to the request line. */
3744 ret = htx_apply_filter_to_req_line(s, req, exp);
3745 if (unlikely(ret < 0))
3746 return -1;
3747
3748 if (likely(ret == 0)) {
3749 /* The filter did not match the request, it can be
3750 * iterated through all headers.
3751 */
3752 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3753 return -1;
3754 }
3755 }
3756 return 0;
3757}
3758
3759/* Iterate the same filter through all response headers contained in <res>.
3760 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3761 */
3762static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3763{
3764 struct http_txn *txn = s->txn;
3765 struct htx *htx;
3766 struct buffer *hdr = get_trash_chunk();
3767 int32_t pos;
3768
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003769 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003770
Christopher Fauleta3f15502019-05-13 15:27:23 +02003771 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003772 struct htx_blk *blk = htx_get_blk(htx, pos);
3773 enum htx_blk_type type;
3774 struct ist n, v;
3775
3776 next_hdr:
3777 type = htx_get_blk_type(blk);
3778 if (type == HTX_BLK_EOH)
3779 break;
3780 if (type != HTX_BLK_HDR)
3781 continue;
3782
3783 if (unlikely(txn->flags & TX_SVDENY))
3784 return 1;
3785 else if (unlikely(txn->flags & TX_SVALLOW) &&
3786 (exp->action == ACT_ALLOW ||
3787 exp->action == ACT_DENY))
3788 return 0;
3789
3790 n = htx_get_blk_name(htx, blk);
3791 v = htx_get_blk_value(htx, blk);
3792
Christopher Faulet02e771a2019-02-26 15:36:05 +01003793 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003794 hdr->area[hdr->data++] = ':';
3795 hdr->area[hdr->data++] = ' ';
3796 chunk_memcat(hdr, v.ptr, v.len);
3797
3798 /* Now we have one header in <hdr> */
3799
3800 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3801 struct http_hdr_ctx ctx;
3802 int len;
3803
3804 switch (exp->action) {
3805 case ACT_ALLOW:
3806 txn->flags |= TX_SVALLOW;
3807 goto end;
3808 break;
3809
3810 case ACT_DENY:
3811 txn->flags |= TX_SVDENY;
3812 goto end;
3813 break;
3814
3815 case ACT_REPLACE:
3816 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3817 if (len < 0)
3818 return -1;
3819
3820 http_parse_header(ist2(trash.area, len), &n, &v);
3821 ctx.blk = blk;
3822 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003823 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003824 if (!http_replace_header(htx, &ctx, n, v))
3825 return -1;
3826 if (!ctx.blk)
3827 goto end;
3828 pos = htx_get_blk_pos(htx, blk);
3829 break;
3830
3831 case ACT_REMOVE:
3832 ctx.blk = blk;
3833 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003834 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003835 if (!http_remove_header(htx, &ctx))
3836 return -1;
3837 if (!ctx.blk)
3838 goto end;
3839 pos = htx_get_blk_pos(htx, blk);
3840 goto next_hdr;
3841 }
3842 }
3843
3844 }
3845 end:
3846 return 0;
3847}
3848
3849/* Apply the filter to the status line in the response buffer <res>.
3850 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3851 * or -1 if a replacement resulted in an invalid status line.
3852 */
3853static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3854{
3855 struct http_txn *txn = s->txn;
3856 struct htx *htx;
3857 struct buffer *resline = get_trash_chunk();
3858 int done;
3859
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003860 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003861
3862 if (unlikely(txn->flags & TX_SVDENY))
3863 return 1;
3864 else if (unlikely(txn->flags & TX_SVALLOW) &&
3865 (exp->action == ACT_ALLOW ||
3866 exp->action == ACT_DENY))
3867 return 0;
3868 else if (exp->action == ACT_REMOVE)
3869 return 0;
3870
3871 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003872 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003873
3874 /* Now we have the status line between cur_ptr and cur_end */
3875 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003876 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003877 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003878 int len;
3879
3880 switch (exp->action) {
3881 case ACT_ALLOW:
3882 txn->flags |= TX_SVALLOW;
3883 done = 1;
3884 break;
3885
3886 case ACT_DENY:
3887 txn->flags |= TX_SVDENY;
3888 done = 1;
3889 break;
3890
3891 case ACT_REPLACE:
3892 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3893 if (len < 0)
3894 return -1;
3895
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003896 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3897 sl->info.res.status = strl2ui(code.ptr, code.len);
3898 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003899 return -1;
3900
3901 done = 1;
3902 return 1;
3903 }
3904 }
3905 return done;
3906}
3907
3908/*
3909 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3910 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3911 * unparsable response.
3912 */
3913static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3914{
3915 struct session *sess = s->sess;
3916 struct http_txn *txn = s->txn;
3917 struct hdr_exp *exp;
3918
3919 for (exp = px->rsp_exp; exp; exp = exp->next) {
3920 int ret;
3921
3922 /*
3923 * The interleaving of transformations and verdicts
3924 * makes it difficult to decide to continue or stop
3925 * the evaluation.
3926 */
3927
3928 if (txn->flags & TX_SVDENY)
3929 break;
3930
3931 if ((txn->flags & TX_SVALLOW) &&
3932 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3933 exp->action == ACT_PASS)) {
3934 exp = exp->next;
3935 continue;
3936 }
3937
3938 /* if this filter had a condition, evaluate it now and skip to
3939 * next filter if the condition does not match.
3940 */
3941 if (exp->cond) {
3942 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3943 ret = acl_pass(ret);
3944 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3945 ret = !ret;
3946 if (!ret)
3947 continue;
3948 }
3949
3950 /* Apply the filter to the status line. */
3951 ret = htx_apply_filter_to_sts_line(s, res, exp);
3952 if (unlikely(ret < 0))
3953 return -1;
3954
3955 if (likely(ret == 0)) {
3956 /* The filter did not match the response, it can be
3957 * iterated through all headers.
3958 */
3959 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3960 return -1;
3961 }
3962 }
3963 return 0;
3964}
3965
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003966/*
3967 * Manage client-side cookie. It can impact performance by about 2% so it is
3968 * desirable to call it only when needed. This code is quite complex because
3969 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3970 * highly recommended not to touch this part without a good reason !
3971 */
3972static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3973{
3974 struct session *sess = s->sess;
3975 struct http_txn *txn = s->txn;
3976 struct htx *htx;
3977 struct http_hdr_ctx ctx;
3978 char *hdr_beg, *hdr_end, *del_from;
3979 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3980 int preserve_hdr;
3981
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003982 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003983 ctx.blk = NULL;
3984 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02003985 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003986 del_from = NULL; /* nothing to be deleted */
3987 preserve_hdr = 0; /* assume we may kill the whole header */
3988
3989 /* Now look for cookies. Conforming to RFC2109, we have to support
3990 * attributes whose name begin with a '$', and associate them with
3991 * the right cookie, if we want to delete this cookie.
3992 * So there are 3 cases for each cookie read :
3993 * 1) it's a special attribute, beginning with a '$' : ignore it.
3994 * 2) it's a server id cookie that we *MAY* want to delete : save
3995 * some pointers on it (last semi-colon, beginning of cookie...)
3996 * 3) it's an application cookie : we *MAY* have to delete a previous
3997 * "special" cookie.
3998 * At the end of loop, if a "special" cookie remains, we may have to
3999 * remove it. If no application cookie persists in the header, we
4000 * *MUST* delete it.
4001 *
4002 * Note: RFC2965 is unclear about the processing of spaces around
4003 * the equal sign in the ATTR=VALUE form. A careful inspection of
4004 * the RFC explicitly allows spaces before it, and not within the
4005 * tokens (attrs or values). An inspection of RFC2109 allows that
4006 * too but section 10.1.3 lets one think that spaces may be allowed
4007 * after the equal sign too, resulting in some (rare) buggy
4008 * implementations trying to do that. So let's do what servers do.
4009 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4010 * allowed quoted strings in values, with any possible character
4011 * after a backslash, including control chars and delimitors, which
4012 * causes parsing to become ambiguous. Browsers also allow spaces
4013 * within values even without quotes.
4014 *
4015 * We have to keep multiple pointers in order to support cookie
4016 * removal at the beginning, middle or end of header without
4017 * corrupting the header. All of these headers are valid :
4018 *
4019 * hdr_beg hdr_end
4020 * | |
4021 * v |
4022 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4023 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4024 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4025 * | | | | | | |
4026 * | | | | | | |
4027 * | | | | | | +--> next
4028 * | | | | | +----> val_end
4029 * | | | | +-----------> val_beg
4030 * | | | +--------------> equal
4031 * | | +----------------> att_end
4032 * | +---------------------> att_beg
4033 * +--------------------------> prev
4034 *
4035 */
4036 hdr_beg = ctx.value.ptr;
4037 hdr_end = hdr_beg + ctx.value.len;
4038 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4039 /* Iterate through all cookies on this line */
4040
4041 /* find att_beg */
4042 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004043 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004044 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004045 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004046
4047 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4048 att_beg++;
4049
4050 /* find att_end : this is the first character after the last non
4051 * space before the equal. It may be equal to hdr_end.
4052 */
4053 equal = att_end = att_beg;
4054 while (equal < hdr_end) {
4055 if (*equal == '=' || *equal == ',' || *equal == ';')
4056 break;
4057 if (HTTP_IS_SPHT(*equal++))
4058 continue;
4059 att_end = equal;
4060 }
4061
4062 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4063 * is between <att_beg> and <equal>, both may be identical.
4064 */
4065 /* look for end of cookie if there is an equal sign */
4066 if (equal < hdr_end && *equal == '=') {
4067 /* look for the beginning of the value */
4068 val_beg = equal + 1;
4069 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4070 val_beg++;
4071
4072 /* find the end of the value, respecting quotes */
4073 next = http_find_cookie_value_end(val_beg, hdr_end);
4074
4075 /* make val_end point to the first white space or delimitor after the value */
4076 val_end = next;
4077 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4078 val_end--;
4079 }
4080 else
4081 val_beg = val_end = next = equal;
4082
4083 /* We have nothing to do with attributes beginning with
4084 * '$'. However, they will automatically be removed if a
4085 * header before them is removed, since they're supposed
4086 * to be linked together.
4087 */
4088 if (*att_beg == '$')
4089 continue;
4090
4091 /* Ignore cookies with no equal sign */
4092 if (equal == next) {
4093 /* This is not our cookie, so we must preserve it. But if we already
4094 * scheduled another cookie for removal, we cannot remove the
4095 * complete header, but we can remove the previous block itself.
4096 */
4097 preserve_hdr = 1;
4098 if (del_from != NULL) {
4099 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4100 val_end += delta;
4101 next += delta;
4102 hdr_end += delta;
4103 prev = del_from;
4104 del_from = NULL;
4105 }
4106 continue;
4107 }
4108
4109 /* if there are spaces around the equal sign, we need to
4110 * strip them otherwise we'll get trouble for cookie captures,
4111 * or even for rewrites. Since this happens extremely rarely,
4112 * it does not hurt performance.
4113 */
4114 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4115 int stripped_before = 0;
4116 int stripped_after = 0;
4117
4118 if (att_end != equal) {
4119 memmove(att_end, equal, hdr_end - equal);
4120 stripped_before = (att_end - equal);
4121 equal += stripped_before;
4122 val_beg += stripped_before;
4123 }
4124
4125 if (val_beg > equal + 1) {
4126 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4127 stripped_after = (equal + 1) - val_beg;
4128 val_beg += stripped_after;
4129 stripped_before += stripped_after;
4130 }
4131
4132 val_end += stripped_before;
4133 next += stripped_before;
4134 hdr_end += stripped_before;
4135 }
4136 /* now everything is as on the diagram above */
4137
4138 /* First, let's see if we want to capture this cookie. We check
4139 * that we don't already have a client side cookie, because we
4140 * can only capture one. Also as an optimisation, we ignore
4141 * cookies shorter than the declared name.
4142 */
4143 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4144 (val_end - att_beg >= sess->fe->capture_namelen) &&
4145 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4146 int log_len = val_end - att_beg;
4147
4148 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4149 ha_alert("HTTP logging : out of memory.\n");
4150 } else {
4151 if (log_len > sess->fe->capture_len)
4152 log_len = sess->fe->capture_len;
4153 memcpy(txn->cli_cookie, att_beg, log_len);
4154 txn->cli_cookie[log_len] = 0;
4155 }
4156 }
4157
4158 /* Persistence cookies in passive, rewrite or insert mode have the
4159 * following form :
4160 *
4161 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4162 *
4163 * For cookies in prefix mode, the form is :
4164 *
4165 * Cookie: NAME=SRV~VALUE
4166 */
4167 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4168 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4169 struct server *srv = s->be->srv;
4170 char *delim;
4171
4172 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4173 * have the server ID between val_beg and delim, and the original cookie between
4174 * delim+1 and val_end. Otherwise, delim==val_end :
4175 *
4176 * hdr_beg
4177 * |
4178 * v
4179 * NAME=SRV; # in all but prefix modes
4180 * NAME=SRV~OPAQUE ; # in prefix mode
4181 * || || | |+-> next
4182 * || || | +--> val_end
4183 * || || +---------> delim
4184 * || |+------------> val_beg
4185 * || +-------------> att_end = equal
4186 * |+-----------------> att_beg
4187 * +------------------> prev
4188 *
4189 */
4190 if (s->be->ck_opts & PR_CK_PFX) {
4191 for (delim = val_beg; delim < val_end; delim++)
4192 if (*delim == COOKIE_DELIM)
4193 break;
4194 }
4195 else {
4196 char *vbar1;
4197 delim = val_end;
4198 /* Now check if the cookie contains a date field, which would
4199 * appear after a vertical bar ('|') just after the server name
4200 * and before the delimiter.
4201 */
4202 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4203 if (vbar1) {
4204 /* OK, so left of the bar is the server's cookie and
4205 * right is the last seen date. It is a base64 encoded
4206 * 30-bit value representing the UNIX date since the
4207 * epoch in 4-second quantities.
4208 */
4209 int val;
4210 delim = vbar1++;
4211 if (val_end - vbar1 >= 5) {
4212 val = b64tos30(vbar1);
4213 if (val > 0)
4214 txn->cookie_last_date = val << 2;
4215 }
4216 /* look for a second vertical bar */
4217 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4218 if (vbar1 && (val_end - vbar1 > 5)) {
4219 val = b64tos30(vbar1 + 1);
4220 if (val > 0)
4221 txn->cookie_first_date = val << 2;
4222 }
4223 }
4224 }
4225
4226 /* if the cookie has an expiration date and the proxy wants to check
4227 * it, then we do that now. We first check if the cookie is too old,
4228 * then only if it has expired. We detect strict overflow because the
4229 * time resolution here is not great (4 seconds). Cookies with dates
4230 * in the future are ignored if their offset is beyond one day. This
4231 * allows an admin to fix timezone issues without expiring everyone
4232 * and at the same time avoids keeping unwanted side effects for too
4233 * long.
4234 */
4235 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4236 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4237 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4238 txn->flags &= ~TX_CK_MASK;
4239 txn->flags |= TX_CK_OLD;
4240 delim = val_beg; // let's pretend we have not found the cookie
4241 txn->cookie_first_date = 0;
4242 txn->cookie_last_date = 0;
4243 }
4244 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4245 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4246 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4247 txn->flags &= ~TX_CK_MASK;
4248 txn->flags |= TX_CK_EXPIRED;
4249 delim = val_beg; // let's pretend we have not found the cookie
4250 txn->cookie_first_date = 0;
4251 txn->cookie_last_date = 0;
4252 }
4253
4254 /* Here, we'll look for the first running server which supports the cookie.
4255 * This allows to share a same cookie between several servers, for example
4256 * to dedicate backup servers to specific servers only.
4257 * However, to prevent clients from sticking to cookie-less backup server
4258 * when they have incidentely learned an empty cookie, we simply ignore
4259 * empty cookies and mark them as invalid.
4260 * The same behaviour is applied when persistence must be ignored.
4261 */
4262 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4263 srv = NULL;
4264
4265 while (srv) {
4266 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4267 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4268 if ((srv->cur_state != SRV_ST_STOPPED) ||
4269 (s->be->options & PR_O_PERSIST) ||
4270 (s->flags & SF_FORCE_PRST)) {
4271 /* we found the server and we can use it */
4272 txn->flags &= ~TX_CK_MASK;
4273 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4274 s->flags |= SF_DIRECT | SF_ASSIGNED;
4275 s->target = &srv->obj_type;
4276 break;
4277 } else {
4278 /* we found a server, but it's down,
4279 * mark it as such and go on in case
4280 * another one is available.
4281 */
4282 txn->flags &= ~TX_CK_MASK;
4283 txn->flags |= TX_CK_DOWN;
4284 }
4285 }
4286 srv = srv->next;
4287 }
4288
4289 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4290 /* no server matched this cookie or we deliberately skipped it */
4291 txn->flags &= ~TX_CK_MASK;
4292 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4293 txn->flags |= TX_CK_UNUSED;
4294 else
4295 txn->flags |= TX_CK_INVALID;
4296 }
4297
4298 /* depending on the cookie mode, we may have to either :
4299 * - delete the complete cookie if we're in insert+indirect mode, so that
4300 * the server never sees it ;
4301 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004302 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004303 * if we're in cookie prefix mode
4304 */
4305 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4306 int delta; /* negative */
4307
4308 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4309 delta = val_beg - (delim + 1);
4310 val_end += delta;
4311 next += delta;
4312 hdr_end += delta;
4313 del_from = NULL;
4314 preserve_hdr = 1; /* we want to keep this cookie */
4315 }
4316 else if (del_from == NULL &&
4317 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4318 del_from = prev;
4319 }
4320 }
4321 else {
4322 /* This is not our cookie, so we must preserve it. But if we already
4323 * scheduled another cookie for removal, we cannot remove the
4324 * complete header, but we can remove the previous block itself.
4325 */
4326 preserve_hdr = 1;
4327
4328 if (del_from != NULL) {
4329 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4330 if (att_beg >= del_from)
4331 att_beg += delta;
4332 if (att_end >= del_from)
4333 att_end += delta;
4334 val_beg += delta;
4335 val_end += delta;
4336 next += delta;
4337 hdr_end += delta;
4338 prev = del_from;
4339 del_from = NULL;
4340 }
4341 }
4342
4343 /* continue with next cookie on this header line */
4344 att_beg = next;
4345 } /* for each cookie */
4346
4347
4348 /* There are no more cookies on this line.
4349 * We may still have one (or several) marked for deletion at the
4350 * end of the line. We must do this now in two ways :
4351 * - if some cookies must be preserved, we only delete from the
4352 * mark to the end of line ;
4353 * - if nothing needs to be preserved, simply delete the whole header
4354 */
4355 if (del_from) {
4356 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4357 }
4358 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004359 if (hdr_beg != hdr_end)
4360 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004361 else
4362 http_remove_header(htx, &ctx);
4363 }
4364 } /* for each "Cookie header */
4365}
4366
4367/*
4368 * Manage server-side cookies. It can impact performance by about 2% so it is
4369 * desirable to call it only when needed. This function is also used when we
4370 * just need to know if there is a cookie (eg: for check-cache).
4371 */
4372static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4373{
4374 struct session *sess = s->sess;
4375 struct http_txn *txn = s->txn;
4376 struct htx *htx;
4377 struct http_hdr_ctx ctx;
4378 struct server *srv;
4379 char *hdr_beg, *hdr_end;
4380 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004381 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004382
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004383 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004384
4385 ctx.blk = NULL;
4386 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004387 int is_first = 1;
4388
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004389 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4390 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4391 break;
4392 is_cookie2 = 1;
4393 }
4394
4395 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4396 * <prev> points to the colon.
4397 */
4398 txn->flags |= TX_SCK_PRESENT;
4399
4400 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4401 * check-cache is enabled) and we are not interested in checking
4402 * them. Warning, the cookie capture is declared in the frontend.
4403 */
4404 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4405 break;
4406
4407 /* OK so now we know we have to process this response cookie.
4408 * The format of the Set-Cookie header is slightly different
4409 * from the format of the Cookie header in that it does not
4410 * support the comma as a cookie delimiter (thus the header
4411 * cannot be folded) because the Expires attribute described in
4412 * the original Netscape's spec may contain an unquoted date
4413 * with a comma inside. We have to live with this because
4414 * many browsers don't support Max-Age and some browsers don't
4415 * support quoted strings. However the Set-Cookie2 header is
4416 * clean.
4417 *
4418 * We have to keep multiple pointers in order to support cookie
4419 * removal at the beginning, middle or end of header without
4420 * corrupting the header (in case of set-cookie2). A special
4421 * pointer, <scav> points to the beginning of the set-cookie-av
4422 * fields after the first semi-colon. The <next> pointer points
4423 * either to the end of line (set-cookie) or next unquoted comma
4424 * (set-cookie2). All of these headers are valid :
4425 *
4426 * hdr_beg hdr_end
4427 * | |
4428 * v |
4429 * NAME1 = VALUE 1 ; Secure; Path="/" |
4430 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4431 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4432 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4433 * | | | | | | | |
4434 * | | | | | | | +-> next
4435 * | | | | | | +------------> scav
4436 * | | | | | +--------------> val_end
4437 * | | | | +--------------------> val_beg
4438 * | | | +----------------------> equal
4439 * | | +------------------------> att_end
4440 * | +----------------------------> att_beg
4441 * +------------------------------> prev
4442 * -------------------------------> hdr_beg
4443 */
4444 hdr_beg = ctx.value.ptr;
4445 hdr_end = hdr_beg + ctx.value.len;
4446 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4447
4448 /* Iterate through all cookies on this line */
4449
4450 /* find att_beg */
4451 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004452 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004453 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004454 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004455
4456 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4457 att_beg++;
4458
4459 /* find att_end : this is the first character after the last non
4460 * space before the equal. It may be equal to hdr_end.
4461 */
4462 equal = att_end = att_beg;
4463
4464 while (equal < hdr_end) {
4465 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4466 break;
4467 if (HTTP_IS_SPHT(*equal++))
4468 continue;
4469 att_end = equal;
4470 }
4471
4472 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4473 * is between <att_beg> and <equal>, both may be identical.
4474 */
4475
4476 /* look for end of cookie if there is an equal sign */
4477 if (equal < hdr_end && *equal == '=') {
4478 /* look for the beginning of the value */
4479 val_beg = equal + 1;
4480 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4481 val_beg++;
4482
4483 /* find the end of the value, respecting quotes */
4484 next = http_find_cookie_value_end(val_beg, hdr_end);
4485
4486 /* make val_end point to the first white space or delimitor after the value */
4487 val_end = next;
4488 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4489 val_end--;
4490 }
4491 else {
4492 /* <equal> points to next comma, semi-colon or EOL */
4493 val_beg = val_end = next = equal;
4494 }
4495
4496 if (next < hdr_end) {
4497 /* Set-Cookie2 supports multiple cookies, and <next> points to
4498 * a colon or semi-colon before the end. So skip all attr-value
4499 * pairs and look for the next comma. For Set-Cookie, since
4500 * commas are permitted in values, skip to the end.
4501 */
4502 if (is_cookie2)
4503 next = http_find_hdr_value_end(next, hdr_end);
4504 else
4505 next = hdr_end;
4506 }
4507
4508 /* Now everything is as on the diagram above */
4509
4510 /* Ignore cookies with no equal sign */
4511 if (equal == val_end)
4512 continue;
4513
4514 /* If there are spaces around the equal sign, we need to
4515 * strip them otherwise we'll get trouble for cookie captures,
4516 * or even for rewrites. Since this happens extremely rarely,
4517 * it does not hurt performance.
4518 */
4519 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4520 int stripped_before = 0;
4521 int stripped_after = 0;
4522
4523 if (att_end != equal) {
4524 memmove(att_end, equal, hdr_end - equal);
4525 stripped_before = (att_end - equal);
4526 equal += stripped_before;
4527 val_beg += stripped_before;
4528 }
4529
4530 if (val_beg > equal + 1) {
4531 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4532 stripped_after = (equal + 1) - val_beg;
4533 val_beg += stripped_after;
4534 stripped_before += stripped_after;
4535 }
4536
4537 val_end += stripped_before;
4538 next += stripped_before;
4539 hdr_end += stripped_before;
4540
Christopher Faulet41dc8432019-06-18 09:49:16 +02004541 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004542 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004543 }
4544
4545 /* First, let's see if we want to capture this cookie. We check
4546 * that we don't already have a server side cookie, because we
4547 * can only capture one. Also as an optimisation, we ignore
4548 * cookies shorter than the declared name.
4549 */
4550 if (sess->fe->capture_name != NULL &&
4551 txn->srv_cookie == NULL &&
4552 (val_end - att_beg >= sess->fe->capture_namelen) &&
4553 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4554 int log_len = val_end - att_beg;
4555 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4556 ha_alert("HTTP logging : out of memory.\n");
4557 }
4558 else {
4559 if (log_len > sess->fe->capture_len)
4560 log_len = sess->fe->capture_len;
4561 memcpy(txn->srv_cookie, att_beg, log_len);
4562 txn->srv_cookie[log_len] = 0;
4563 }
4564 }
4565
4566 srv = objt_server(s->target);
4567 /* now check if we need to process it for persistence */
4568 if (!(s->flags & SF_IGNORE_PRST) &&
4569 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4570 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4571 /* assume passive cookie by default */
4572 txn->flags &= ~TX_SCK_MASK;
4573 txn->flags |= TX_SCK_FOUND;
4574
4575 /* If the cookie is in insert mode on a known server, we'll delete
4576 * this occurrence because we'll insert another one later.
4577 * We'll delete it too if the "indirect" option is set and we're in
4578 * a direct access.
4579 */
4580 if (s->be->ck_opts & PR_CK_PSV) {
4581 /* The "preserve" flag was set, we don't want to touch the
4582 * server's cookie.
4583 */
4584 }
4585 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4586 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4587 /* this cookie must be deleted */
4588 if (prev == hdr_beg && next == hdr_end) {
4589 /* whole header */
4590 http_remove_header(htx, &ctx);
4591 /* note: while both invalid now, <next> and <hdr_end>
4592 * are still equal, so the for() will stop as expected.
4593 */
4594 } else {
4595 /* just remove the value */
4596 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4597 next = prev;
4598 hdr_end += delta;
4599 }
4600 txn->flags &= ~TX_SCK_MASK;
4601 txn->flags |= TX_SCK_DELETED;
4602 /* and go on with next cookie */
4603 }
4604 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4605 /* replace bytes val_beg->val_end with the cookie name associated
4606 * with this server since we know it.
4607 */
4608 int sliding, delta;
4609
4610 ctx.value = ist2(val_beg, val_end - val_beg);
4611 ctx.lws_before = ctx.lws_after = 0;
4612 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4613 delta = srv->cklen - (val_end - val_beg);
4614 sliding = (ctx.value.ptr - val_beg);
4615 hdr_beg += sliding;
4616 val_beg += sliding;
4617 next += sliding + delta;
4618 hdr_end += sliding + delta;
4619
4620 txn->flags &= ~TX_SCK_MASK;
4621 txn->flags |= TX_SCK_REPLACED;
4622 }
4623 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4624 /* insert the cookie name associated with this server
4625 * before existing cookie, and insert a delimiter between them..
4626 */
4627 int sliding, delta;
4628 ctx.value = ist2(val_beg, 0);
4629 ctx.lws_before = ctx.lws_after = 0;
4630 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4631 delta = srv->cklen + 1;
4632 sliding = (ctx.value.ptr - val_beg);
4633 hdr_beg += sliding;
4634 val_beg += sliding;
4635 next += sliding + delta;
4636 hdr_end += sliding + delta;
4637
4638 val_beg[srv->cklen] = COOKIE_DELIM;
4639 txn->flags &= ~TX_SCK_MASK;
4640 txn->flags |= TX_SCK_REPLACED;
4641 }
4642 }
4643 /* that's done for this cookie, check the next one on the same
4644 * line when next != hdr_end (only if is_cookie2).
4645 */
4646 }
4647 }
4648}
4649
Christopher Faulet25a02f62018-10-24 12:00:25 +02004650/*
4651 * Parses the Cache-Control and Pragma request header fields to determine if
4652 * the request may be served from the cache and/or if it is cacheable. Updates
4653 * s->txn->flags.
4654 */
4655void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4656{
4657 struct http_txn *txn = s->txn;
4658 struct htx *htx;
4659 int32_t pos;
4660 int pragma_found, cc_found, i;
4661
4662 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4663 return; /* nothing more to do here */
4664
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004665 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004666 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004667 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004668 struct htx_blk *blk = htx_get_blk(htx, pos);
4669 enum htx_blk_type type = htx_get_blk_type(blk);
4670 struct ist n, v;
4671
4672 if (type == HTX_BLK_EOH)
4673 break;
4674 if (type != HTX_BLK_HDR)
4675 continue;
4676
4677 n = htx_get_blk_name(htx, blk);
4678 v = htx_get_blk_value(htx, blk);
4679
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004680 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004681 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4682 pragma_found = 1;
4683 continue;
4684 }
4685 }
4686
4687 /* Don't use the cache and don't try to store if we found the
4688 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004689 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004690 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4691 txn->flags |= TX_CACHE_IGNORE;
4692 continue;
4693 }
4694
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004695 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004696 continue;
4697
4698 /* OK, right now we know we have a cache-control header */
4699 cc_found = 1;
4700 if (!v.len) /* no info */
4701 continue;
4702
4703 i = 0;
4704 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4705 !isspace((unsigned char)*(v.ptr+i)))
4706 i++;
4707
4708 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4709 * values after max-age, max-stale nor min-fresh, we simply don't
4710 * use the cache when they're specified.
4711 */
4712 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4713 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4714 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4715 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4716 txn->flags |= TX_CACHE_IGNORE;
4717 continue;
4718 }
4719
4720 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4721 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4722 continue;
4723 }
4724 }
4725
4726 /* RFC7234#5.4:
4727 * When the Cache-Control header field is also present and
4728 * understood in a request, Pragma is ignored.
4729 * When the Cache-Control header field is not present in a
4730 * request, caches MUST consider the no-cache request
4731 * pragma-directive as having the same effect as if
4732 * "Cache-Control: no-cache" were present.
4733 */
4734 if (!cc_found && pragma_found)
4735 txn->flags |= TX_CACHE_IGNORE;
4736}
4737
4738/*
4739 * Check if response is cacheable or not. Updates s->txn->flags.
4740 */
4741void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4742{
4743 struct http_txn *txn = s->txn;
4744 struct htx *htx;
4745 int32_t pos;
4746 int i;
4747
4748 if (txn->status < 200) {
4749 /* do not try to cache interim responses! */
4750 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4751 return;
4752 }
4753
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004754 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004755 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004756 struct htx_blk *blk = htx_get_blk(htx, pos);
4757 enum htx_blk_type type = htx_get_blk_type(blk);
4758 struct ist n, v;
4759
4760 if (type == HTX_BLK_EOH)
4761 break;
4762 if (type != HTX_BLK_HDR)
4763 continue;
4764
4765 n = htx_get_blk_name(htx, blk);
4766 v = htx_get_blk_value(htx, blk);
4767
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004768 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004769 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4770 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4771 return;
4772 }
4773 }
4774
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004775 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004776 continue;
4777
4778 /* OK, right now we know we have a cache-control header */
4779 if (!v.len) /* no info */
4780 continue;
4781
4782 i = 0;
4783 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4784 !isspace((unsigned char)*(v.ptr+i)))
4785 i++;
4786
4787 /* we have a complete value between v.ptr and (v.ptr+i) */
4788 if (i < v.len && *(v.ptr + i) == '=') {
4789 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4790 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4791 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4792 continue;
4793 }
4794
4795 /* we have something of the form no-cache="set-cookie" */
4796 if ((v.len >= 21) &&
4797 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4798 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4799 txn->flags &= ~TX_CACHE_COOK;
4800 continue;
4801 }
4802
4803 /* OK, so we know that either p2 points to the end of string or to a comma */
4804 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4805 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4806 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4807 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4808 return;
4809 }
4810
4811 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4812 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4813 continue;
4814 }
4815 }
4816}
4817
Christopher Faulet64159df2018-10-24 21:15:35 +02004818/* send a server's name with an outgoing request over an established connection.
4819 * Note: this function is designed to be called once the request has been
4820 * scheduled for being forwarded. This is the reason why the number of forwarded
4821 * bytes have to be adjusted.
4822 */
4823int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4824{
4825 struct htx *htx;
4826 struct http_hdr_ctx ctx;
4827 struct ist hdr;
4828 uint32_t data;
4829
4830 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004831 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004832 data = htx->data;
4833
4834 ctx.blk = NULL;
4835 while (http_find_header(htx, hdr, &ctx, 1))
4836 http_remove_header(htx, &ctx);
4837 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4838
4839 if (co_data(&s->req)) {
4840 if (data >= htx->data)
4841 c_rew(&s->req, data - htx->data);
4842 else
4843 c_adv(&s->req, htx->data - data);
4844 }
4845 return 0;
4846}
4847
Christopher Faulet377c5a52018-10-24 21:21:30 +02004848/*
4849 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4850 * for the current backend.
4851 *
4852 * It is assumed that the request is either a HEAD, GET, or POST and that the
4853 * uri_auth field is valid.
4854 *
4855 * Returns 1 if stats should be provided, otherwise 0.
4856 */
4857static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4858{
4859 struct uri_auth *uri_auth = backend->uri_auth;
4860 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004861 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004862 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004863
4864 if (!uri_auth)
4865 return 0;
4866
4867 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4868 return 0;
4869
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004870 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004871 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004872 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004873
4874 /* check URI size */
4875 if (uri_auth->uri_len > uri.len)
4876 return 0;
4877
4878 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4879 return 0;
4880
4881 return 1;
4882}
4883
4884/* This function prepares an applet to handle the stats. It can deal with the
4885 * "100-continue" expectation, check that admin rules are met for POST requests,
4886 * and program a response message if something was unexpected. It cannot fail
4887 * and always relies on the stats applet to complete the job. It does not touch
4888 * analysers nor counters, which are left to the caller. It does not touch
4889 * s->target which is supposed to already point to the stats applet. The caller
4890 * is expected to have already assigned an appctx to the stream.
4891 */
4892static int htx_handle_stats(struct stream *s, struct channel *req)
4893{
4894 struct stats_admin_rule *stats_admin_rule;
4895 struct stream_interface *si = &s->si[1];
4896 struct session *sess = s->sess;
4897 struct http_txn *txn = s->txn;
4898 struct http_msg *msg = &txn->req;
4899 struct uri_auth *uri_auth = s->be->uri_auth;
4900 const char *h, *lookup, *end;
4901 struct appctx *appctx;
4902 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004903 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004904
4905 appctx = si_appctx(si);
4906 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4907 appctx->st1 = appctx->st2 = 0;
4908 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4909 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4910 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4911 appctx->ctx.stats.flags |= STAT_CHUNKED;
4912
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004913 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004914 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004915 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4916 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004917
4918 for (h = lookup; h <= end - 3; h++) {
4919 if (memcmp(h, ";up", 3) == 0) {
4920 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4921 break;
4922 }
4923 }
4924
4925 if (uri_auth->refresh) {
4926 for (h = lookup; h <= end - 10; h++) {
4927 if (memcmp(h, ";norefresh", 10) == 0) {
4928 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4929 break;
4930 }
4931 }
4932 }
4933
4934 for (h = lookup; h <= end - 4; h++) {
4935 if (memcmp(h, ";csv", 4) == 0) {
4936 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4937 break;
4938 }
4939 }
4940
4941 for (h = lookup; h <= end - 6; h++) {
4942 if (memcmp(h, ";typed", 6) == 0) {
4943 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4944 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4945 break;
4946 }
4947 }
4948
4949 for (h = lookup; h <= end - 8; h++) {
4950 if (memcmp(h, ";st=", 4) == 0) {
4951 int i;
4952 h += 4;
4953 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4954 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4955 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4956 appctx->ctx.stats.st_code = i;
4957 break;
4958 }
4959 }
4960 break;
4961 }
4962 }
4963
4964 appctx->ctx.stats.scope_str = 0;
4965 appctx->ctx.stats.scope_len = 0;
4966 for (h = lookup; h <= end - 8; h++) {
4967 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4968 int itx = 0;
4969 const char *h2;
4970 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4971 const char *err;
4972
4973 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4974 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004975 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4976 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004977 if (*h == ';' || *h == '&' || *h == ' ')
4978 break;
4979 itx++;
4980 h++;
4981 }
4982
4983 if (itx > STAT_SCOPE_TXT_MAXLEN)
4984 itx = STAT_SCOPE_TXT_MAXLEN;
4985 appctx->ctx.stats.scope_len = itx;
4986
4987 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4988 memcpy(scope_txt, h2, itx);
4989 scope_txt[itx] = '\0';
4990 err = invalid_char(scope_txt);
4991 if (err) {
4992 /* bad char in search text => clear scope */
4993 appctx->ctx.stats.scope_str = 0;
4994 appctx->ctx.stats.scope_len = 0;
4995 }
4996 break;
4997 }
4998 }
4999
5000 /* now check whether we have some admin rules for this request */
5001 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5002 int ret = 1;
5003
5004 if (stats_admin_rule->cond) {
5005 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5006 ret = acl_pass(ret);
5007 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5008 ret = !ret;
5009 }
5010
5011 if (ret) {
5012 /* no rule, or the rule matches */
5013 appctx->ctx.stats.flags |= STAT_ADMIN;
5014 break;
5015 }
5016 }
5017
Christopher Faulet5d45e382019-02-27 15:15:23 +01005018 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5019 appctx->st0 = STAT_HTTP_HEAD;
5020 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005021 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005022 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005023 if (msg->msg_state < HTTP_MSG_DATA)
5024 req->analysers |= AN_REQ_HTTP_BODY;
5025 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005026 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005027 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005028 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5029 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5030 appctx->st0 = STAT_HTTP_LAST;
5031 }
5032 }
5033 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005034 /* Unsupported method */
5035 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5036 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5037 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005038 }
5039
5040 s->task->nice = -32; /* small boost for HTTP statistics */
5041 return 1;
5042}
5043
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005044void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5045{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005046 struct channel *req = &s->req;
5047 struct channel *res = &s->res;
5048 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005049 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005050 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005051 struct ist path, location;
5052 unsigned int flags;
5053 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005054
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005055 /*
5056 * Create the location
5057 */
5058 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005059
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005060 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005061 /* special prefix "/" means don't change URL */
5062 srv = __objt_server(s->target);
5063 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5064 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5065 return;
5066 }
5067
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005068 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005069 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005070 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005071 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005072 if (!path.ptr)
5073 return;
5074
5075 if (!chunk_memcat(&trash, path.ptr, path.len))
5076 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005077 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005078
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005079 /*
5080 * Create the 302 respone
5081 */
5082 htx = htx_from_buf(&res->buf);
5083 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5084 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5085 ist("HTTP/1.1"), ist("302"), ist("Found"));
5086 if (!sl)
5087 goto fail;
5088 sl->info.res.status = 302;
5089 s->txn->status = 302;
5090
5091 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5092 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5093 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5094 !htx_add_header(htx, ist("Location"), location))
5095 goto fail;
5096
5097 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5098 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005099
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005100 /*
5101 * Send the message
5102 */
5103 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005104 c_adv(res, data);
5105 res->total += data;
5106
5107 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005108 si_shutr(si);
5109 si_shutw(si);
5110 si->err_type = SI_ET_NONE;
5111 si->state = SI_ST_CLO;
5112
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005113 channel_auto_read(req);
5114 channel_abort(req);
5115 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005116 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005117 channel_auto_read(res);
5118 channel_auto_close(res);
5119
5120 if (!(s->flags & SF_ERR_MASK))
5121 s->flags |= SF_ERR_LOCAL;
5122 if (!(s->flags & SF_FINST_MASK))
5123 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005124
5125 /* FIXME: we should increase a counter of redirects per server and per backend. */
5126 srv_inc_sess_ctr(srv);
5127 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005128 return;
5129
5130 fail:
5131 /* If an error occurred, remove the incomplete HTTP response from the
5132 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005133 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005134}
5135
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136/* This function terminates the request because it was completly analyzed or
5137 * because an error was triggered during the body forwarding.
5138 */
5139static void htx_end_request(struct stream *s)
5140{
5141 struct channel *chn = &s->req;
5142 struct http_txn *txn = s->txn;
5143
5144 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5145 now_ms, __FUNCTION__, s,
5146 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5147 s->req.analysers, s->res.analysers);
5148
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005149 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5150 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005151 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005152 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005153 goto end;
5154 }
5155
5156 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5157 return;
5158
5159 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 /* No need to read anymore, the request was completely parsed.
5161 * We can shut the read side unless we want to abort_on_close,
5162 * or we have a POST request. The issue with POST requests is
5163 * that some browsers still send a CRLF after the request, and
5164 * this CRLF must be read so that it does not remain in the kernel
5165 * buffers, otherwise a close could cause an RST on some systems
5166 * (eg: Linux).
5167 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005168 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005169 channel_dont_read(chn);
5170
5171 /* if the server closes the connection, we want to immediately react
5172 * and close the socket to save packets and syscalls.
5173 */
5174 s->si[1].flags |= SI_FL_NOHALF;
5175
5176 /* In any case we've finished parsing the request so we must
5177 * disable Nagle when sending data because 1) we're not going
5178 * to shut this side, and 2) the server is waiting for us to
5179 * send pending data.
5180 */
5181 chn->flags |= CF_NEVER_WAIT;
5182
Christopher Fauletd01ce402019-01-02 17:44:13 +01005183 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5184 /* The server has not finished to respond, so we
5185 * don't want to move in order not to upset it.
5186 */
5187 return;
5188 }
5189
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 /* When we get here, it means that both the request and the
5191 * response have finished receiving. Depending on the connection
5192 * mode, we'll have to wait for the last bytes to leave in either
5193 * direction, and sometimes for a close to be effective.
5194 */
5195 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5196 /* Tunnel mode will not have any analyser so it needs to
5197 * poll for reads.
5198 */
5199 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005200 if (b_data(&chn->buf))
5201 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005202 txn->req.msg_state = HTTP_MSG_TUNNEL;
5203 }
5204 else {
5205 /* we're not expecting any new data to come for this
5206 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005207 *
5208 * However, there is an exception if the response
5209 * length is undefined. In this case, we need to wait
5210 * the close from the server. The response will be
5211 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005212 */
5213 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5214 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005215 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005216
5217 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5218 channel_shutr_now(chn);
5219 channel_shutw_now(chn);
5220 }
5221 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005222 goto check_channel_flags;
5223 }
5224
5225 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5226 http_msg_closing:
5227 /* nothing else to forward, just waiting for the output buffer
5228 * to be empty and for the shutw_now to take effect.
5229 */
5230 if (channel_is_empty(chn)) {
5231 txn->req.msg_state = HTTP_MSG_CLOSED;
5232 goto http_msg_closed;
5233 }
5234 else if (chn->flags & CF_SHUTW) {
5235 txn->req.err_state = txn->req.msg_state;
5236 txn->req.msg_state = HTTP_MSG_ERROR;
5237 goto end;
5238 }
5239 return;
5240 }
5241
5242 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5243 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005244 /* if we don't know whether the server will close, we need to hard close */
5245 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5246 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005247 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005248 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005249 channel_dont_read(chn);
5250 goto end;
5251 }
5252
5253 check_channel_flags:
5254 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5255 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5256 /* if we've just closed an output, let's switch */
5257 txn->req.msg_state = HTTP_MSG_CLOSING;
5258 goto http_msg_closing;
5259 }
5260
5261 end:
5262 chn->analysers &= AN_REQ_FLT_END;
5263 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5264 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5265 channel_auto_close(chn);
5266 channel_auto_read(chn);
5267}
5268
5269
5270/* This function terminates the response because it was completly analyzed or
5271 * because an error was triggered during the body forwarding.
5272 */
5273static void htx_end_response(struct stream *s)
5274{
5275 struct channel *chn = &s->res;
5276 struct http_txn *txn = s->txn;
5277
5278 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5279 now_ms, __FUNCTION__, s,
5280 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5281 s->req.analysers, s->res.analysers);
5282
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005283 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5284 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005285 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005286 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005287 goto end;
5288 }
5289
5290 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5291 return;
5292
5293 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5294 /* In theory, we don't need to read anymore, but we must
5295 * still monitor the server connection for a possible close
5296 * while the request is being uploaded, so we don't disable
5297 * reading.
5298 */
5299 /* channel_dont_read(chn); */
5300
5301 if (txn->req.msg_state < HTTP_MSG_DONE) {
5302 /* The client seems to still be sending data, probably
5303 * because we got an error response during an upload.
5304 * We have the choice of either breaking the connection
5305 * or letting it pass through. Let's do the later.
5306 */
5307 return;
5308 }
5309
5310 /* When we get here, it means that both the request and the
5311 * response have finished receiving. Depending on the connection
5312 * mode, we'll have to wait for the last bytes to leave in either
5313 * direction, and sometimes for a close to be effective.
5314 */
5315 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5316 channel_auto_read(chn);
5317 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005318 if (b_data(&chn->buf))
5319 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005320 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5321 }
5322 else {
5323 /* we're not expecting any new data to come for this
5324 * transaction, so we can close it.
5325 */
5326 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5327 channel_shutr_now(chn);
5328 channel_shutw_now(chn);
5329 }
5330 }
5331 goto check_channel_flags;
5332 }
5333
5334 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5335 http_msg_closing:
5336 /* nothing else to forward, just waiting for the output buffer
5337 * to be empty and for the shutw_now to take effect.
5338 */
5339 if (channel_is_empty(chn)) {
5340 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5341 goto http_msg_closed;
5342 }
5343 else if (chn->flags & CF_SHUTW) {
5344 txn->rsp.err_state = txn->rsp.msg_state;
5345 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005346 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005347 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005348 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005349 goto end;
5350 }
5351 return;
5352 }
5353
5354 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5355 http_msg_closed:
5356 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005357 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005358 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005359 goto end;
5360 }
5361
5362 check_channel_flags:
5363 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5364 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5365 /* if we've just closed an output, let's switch */
5366 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5367 goto http_msg_closing;
5368 }
5369
5370 end:
5371 chn->analysers &= AN_RES_FLT_END;
5372 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5373 chn->analysers |= AN_RES_FLT_XFER_DATA;
5374 channel_auto_close(chn);
5375 channel_auto_read(chn);
5376}
5377
Christopher Faulet0f226952018-10-22 09:29:56 +02005378void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5379 int finst, const struct buffer *msg)
5380{
5381 channel_auto_read(si_oc(si));
5382 channel_abort(si_oc(si));
5383 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005384 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005385 channel_auto_close(si_ic(si));
5386 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005387
5388 /* <msg> is an HTX structure. So we copy it in the response's
5389 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005390 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005391 struct channel *chn = si_ic(si);
5392 struct htx *htx;
5393
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005394 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005395 chn->buf.data = msg->data;
5396 memcpy(chn->buf.area, msg->area, msg->data);
5397 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005398 c_adv(chn, htx->data);
5399 chn->total += htx->data;
5400 }
5401 if (!(s->flags & SF_ERR_MASK))
5402 s->flags |= err;
5403 if (!(s->flags & SF_FINST_MASK))
5404 s->flags |= finst;
5405}
5406
5407void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5408{
5409 channel_auto_read(&s->req);
5410 channel_abort(&s->req);
5411 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005412 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5413 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005414
5415 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005416
5417 /* <msg> is an HTX structure. So we copy it in the response's
5418 * channel */
5419 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005420 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005421 struct channel *chn = &s->res;
5422 struct htx *htx;
5423
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005424 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005425 chn->buf.data = msg->data;
5426 memcpy(chn->buf.area, msg->area, msg->data);
5427 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005428 c_adv(chn, htx->data);
5429 chn->total += htx->data;
5430 }
5431
5432 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5433 channel_auto_read(&s->res);
5434 channel_auto_close(&s->res);
5435 channel_shutr_now(&s->res);
5436}
5437
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005438struct buffer *htx_error_message(struct stream *s)
5439{
5440 const int msgnum = http_get_status_idx(s->txn->status);
5441
5442 if (s->be->errmsg[msgnum].area)
5443 return &s->be->errmsg[msgnum];
5444 else if (strm_fe(s)->errmsg[msgnum].area)
5445 return &strm_fe(s)->errmsg[msgnum];
5446 else
5447 return &htx_err_chunks[msgnum];
5448}
5449
5450
Christopher Faulet4a28a532019-03-01 11:19:40 +01005451/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5452 * on success and -1 on error.
5453 */
5454static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5455{
5456 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5457 * then we must send an HTTP/1.1 100 Continue intermediate response.
5458 */
5459 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5460 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5461 struct ist hdr = { .ptr = "Expect", .len = 6 };
5462 struct http_hdr_ctx ctx;
5463
5464 ctx.blk = NULL;
5465 /* Expect is allowed in 1.1, look for it */
5466 if (http_find_header(htx, hdr, &ctx, 0) &&
5467 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5468 if (htx_reply_100_continue(s) == -1)
5469 return -1;
5470 http_remove_header(htx, &ctx);
5471 }
5472 }
5473 return 0;
5474}
5475
Christopher Faulet23a3c792018-11-28 10:01:23 +01005476/* Send a 100-Continue response to the client. It returns 0 on success and -1
5477 * on error. The response channel is updated accordingly.
5478 */
5479static int htx_reply_100_continue(struct stream *s)
5480{
5481 struct channel *res = &s->res;
5482 struct htx *htx = htx_from_buf(&res->buf);
5483 struct htx_sl *sl;
5484 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5485 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5486 size_t data;
5487
5488 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5489 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5490 if (!sl)
5491 goto fail;
5492 sl->info.res.status = 100;
5493
Christopher Faulet9869f932019-06-26 14:23:54 +02005494 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005495 goto fail;
5496
5497 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005498 c_adv(res, data);
5499 res->total += data;
5500 return 0;
5501
5502 fail:
5503 /* If an error occurred, remove the incomplete HTTP response from the
5504 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005505 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005506 return -1;
5507}
5508
Christopher Faulet12c51e22018-11-28 15:59:42 +01005509
5510/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5511 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5512 * error. The response channel is updated accordingly.
5513 */
5514static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5515{
5516 struct channel *res = &s->res;
5517 struct htx *htx = htx_from_buf(&res->buf);
5518 struct htx_sl *sl;
5519 struct ist code, body;
5520 int status;
5521 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5522 size_t data;
5523
5524 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5525 status = 401;
5526 code = ist("401");
5527 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5528 "You need a valid user and password to access this content.\n"
5529 "</body></html>\n");
5530 }
5531 else {
5532 status = 407;
5533 code = ist("407");
5534 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5535 "You need a valid user and password to access this content.\n"
5536 "</body></html>\n");
5537 }
5538
5539 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5540 ist("HTTP/1.1"), code, ist("Unauthorized"));
5541 if (!sl)
5542 goto fail;
5543 sl->info.res.status = status;
5544 s->txn->status = status;
5545
5546 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5547 goto fail;
5548
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005549 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5550 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005551 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005552 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5553 goto fail;
5554 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5555 goto fail;
5556 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005557 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005558 if (!htx_add_endof(htx, HTX_BLK_EOH))
5559 goto fail;
5560
5561 while (body.len) {
5562 size_t sent = htx_add_data(htx, body);
5563 if (!sent)
5564 goto fail;
5565 body.ptr += sent;
5566 body.len -= sent;
5567 }
5568
5569 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005570 goto fail;
5571
5572 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005573 c_adv(res, data);
5574 res->total += data;
5575
5576 channel_auto_read(&s->req);
5577 channel_abort(&s->req);
5578 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005579 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005580
5581 res->wex = tick_add_ifset(now_ms, res->wto);
5582 channel_auto_read(res);
5583 channel_auto_close(res);
5584 channel_shutr_now(res);
5585 return 0;
5586
5587 fail:
5588 /* If an error occurred, remove the incomplete HTTP response from the
5589 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005590 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005591 return -1;
5592}
5593
Christopher Faulet0f226952018-10-22 09:29:56 +02005594/*
5595 * Capture headers from message <htx> according to header list <cap_hdr>, and
5596 * fill the <cap> pointers appropriately.
5597 */
5598static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5599{
5600 struct cap_hdr *h;
5601 int32_t pos;
5602
Christopher Fauleta3f15502019-05-13 15:27:23 +02005603 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005604 struct htx_blk *blk = htx_get_blk(htx, pos);
5605 enum htx_blk_type type = htx_get_blk_type(blk);
5606 struct ist n, v;
5607
5608 if (type == HTX_BLK_EOH)
5609 break;
5610 if (type != HTX_BLK_HDR)
5611 continue;
5612
5613 n = htx_get_blk_name(htx, blk);
5614
5615 for (h = cap_hdr; h; h = h->next) {
5616 if (h->namelen && (h->namelen == n.len) &&
5617 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5618 if (cap[h->index] == NULL)
5619 cap[h->index] =
5620 pool_alloc(h->pool);
5621
5622 if (cap[h->index] == NULL) {
5623 ha_alert("HTTP capture : out of memory.\n");
5624 break;
5625 }
5626
5627 v = htx_get_blk_value(htx, blk);
5628 if (v.len > h->len)
5629 v.len = h->len;
5630
5631 memcpy(cap[h->index], v.ptr, v.len);
5632 cap[h->index][v.len]=0;
5633 }
5634 }
5635 }
5636}
5637
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005638/* Delete a value in a header between delimiters <from> and <next>. The header
5639 * itself is delimited by <start> and <end> pointers. The number of characters
5640 * displaced is returned, and the pointer to the first delimiter is updated if
5641 * required. The function tries as much as possible to respect the following
5642 * principles :
5643 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5644 * in which case <next> is simply removed
5645 * - set exactly one space character after the new first delimiter, unless there
5646 * are not enough characters in the block being moved to do so.
5647 * - remove unneeded spaces before the previous delimiter and after the new
5648 * one.
5649 *
5650 * It is the caller's responsibility to ensure that :
5651 * - <from> points to a valid delimiter or <start> ;
5652 * - <next> points to a valid delimiter or <end> ;
5653 * - there are non-space chars before <from>.
5654 */
5655static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5656{
5657 char *prev = *from;
5658
5659 if (prev == start) {
5660 /* We're removing the first value. eat the semicolon, if <next>
5661 * is lower than <end> */
5662 if (next < end)
5663 next++;
5664
5665 while (next < end && HTTP_IS_SPHT(*next))
5666 next++;
5667 }
5668 else {
5669 /* Remove useless spaces before the old delimiter. */
5670 while (HTTP_IS_SPHT(*(prev-1)))
5671 prev--;
5672 *from = prev;
5673
5674 /* copy the delimiter and if possible a space if we're
5675 * not at the end of the line.
5676 */
5677 if (next < end) {
5678 *prev++ = *next++;
5679 if (prev + 1 < next)
5680 *prev++ = ' ';
5681 while (next < end && HTTP_IS_SPHT(*next))
5682 next++;
5683 }
5684 }
5685 memmove(prev, next, end - next);
5686 return (prev - next);
5687}
5688
Christopher Faulet0f226952018-10-22 09:29:56 +02005689
5690/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005691 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005692 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005693static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005694{
5695 struct ist dst = ist2(str, 0);
5696
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005697 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005698 goto end;
5699 if (dst.len + 1 > len)
5700 goto end;
5701 dst.ptr[dst.len++] = ' ';
5702
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005703 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005704 goto end;
5705 if (dst.len + 1 > len)
5706 goto end;
5707 dst.ptr[dst.len++] = ' ';
5708
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005709 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 end:
5711 return dst.len;
5712}
5713
Christopher Fauletf0523542018-10-24 11:06:58 +02005714/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005715 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005716 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005717static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005718{
5719 struct ist dst = ist2(str, 0);
5720
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005721 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005722 goto end;
5723 if (dst.len + 1 > len)
5724 goto end;
5725 dst.ptr[dst.len++] = ' ';
5726
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005727 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005728 goto end;
5729 if (dst.len + 1 > len)
5730 goto end;
5731 dst.ptr[dst.len++] = ' ';
5732
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005733 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005734 end:
5735 return dst.len;
5736}
5737
5738
Christopher Faulet0f226952018-10-22 09:29:56 +02005739/*
5740 * Print a debug line with a start line.
5741 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005742static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005743{
5744 struct session *sess = strm_sess(s);
5745 int max;
5746
5747 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5748 dir,
5749 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5750 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5751
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005752 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005753 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005754 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005755 trash.area[trash.data++] = ' ';
5756
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005757 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005758 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005759 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005760 trash.area[trash.data++] = ' ';
5761
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005762 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005763 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005764 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005765 trash.area[trash.data++] = '\n';
5766
5767 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5768}
5769
5770/*
5771 * Print a debug line with a header.
5772 */
5773static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5774{
5775 struct session *sess = strm_sess(s);
5776 int max;
5777
5778 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5779 dir,
5780 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5781 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5782
5783 max = n.len;
5784 UBOUND(max, trash.size - trash.data - 3);
5785 chunk_memcat(&trash, n.ptr, max);
5786 trash.area[trash.data++] = ':';
5787 trash.area[trash.data++] = ' ';
5788
5789 max = v.len;
5790 UBOUND(max, trash.size - trash.data - 1);
5791 chunk_memcat(&trash, v.ptr, max);
5792 trash.area[trash.data++] = '\n';
5793
5794 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5795}
5796
5797
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005798__attribute__((constructor))
5799static void __htx_protocol_init(void)
5800{
5801}
5802
5803
5804/*
5805 * Local variables:
5806 * c-indent-level: 8
5807 * c-basic-offset: 8
5808 * End:
5809 */