blob: 89e428496a1a7bb303fead2b7000da4637dfd0b7 [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 */
Christopher Faulet304cc402019-07-15 15:46:28 +0200109 s->srv_error = htx_return_srv_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200110
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 Faulet8f1aa772019-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 Tarreau69564b12019-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 Houchard29cac3c2019-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
Christopher Faulete0768eb2018-10-03 16:38:02 +02001188 /* in most states, we should abort in case of early close */
1189 channel_auto_close(req);
1190
1191 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001192 if (req->to_forward == CHN_INFINITE_FORWARD) {
1193 if (req->flags & (CF_SHUTR|CF_EOI)) {
1194 msg->msg_state = HTTP_MSG_DONE;
1195 req->to_forward = 0;
1196 goto done;
1197 }
1198 }
1199 else {
1200 /* We can't process the buffer's contents yet */
1201 req->flags |= CF_WAKE_WRITE;
1202 goto missing_data_or_waiting;
1203 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001204 }
1205
Christopher Faulet9768c262018-10-22 09:34:31 +02001206 if (msg->msg_state >= HTTP_MSG_DONE)
1207 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001208 /* Forward input data. We get it by removing all outgoing data not
1209 * forwarded yet from HTX data size. If there are some data filters, we
1210 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001211 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001212 if (HAS_REQ_DATA_FILTERS(s)) {
1213 ret = flt_http_payload(s, msg, htx->data);
1214 if (ret < 0)
1215 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001216 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001217 }
1218 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001219 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001220 if (msg->flags & HTTP_MSGF_XFER_LEN)
1221 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001222 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001223
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001224 if (txn->meth == HTTP_METH_CONNECT) {
1225 msg->msg_state = HTTP_MSG_TUNNEL;
1226 goto done;
1227 }
1228
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001229
Christopher Faulet9768c262018-10-22 09:34:31 +02001230 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001231 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1232 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001233 */
1234 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1235 goto missing_data_or_waiting;
1236
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001237 msg->msg_state = HTTP_MSG_ENDING;
1238 if (htx->data != co_data(req))
1239 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001240 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001241 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001242
1243 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001244 /* other states, DONE...TUNNEL */
1245 /* we don't want to forward closes on DONE except in tunnel mode. */
1246 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1247 channel_dont_close(req);
1248
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001249 if (HAS_REQ_DATA_FILTERS(s)) {
1250 ret = flt_http_end(s, msg);
1251 if (ret <= 0) {
1252 if (!ret)
1253 goto missing_data_or_waiting;
1254 goto return_bad_req;
1255 }
1256 }
1257
Christopher Fauletf2824e62018-10-01 12:12:37 +02001258 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001259 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001260 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001261 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1262 if (req->flags & CF_SHUTW) {
1263 /* request errors are most likely due to the
1264 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001265 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001266 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001267 goto return_bad_req;
1268 }
1269 return 1;
1270 }
1271
1272 /* If "option abortonclose" is set on the backend, we want to monitor
1273 * the client's connection and forward any shutdown notification to the
1274 * server, which will decide whether to close or to go on processing the
1275 * request. We only do that in tunnel mode, and not in other modes since
1276 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001277 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 channel_auto_read(req);
1279 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1280 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1281 s->si[1].flags |= SI_FL_NOLINGER;
1282 channel_auto_close(req);
1283 }
1284 else if (s->txn->meth == HTTP_METH_POST) {
1285 /* POST requests may require to read extra CRLF sent by broken
1286 * browsers and which could cause an RST to be sent upon close
1287 * on some systems (eg: Linux). */
1288 channel_auto_read(req);
1289 }
1290 return 0;
1291
1292 missing_data_or_waiting:
1293 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001294 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001295 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001296
1297 waiting:
1298 /* waiting for the last bits to leave the buffer */
1299 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001300 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001301
Christopher Faulet47365272018-10-31 17:40:50 +01001302 if (htx->flags & HTX_FL_PARSING_ERROR)
1303 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001304
Christopher Faulete0768eb2018-10-03 16:38:02 +02001305 /* When TE: chunked is used, we need to get there again to parse remaining
1306 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1307 * And when content-length is used, we never want to let the possible
1308 * shutdown be forwarded to the other side, as the state machine will
1309 * take care of it once the client responds. It's also important to
1310 * prevent TIME_WAITs from accumulating on the backend side, and for
1311 * HTTP/2 where the last frame comes with a shutdown.
1312 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001313 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001314 channel_dont_close(req);
1315
1316 /* We know that more data are expected, but we couldn't send more that
1317 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1318 * system knows it must not set a PUSH on this first part. Interactive
1319 * modes are already handled by the stream sock layer. We must not do
1320 * this in content-length mode because it could present the MSG_MORE
1321 * flag with the last block of forwarded data, which would cause an
1322 * additional delay to be observed by the receiver.
1323 */
1324 if (msg->flags & HTTP_MSGF_TE_CHNK)
1325 req->flags |= CF_EXPECT_MORE;
1326
1327 return 0;
1328
Christopher Faulet93e02d82019-03-08 14:18:50 +01001329 return_cli_abort:
1330 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1331 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1332 if (objt_server(s->target))
1333 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1334 if (!(s->flags & SF_ERR_MASK))
1335 s->flags |= SF_ERR_CLICL;
1336 status = 400;
1337 goto return_error;
1338
1339 return_srv_abort:
1340 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1341 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1342 if (objt_server(s->target))
1343 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1344 if (!(s->flags & SF_ERR_MASK))
1345 s->flags |= SF_ERR_SRVCL;
1346 status = 502;
1347 goto return_error;
1348
1349 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001351 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001352 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001353 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001354 s->flags |= SF_ERR_CLICL;
1355 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001356
Christopher Faulet93e02d82019-03-08 14:18:50 +01001357 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 txn->req.err_state = txn->req.msg_state;
1359 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001360 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001362 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001364 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001365 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 }
1367 req->analysers &= AN_REQ_FLT_END;
1368 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 +01001369 if (!(s->flags & SF_FINST_MASK))
1370 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 return 0;
1372}
1373
Olivier Houcharda254a372019-04-05 15:30:12 +02001374/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1375/* Returns 0 if we can attempt to retry, -1 otherwise */
1376static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1377{
1378 struct channel *req, *res;
1379 int co_data;
1380
1381 si->conn_retries--;
1382 if (si->conn_retries < 0)
1383 return -1;
1384
Willy Tarreau223995e2019-05-04 10:38:31 +02001385 if (objt_server(s->target))
1386 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1387 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1388
Olivier Houcharda254a372019-04-05 15:30:12 +02001389 req = &s->req;
1390 res = &s->res;
1391 /* Remove any write error from the request, and read error from the response */
1392 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1393 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1394 res->analysers = 0;
1395 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard4bd58672019-07-12 16:16:59 +02001396 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001397 si->exp = TICK_ETERNITY;
1398 res->rex = TICK_ETERNITY;
1399 res->to_forward = 0;
1400 res->analyse_exp = TICK_ETERNITY;
1401 res->total = 0;
Olivier Houchard4bd58672019-07-12 16:16:59 +02001402 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001403 si_release_endpoint(&s->si[1]);
1404 b_free(&req->buf);
1405 /* Swap the L7 buffer with the channel buffer */
1406 /* We know we stored the co_data as b_data, so get it there */
1407 co_data = b_data(&si->l7_buffer);
1408 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1409 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1410
1411 co_set_data(req, co_data);
1412 b_reset(&res->buf);
1413 co_set_data(res, 0);
1414 return 0;
1415}
1416
Christopher Faulete0768eb2018-10-03 16:38:02 +02001417/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1418 * processing can continue on next analysers, or zero if it either needs more
1419 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1420 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1421 * when it has nothing left to do, and may remove any analyser when it wants to
1422 * abort.
1423 */
1424int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1425{
Christopher Faulet9768c262018-10-22 09:34:31 +02001426 /*
1427 * We will analyze a complete HTTP response to check the its syntax.
1428 *
1429 * Once the start line and all headers are received, we may perform a
1430 * capture of the error (if any), and we will set a few fields. We also
1431 * logging and finally headers capture.
1432 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001433 struct session *sess = s->sess;
1434 struct http_txn *txn = s->txn;
1435 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001436 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001437 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001438 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001439 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001440 int n;
1441
1442 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1443 now_ms, __FUNCTION__,
1444 s,
1445 rep,
1446 rep->rex, rep->wex,
1447 rep->flags,
1448 ci_data(rep),
1449 rep->analysers);
1450
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001451 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452
Willy Tarreau4236f032019-03-05 10:43:32 +01001453 /* Parsing errors are caught here */
1454 if (htx->flags & HTX_FL_PARSING_ERROR)
1455 goto return_bad_res;
1456
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 /*
1458 * Now we quickly check if we have found a full valid response.
1459 * If not so, we check the FD and buffer states before leaving.
1460 * A full response is indicated by the fact that we have seen
1461 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1462 * responses are checked first.
1463 *
1464 * Depending on whether the client is still there or not, we
1465 * may send an error response back or not. Note that normally
1466 * we should only check for HTTP status there, and check I/O
1467 * errors somewhere else.
1468 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001469 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001470 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001471 /* 1: have we encountered a read error ? */
1472 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001473 struct connection *conn = NULL;
1474
Olivier Houchard865d8392019-05-03 22:46:27 +02001475 if (objt_cs(s->si[1].end))
1476 conn = objt_cs(s->si[1].end)->conn;
1477
1478 if (si_b->flags & SI_FL_L7_RETRY &&
1479 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001480 /* If we arrive here, then CF_READ_ERROR was
1481 * set by si_cs_recv() because we matched a
1482 * status, overwise it would have removed
1483 * the SI_FL_L7_RETRY flag, so it's ok not
1484 * to check s->be->retry_type.
1485 */
1486 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1487 return 0;
1488 }
1489
Olivier Houchard6db16992019-05-17 15:40:49 +02001490 if (txn->flags & TX_NOT_FIRST)
1491 goto abort_keep_alive;
1492
Olivier Houcharda798bf52019-03-08 18:52:00 +01001493 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001495 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001496 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001497 }
1498
Christopher Faulete0768eb2018-10-03 16:38:02 +02001499 rep->analysers &= AN_RES_FLT_END;
1500 txn->status = 502;
1501
1502 /* Check to see if the server refused the early data.
1503 * If so, just send a 425
1504 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001505 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1506 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001507 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001508 do_l7_retry(s, si_b) == 0)
1509 return 0;
1510 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511 }
1512
1513 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001514 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515
1516 if (!(s->flags & SF_ERR_MASK))
1517 s->flags |= SF_ERR_SRVCL;
1518 if (!(s->flags & SF_FINST_MASK))
1519 s->flags |= SF_FINST_H;
1520 return 0;
1521 }
1522
Christopher Faulet9768c262018-10-22 09:34:31 +02001523 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001525 if ((si_b->flags & SI_FL_L7_RETRY) &&
1526 (s->be->retry_type & PR_RE_TIMEOUT)) {
1527 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1528 return 0;
1529 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001530 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001532 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001533 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 rep->analysers &= AN_RES_FLT_END;
1537 txn->status = 504;
1538 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001539 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540
1541 if (!(s->flags & SF_ERR_MASK))
1542 s->flags |= SF_ERR_SRVTO;
1543 if (!(s->flags & SF_FINST_MASK))
1544 s->flags |= SF_FINST_H;
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001550 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1551 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 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.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554
1555 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001557 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558
1559 if (!(s->flags & SF_ERR_MASK))
1560 s->flags |= SF_ERR_CLICL;
1561 if (!(s->flags & SF_FINST_MASK))
1562 s->flags |= SF_FINST_H;
1563
1564 /* process_stream() will take care of the error */
1565 return 0;
1566 }
1567
Christopher Faulet9768c262018-10-22 09:34:31 +02001568 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001570 if ((si_b->flags & SI_FL_L7_RETRY) &&
1571 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1572 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1573 return 0;
1574 }
1575
Olivier Houchard6db16992019-05-17 15:40:49 +02001576 if (txn->flags & TX_NOT_FIRST)
1577 goto abort_keep_alive;
1578
Olivier Houcharda798bf52019-03-08 18:52:00 +01001579 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001580 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001581 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001582 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583 }
1584
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585 rep->analysers &= AN_RES_FLT_END;
1586 txn->status = 502;
1587 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001588 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001589
1590 if (!(s->flags & SF_ERR_MASK))
1591 s->flags |= SF_ERR_SRVCL;
1592 if (!(s->flags & SF_FINST_MASK))
1593 s->flags |= SF_FINST_H;
1594 return 0;
1595 }
1596
Christopher Faulet9768c262018-10-22 09:34:31 +02001597 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001598 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001599 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600 goto abort_keep_alive;
1601
Olivier Houcharda798bf52019-03-08 18:52:00 +01001602 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604
1605 if (!(s->flags & SF_ERR_MASK))
1606 s->flags |= SF_ERR_CLICL;
1607 if (!(s->flags & SF_FINST_MASK))
1608 s->flags |= SF_FINST_H;
1609
1610 /* process_stream() will take care of the error */
1611 return 0;
1612 }
1613
1614 channel_dont_close(rep);
1615 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1616 return 0;
1617 }
1618
1619 /* More interesting part now : we know that we have a complete
1620 * response which at least looks like HTTP. We have an indicator
1621 * of each header's length, so we can parse them quickly.
1622 */
1623
Christopher Faulet9768c262018-10-22 09:34:31 +02001624 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001625 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001626 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 /* 0: we might have to print this header in debug mode */
1629 if (unlikely((global.mode & MODE_DEBUG) &&
1630 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1631 int32_t pos;
1632
Christopher Faulet03599112018-11-27 11:21:21 +01001633 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001634
Christopher Fauleta3f15502019-05-13 15:27:23 +02001635 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001636 struct htx_blk *blk = htx_get_blk(htx, pos);
1637 enum htx_blk_type type = htx_get_blk_type(blk);
1638
1639 if (type == HTX_BLK_EOH)
1640 break;
1641 if (type != HTX_BLK_HDR)
1642 continue;
1643
1644 htx_debug_hdr("srvhdr", s,
1645 htx_get_blk_name(htx, blk),
1646 htx_get_blk_value(htx, blk));
1647 }
1648 }
1649
Christopher Faulet03599112018-11-27 11:21:21 +01001650 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001651 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001652 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001653 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001654 if (sl->flags & HTX_SL_F_XFER_LEN) {
1655 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001656 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001657 if (sl->flags & HTX_SL_F_BODYLESS)
1658 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001659 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001660
1661 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001662 if (n < 1 || n > 5)
1663 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001664
Christopher Faulete0768eb2018-10-03 16:38:02 +02001665 /* when the client triggers a 4xx from the server, it's most often due
1666 * to a missing object or permission. These events should be tracked
1667 * because if they happen often, it may indicate a brute force or a
1668 * vulnerability scan.
1669 */
1670 if (n == 4)
1671 stream_inc_http_err_ctr(s);
1672
1673 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001674 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675
Christopher Faulete0768eb2018-10-03 16:38:02 +02001676 /* Adjust server's health based on status code. Note: status codes 501
1677 * and 505 are triggered on demand by client request, so we must not
1678 * count them as server failures.
1679 */
1680 if (objt_server(s->target)) {
1681 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001682 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001683 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001684 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001685 }
1686
1687 /*
1688 * We may be facing a 100-continue response, or any other informational
1689 * 1xx response which is non-final, in which case this is not the right
1690 * response, and we're waiting for the next one. Let's allow this response
1691 * to go to the client and wait for the next one. There's an exception for
1692 * 101 which is used later in the code to switch protocols.
1693 */
1694 if (txn->status < 200 &&
1695 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001696 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001697 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001698 msg->msg_state = HTTP_MSG_RPBEFORE;
1699 txn->status = 0;
1700 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001701 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 }
1703
1704 /*
1705 * 2: check for cacheability.
1706 */
1707
1708 switch (txn->status) {
1709 case 200:
1710 case 203:
1711 case 204:
1712 case 206:
1713 case 300:
1714 case 301:
1715 case 404:
1716 case 405:
1717 case 410:
1718 case 414:
1719 case 501:
1720 break;
1721 default:
1722 /* RFC7231#6.1:
1723 * Responses with status codes that are defined as
1724 * cacheable by default (e.g., 200, 203, 204, 206,
1725 * 300, 301, 404, 405, 410, 414, and 501 in this
1726 * specification) can be reused by a cache with
1727 * heuristic expiration unless otherwise indicated
1728 * by the method definition or explicit cache
1729 * controls [RFC7234]; all other status codes are
1730 * not cacheable by default.
1731 */
1732 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1733 break;
1734 }
1735
1736 /*
1737 * 3: we may need to capture headers
1738 */
1739 s->logs.logwait &= ~LW_RESP;
1740 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001741 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001742
Christopher Faulet9768c262018-10-22 09:34:31 +02001743 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001744 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1745 txn->status == 101)) {
1746 /* Either we've established an explicit tunnel, or we're
1747 * switching the protocol. In both cases, we're very unlikely
1748 * to understand the next protocols. We have to switch to tunnel
1749 * mode, so that we transfer the request and responses then let
1750 * this protocol pass unmodified. When we later implement specific
1751 * parsers for such protocols, we'll want to check the Upgrade
1752 * header which contains information about that protocol for
1753 * responses with status 101 (eg: see RFC2817 about TLS).
1754 */
1755 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001756 }
1757
Christopher Faulet61608322018-11-23 16:23:45 +01001758 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1759 * 407 (Proxy-Authenticate) responses and set the connection to private
1760 */
1761 srv_conn = cs_conn(objt_cs(s->si[1].end));
1762 if (srv_conn) {
1763 struct ist hdr;
1764 struct http_hdr_ctx ctx;
1765
1766 if (txn->status == 401)
1767 hdr = ist("WWW-Authenticate");
1768 else if (txn->status == 407)
1769 hdr = ist("Proxy-Authenticate");
1770 else
1771 goto end;
1772
1773 ctx.blk = NULL;
1774 while (http_find_header(htx, hdr, &ctx, 0)) {
1775 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001776 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1777 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001778 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001779 }
Christopher Faulet61608322018-11-23 16:23:45 +01001780 }
1781 }
1782
1783 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 /* we want to have the response time before we start processing it */
1785 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1786
1787 /* end of job, return OK */
1788 rep->analysers &= ~an_bit;
1789 rep->analyse_exp = TICK_ETERNITY;
1790 channel_auto_close(rep);
1791 return 1;
1792
Christopher Faulet47365272018-10-31 17:40:50 +01001793 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001794 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001795 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001796 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001797 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001798 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001799 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001800 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001801 do_l7_retry(s, si_b) == 0)
1802 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001803 txn->status = 502;
1804 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001805 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001806 rep->analysers &= AN_RES_FLT_END;
1807
1808 if (!(s->flags & SF_ERR_MASK))
1809 s->flags |= SF_ERR_PRXCOND;
1810 if (!(s->flags & SF_FINST_MASK))
1811 s->flags |= SF_FINST_H;
1812 return 0;
1813
Christopher Faulete0768eb2018-10-03 16:38:02 +02001814 abort_keep_alive:
1815 /* A keep-alive request to the server failed on a network error.
1816 * The client is required to retry. We need to close without returning
1817 * any other information so that the client retries.
1818 */
1819 txn->status = 0;
1820 rep->analysers &= AN_RES_FLT_END;
1821 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001822 s->logs.logwait = 0;
1823 s->logs.level = 0;
1824 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001825 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001826 return 0;
1827}
1828
1829/* This function performs all the processing enabled for the current response.
1830 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1831 * and updates s->res.analysers. It might make sense to explode it into several
1832 * other functions. It works like process_request (see indications above).
1833 */
1834int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1835{
1836 struct session *sess = s->sess;
1837 struct http_txn *txn = s->txn;
1838 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001839 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001840 struct proxy *cur_proxy;
1841 struct cond_wordlist *wl;
1842 enum rule_result ret = HTTP_RULE_RES_CONT;
1843
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001844 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1845 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001846
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1848 now_ms, __FUNCTION__,
1849 s,
1850 rep,
1851 rep->rex, rep->wex,
1852 rep->flags,
1853 ci_data(rep),
1854 rep->analysers);
1855
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001856 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001857
1858 /* The stats applet needs to adjust the Connection header but we don't
1859 * apply any filter there.
1860 */
1861 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1862 rep->analysers &= ~an_bit;
1863 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001864 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001865 }
1866
1867 /*
1868 * We will have to evaluate the filters.
1869 * As opposed to version 1.2, now they will be evaluated in the
1870 * filters order and not in the header order. This means that
1871 * each filter has to be validated among all headers.
1872 *
1873 * Filters are tried with ->be first, then with ->fe if it is
1874 * different from ->be.
1875 *
1876 * Maybe we are in resume condiion. In this case I choose the
1877 * "struct proxy" which contains the rule list matching the resume
1878 * pointer. If none of theses "struct proxy" match, I initialise
1879 * the process with the first one.
1880 *
1881 * In fact, I check only correspondance betwwen the current list
1882 * pointer and the ->fe rule list. If it doesn't match, I initialize
1883 * the loop with the ->be.
1884 */
1885 if (s->current_rule_list == &sess->fe->http_res_rules)
1886 cur_proxy = sess->fe;
1887 else
1888 cur_proxy = s->be;
1889 while (1) {
1890 struct proxy *rule_set = cur_proxy;
1891
1892 /* evaluate http-response rules */
1893 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001894 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001895
1896 if (ret == HTTP_RULE_RES_BADREQ)
1897 goto return_srv_prx_502;
1898
1899 if (ret == HTTP_RULE_RES_DONE) {
1900 rep->analysers &= ~an_bit;
1901 rep->analyse_exp = TICK_ETERNITY;
1902 return 1;
1903 }
1904 }
1905
1906 /* we need to be called again. */
1907 if (ret == HTTP_RULE_RES_YIELD) {
1908 channel_dont_close(rep);
1909 return 0;
1910 }
1911
1912 /* try headers filters */
1913 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001914 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1915 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001916 }
1917
1918 /* has the response been denied ? */
1919 if (txn->flags & TX_SVDENY) {
1920 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001921 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001922
Olivier Houcharda798bf52019-03-08 18:52:00 +01001923 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1924 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001925 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001926 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001927 goto return_srv_prx_502;
1928 }
1929
1930 /* add response headers from the rule sets in the same order */
1931 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001932 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933 if (txn->status < 200 && txn->status != 101)
1934 break;
1935 if (wl->cond) {
1936 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1937 ret = acl_pass(ret);
1938 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1939 ret = !ret;
1940 if (!ret)
1941 continue;
1942 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001943
1944 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1945 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001946 goto return_bad_resp;
1947 }
1948
1949 /* check whether we're already working on the frontend */
1950 if (cur_proxy == sess->fe)
1951 break;
1952 cur_proxy = sess->fe;
1953 }
1954
1955 /* After this point, this anayzer can't return yield, so we can
1956 * remove the bit corresponding to this analyzer from the list.
1957 *
1958 * Note that the intermediate returns and goto found previously
1959 * reset the analyzers.
1960 */
1961 rep->analysers &= ~an_bit;
1962 rep->analyse_exp = TICK_ETERNITY;
1963
1964 /* OK that's all we can do for 1xx responses */
1965 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001966 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967
1968 /*
1969 * Now check for a server cookie.
1970 */
1971 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001972 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001973
1974 /*
1975 * Check for cache-control or pragma headers if required.
1976 */
1977 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
Christopher Faulet75b4cd92019-07-15 22:26:28 +02001978 htx_check_response_for_cacheability(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001979
1980 /*
1981 * Add server cookie in the response if needed
1982 */
1983 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1984 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1985 (!(s->flags & SF_DIRECT) ||
1986 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1987 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1988 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1989 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1990 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1991 !(s->flags & SF_IGNORE_PRST)) {
1992 /* the server is known, it's not the one the client requested, or the
1993 * cookie's last seen date needs to be refreshed. We have to
1994 * insert a set-cookie here, except if we want to insert only on POST
1995 * requests and this one isn't. Note that servers which don't have cookies
1996 * (eg: some backup servers) will return a full cookie removal request.
1997 */
1998 if (!objt_server(s->target)->cookie) {
1999 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002000 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002001 s->be->cookie_name);
2002 }
2003 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002004 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002005
2006 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2007 /* emit last_date, which is mandatory */
2008 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2009 s30tob64((date.tv_sec+3) >> 2,
2010 trash.area + trash.data);
2011 trash.data += 5;
2012
2013 if (s->be->cookie_maxlife) {
2014 /* emit first_date, which is either the original one or
2015 * the current date.
2016 */
2017 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2018 s30tob64(txn->cookie_first_date ?
2019 txn->cookie_first_date >> 2 :
2020 (date.tv_sec+3) >> 2,
2021 trash.area + trash.data);
2022 trash.data += 5;
2023 }
2024 }
2025 chunk_appendf(&trash, "; path=/");
2026 }
2027
2028 if (s->be->cookie_domain)
2029 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2030
2031 if (s->be->ck_opts & PR_CK_HTTPONLY)
2032 chunk_appendf(&trash, "; HttpOnly");
2033
2034 if (s->be->ck_opts & PR_CK_SECURE)
2035 chunk_appendf(&trash, "; Secure");
2036
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002037 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002038 goto return_bad_resp;
2039
2040 txn->flags &= ~TX_SCK_MASK;
2041 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2042 /* the server did not change, only the date was updated */
2043 txn->flags |= TX_SCK_UPDATED;
2044 else
2045 txn->flags |= TX_SCK_INSERTED;
2046
2047 /* Here, we will tell an eventual cache on the client side that we don't
2048 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2049 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2050 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2051 */
2052 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2053
2054 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2055
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002057 goto return_bad_resp;
2058 }
2059 }
2060
2061 /*
2062 * Check if result will be cacheable with a cookie.
2063 * We'll block the response if security checks have caught
2064 * nasty things such as a cacheable cookie.
2065 */
2066 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2067 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2068 (s->be->options & PR_O_CHK_CACHE)) {
2069 /* we're in presence of a cacheable response containing
2070 * a set-cookie header. We'll block it as requested by
2071 * the 'checkcache' option, and send an alert.
2072 */
2073 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002074 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002075
Olivier Houcharda798bf52019-03-08 18:52:00 +01002076 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2077 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002078 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002079 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002080
2081 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2082 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2083 send_log(s->be, LOG_ALERT,
2084 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2085 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2086 goto return_srv_prx_502;
2087 }
2088
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002089 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090 /* Always enter in the body analyzer */
2091 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2092 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2093
2094 /* if the user wants to log as soon as possible, without counting
2095 * bytes from the server, then this is the right moment. We have
2096 * to temporarily assign bytes_out to log what we currently have.
2097 */
2098 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2099 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002100 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101 s->do_log(s);
2102 s->logs.bytes_out = 0;
2103 }
2104 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002105
2106 return_bad_resp:
2107 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002108 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002109 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002110 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002111 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112
2113 return_srv_prx_502:
2114 rep->analysers &= AN_RES_FLT_END;
2115 txn->status = 502;
2116 s->logs.t_data = -1; /* was not a valid response */
2117 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002118 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002119 if (!(s->flags & SF_ERR_MASK))
2120 s->flags |= SF_ERR_PRXCOND;
2121 if (!(s->flags & SF_FINST_MASK))
2122 s->flags |= SF_FINST_H;
2123 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124}
2125
2126/* This function is an analyser which forwards response body (including chunk
2127 * sizes if any). It is called as soon as we must forward, even if we forward
2128 * zero byte. The only situation where it must not be called is when we're in
2129 * tunnel mode and we want to forward till the close. It's used both to forward
2130 * remaining data and to resync after end of body. It expects the msg_state to
2131 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2132 * read more data, or 1 once we can go on with next request or end the stream.
2133 *
2134 * It is capable of compressing response data both in content-length mode and
2135 * in chunked mode. The state machines follows different flows depending on
2136 * whether content-length and chunked modes are used, since there are no
2137 * trailers in content-length :
2138 *
2139 * chk-mode cl-mode
2140 * ,----- BODY -----.
2141 * / \
2142 * V size > 0 V chk-mode
2143 * .--> SIZE -------------> DATA -------------> CRLF
2144 * | | size == 0 | last byte |
2145 * | v final crlf v inspected |
2146 * | TRAILERS -----------> DONE |
2147 * | |
2148 * `----------------------------------------------'
2149 *
2150 * Compression only happens in the DATA state, and must be flushed in final
2151 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2152 * is performed at once on final states for all bytes parsed, or when leaving
2153 * on missing data.
2154 */
2155int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2156{
2157 struct session *sess = s->sess;
2158 struct http_txn *txn = s->txn;
2159 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002160 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002161 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002162
2163 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2164 now_ms, __FUNCTION__,
2165 s,
2166 res,
2167 res->rex, res->wex,
2168 res->flags,
2169 ci_data(res),
2170 res->analysers);
2171
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002172 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002173
2174 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002175 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002176 /* Output closed while we were sending data. We must abort and
2177 * wake the other side up.
2178 */
2179 msg->err_state = msg->msg_state;
2180 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002181 htx_end_response(s);
2182 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183 return 1;
2184 }
2185
Christopher Faulet9768c262018-10-22 09:34:31 +02002186 if (msg->msg_state == HTTP_MSG_BODY)
2187 msg->msg_state = HTTP_MSG_DATA;
2188
Christopher Faulete0768eb2018-10-03 16:38:02 +02002189 /* in most states, we should abort in case of early close */
2190 channel_auto_close(res);
2191
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002193 if (res->to_forward == CHN_INFINITE_FORWARD) {
2194 if (res->flags & (CF_SHUTR|CF_EOI)) {
2195 msg->msg_state = HTTP_MSG_DONE;
2196 res->to_forward = 0;
2197 goto done;
2198 }
2199 }
2200 else {
2201 /* We can't process the buffer's contents yet */
2202 res->flags |= CF_WAKE_WRITE;
2203 goto missing_data_or_waiting;
2204 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 }
2206
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 if (msg->msg_state >= HTTP_MSG_DONE)
2208 goto done;
2209
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002210 /* Forward input data. We get it by removing all outgoing data not
2211 * forwarded yet from HTX data size. If there are some data filters, we
2212 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002213 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 if (HAS_RSP_DATA_FILTERS(s)) {
2215 ret = flt_http_payload(s, msg, htx->data);
2216 if (ret < 0)
2217 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002218 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002219 }
2220 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002221 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002222 if (msg->flags & HTTP_MSGF_XFER_LEN)
2223 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002224 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002225
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002226 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2227 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2228 msg->msg_state = HTTP_MSG_TUNNEL;
2229 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 }
2231
Christopher Faulet9768c262018-10-22 09:34:31 +02002232 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002233 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2234 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002235 */
2236 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2237 goto missing_data_or_waiting;
2238
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002239 msg->msg_state = HTTP_MSG_ENDING;
2240 if (htx->data != co_data(res))
2241 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002242 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002243 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002244
2245 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002246 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002247 channel_dont_close(res);
2248
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002249 if (HAS_RSP_DATA_FILTERS(s)) {
2250 ret = flt_http_end(s, msg);
2251 if (ret <= 0) {
2252 if (!ret)
2253 goto missing_data_or_waiting;
2254 goto return_bad_res;
2255 }
2256 }
2257
Christopher Fauletf2824e62018-10-01 12:12:37 +02002258 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002260 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2262 if (res->flags & CF_SHUTW) {
2263 /* response errors are most likely due to the
2264 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002265 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002267 goto return_bad_res;
2268 }
2269 return 1;
2270 }
2271 return 0;
2272
2273 missing_data_or_waiting:
2274 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276
Christopher Faulet47365272018-10-31 17:40:50 +01002277 if (htx->flags & HTX_FL_PARSING_ERROR)
2278 goto return_bad_res;
2279
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 /* stop waiting for data if the input is closed before the end. If the
2281 * client side was already closed, it means that the client has aborted,
2282 * so we don't want to count this as a server abort. Otherwise it's a
2283 * server abort.
2284 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002285 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002289 if (htx_is_empty(htx))
2290 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002291 }
2292
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 /* When TE: chunked is used, we need to get there again to parse
2294 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002295 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2296 * are filters registered on the stream, we don't want to forward a
2297 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002299 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 channel_dont_close(res);
2301
2302 /* We know that more data are expected, but we couldn't send more that
2303 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2304 * system knows it must not set a PUSH on this first part. Interactive
2305 * modes are already handled by the stream sock layer. We must not do
2306 * this in content-length mode because it could present the MSG_MORE
2307 * flag with the last block of forwarded data, which would cause an
2308 * additional delay to be observed by the receiver.
2309 */
2310 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2311 res->flags |= CF_EXPECT_MORE;
2312
2313 /* the stream handler will take care of timeouts and errors */
2314 return 0;
2315
Christopher Faulet93e02d82019-03-08 14:18:50 +01002316 return_srv_abort:
2317 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2318 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002319 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002320 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2321 if (!(s->flags & SF_ERR_MASK))
2322 s->flags |= SF_ERR_SRVCL;
2323 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002324
Christopher Faulet93e02d82019-03-08 14:18:50 +01002325 return_cli_abort:
2326 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2327 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2330 if (!(s->flags & SF_ERR_MASK))
2331 s->flags |= SF_ERR_CLICL;
2332 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333
Christopher Faulet93e02d82019-03-08 14:18:50 +01002334 return_bad_res:
2335 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2336 if (objt_server(s->target)) {
2337 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2338 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2339 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002340 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002341 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342
Christopher Faulet93e02d82019-03-08 14:18:50 +01002343 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002344 txn->rsp.err_state = txn->rsp.msg_state;
2345 txn->rsp.msg_state = HTTP_MSG_ERROR;
2346 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002347 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002348 res->analysers &= AN_RES_FLT_END;
2349 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 +02002350 if (!(s->flags & SF_FINST_MASK))
2351 s->flags |= SF_FINST_D;
2352 return 0;
2353}
2354
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357 * as too large a request to build a valid response.
2358 */
2359int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2360{
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 struct channel *req = &s->req;
2362 struct channel *res = &s->res;
2363 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002364 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002365 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002366 struct ist status, reason, location;
2367 unsigned int flags;
2368 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002369 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002370
2371 chunk = alloc_trash_chunk();
2372 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 /*
2376 * Create the location
2377 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002378 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 case REDIRECT_TYPE_SCHEME: {
2381 struct http_hdr_ctx ctx;
2382 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
Christopher Faulet99daf282018-11-28 22:58:13 +01002384 host = ist("");
2385 ctx.blk = NULL;
2386 if (http_find_header(htx, ist("Host"), &ctx, 0))
2387 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
Christopher Faulet297fbb42019-05-13 14:41:27 +02002389 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002390 path = http_get_path(htx_sl_req_uri(sl));
2391 /* build message using path */
2392 if (path.ptr) {
2393 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2394 int qs = 0;
2395 while (qs < path.len) {
2396 if (*(path.ptr + qs) == '?') {
2397 path.len = qs;
2398 break;
2399 }
2400 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402 }
2403 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 else
2405 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 if (rule->rdr_str) { /* this is an old "redirect" rule */
2408 /* add scheme */
2409 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2410 goto fail;
2411 }
2412 else {
2413 /* add scheme with executing log format */
2414 chunk->data += build_logline(s, chunk->area + chunk->data,
2415 chunk->size - chunk->data,
2416 &rule->rdr_fmt);
2417 }
2418 /* add "://" + host + path */
2419 if (!chunk_memcat(chunk, "://", 3) ||
2420 !chunk_memcat(chunk, host.ptr, host.len) ||
2421 !chunk_memcat(chunk, path.ptr, path.len))
2422 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 /* append a slash at the end of the location if needed and missing */
2425 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2426 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2427 if (chunk->data + 1 >= chunk->size)
2428 goto fail;
2429 chunk->area[chunk->data++] = '/';
2430 }
2431 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002433
Christopher Faulet99daf282018-11-28 22:58:13 +01002434 case REDIRECT_TYPE_PREFIX: {
2435 struct ist path;
2436
Christopher Faulet297fbb42019-05-13 14:41:27 +02002437 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 path = http_get_path(htx_sl_req_uri(sl));
2439 /* build message using path */
2440 if (path.ptr) {
2441 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2442 int qs = 0;
2443 while (qs < path.len) {
2444 if (*(path.ptr + qs) == '?') {
2445 path.len = qs;
2446 break;
2447 }
2448 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 }
2451 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 else
2453 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002454
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 if (rule->rdr_str) { /* this is an old "redirect" rule */
2456 /* add prefix. Note that if prefix == "/", we don't want to
2457 * add anything, otherwise it makes it hard for the user to
2458 * configure a self-redirection.
2459 */
2460 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2461 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2462 goto fail;
2463 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002465 else {
2466 /* add prefix with executing log format */
2467 chunk->data += build_logline(s, chunk->area + chunk->data,
2468 chunk->size - chunk->data,
2469 &rule->rdr_fmt);
2470 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471
Christopher Faulet99daf282018-11-28 22:58:13 +01002472 /* add path */
2473 if (!chunk_memcat(chunk, path.ptr, path.len))
2474 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002475
Christopher Faulet99daf282018-11-28 22:58:13 +01002476 /* append a slash at the end of the location if needed and missing */
2477 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2478 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2479 if (chunk->data + 1 >= chunk->size)
2480 goto fail;
2481 chunk->area[chunk->data++] = '/';
2482 }
2483 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002484 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002485 case REDIRECT_TYPE_LOCATION:
2486 default:
2487 if (rule->rdr_str) { /* this is an old "redirect" rule */
2488 /* add location */
2489 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2490 goto fail;
2491 }
2492 else {
2493 /* add location with executing log format */
2494 chunk->data += build_logline(s, chunk->area + chunk->data,
2495 chunk->size - chunk->data,
2496 &rule->rdr_fmt);
2497 }
2498 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002499 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002500 location = ist2(chunk->area, chunk->data);
2501
2502 /*
2503 * Create the 30x response
2504 */
2505 switch (rule->code) {
2506 case 308:
2507 status = ist("308");
2508 reason = ist("Permanent Redirect");
2509 break;
2510 case 307:
2511 status = ist("307");
2512 reason = ist("Temporary Redirect");
2513 break;
2514 case 303:
2515 status = ist("303");
2516 reason = ist("See Other");
2517 break;
2518 case 301:
2519 status = ist("301");
2520 reason = ist("Moved Permanently");
2521 break;
2522 case 302:
2523 default:
2524 status = ist("302");
2525 reason = ist("Found");
2526 break;
2527 }
2528
Christopher Faulet08e66462019-05-23 16:44:59 +02002529 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2530 close = 1;
2531
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 htx = htx_from_buf(&res->buf);
2533 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2534 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2535 if (!sl)
2536 goto fail;
2537 sl->info.res.status = rule->code;
2538 s->txn->status = rule->code;
2539
Christopher Faulet08e66462019-05-23 16:44:59 +02002540 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2541 goto fail;
2542
2543 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002544 !htx_add_header(htx, ist("Location"), location))
2545 goto fail;
2546
2547 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2548 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2549 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002550 }
2551
2552 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002553 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2554 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002555 }
2556
Christopher Faulet99daf282018-11-28 22:58:13 +01002557 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2558 goto fail;
2559
Christopher Fauletf2824e62018-10-01 12:12:37 +02002560 /* let's log the request time */
2561 s->logs.tv_request = now;
2562
Christopher Faulet99daf282018-11-28 22:58:13 +01002563 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002564 c_adv(res, data);
2565 res->total += data;
2566
2567 channel_auto_read(req);
2568 channel_abort(req);
2569 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002570 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002571
2572 res->wex = tick_add_ifset(now_ms, res->wto);
2573 channel_auto_read(res);
2574 channel_auto_close(res);
2575 channel_shutr_now(res);
2576
2577 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002578
2579 if (!(s->flags & SF_ERR_MASK))
2580 s->flags |= SF_ERR_LOCAL;
2581 if (!(s->flags & SF_FINST_MASK))
2582 s->flags |= SF_FINST_R;
2583
Christopher Faulet99daf282018-11-28 22:58:13 +01002584 free_trash_chunk(chunk);
2585 return 1;
2586
2587 fail:
2588 /* If an error occurred, remove the incomplete HTTP response from the
2589 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002590 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002592 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002593}
2594
Christopher Faulet72333522018-10-24 11:25:02 +02002595int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2596 struct ist name, const char *str, struct my_regex *re, int action)
2597{
2598 struct http_hdr_ctx ctx;
2599 struct buffer *output = get_trash_chunk();
2600
2601 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2602 ctx.blk = NULL;
2603 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2604 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2605 continue;
2606
2607 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2608 if (output->data == -1)
2609 return -1;
2610 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2611 return -1;
2612 }
2613 return 0;
2614}
2615
2616static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2617 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2618{
2619 struct buffer *replace;
2620 int ret = -1;
2621
2622 replace = alloc_trash_chunk();
2623 if (!replace)
2624 goto leave;
2625
2626 replace->data = build_logline(s, replace->area, replace->size, fmt);
2627 if (replace->data >= replace->size - 1)
2628 goto leave;
2629
2630 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2631
2632 leave:
2633 free_trash_chunk(replace);
2634 return ret;
2635}
2636
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637
2638/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2639 * on success and -1 on error. The response channel is updated accordingly.
2640 */
2641static int htx_reply_103_early_hints(struct channel *res)
2642{
2643 struct htx *htx = htx_from_buf(&res->buf);
2644 size_t data;
2645
Christopher Faulet1d5ec092019-06-26 14:23:54 +02002646 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002647 /* If an error occurred during an Early-hint rule,
2648 * remove the incomplete HTTP 103 response from the
2649 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002650 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 return -1;
2652 }
2653
2654 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002655 c_adv(res, data);
2656 res->total += data;
2657 return 0;
2658}
2659
Christopher Faulet6eb92892018-11-15 16:39:29 +01002660/*
2661 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2662 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002663 * If <early_hints> is 0, it is starts a new response by adding the start
2664 * line. If an error occurred -1 is returned. On success 0 is returned. The
2665 * channel is not updated here. It must be done calling the function
2666 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002668static 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 +01002669{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 struct channel *res = &s->res;
2671 struct htx *htx = htx_from_buf(&res->buf);
2672 struct buffer *value = alloc_trash_chunk();
2673
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002675 struct htx_sl *sl;
2676 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2677 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2678
2679 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2680 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2681 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002682 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002683 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002684 }
2685
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002686 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2687 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002688 goto fail;
2689
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002691 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002692
2693 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002694 /* If an error occurred during an Early-hint rule, remove the incomplete
2695 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002696 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002697 free_trash_chunk(value);
2698 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002699}
2700
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002701/* This function executes one of the set-{method,path,query,uri} actions. It
2702 * takes the string from the variable 'replace' with length 'len', then modifies
2703 * the relevant part of the request line accordingly. Then it updates various
2704 * pointers to the next elements which were moved, and the total buffer length.
2705 * It finds the action to be performed in p[2], previously filled by function
2706 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2707 * error, though this can be revisited when this code is finally exploited.
2708 *
2709 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2710 * query string and 3 to replace uri.
2711 *
2712 * In query string case, the mark question '?' must be set at the start of the
2713 * string by the caller, event if the replacement query string is empty.
2714 */
2715int htx_req_replace_stline(int action, const char *replace, int len,
2716 struct proxy *px, struct stream *s)
2717{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002718 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002719
2720 switch (action) {
2721 case 0: // method
2722 if (!http_replace_req_meth(htx, ist2(replace, len)))
2723 return -1;
2724 break;
2725
2726 case 1: // path
2727 if (!http_replace_req_path(htx, ist2(replace, len)))
2728 return -1;
2729 break;
2730
2731 case 2: // query
2732 if (!http_replace_req_query(htx, ist2(replace, len)))
2733 return -1;
2734 break;
2735
2736 case 3: // uri
2737 if (!http_replace_req_uri(htx, ist2(replace, len)))
2738 return -1;
2739 break;
2740
2741 default:
2742 return -1;
2743 }
2744 return 0;
2745}
2746
2747/* This function replace the HTTP status code and the associated message. The
2748 * variable <status> contains the new status code. This function never fails.
2749 */
2750void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2751{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002752 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002753 char *res;
2754
2755 chunk_reset(&trash);
2756 res = ultoa_o(status, trash.area, trash.size);
2757 trash.data = res - trash.area;
2758
2759 /* Do we have a custom reason format string? */
2760 if (reason == NULL)
2761 reason = http_get_reason(status);
2762
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002763 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002764 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2765}
2766
Christopher Faulet3e964192018-10-24 11:39:23 +02002767/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2768 * transaction <txn>. Returns the verdict of the first rule that prevents
2769 * further processing of the request (auth, deny, ...), and defaults to
2770 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2771 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2772 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2773 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2774 * status.
2775 */
2776static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2777 struct stream *s, int *deny_status)
2778{
2779 struct session *sess = strm_sess(s);
2780 struct http_txn *txn = s->txn;
2781 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002782 struct act_rule *rule;
2783 struct http_hdr_ctx ctx;
2784 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002785 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2786 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002787 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002788
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002789 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002790
2791 /* If "the current_rule_list" match the executed rule list, we are in
2792 * resume condition. If a resume is needed it is always in the action
2793 * and never in the ACL or converters. In this case, we initialise the
2794 * current rule, and go to the action execution point.
2795 */
2796 if (s->current_rule) {
2797 rule = s->current_rule;
2798 s->current_rule = NULL;
2799 if (s->current_rule_list == rules)
2800 goto resume_execution;
2801 }
2802 s->current_rule_list = rules;
2803
2804 list_for_each_entry(rule, rules, list) {
2805 /* check optional condition */
2806 if (rule->cond) {
2807 int ret;
2808
2809 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2810 ret = acl_pass(ret);
2811
2812 if (rule->cond->pol == ACL_COND_UNLESS)
2813 ret = !ret;
2814
2815 if (!ret) /* condition not matched */
2816 continue;
2817 }
2818
2819 act_flags |= ACT_FLAG_FIRST;
2820 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002821 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2822 early_hints = 0;
2823 if (htx_reply_103_early_hints(&s->res) == -1) {
2824 rule_ret = HTTP_RULE_RES_BADREQ;
2825 goto end;
2826 }
2827 }
2828
Christopher Faulet3e964192018-10-24 11:39:23 +02002829 switch (rule->action) {
2830 case ACT_ACTION_ALLOW:
2831 rule_ret = HTTP_RULE_RES_STOP;
2832 goto end;
2833
2834 case ACT_ACTION_DENY:
2835 if (deny_status)
2836 *deny_status = rule->deny_status;
2837 rule_ret = HTTP_RULE_RES_DENY;
2838 goto end;
2839
2840 case ACT_HTTP_REQ_TARPIT:
2841 txn->flags |= TX_CLTARPIT;
2842 if (deny_status)
2843 *deny_status = rule->deny_status;
2844 rule_ret = HTTP_RULE_RES_DENY;
2845 goto end;
2846
2847 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002848 /* Auth might be performed on regular http-req rules as well as on stats */
2849 auth_realm = rule->arg.auth.realm;
2850 if (!auth_realm) {
2851 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2852 auth_realm = STATS_DEFAULT_REALM;
2853 else
2854 auth_realm = px->id;
2855 }
2856 /* send 401/407 depending on whether we use a proxy or not. We still
2857 * count one error, because normal browsing won't significantly
2858 * increase the counter but brute force attempts will.
2859 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002860 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002861 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2862 rule_ret = HTTP_RULE_RES_BADREQ;
2863 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002864 goto end;
2865
2866 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002867 rule_ret = HTTP_RULE_RES_DONE;
2868 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2869 rule_ret = HTTP_RULE_RES_BADREQ;
2870 goto end;
2871
2872 case ACT_HTTP_SET_NICE:
2873 s->task->nice = rule->arg.nice;
2874 break;
2875
2876 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002877 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002878 break;
2879
2880 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002881 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002882 break;
2883
2884 case ACT_HTTP_SET_LOGL:
2885 s->logs.level = rule->arg.loglevel;
2886 break;
2887
2888 case ACT_HTTP_REPLACE_HDR:
2889 case ACT_HTTP_REPLACE_VAL:
2890 if (htx_transform_header(s, &s->req, htx,
2891 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2892 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002893 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002894 rule_ret = HTTP_RULE_RES_BADREQ;
2895 goto end;
2896 }
2897 break;
2898
2899 case ACT_HTTP_DEL_HDR:
2900 /* remove all occurrences of the header */
2901 ctx.blk = NULL;
2902 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2903 http_remove_header(htx, &ctx);
2904 break;
2905
2906 case ACT_HTTP_SET_HDR:
2907 case ACT_HTTP_ADD_HDR: {
2908 /* The scope of the trash buffer must be limited to this function. The
2909 * build_logline() function can execute a lot of other function which
2910 * can use the trash buffer. So for limiting the scope of this global
2911 * buffer, we build first the header value using build_logline, and
2912 * after we store the header name.
2913 */
2914 struct buffer *replace;
2915 struct ist n, v;
2916
2917 replace = alloc_trash_chunk();
2918 if (!replace) {
2919 rule_ret = HTTP_RULE_RES_BADREQ;
2920 goto end;
2921 }
2922
2923 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2924 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2925 v = ist2(replace->area, replace->data);
2926
2927 if (rule->action == ACT_HTTP_SET_HDR) {
2928 /* remove all occurrences of the header */
2929 ctx.blk = NULL;
2930 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2931 http_remove_header(htx, &ctx);
2932 }
2933
2934 if (!http_add_header(htx, n, v)) {
2935 static unsigned char rate_limit = 0;
2936
2937 if ((rate_limit++ & 255) == 0) {
2938 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);
2939 }
2940
Olivier Houcharda798bf52019-03-08 18:52:00 +01002941 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002943 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002945 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002946 }
2947 free_trash_chunk(replace);
2948 break;
2949 }
2950
2951 case ACT_HTTP_DEL_ACL:
2952 case ACT_HTTP_DEL_MAP: {
2953 struct pat_ref *ref;
2954 struct buffer *key;
2955
2956 /* collect reference */
2957 ref = pat_ref_lookup(rule->arg.map.ref);
2958 if (!ref)
2959 continue;
2960
2961 /* allocate key */
2962 key = alloc_trash_chunk();
2963 if (!key) {
2964 rule_ret = HTTP_RULE_RES_BADREQ;
2965 goto end;
2966 }
2967
2968 /* collect key */
2969 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2970 key->area[key->data] = '\0';
2971
2972 /* perform update */
2973 /* returned code: 1=ok, 0=ko */
2974 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2975 pat_ref_delete(ref, key->area);
2976 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2977
2978 free_trash_chunk(key);
2979 break;
2980 }
2981
2982 case ACT_HTTP_ADD_ACL: {
2983 struct pat_ref *ref;
2984 struct buffer *key;
2985
2986 /* collect reference */
2987 ref = pat_ref_lookup(rule->arg.map.ref);
2988 if (!ref)
2989 continue;
2990
2991 /* allocate key */
2992 key = alloc_trash_chunk();
2993 if (!key) {
2994 rule_ret = HTTP_RULE_RES_BADREQ;
2995 goto end;
2996 }
2997
2998 /* collect key */
2999 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3000 key->area[key->data] = '\0';
3001
3002 /* perform update */
3003 /* add entry only if it does not already exist */
3004 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3005 if (pat_ref_find_elt(ref, key->area) == NULL)
3006 pat_ref_add(ref, key->area, NULL, NULL);
3007 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3008
3009 free_trash_chunk(key);
3010 break;
3011 }
3012
3013 case ACT_HTTP_SET_MAP: {
3014 struct pat_ref *ref;
3015 struct buffer *key, *value;
3016
3017 /* collect reference */
3018 ref = pat_ref_lookup(rule->arg.map.ref);
3019 if (!ref)
3020 continue;
3021
3022 /* allocate key */
3023 key = alloc_trash_chunk();
3024 if (!key) {
3025 rule_ret = HTTP_RULE_RES_BADREQ;
3026 goto end;
3027 }
3028
3029 /* allocate value */
3030 value = alloc_trash_chunk();
3031 if (!value) {
3032 free_trash_chunk(key);
3033 rule_ret = HTTP_RULE_RES_BADREQ;
3034 goto end;
3035 }
3036
3037 /* collect key */
3038 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3039 key->area[key->data] = '\0';
3040
3041 /* collect value */
3042 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3043 value->area[value->data] = '\0';
3044
3045 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003046 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003047 if (pat_ref_find_elt(ref, key->area) != NULL)
3048 /* update entry if it exists */
3049 pat_ref_set(ref, key->area, value->area, NULL);
3050 else
3051 /* insert a new entry */
3052 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003053 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003054 free_trash_chunk(key);
3055 free_trash_chunk(value);
3056 break;
3057 }
3058
3059 case ACT_HTTP_EARLY_HINT:
3060 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3061 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003062 early_hints = htx_add_early_hint_header(s, early_hints,
3063 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003064 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003065 if (early_hints == -1) {
3066 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003067 goto end;
3068 }
3069 break;
3070
3071 case ACT_CUSTOM:
3072 if ((s->req.flags & CF_READ_ERROR) ||
3073 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003074 (px->options & PR_O_ABRT_CLOSE)))
3075 act_flags |= ACT_FLAG_FINAL;
3076
3077 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3078 case ACT_RET_ERR:
3079 case ACT_RET_CONT:
3080 break;
3081 case ACT_RET_STOP:
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003082 rule_ret = HTTP_RULE_RES_STOP;
3083 goto end;
3084 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003085 rule_ret = HTTP_RULE_RES_DONE;
3086 goto end;
3087 case ACT_RET_YIELD:
3088 s->current_rule = rule;
3089 rule_ret = HTTP_RULE_RES_YIELD;
3090 goto end;
3091 }
3092 break;
3093
3094 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3095 /* Note: only the first valid tracking parameter of each
3096 * applies.
3097 */
3098
3099 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3100 struct stktable *t;
3101 struct stksess *ts;
3102 struct stktable_key *key;
3103 void *ptr1, *ptr2;
3104
3105 t = rule->arg.trk_ctr.table.t;
3106 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3107 rule->arg.trk_ctr.expr, NULL);
3108
3109 if (key && (ts = stktable_get_entry(t, key))) {
3110 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3111
3112 /* let's count a new HTTP request as it's the first time we do it */
3113 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3114 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3115 if (ptr1 || ptr2) {
3116 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3117
3118 if (ptr1)
3119 stktable_data_cast(ptr1, http_req_cnt)++;
3120
3121 if (ptr2)
3122 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3123 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3124
3125 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3126
3127 /* If data was modified, we need to touch to re-schedule sync */
3128 stktable_touch_local(t, ts, 0);
3129 }
3130
3131 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3132 if (sess->fe != s->be)
3133 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3134 }
3135 }
3136 break;
3137
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003138 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003139 default:
3140 break;
3141 }
3142 }
3143
3144 end:
3145 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003146 if (htx_reply_103_early_hints(&s->res) == -1)
3147 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003148 }
3149
3150 /* we reached the end of the rules, nothing to report */
3151 return rule_ret;
3152}
3153
3154/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3155 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3156 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3157 * is returned, the process can continue the evaluation of next rule list. If
3158 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3159 * is returned, it means the operation could not be processed and a server error
3160 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3161 * deny rule. If *YIELD is returned, the caller must call again the function
3162 * with the same context.
3163 */
3164static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3165 struct stream *s)
3166{
3167 struct session *sess = strm_sess(s);
3168 struct http_txn *txn = s->txn;
3169 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003170 struct act_rule *rule;
3171 struct http_hdr_ctx ctx;
3172 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3173 int act_flags = 0;
3174
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003175 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003176
3177 /* If "the current_rule_list" match the executed rule list, we are in
3178 * resume condition. If a resume is needed it is always in the action
3179 * and never in the ACL or converters. In this case, we initialise the
3180 * current rule, and go to the action execution point.
3181 */
3182 if (s->current_rule) {
3183 rule = s->current_rule;
3184 s->current_rule = NULL;
3185 if (s->current_rule_list == rules)
3186 goto resume_execution;
3187 }
3188 s->current_rule_list = rules;
3189
3190 list_for_each_entry(rule, rules, list) {
3191 /* check optional condition */
3192 if (rule->cond) {
3193 int ret;
3194
3195 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3196 ret = acl_pass(ret);
3197
3198 if (rule->cond->pol == ACL_COND_UNLESS)
3199 ret = !ret;
3200
3201 if (!ret) /* condition not matched */
3202 continue;
3203 }
3204
3205 act_flags |= ACT_FLAG_FIRST;
3206resume_execution:
3207 switch (rule->action) {
3208 case ACT_ACTION_ALLOW:
3209 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3210 goto end;
3211
3212 case ACT_ACTION_DENY:
3213 txn->flags |= TX_SVDENY;
3214 rule_ret = HTTP_RULE_RES_STOP;
3215 goto end;
3216
3217 case ACT_HTTP_SET_NICE:
3218 s->task->nice = rule->arg.nice;
3219 break;
3220
3221 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003222 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003223 break;
3224
3225 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003226 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003227 break;
3228
3229 case ACT_HTTP_SET_LOGL:
3230 s->logs.level = rule->arg.loglevel;
3231 break;
3232
3233 case ACT_HTTP_REPLACE_HDR:
3234 case ACT_HTTP_REPLACE_VAL:
3235 if (htx_transform_header(s, &s->res, htx,
3236 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3237 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003238 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003239 rule_ret = HTTP_RULE_RES_BADREQ;
3240 goto end;
3241 }
3242 break;
3243
3244 case ACT_HTTP_DEL_HDR:
3245 /* remove all occurrences of the header */
3246 ctx.blk = NULL;
3247 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3248 http_remove_header(htx, &ctx);
3249 break;
3250
3251 case ACT_HTTP_SET_HDR:
3252 case ACT_HTTP_ADD_HDR: {
3253 struct buffer *replace;
3254 struct ist n, v;
3255
3256 replace = alloc_trash_chunk();
3257 if (!replace) {
3258 rule_ret = HTTP_RULE_RES_BADREQ;
3259 goto end;
3260 }
3261
3262 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3263 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3264 v = ist2(replace->area, replace->data);
3265
3266 if (rule->action == ACT_HTTP_SET_HDR) {
3267 /* remove all occurrences of the header */
3268 ctx.blk = NULL;
3269 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3270 http_remove_header(htx, &ctx);
3271 }
3272
3273 if (!http_add_header(htx, n, v)) {
3274 static unsigned char rate_limit = 0;
3275
3276 if ((rate_limit++ & 255) == 0) {
3277 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);
3278 }
3279
Olivier Houcharda798bf52019-03-08 18:52:00 +01003280 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003281 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003282 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003283 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003284 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003285 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003286 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003287 }
3288 free_trash_chunk(replace);
3289 break;
3290 }
3291
3292 case ACT_HTTP_DEL_ACL:
3293 case ACT_HTTP_DEL_MAP: {
3294 struct pat_ref *ref;
3295 struct buffer *key;
3296
3297 /* collect reference */
3298 ref = pat_ref_lookup(rule->arg.map.ref);
3299 if (!ref)
3300 continue;
3301
3302 /* allocate key */
3303 key = alloc_trash_chunk();
3304 if (!key) {
3305 rule_ret = HTTP_RULE_RES_BADREQ;
3306 goto end;
3307 }
3308
3309 /* collect key */
3310 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3311 key->area[key->data] = '\0';
3312
3313 /* perform update */
3314 /* returned code: 1=ok, 0=ko */
3315 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3316 pat_ref_delete(ref, key->area);
3317 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3318
3319 free_trash_chunk(key);
3320 break;
3321 }
3322
3323 case ACT_HTTP_ADD_ACL: {
3324 struct pat_ref *ref;
3325 struct buffer *key;
3326
3327 /* collect reference */
3328 ref = pat_ref_lookup(rule->arg.map.ref);
3329 if (!ref)
3330 continue;
3331
3332 /* allocate key */
3333 key = alloc_trash_chunk();
3334 if (!key) {
3335 rule_ret = HTTP_RULE_RES_BADREQ;
3336 goto end;
3337 }
3338
3339 /* collect key */
3340 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3341 key->area[key->data] = '\0';
3342
3343 /* perform update */
3344 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003345 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003346 if (pat_ref_find_elt(ref, key->area) == NULL)
3347 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003348 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003349 free_trash_chunk(key);
3350 break;
3351 }
3352
3353 case ACT_HTTP_SET_MAP: {
3354 struct pat_ref *ref;
3355 struct buffer *key, *value;
3356
3357 /* collect reference */
3358 ref = pat_ref_lookup(rule->arg.map.ref);
3359 if (!ref)
3360 continue;
3361
3362 /* allocate key */
3363 key = alloc_trash_chunk();
3364 if (!key) {
3365 rule_ret = HTTP_RULE_RES_BADREQ;
3366 goto end;
3367 }
3368
3369 /* allocate value */
3370 value = alloc_trash_chunk();
3371 if (!value) {
3372 free_trash_chunk(key);
3373 rule_ret = HTTP_RULE_RES_BADREQ;
3374 goto end;
3375 }
3376
3377 /* collect key */
3378 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3379 key->area[key->data] = '\0';
3380
3381 /* collect value */
3382 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3383 value->area[value->data] = '\0';
3384
3385 /* perform update */
3386 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3387 if (pat_ref_find_elt(ref, key->area) != NULL)
3388 /* update entry if it exists */
3389 pat_ref_set(ref, key->area, value->area, NULL);
3390 else
3391 /* insert a new entry */
3392 pat_ref_add(ref, key->area, value->area, NULL);
3393 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3394 free_trash_chunk(key);
3395 free_trash_chunk(value);
3396 break;
3397 }
3398
3399 case ACT_HTTP_REDIR:
3400 rule_ret = HTTP_RULE_RES_DONE;
Christopher Faulet00618aa2019-07-15 12:05:35 +02003401 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02003402 rule_ret = HTTP_RULE_RES_BADREQ;
3403 goto end;
3404
3405 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3406 /* Note: only the first valid tracking parameter of each
3407 * applies.
3408 */
3409 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3410 struct stktable *t;
3411 struct stksess *ts;
3412 struct stktable_key *key;
3413 void *ptr;
3414
3415 t = rule->arg.trk_ctr.table.t;
3416 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3417 rule->arg.trk_ctr.expr, NULL);
3418
3419 if (key && (ts = stktable_get_entry(t, key))) {
3420 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3421
3422 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3423
3424 /* let's count a new HTTP request as it's the first time we do it */
3425 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3426 if (ptr)
3427 stktable_data_cast(ptr, http_req_cnt)++;
3428
3429 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3430 if (ptr)
3431 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3432 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3433
3434 /* When the client triggers a 4xx from the server, it's most often due
3435 * to a missing object or permission. These events should be tracked
3436 * because if they happen often, it may indicate a brute force or a
3437 * vulnerability scan. Normally this is done when receiving the response
3438 * but here we're tracking after this ought to have been done so we have
3439 * to do it on purpose.
3440 */
3441 if ((unsigned)(txn->status - 400) < 100) {
3442 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3443 if (ptr)
3444 stktable_data_cast(ptr, http_err_cnt)++;
3445
3446 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3447 if (ptr)
3448 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3449 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3450 }
3451
3452 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3453
3454 /* If data was modified, we need to touch to re-schedule sync */
3455 stktable_touch_local(t, ts, 0);
3456
3457 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3458 if (sess->fe != s->be)
3459 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3460 }
3461 }
3462 break;
3463
3464 case ACT_CUSTOM:
3465 if ((s->req.flags & CF_READ_ERROR) ||
3466 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003467 (px->options & PR_O_ABRT_CLOSE)))
3468 act_flags |= ACT_FLAG_FINAL;
3469
3470 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3471 case ACT_RET_ERR:
3472 case ACT_RET_CONT:
3473 break;
3474 case ACT_RET_STOP:
3475 rule_ret = HTTP_RULE_RES_STOP;
3476 goto end;
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003477 case ACT_RET_DONE:
3478 rule_ret = HTTP_RULE_RES_DONE;
3479 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003480 case ACT_RET_YIELD:
3481 s->current_rule = rule;
3482 rule_ret = HTTP_RULE_RES_YIELD;
3483 goto end;
3484 }
3485 break;
3486
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003487 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003488 default:
3489 break;
3490 }
3491 }
3492
3493 end:
3494 /* we reached the end of the rules, nothing to report */
3495 return rule_ret;
3496}
3497
Christopher Faulet33640082018-10-24 11:53:01 +02003498/* Iterate the same filter through all request headers.
3499 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3500 * Since it can manage the switch to another backend, it updates the per-proxy
3501 * DENY stats.
3502 */
3503static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3504{
3505 struct http_txn *txn = s->txn;
3506 struct htx *htx;
3507 struct buffer *hdr = get_trash_chunk();
3508 int32_t pos;
3509
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003510 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003511
Christopher Fauleta3f15502019-05-13 15:27:23 +02003512 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003513 struct htx_blk *blk = htx_get_blk(htx, pos);
3514 enum htx_blk_type type;
3515 struct ist n, v;
3516
3517 next_hdr:
3518 type = htx_get_blk_type(blk);
3519 if (type == HTX_BLK_EOH)
3520 break;
3521 if (type != HTX_BLK_HDR)
3522 continue;
3523
3524 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3525 return 1;
3526 else if (unlikely(txn->flags & TX_CLALLOW) &&
3527 (exp->action == ACT_ALLOW ||
3528 exp->action == ACT_DENY ||
3529 exp->action == ACT_TARPIT))
3530 return 0;
3531
3532 n = htx_get_blk_name(htx, blk);
3533 v = htx_get_blk_value(htx, blk);
3534
Christopher Faulet02e771a2019-02-26 15:36:05 +01003535 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003536 hdr->area[hdr->data++] = ':';
3537 hdr->area[hdr->data++] = ' ';
3538 chunk_memcat(hdr, v.ptr, v.len);
3539
3540 /* Now we have one header in <hdr> */
3541
3542 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3543 struct http_hdr_ctx ctx;
3544 int len;
3545
3546 switch (exp->action) {
3547 case ACT_ALLOW:
3548 txn->flags |= TX_CLALLOW;
3549 goto end;
3550
3551 case ACT_DENY:
3552 txn->flags |= TX_CLDENY;
3553 goto end;
3554
3555 case ACT_TARPIT:
3556 txn->flags |= TX_CLTARPIT;
3557 goto end;
3558
3559 case ACT_REPLACE:
3560 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3561 if (len < 0)
3562 return -1;
3563
3564 http_parse_header(ist2(trash.area, len), &n, &v);
3565 ctx.blk = blk;
3566 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003567 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003568 if (!http_replace_header(htx, &ctx, n, v))
3569 return -1;
3570 if (!ctx.blk)
3571 goto end;
3572 pos = htx_get_blk_pos(htx, blk);
3573 break;
3574
3575 case ACT_REMOVE:
3576 ctx.blk = blk;
3577 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003578 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003579 if (!http_remove_header(htx, &ctx))
3580 return -1;
3581 if (!ctx.blk)
3582 goto end;
3583 pos = htx_get_blk_pos(htx, blk);
3584 goto next_hdr;
3585
3586 }
3587 }
3588 }
3589 end:
3590 return 0;
3591}
3592
3593/* Apply the filter to the request line.
3594 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3595 * or -1 if a replacement resulted in an invalid request line.
3596 * Since it can manage the switch to another backend, it updates the per-proxy
3597 * DENY stats.
3598 */
3599static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3600{
3601 struct http_txn *txn = s->txn;
3602 struct htx *htx;
3603 struct buffer *reqline = get_trash_chunk();
3604 int done;
3605
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003606 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003607
3608 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3609 return 1;
3610 else if (unlikely(txn->flags & TX_CLALLOW) &&
3611 (exp->action == ACT_ALLOW ||
3612 exp->action == ACT_DENY ||
3613 exp->action == ACT_TARPIT))
3614 return 0;
3615 else if (exp->action == ACT_REMOVE)
3616 return 0;
3617
3618 done = 0;
3619
Christopher Faulet297fbb42019-05-13 14:41:27 +02003620 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003621
3622 /* Now we have the request line between cur_ptr and cur_end */
3623 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003624 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003625 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003626 int len;
3627
3628 switch (exp->action) {
3629 case ACT_ALLOW:
3630 txn->flags |= TX_CLALLOW;
3631 done = 1;
3632 break;
3633
3634 case ACT_DENY:
3635 txn->flags |= TX_CLDENY;
3636 done = 1;
3637 break;
3638
3639 case ACT_TARPIT:
3640 txn->flags |= TX_CLTARPIT;
3641 done = 1;
3642 break;
3643
3644 case ACT_REPLACE:
3645 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3646 if (len < 0)
3647 return -1;
3648
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003649 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3650 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3651 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003652 return -1;
3653 done = 1;
3654 break;
3655 }
3656 }
3657 return done;
3658}
3659
3660/*
3661 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3662 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3663 * unparsable request. Since it can manage the switch to another backend, it
3664 * updates the per-proxy DENY stats.
3665 */
3666static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3667{
3668 struct session *sess = s->sess;
3669 struct http_txn *txn = s->txn;
3670 struct hdr_exp *exp;
3671
3672 for (exp = px->req_exp; exp; exp = exp->next) {
3673 int ret;
3674
3675 /*
3676 * The interleaving of transformations and verdicts
3677 * makes it difficult to decide to continue or stop
3678 * the evaluation.
3679 */
3680
3681 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3682 break;
3683
3684 if ((txn->flags & TX_CLALLOW) &&
3685 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3686 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3687 continue;
3688
3689 /* if this filter had a condition, evaluate it now and skip to
3690 * next filter if the condition does not match.
3691 */
3692 if (exp->cond) {
3693 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3694 ret = acl_pass(ret);
3695 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3696 ret = !ret;
3697
3698 if (!ret)
3699 continue;
3700 }
3701
3702 /* Apply the filter to the request line. */
3703 ret = htx_apply_filter_to_req_line(s, req, exp);
3704 if (unlikely(ret < 0))
3705 return -1;
3706
3707 if (likely(ret == 0)) {
3708 /* The filter did not match the request, it can be
3709 * iterated through all headers.
3710 */
3711 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3712 return -1;
3713 }
3714 }
3715 return 0;
3716}
3717
3718/* Iterate the same filter through all response headers contained in <res>.
3719 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3720 */
3721static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3722{
3723 struct http_txn *txn = s->txn;
3724 struct htx *htx;
3725 struct buffer *hdr = get_trash_chunk();
3726 int32_t pos;
3727
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003728 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003729
Christopher Fauleta3f15502019-05-13 15:27:23 +02003730 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003731 struct htx_blk *blk = htx_get_blk(htx, pos);
3732 enum htx_blk_type type;
3733 struct ist n, v;
3734
3735 next_hdr:
3736 type = htx_get_blk_type(blk);
3737 if (type == HTX_BLK_EOH)
3738 break;
3739 if (type != HTX_BLK_HDR)
3740 continue;
3741
3742 if (unlikely(txn->flags & TX_SVDENY))
3743 return 1;
3744 else if (unlikely(txn->flags & TX_SVALLOW) &&
3745 (exp->action == ACT_ALLOW ||
3746 exp->action == ACT_DENY))
3747 return 0;
3748
3749 n = htx_get_blk_name(htx, blk);
3750 v = htx_get_blk_value(htx, blk);
3751
Christopher Faulet02e771a2019-02-26 15:36:05 +01003752 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003753 hdr->area[hdr->data++] = ':';
3754 hdr->area[hdr->data++] = ' ';
3755 chunk_memcat(hdr, v.ptr, v.len);
3756
3757 /* Now we have one header in <hdr> */
3758
3759 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3760 struct http_hdr_ctx ctx;
3761 int len;
3762
3763 switch (exp->action) {
3764 case ACT_ALLOW:
3765 txn->flags |= TX_SVALLOW;
3766 goto end;
3767 break;
3768
3769 case ACT_DENY:
3770 txn->flags |= TX_SVDENY;
3771 goto end;
3772 break;
3773
3774 case ACT_REPLACE:
3775 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3776 if (len < 0)
3777 return -1;
3778
3779 http_parse_header(ist2(trash.area, len), &n, &v);
3780 ctx.blk = blk;
3781 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003782 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003783 if (!http_replace_header(htx, &ctx, n, v))
3784 return -1;
3785 if (!ctx.blk)
3786 goto end;
3787 pos = htx_get_blk_pos(htx, blk);
3788 break;
3789
3790 case ACT_REMOVE:
3791 ctx.blk = blk;
3792 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003793 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003794 if (!http_remove_header(htx, &ctx))
3795 return -1;
3796 if (!ctx.blk)
3797 goto end;
3798 pos = htx_get_blk_pos(htx, blk);
3799 goto next_hdr;
3800 }
3801 }
3802
3803 }
3804 end:
3805 return 0;
3806}
3807
3808/* Apply the filter to the status line in the response buffer <res>.
3809 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3810 * or -1 if a replacement resulted in an invalid status line.
3811 */
3812static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3813{
3814 struct http_txn *txn = s->txn;
3815 struct htx *htx;
3816 struct buffer *resline = get_trash_chunk();
3817 int done;
3818
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003819 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003820
3821 if (unlikely(txn->flags & TX_SVDENY))
3822 return 1;
3823 else if (unlikely(txn->flags & TX_SVALLOW) &&
3824 (exp->action == ACT_ALLOW ||
3825 exp->action == ACT_DENY))
3826 return 0;
3827 else if (exp->action == ACT_REMOVE)
3828 return 0;
3829
3830 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003831 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003832
3833 /* Now we have the status line between cur_ptr and cur_end */
3834 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003835 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003836 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003837 int len;
3838
3839 switch (exp->action) {
3840 case ACT_ALLOW:
3841 txn->flags |= TX_SVALLOW;
3842 done = 1;
3843 break;
3844
3845 case ACT_DENY:
3846 txn->flags |= TX_SVDENY;
3847 done = 1;
3848 break;
3849
3850 case ACT_REPLACE:
3851 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3852 if (len < 0)
3853 return -1;
3854
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003855 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3856 sl->info.res.status = strl2ui(code.ptr, code.len);
3857 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003858 return -1;
3859
3860 done = 1;
3861 return 1;
3862 }
3863 }
3864 return done;
3865}
3866
3867/*
3868 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3869 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3870 * unparsable response.
3871 */
3872static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3873{
3874 struct session *sess = s->sess;
3875 struct http_txn *txn = s->txn;
3876 struct hdr_exp *exp;
3877
3878 for (exp = px->rsp_exp; exp; exp = exp->next) {
3879 int ret;
3880
3881 /*
3882 * The interleaving of transformations and verdicts
3883 * makes it difficult to decide to continue or stop
3884 * the evaluation.
3885 */
3886
3887 if (txn->flags & TX_SVDENY)
3888 break;
3889
3890 if ((txn->flags & TX_SVALLOW) &&
3891 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3892 exp->action == ACT_PASS)) {
3893 exp = exp->next;
3894 continue;
3895 }
3896
3897 /* if this filter had a condition, evaluate it now and skip to
3898 * next filter if the condition does not match.
3899 */
3900 if (exp->cond) {
3901 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3902 ret = acl_pass(ret);
3903 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3904 ret = !ret;
3905 if (!ret)
3906 continue;
3907 }
3908
3909 /* Apply the filter to the status line. */
3910 ret = htx_apply_filter_to_sts_line(s, res, exp);
3911 if (unlikely(ret < 0))
3912 return -1;
3913
3914 if (likely(ret == 0)) {
3915 /* The filter did not match the response, it can be
3916 * iterated through all headers.
3917 */
3918 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3919 return -1;
3920 }
3921 }
3922 return 0;
3923}
3924
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003925/*
3926 * Manage client-side cookie. It can impact performance by about 2% so it is
3927 * desirable to call it only when needed. This code is quite complex because
3928 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3929 * highly recommended not to touch this part without a good reason !
3930 */
3931static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3932{
3933 struct session *sess = s->sess;
3934 struct http_txn *txn = s->txn;
3935 struct htx *htx;
3936 struct http_hdr_ctx ctx;
3937 char *hdr_beg, *hdr_end, *del_from;
3938 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3939 int preserve_hdr;
3940
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003941 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003942 ctx.blk = NULL;
3943 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3944 del_from = NULL; /* nothing to be deleted */
3945 preserve_hdr = 0; /* assume we may kill the whole header */
3946
3947 /* Now look for cookies. Conforming to RFC2109, we have to support
3948 * attributes whose name begin with a '$', and associate them with
3949 * the right cookie, if we want to delete this cookie.
3950 * So there are 3 cases for each cookie read :
3951 * 1) it's a special attribute, beginning with a '$' : ignore it.
3952 * 2) it's a server id cookie that we *MAY* want to delete : save
3953 * some pointers on it (last semi-colon, beginning of cookie...)
3954 * 3) it's an application cookie : we *MAY* have to delete a previous
3955 * "special" cookie.
3956 * At the end of loop, if a "special" cookie remains, we may have to
3957 * remove it. If no application cookie persists in the header, we
3958 * *MUST* delete it.
3959 *
3960 * Note: RFC2965 is unclear about the processing of spaces around
3961 * the equal sign in the ATTR=VALUE form. A careful inspection of
3962 * the RFC explicitly allows spaces before it, and not within the
3963 * tokens (attrs or values). An inspection of RFC2109 allows that
3964 * too but section 10.1.3 lets one think that spaces may be allowed
3965 * after the equal sign too, resulting in some (rare) buggy
3966 * implementations trying to do that. So let's do what servers do.
3967 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3968 * allowed quoted strings in values, with any possible character
3969 * after a backslash, including control chars and delimitors, which
3970 * causes parsing to become ambiguous. Browsers also allow spaces
3971 * within values even without quotes.
3972 *
3973 * We have to keep multiple pointers in order to support cookie
3974 * removal at the beginning, middle or end of header without
3975 * corrupting the header. All of these headers are valid :
3976 *
3977 * hdr_beg hdr_end
3978 * | |
3979 * v |
3980 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3981 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3982 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3983 * | | | | | | |
3984 * | | | | | | |
3985 * | | | | | | +--> next
3986 * | | | | | +----> val_end
3987 * | | | | +-----------> val_beg
3988 * | | | +--------------> equal
3989 * | | +----------------> att_end
3990 * | +---------------------> att_beg
3991 * +--------------------------> prev
3992 *
3993 */
3994 hdr_beg = ctx.value.ptr;
3995 hdr_end = hdr_beg + ctx.value.len;
3996 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3997 /* Iterate through all cookies on this line */
3998
3999 /* find att_beg */
4000 att_beg = prev;
4001 if (prev > hdr_beg)
4002 att_beg++;
4003
4004 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4005 att_beg++;
4006
4007 /* find att_end : this is the first character after the last non
4008 * space before the equal. It may be equal to hdr_end.
4009 */
4010 equal = att_end = att_beg;
4011 while (equal < hdr_end) {
4012 if (*equal == '=' || *equal == ',' || *equal == ';')
4013 break;
4014 if (HTTP_IS_SPHT(*equal++))
4015 continue;
4016 att_end = equal;
4017 }
4018
4019 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4020 * is between <att_beg> and <equal>, both may be identical.
4021 */
4022 /* look for end of cookie if there is an equal sign */
4023 if (equal < hdr_end && *equal == '=') {
4024 /* look for the beginning of the value */
4025 val_beg = equal + 1;
4026 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4027 val_beg++;
4028
4029 /* find the end of the value, respecting quotes */
4030 next = http_find_cookie_value_end(val_beg, hdr_end);
4031
4032 /* make val_end point to the first white space or delimitor after the value */
4033 val_end = next;
4034 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4035 val_end--;
4036 }
4037 else
4038 val_beg = val_end = next = equal;
4039
4040 /* We have nothing to do with attributes beginning with
4041 * '$'. However, they will automatically be removed if a
4042 * header before them is removed, since they're supposed
4043 * to be linked together.
4044 */
4045 if (*att_beg == '$')
4046 continue;
4047
4048 /* Ignore cookies with no equal sign */
4049 if (equal == next) {
4050 /* This is not our cookie, so we must preserve it. But if we already
4051 * scheduled another cookie for removal, we cannot remove the
4052 * complete header, but we can remove the previous block itself.
4053 */
4054 preserve_hdr = 1;
4055 if (del_from != NULL) {
4056 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4057 val_end += delta;
4058 next += delta;
4059 hdr_end += delta;
4060 prev = del_from;
4061 del_from = NULL;
4062 }
4063 continue;
4064 }
4065
4066 /* if there are spaces around the equal sign, we need to
4067 * strip them otherwise we'll get trouble for cookie captures,
4068 * or even for rewrites. Since this happens extremely rarely,
4069 * it does not hurt performance.
4070 */
4071 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4072 int stripped_before = 0;
4073 int stripped_after = 0;
4074
4075 if (att_end != equal) {
4076 memmove(att_end, equal, hdr_end - equal);
4077 stripped_before = (att_end - equal);
4078 equal += stripped_before;
4079 val_beg += stripped_before;
4080 }
4081
4082 if (val_beg > equal + 1) {
4083 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4084 stripped_after = (equal + 1) - val_beg;
4085 val_beg += stripped_after;
4086 stripped_before += stripped_after;
4087 }
4088
4089 val_end += stripped_before;
4090 next += stripped_before;
4091 hdr_end += stripped_before;
4092 }
4093 /* now everything is as on the diagram above */
4094
4095 /* First, let's see if we want to capture this cookie. We check
4096 * that we don't already have a client side cookie, because we
4097 * can only capture one. Also as an optimisation, we ignore
4098 * cookies shorter than the declared name.
4099 */
4100 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4101 (val_end - att_beg >= sess->fe->capture_namelen) &&
4102 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4103 int log_len = val_end - att_beg;
4104
4105 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4106 ha_alert("HTTP logging : out of memory.\n");
4107 } else {
4108 if (log_len > sess->fe->capture_len)
4109 log_len = sess->fe->capture_len;
4110 memcpy(txn->cli_cookie, att_beg, log_len);
4111 txn->cli_cookie[log_len] = 0;
4112 }
4113 }
4114
4115 /* Persistence cookies in passive, rewrite or insert mode have the
4116 * following form :
4117 *
4118 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4119 *
4120 * For cookies in prefix mode, the form is :
4121 *
4122 * Cookie: NAME=SRV~VALUE
4123 */
4124 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4125 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4126 struct server *srv = s->be->srv;
4127 char *delim;
4128
4129 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4130 * have the server ID between val_beg and delim, and the original cookie between
4131 * delim+1 and val_end. Otherwise, delim==val_end :
4132 *
4133 * hdr_beg
4134 * |
4135 * v
4136 * NAME=SRV; # in all but prefix modes
4137 * NAME=SRV~OPAQUE ; # in prefix mode
4138 * || || | |+-> next
4139 * || || | +--> val_end
4140 * || || +---------> delim
4141 * || |+------------> val_beg
4142 * || +-------------> att_end = equal
4143 * |+-----------------> att_beg
4144 * +------------------> prev
4145 *
4146 */
4147 if (s->be->ck_opts & PR_CK_PFX) {
4148 for (delim = val_beg; delim < val_end; delim++)
4149 if (*delim == COOKIE_DELIM)
4150 break;
4151 }
4152 else {
4153 char *vbar1;
4154 delim = val_end;
4155 /* Now check if the cookie contains a date field, which would
4156 * appear after a vertical bar ('|') just after the server name
4157 * and before the delimiter.
4158 */
4159 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4160 if (vbar1) {
4161 /* OK, so left of the bar is the server's cookie and
4162 * right is the last seen date. It is a base64 encoded
4163 * 30-bit value representing the UNIX date since the
4164 * epoch in 4-second quantities.
4165 */
4166 int val;
4167 delim = vbar1++;
4168 if (val_end - vbar1 >= 5) {
4169 val = b64tos30(vbar1);
4170 if (val > 0)
4171 txn->cookie_last_date = val << 2;
4172 }
4173 /* look for a second vertical bar */
4174 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4175 if (vbar1 && (val_end - vbar1 > 5)) {
4176 val = b64tos30(vbar1 + 1);
4177 if (val > 0)
4178 txn->cookie_first_date = val << 2;
4179 }
4180 }
4181 }
4182
4183 /* if the cookie has an expiration date and the proxy wants to check
4184 * it, then we do that now. We first check if the cookie is too old,
4185 * then only if it has expired. We detect strict overflow because the
4186 * time resolution here is not great (4 seconds). Cookies with dates
4187 * in the future are ignored if their offset is beyond one day. This
4188 * allows an admin to fix timezone issues without expiring everyone
4189 * and at the same time avoids keeping unwanted side effects for too
4190 * long.
4191 */
4192 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4193 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4194 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4195 txn->flags &= ~TX_CK_MASK;
4196 txn->flags |= TX_CK_OLD;
4197 delim = val_beg; // let's pretend we have not found the cookie
4198 txn->cookie_first_date = 0;
4199 txn->cookie_last_date = 0;
4200 }
4201 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4202 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4203 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4204 txn->flags &= ~TX_CK_MASK;
4205 txn->flags |= TX_CK_EXPIRED;
4206 delim = val_beg; // let's pretend we have not found the cookie
4207 txn->cookie_first_date = 0;
4208 txn->cookie_last_date = 0;
4209 }
4210
4211 /* Here, we'll look for the first running server which supports the cookie.
4212 * This allows to share a same cookie between several servers, for example
4213 * to dedicate backup servers to specific servers only.
4214 * However, to prevent clients from sticking to cookie-less backup server
4215 * when they have incidentely learned an empty cookie, we simply ignore
4216 * empty cookies and mark them as invalid.
4217 * The same behaviour is applied when persistence must be ignored.
4218 */
4219 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4220 srv = NULL;
4221
4222 while (srv) {
4223 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4224 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4225 if ((srv->cur_state != SRV_ST_STOPPED) ||
4226 (s->be->options & PR_O_PERSIST) ||
4227 (s->flags & SF_FORCE_PRST)) {
4228 /* we found the server and we can use it */
4229 txn->flags &= ~TX_CK_MASK;
4230 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4231 s->flags |= SF_DIRECT | SF_ASSIGNED;
4232 s->target = &srv->obj_type;
4233 break;
4234 } else {
4235 /* we found a server, but it's down,
4236 * mark it as such and go on in case
4237 * another one is available.
4238 */
4239 txn->flags &= ~TX_CK_MASK;
4240 txn->flags |= TX_CK_DOWN;
4241 }
4242 }
4243 srv = srv->next;
4244 }
4245
4246 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4247 /* no server matched this cookie or we deliberately skipped it */
4248 txn->flags &= ~TX_CK_MASK;
4249 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4250 txn->flags |= TX_CK_UNUSED;
4251 else
4252 txn->flags |= TX_CK_INVALID;
4253 }
4254
4255 /* depending on the cookie mode, we may have to either :
4256 * - delete the complete cookie if we're in insert+indirect mode, so that
4257 * the server never sees it ;
4258 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004259 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004260 * if we're in cookie prefix mode
4261 */
4262 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4263 int delta; /* negative */
4264
4265 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4266 delta = val_beg - (delim + 1);
4267 val_end += delta;
4268 next += delta;
4269 hdr_end += delta;
4270 del_from = NULL;
4271 preserve_hdr = 1; /* we want to keep this cookie */
4272 }
4273 else if (del_from == NULL &&
4274 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4275 del_from = prev;
4276 }
4277 }
4278 else {
4279 /* This is not our cookie, so we must preserve it. But if we already
4280 * scheduled another cookie for removal, we cannot remove the
4281 * complete header, but we can remove the previous block itself.
4282 */
4283 preserve_hdr = 1;
4284
4285 if (del_from != NULL) {
4286 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4287 if (att_beg >= del_from)
4288 att_beg += delta;
4289 if (att_end >= del_from)
4290 att_end += delta;
4291 val_beg += delta;
4292 val_end += delta;
4293 next += delta;
4294 hdr_end += delta;
4295 prev = del_from;
4296 del_from = NULL;
4297 }
4298 }
4299
4300 /* continue with next cookie on this header line */
4301 att_beg = next;
4302 } /* for each cookie */
4303
4304
4305 /* There are no more cookies on this line.
4306 * We may still have one (or several) marked for deletion at the
4307 * end of the line. We must do this now in two ways :
4308 * - if some cookies must be preserved, we only delete from the
4309 * mark to the end of line ;
4310 * - if nothing needs to be preserved, simply delete the whole header
4311 */
4312 if (del_from) {
4313 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4314 }
4315 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004316 if (hdr_beg != hdr_end)
4317 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004318 else
4319 http_remove_header(htx, &ctx);
4320 }
4321 } /* for each "Cookie header */
4322}
4323
4324/*
4325 * Manage server-side cookies. It can impact performance by about 2% so it is
4326 * desirable to call it only when needed. This function is also used when we
4327 * just need to know if there is a cookie (eg: for check-cache).
4328 */
4329static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4330{
4331 struct session *sess = s->sess;
4332 struct http_txn *txn = s->txn;
4333 struct htx *htx;
4334 struct http_hdr_ctx ctx;
4335 struct server *srv;
4336 char *hdr_beg, *hdr_end;
4337 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004338 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004339
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004340 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004341
4342 ctx.blk = NULL;
4343 while (1) {
4344 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4345 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4346 break;
4347 is_cookie2 = 1;
4348 }
4349
4350 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4351 * <prev> points to the colon.
4352 */
4353 txn->flags |= TX_SCK_PRESENT;
4354
4355 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4356 * check-cache is enabled) and we are not interested in checking
4357 * them. Warning, the cookie capture is declared in the frontend.
4358 */
4359 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4360 break;
4361
4362 /* OK so now we know we have to process this response cookie.
4363 * The format of the Set-Cookie header is slightly different
4364 * from the format of the Cookie header in that it does not
4365 * support the comma as a cookie delimiter (thus the header
4366 * cannot be folded) because the Expires attribute described in
4367 * the original Netscape's spec may contain an unquoted date
4368 * with a comma inside. We have to live with this because
4369 * many browsers don't support Max-Age and some browsers don't
4370 * support quoted strings. However the Set-Cookie2 header is
4371 * clean.
4372 *
4373 * We have to keep multiple pointers in order to support cookie
4374 * removal at the beginning, middle or end of header without
4375 * corrupting the header (in case of set-cookie2). A special
4376 * pointer, <scav> points to the beginning of the set-cookie-av
4377 * fields after the first semi-colon. The <next> pointer points
4378 * either to the end of line (set-cookie) or next unquoted comma
4379 * (set-cookie2). All of these headers are valid :
4380 *
4381 * hdr_beg hdr_end
4382 * | |
4383 * v |
4384 * NAME1 = VALUE 1 ; Secure; Path="/" |
4385 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4386 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4387 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4388 * | | | | | | | |
4389 * | | | | | | | +-> next
4390 * | | | | | | +------------> scav
4391 * | | | | | +--------------> val_end
4392 * | | | | +--------------------> val_beg
4393 * | | | +----------------------> equal
4394 * | | +------------------------> att_end
4395 * | +----------------------------> att_beg
4396 * +------------------------------> prev
4397 * -------------------------------> hdr_beg
4398 */
4399 hdr_beg = ctx.value.ptr;
4400 hdr_end = hdr_beg + ctx.value.len;
4401 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4402
4403 /* Iterate through all cookies on this line */
4404
4405 /* find att_beg */
4406 att_beg = prev;
4407 if (prev > hdr_beg)
4408 att_beg++;
4409
4410 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4411 att_beg++;
4412
4413 /* find att_end : this is the first character after the last non
4414 * space before the equal. It may be equal to hdr_end.
4415 */
4416 equal = att_end = att_beg;
4417
4418 while (equal < hdr_end) {
4419 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4420 break;
4421 if (HTTP_IS_SPHT(*equal++))
4422 continue;
4423 att_end = equal;
4424 }
4425
4426 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4427 * is between <att_beg> and <equal>, both may be identical.
4428 */
4429
4430 /* look for end of cookie if there is an equal sign */
4431 if (equal < hdr_end && *equal == '=') {
4432 /* look for the beginning of the value */
4433 val_beg = equal + 1;
4434 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4435 val_beg++;
4436
4437 /* find the end of the value, respecting quotes */
4438 next = http_find_cookie_value_end(val_beg, hdr_end);
4439
4440 /* make val_end point to the first white space or delimitor after the value */
4441 val_end = next;
4442 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4443 val_end--;
4444 }
4445 else {
4446 /* <equal> points to next comma, semi-colon or EOL */
4447 val_beg = val_end = next = equal;
4448 }
4449
4450 if (next < hdr_end) {
4451 /* Set-Cookie2 supports multiple cookies, and <next> points to
4452 * a colon or semi-colon before the end. So skip all attr-value
4453 * pairs and look for the next comma. For Set-Cookie, since
4454 * commas are permitted in values, skip to the end.
4455 */
4456 if (is_cookie2)
4457 next = http_find_hdr_value_end(next, hdr_end);
4458 else
4459 next = hdr_end;
4460 }
4461
4462 /* Now everything is as on the diagram above */
4463
4464 /* Ignore cookies with no equal sign */
4465 if (equal == val_end)
4466 continue;
4467
4468 /* If there are spaces around the equal sign, we need to
4469 * strip them otherwise we'll get trouble for cookie captures,
4470 * or even for rewrites. Since this happens extremely rarely,
4471 * it does not hurt performance.
4472 */
4473 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4474 int stripped_before = 0;
4475 int stripped_after = 0;
4476
4477 if (att_end != equal) {
4478 memmove(att_end, equal, hdr_end - equal);
4479 stripped_before = (att_end - equal);
4480 equal += stripped_before;
4481 val_beg += stripped_before;
4482 }
4483
4484 if (val_beg > equal + 1) {
4485 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4486 stripped_after = (equal + 1) - val_beg;
4487 val_beg += stripped_after;
4488 stripped_before += stripped_after;
4489 }
4490
4491 val_end += stripped_before;
4492 next += stripped_before;
4493 hdr_end += stripped_before;
4494
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004495 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004496 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004497 }
4498
4499 /* First, let's see if we want to capture this cookie. We check
4500 * that we don't already have a server side cookie, because we
4501 * can only capture one. Also as an optimisation, we ignore
4502 * cookies shorter than the declared name.
4503 */
4504 if (sess->fe->capture_name != NULL &&
4505 txn->srv_cookie == NULL &&
4506 (val_end - att_beg >= sess->fe->capture_namelen) &&
4507 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4508 int log_len = val_end - att_beg;
4509 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4510 ha_alert("HTTP logging : out of memory.\n");
4511 }
4512 else {
4513 if (log_len > sess->fe->capture_len)
4514 log_len = sess->fe->capture_len;
4515 memcpy(txn->srv_cookie, att_beg, log_len);
4516 txn->srv_cookie[log_len] = 0;
4517 }
4518 }
4519
4520 srv = objt_server(s->target);
4521 /* now check if we need to process it for persistence */
4522 if (!(s->flags & SF_IGNORE_PRST) &&
4523 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4524 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4525 /* assume passive cookie by default */
4526 txn->flags &= ~TX_SCK_MASK;
4527 txn->flags |= TX_SCK_FOUND;
4528
4529 /* If the cookie is in insert mode on a known server, we'll delete
4530 * this occurrence because we'll insert another one later.
4531 * We'll delete it too if the "indirect" option is set and we're in
4532 * a direct access.
4533 */
4534 if (s->be->ck_opts & PR_CK_PSV) {
4535 /* The "preserve" flag was set, we don't want to touch the
4536 * server's cookie.
4537 */
4538 }
4539 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4540 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4541 /* this cookie must be deleted */
4542 if (prev == hdr_beg && next == hdr_end) {
4543 /* whole header */
4544 http_remove_header(htx, &ctx);
4545 /* note: while both invalid now, <next> and <hdr_end>
4546 * are still equal, so the for() will stop as expected.
4547 */
4548 } else {
4549 /* just remove the value */
4550 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4551 next = prev;
4552 hdr_end += delta;
4553 }
4554 txn->flags &= ~TX_SCK_MASK;
4555 txn->flags |= TX_SCK_DELETED;
4556 /* and go on with next cookie */
4557 }
4558 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4559 /* replace bytes val_beg->val_end with the cookie name associated
4560 * with this server since we know it.
4561 */
4562 int sliding, delta;
4563
4564 ctx.value = ist2(val_beg, val_end - val_beg);
4565 ctx.lws_before = ctx.lws_after = 0;
4566 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4567 delta = srv->cklen - (val_end - val_beg);
4568 sliding = (ctx.value.ptr - val_beg);
4569 hdr_beg += sliding;
4570 val_beg += sliding;
4571 next += sliding + delta;
4572 hdr_end += sliding + delta;
4573
4574 txn->flags &= ~TX_SCK_MASK;
4575 txn->flags |= TX_SCK_REPLACED;
4576 }
4577 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4578 /* insert the cookie name associated with this server
4579 * before existing cookie, and insert a delimiter between them..
4580 */
4581 int sliding, delta;
4582 ctx.value = ist2(val_beg, 0);
4583 ctx.lws_before = ctx.lws_after = 0;
4584 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4585 delta = srv->cklen + 1;
4586 sliding = (ctx.value.ptr - val_beg);
4587 hdr_beg += sliding;
4588 val_beg += sliding;
4589 next += sliding + delta;
4590 hdr_end += sliding + delta;
4591
4592 val_beg[srv->cklen] = COOKIE_DELIM;
4593 txn->flags &= ~TX_SCK_MASK;
4594 txn->flags |= TX_SCK_REPLACED;
4595 }
4596 }
4597 /* that's done for this cookie, check the next one on the same
4598 * line when next != hdr_end (only if is_cookie2).
4599 */
4600 }
4601 }
4602}
4603
Christopher Faulet25a02f62018-10-24 12:00:25 +02004604/*
4605 * Parses the Cache-Control and Pragma request header fields to determine if
4606 * the request may be served from the cache and/or if it is cacheable. Updates
4607 * s->txn->flags.
4608 */
4609void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4610{
4611 struct http_txn *txn = s->txn;
4612 struct htx *htx;
4613 int32_t pos;
4614 int pragma_found, cc_found, i;
4615
4616 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4617 return; /* nothing more to do here */
4618
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004619 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004620 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004621 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004622 struct htx_blk *blk = htx_get_blk(htx, pos);
4623 enum htx_blk_type type = htx_get_blk_type(blk);
4624 struct ist n, v;
4625
4626 if (type == HTX_BLK_EOH)
4627 break;
4628 if (type != HTX_BLK_HDR)
4629 continue;
4630
4631 n = htx_get_blk_name(htx, blk);
4632 v = htx_get_blk_value(htx, blk);
4633
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004634 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004635 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4636 pragma_found = 1;
4637 continue;
4638 }
4639 }
4640
4641 /* Don't use the cache and don't try to store if we found the
4642 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004643 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004644 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4645 txn->flags |= TX_CACHE_IGNORE;
4646 continue;
4647 }
4648
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004649 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004650 continue;
4651
4652 /* OK, right now we know we have a cache-control header */
4653 cc_found = 1;
4654 if (!v.len) /* no info */
4655 continue;
4656
4657 i = 0;
4658 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4659 !isspace((unsigned char)*(v.ptr+i)))
4660 i++;
4661
4662 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4663 * values after max-age, max-stale nor min-fresh, we simply don't
4664 * use the cache when they're specified.
4665 */
4666 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4667 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4668 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4669 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4670 txn->flags |= TX_CACHE_IGNORE;
4671 continue;
4672 }
4673
4674 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4675 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4676 continue;
4677 }
4678 }
4679
4680 /* RFC7234#5.4:
4681 * When the Cache-Control header field is also present and
4682 * understood in a request, Pragma is ignored.
4683 * When the Cache-Control header field is not present in a
4684 * request, caches MUST consider the no-cache request
4685 * pragma-directive as having the same effect as if
4686 * "Cache-Control: no-cache" were present.
4687 */
4688 if (!cc_found && pragma_found)
4689 txn->flags |= TX_CACHE_IGNORE;
4690}
4691
4692/*
4693 * Check if response is cacheable or not. Updates s->txn->flags.
4694 */
4695void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4696{
4697 struct http_txn *txn = s->txn;
4698 struct htx *htx;
4699 int32_t pos;
4700 int i;
4701
4702 if (txn->status < 200) {
4703 /* do not try to cache interim responses! */
4704 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4705 return;
4706 }
4707
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004708 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004709 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004710 struct htx_blk *blk = htx_get_blk(htx, pos);
4711 enum htx_blk_type type = htx_get_blk_type(blk);
4712 struct ist n, v;
4713
4714 if (type == HTX_BLK_EOH)
4715 break;
4716 if (type != HTX_BLK_HDR)
4717 continue;
4718
4719 n = htx_get_blk_name(htx, blk);
4720 v = htx_get_blk_value(htx, blk);
4721
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004722 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004723 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4724 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4725 return;
4726 }
4727 }
4728
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004729 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004730 continue;
4731
4732 /* OK, right now we know we have a cache-control header */
4733 if (!v.len) /* no info */
4734 continue;
4735
4736 i = 0;
4737 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4738 !isspace((unsigned char)*(v.ptr+i)))
4739 i++;
4740
4741 /* we have a complete value between v.ptr and (v.ptr+i) */
4742 if (i < v.len && *(v.ptr + i) == '=') {
4743 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4744 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4745 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4746 continue;
4747 }
4748
4749 /* we have something of the form no-cache="set-cookie" */
4750 if ((v.len >= 21) &&
4751 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4752 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4753 txn->flags &= ~TX_CACHE_COOK;
4754 continue;
4755 }
4756
4757 /* OK, so we know that either p2 points to the end of string or to a comma */
4758 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4759 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4760 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4761 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4762 return;
4763 }
4764
4765 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4766 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4767 continue;
4768 }
4769 }
4770}
4771
Christopher Faulet64159df2018-10-24 21:15:35 +02004772/* send a server's name with an outgoing request over an established connection.
4773 * Note: this function is designed to be called once the request has been
4774 * scheduled for being forwarded. This is the reason why the number of forwarded
4775 * bytes have to be adjusted.
4776 */
4777int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4778{
4779 struct htx *htx;
4780 struct http_hdr_ctx ctx;
4781 struct ist hdr;
4782 uint32_t data;
4783
4784 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004785 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004786 data = htx->data;
4787
4788 ctx.blk = NULL;
4789 while (http_find_header(htx, hdr, &ctx, 1))
4790 http_remove_header(htx, &ctx);
4791 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4792
4793 if (co_data(&s->req)) {
4794 if (data >= htx->data)
4795 c_rew(&s->req, data - htx->data);
4796 else
4797 c_adv(&s->req, htx->data - data);
4798 }
4799 return 0;
4800}
4801
Christopher Faulet377c5a52018-10-24 21:21:30 +02004802/*
4803 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4804 * for the current backend.
4805 *
4806 * It is assumed that the request is either a HEAD, GET, or POST and that the
4807 * uri_auth field is valid.
4808 *
4809 * Returns 1 if stats should be provided, otherwise 0.
4810 */
4811static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4812{
4813 struct uri_auth *uri_auth = backend->uri_auth;
4814 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004815 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004816 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004817
4818 if (!uri_auth)
4819 return 0;
4820
4821 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4822 return 0;
4823
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004824 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004825 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004826 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004827
4828 /* check URI size */
4829 if (uri_auth->uri_len > uri.len)
4830 return 0;
4831
4832 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4833 return 0;
4834
4835 return 1;
4836}
4837
4838/* This function prepares an applet to handle the stats. It can deal with the
4839 * "100-continue" expectation, check that admin rules are met for POST requests,
4840 * and program a response message if something was unexpected. It cannot fail
4841 * and always relies on the stats applet to complete the job. It does not touch
4842 * analysers nor counters, which are left to the caller. It does not touch
4843 * s->target which is supposed to already point to the stats applet. The caller
4844 * is expected to have already assigned an appctx to the stream.
4845 */
4846static int htx_handle_stats(struct stream *s, struct channel *req)
4847{
4848 struct stats_admin_rule *stats_admin_rule;
4849 struct stream_interface *si = &s->si[1];
4850 struct session *sess = s->sess;
4851 struct http_txn *txn = s->txn;
4852 struct http_msg *msg = &txn->req;
4853 struct uri_auth *uri_auth = s->be->uri_auth;
4854 const char *h, *lookup, *end;
4855 struct appctx *appctx;
4856 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004857 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004858
4859 appctx = si_appctx(si);
4860 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4861 appctx->st1 = appctx->st2 = 0;
4862 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4863 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4864 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4865 appctx->ctx.stats.flags |= STAT_CHUNKED;
4866
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004867 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004868 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004869 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4870 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004871
4872 for (h = lookup; h <= end - 3; h++) {
4873 if (memcmp(h, ";up", 3) == 0) {
4874 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4875 break;
4876 }
4877 }
4878
4879 if (uri_auth->refresh) {
4880 for (h = lookup; h <= end - 10; h++) {
4881 if (memcmp(h, ";norefresh", 10) == 0) {
4882 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4883 break;
4884 }
4885 }
4886 }
4887
4888 for (h = lookup; h <= end - 4; h++) {
4889 if (memcmp(h, ";csv", 4) == 0) {
4890 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4891 break;
4892 }
4893 }
4894
4895 for (h = lookup; h <= end - 6; h++) {
4896 if (memcmp(h, ";typed", 6) == 0) {
4897 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4898 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4899 break;
4900 }
4901 }
4902
4903 for (h = lookup; h <= end - 8; h++) {
4904 if (memcmp(h, ";st=", 4) == 0) {
4905 int i;
4906 h += 4;
4907 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4908 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4909 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4910 appctx->ctx.stats.st_code = i;
4911 break;
4912 }
4913 }
4914 break;
4915 }
4916 }
4917
4918 appctx->ctx.stats.scope_str = 0;
4919 appctx->ctx.stats.scope_len = 0;
4920 for (h = lookup; h <= end - 8; h++) {
4921 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4922 int itx = 0;
4923 const char *h2;
4924 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4925 const char *err;
4926
4927 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4928 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004929 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4930 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004931 if (*h == ';' || *h == '&' || *h == ' ')
4932 break;
4933 itx++;
4934 h++;
4935 }
4936
4937 if (itx > STAT_SCOPE_TXT_MAXLEN)
4938 itx = STAT_SCOPE_TXT_MAXLEN;
4939 appctx->ctx.stats.scope_len = itx;
4940
4941 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4942 memcpy(scope_txt, h2, itx);
4943 scope_txt[itx] = '\0';
4944 err = invalid_char(scope_txt);
4945 if (err) {
4946 /* bad char in search text => clear scope */
4947 appctx->ctx.stats.scope_str = 0;
4948 appctx->ctx.stats.scope_len = 0;
4949 }
4950 break;
4951 }
4952 }
4953
4954 /* now check whether we have some admin rules for this request */
4955 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4956 int ret = 1;
4957
4958 if (stats_admin_rule->cond) {
4959 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4960 ret = acl_pass(ret);
4961 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4962 ret = !ret;
4963 }
4964
4965 if (ret) {
4966 /* no rule, or the rule matches */
4967 appctx->ctx.stats.flags |= STAT_ADMIN;
4968 break;
4969 }
4970 }
4971
Christopher Faulet5d45e382019-02-27 15:15:23 +01004972 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4973 appctx->st0 = STAT_HTTP_HEAD;
4974 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004975 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004976 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004977 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004978 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004979 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4980 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4981 appctx->st0 = STAT_HTTP_LAST;
4982 }
4983 }
4984 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004985 /* Unsupported method */
4986 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4987 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4988 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004989 }
4990
4991 s->task->nice = -32; /* small boost for HTTP statistics */
4992 return 1;
4993}
4994
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4996{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 struct channel *req = &s->req;
4998 struct channel *res = &s->res;
4999 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005000 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005001 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005002 struct ist path, location;
5003 unsigned int flags;
5004 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005006 /*
5007 * Create the location
5008 */
5009 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005010
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005011 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005012 /* special prefix "/" means don't change URL */
5013 srv = __objt_server(s->target);
5014 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5015 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5016 return;
5017 }
5018
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005019 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005020 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005021 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005022 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005023 if (!path.ptr)
5024 return;
5025
5026 if (!chunk_memcat(&trash, path.ptr, path.len))
5027 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005028 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005029
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005030 /*
5031 * Create the 302 respone
5032 */
5033 htx = htx_from_buf(&res->buf);
5034 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5035 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5036 ist("HTTP/1.1"), ist("302"), ist("Found"));
5037 if (!sl)
5038 goto fail;
5039 sl->info.res.status = 302;
5040 s->txn->status = 302;
5041
5042 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5043 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5044 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5045 !htx_add_header(htx, ist("Location"), location))
5046 goto fail;
5047
5048 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5049 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005050
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005051 /*
5052 * Send the message
5053 */
5054 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005055 c_adv(res, data);
5056 res->total += data;
5057
5058 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005059 si_shutr(si);
5060 si_shutw(si);
5061 si->err_type = SI_ET_NONE;
5062 si->state = SI_ST_CLO;
5063
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005064 channel_auto_read(req);
5065 channel_abort(req);
5066 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005067 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005068 channel_auto_read(res);
5069 channel_auto_close(res);
5070
5071 if (!(s->flags & SF_ERR_MASK))
5072 s->flags |= SF_ERR_LOCAL;
5073 if (!(s->flags & SF_FINST_MASK))
5074 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005075
5076 /* FIXME: we should increase a counter of redirects per server and per backend. */
5077 srv_inc_sess_ctr(srv);
5078 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005079 return;
5080
5081 fail:
5082 /* If an error occurred, remove the incomplete HTTP response from the
5083 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005084 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005085}
5086
Christopher Fauletf2824e62018-10-01 12:12:37 +02005087/* This function terminates the request because it was completly analyzed or
5088 * because an error was triggered during the body forwarding.
5089 */
5090static void htx_end_request(struct stream *s)
5091{
5092 struct channel *chn = &s->req;
5093 struct http_txn *txn = s->txn;
5094
5095 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5096 now_ms, __FUNCTION__, s,
5097 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5098 s->req.analysers, s->res.analysers);
5099
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005100 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5101 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005102 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005103 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005104 goto end;
5105 }
5106
5107 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5108 return;
5109
5110 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005111 /* No need to read anymore, the request was completely parsed.
5112 * We can shut the read side unless we want to abort_on_close,
5113 * or we have a POST request. The issue with POST requests is
5114 * that some browsers still send a CRLF after the request, and
5115 * this CRLF must be read so that it does not remain in the kernel
5116 * buffers, otherwise a close could cause an RST on some systems
5117 * (eg: Linux).
5118 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005119 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005120 channel_dont_read(chn);
5121
5122 /* if the server closes the connection, we want to immediately react
5123 * and close the socket to save packets and syscalls.
5124 */
5125 s->si[1].flags |= SI_FL_NOHALF;
5126
5127 /* In any case we've finished parsing the request so we must
5128 * disable Nagle when sending data because 1) we're not going
5129 * to shut this side, and 2) the server is waiting for us to
5130 * send pending data.
5131 */
5132 chn->flags |= CF_NEVER_WAIT;
5133
Christopher Fauletd01ce402019-01-02 17:44:13 +01005134 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5135 /* The server has not finished to respond, so we
5136 * don't want to move in order not to upset it.
5137 */
5138 return;
5139 }
5140
Christopher Fauletf2824e62018-10-01 12:12:37 +02005141 /* When we get here, it means that both the request and the
5142 * response have finished receiving. Depending on the connection
5143 * mode, we'll have to wait for the last bytes to leave in either
5144 * direction, and sometimes for a close to be effective.
5145 */
5146 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5147 /* Tunnel mode will not have any analyser so it needs to
5148 * poll for reads.
5149 */
5150 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005151 if (b_data(&chn->buf))
5152 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005153 txn->req.msg_state = HTTP_MSG_TUNNEL;
5154 }
5155 else {
5156 /* we're not expecting any new data to come for this
5157 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005158 *
5159 * However, there is an exception if the response
5160 * length is undefined. In this case, we need to wait
5161 * the close from the server. The response will be
5162 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005163 */
5164 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5165 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005166 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005167
5168 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5169 channel_shutr_now(chn);
5170 channel_shutw_now(chn);
5171 }
5172 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005173 goto check_channel_flags;
5174 }
5175
5176 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5177 http_msg_closing:
5178 /* nothing else to forward, just waiting for the output buffer
5179 * to be empty and for the shutw_now to take effect.
5180 */
5181 if (channel_is_empty(chn)) {
5182 txn->req.msg_state = HTTP_MSG_CLOSED;
5183 goto http_msg_closed;
5184 }
5185 else if (chn->flags & CF_SHUTW) {
5186 txn->req.err_state = txn->req.msg_state;
5187 txn->req.msg_state = HTTP_MSG_ERROR;
5188 goto end;
5189 }
5190 return;
5191 }
5192
5193 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5194 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 /* if we don't know whether the server will close, we need to hard close */
5196 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5197 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005198 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005199 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005200 channel_dont_read(chn);
5201 goto end;
5202 }
5203
5204 check_channel_flags:
5205 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5206 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5207 /* if we've just closed an output, let's switch */
5208 txn->req.msg_state = HTTP_MSG_CLOSING;
5209 goto http_msg_closing;
5210 }
5211
5212 end:
5213 chn->analysers &= AN_REQ_FLT_END;
5214 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5215 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5216 channel_auto_close(chn);
5217 channel_auto_read(chn);
5218}
5219
5220
5221/* This function terminates the response because it was completly analyzed or
5222 * because an error was triggered during the body forwarding.
5223 */
5224static void htx_end_response(struct stream *s)
5225{
5226 struct channel *chn = &s->res;
5227 struct http_txn *txn = s->txn;
5228
5229 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5230 now_ms, __FUNCTION__, s,
5231 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5232 s->req.analysers, s->res.analysers);
5233
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005234 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5235 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005236 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005237 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005238 goto end;
5239 }
5240
5241 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5242 return;
5243
5244 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5245 /* In theory, we don't need to read anymore, but we must
5246 * still monitor the server connection for a possible close
5247 * while the request is being uploaded, so we don't disable
5248 * reading.
5249 */
5250 /* channel_dont_read(chn); */
5251
5252 if (txn->req.msg_state < HTTP_MSG_DONE) {
5253 /* The client seems to still be sending data, probably
5254 * because we got an error response during an upload.
5255 * We have the choice of either breaking the connection
5256 * or letting it pass through. Let's do the later.
5257 */
5258 return;
5259 }
5260
5261 /* When we get here, it means that both the request and the
5262 * response have finished receiving. Depending on the connection
5263 * mode, we'll have to wait for the last bytes to leave in either
5264 * direction, and sometimes for a close to be effective.
5265 */
5266 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5267 channel_auto_read(chn);
5268 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005269 if (b_data(&chn->buf))
5270 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005271 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5272 }
5273 else {
5274 /* we're not expecting any new data to come for this
5275 * transaction, so we can close it.
5276 */
5277 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5278 channel_shutr_now(chn);
5279 channel_shutw_now(chn);
5280 }
5281 }
5282 goto check_channel_flags;
5283 }
5284
5285 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5286 http_msg_closing:
5287 /* nothing else to forward, just waiting for the output buffer
5288 * to be empty and for the shutw_now to take effect.
5289 */
5290 if (channel_is_empty(chn)) {
5291 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5292 goto http_msg_closed;
5293 }
5294 else if (chn->flags & CF_SHUTW) {
5295 txn->rsp.err_state = txn->rsp.msg_state;
5296 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005297 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005298 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005299 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005300 goto end;
5301 }
5302 return;
5303 }
5304
5305 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5306 http_msg_closed:
5307 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005308 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005309 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005310 goto end;
5311 }
5312
5313 check_channel_flags:
5314 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5315 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5316 /* if we've just closed an output, let's switch */
5317 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5318 goto http_msg_closing;
5319 }
5320
5321 end:
5322 chn->analysers &= AN_RES_FLT_END;
5323 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5324 chn->analysers |= AN_RES_FLT_XFER_DATA;
5325 channel_auto_close(chn);
5326 channel_auto_read(chn);
5327}
5328
Christopher Faulet0f226952018-10-22 09:29:56 +02005329void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5330 int finst, const struct buffer *msg)
5331{
5332 channel_auto_read(si_oc(si));
5333 channel_abort(si_oc(si));
5334 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005335 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005336 channel_auto_close(si_ic(si));
5337 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005338
5339 /* <msg> is an HTX structure. So we copy it in the response's
5340 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005341 if (msg) {
5342 struct channel *chn = si_ic(si);
5343 struct htx *htx;
5344
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005345 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005346 chn->buf.data = msg->data;
5347 memcpy(chn->buf.area, msg->area, msg->data);
5348 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005349 c_adv(chn, htx->data);
5350 chn->total += htx->data;
5351 }
5352 if (!(s->flags & SF_ERR_MASK))
5353 s->flags |= err;
5354 if (!(s->flags & SF_FINST_MASK))
5355 s->flags |= finst;
5356}
5357
5358void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5359{
5360 channel_auto_read(&s->req);
5361 channel_abort(&s->req);
5362 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005363 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5364 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005365
5366 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005367
5368 /* <msg> is an HTX structure. So we copy it in the response's
5369 * channel */
5370 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005371 if (msg) {
5372 struct channel *chn = &s->res;
5373 struct htx *htx;
5374
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005375 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005376 chn->buf.data = msg->data;
5377 memcpy(chn->buf.area, msg->area, msg->data);
5378 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005379 c_adv(chn, htx->data);
5380 chn->total += htx->data;
5381 }
5382
5383 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5384 channel_auto_read(&s->res);
5385 channel_auto_close(&s->res);
5386 channel_shutr_now(&s->res);
5387}
5388
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005389struct buffer *htx_error_message(struct stream *s)
5390{
5391 const int msgnum = http_get_status_idx(s->txn->status);
5392
5393 if (s->be->errmsg[msgnum].area)
5394 return &s->be->errmsg[msgnum];
5395 else if (strm_fe(s)->errmsg[msgnum].area)
5396 return &strm_fe(s)->errmsg[msgnum];
5397 else
5398 return &htx_err_chunks[msgnum];
5399}
5400
Christopher Faulet304cc402019-07-15 15:46:28 +02005401/* Return the error message corresponding to si->err_type. It is assumed
5402 * that the server side is closed. Note that err_type is actually a
5403 * bitmask, where almost only aborts may be cumulated with other
5404 * values. We consider that aborted operations are more important
5405 * than timeouts or errors due to the fact that nobody else in the
5406 * logs might explain incomplete retries. All others should avoid
5407 * being cumulated. It should normally not be possible to have multiple
5408 * aborts at once, but just in case, the first one in sequence is reported.
5409 * Note that connection errors appearing on the second request of a keep-alive
5410 * connection are not reported since this allows the client to retry.
5411 */
5412void htx_return_srv_error(struct stream *s, struct stream_interface *si)
5413{
5414 int err_type = si->err_type;
5415
5416 /* set s->txn->status for http_error_message(s) */
5417 s->txn->status = 503;
5418
5419 if (err_type & SI_ET_QUEUE_ABRT)
5420 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
5421 htx_error_message(s));
5422 else if (err_type & SI_ET_CONN_ABRT)
5423 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
5424 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5425 htx_error_message(s));
5426 else if (err_type & SI_ET_QUEUE_TO)
5427 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
5428 htx_error_message(s));
5429 else if (err_type & SI_ET_QUEUE_ERR)
5430 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
5431 htx_error_message(s));
5432 else if (err_type & SI_ET_CONN_TO)
5433 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
5434 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5435 htx_error_message(s));
5436 else if (err_type & SI_ET_CONN_ERR)
5437 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
5438 (s->flags & SF_SRV_REUSED) ? NULL :
5439 htx_error_message(s));
5440 else if (err_type & SI_ET_CONN_RES)
5441 htx_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
5442 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5443 htx_error_message(s));
5444 else { /* SI_ET_CONN_OTHER and others */
5445 s->txn->status = 500;
5446 htx_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
5447 htx_error_message(s));
5448 }
5449}
5450
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005451
Christopher Faulet4a28a532019-03-01 11:19:40 +01005452/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5453 * on success and -1 on error.
5454 */
5455static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5456{
5457 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5458 * then we must send an HTTP/1.1 100 Continue intermediate response.
5459 */
5460 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5461 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5462 struct ist hdr = { .ptr = "Expect", .len = 6 };
5463 struct http_hdr_ctx ctx;
5464
5465 ctx.blk = NULL;
5466 /* Expect is allowed in 1.1, look for it */
5467 if (http_find_header(htx, hdr, &ctx, 0) &&
5468 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5469 if (htx_reply_100_continue(s) == -1)
5470 return -1;
5471 http_remove_header(htx, &ctx);
5472 }
5473 }
5474 return 0;
5475}
5476
Christopher Faulet23a3c792018-11-28 10:01:23 +01005477/* Send a 100-Continue response to the client. It returns 0 on success and -1
5478 * on error. The response channel is updated accordingly.
5479 */
5480static int htx_reply_100_continue(struct stream *s)
5481{
5482 struct channel *res = &s->res;
5483 struct htx *htx = htx_from_buf(&res->buf);
5484 struct htx_sl *sl;
5485 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5486 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5487 size_t data;
5488
5489 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5490 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5491 if (!sl)
5492 goto fail;
5493 sl->info.res.status = 100;
5494
Christopher Faulet1d5ec092019-06-26 14:23:54 +02005495 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005496 goto fail;
5497
5498 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005499 c_adv(res, data);
5500 res->total += data;
5501 return 0;
5502
5503 fail:
5504 /* If an error occurred, remove the incomplete HTTP response from the
5505 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005506 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005507 return -1;
5508}
5509
Christopher Faulet12c51e22018-11-28 15:59:42 +01005510
5511/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5512 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5513 * error. The response channel is updated accordingly.
5514 */
5515static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5516{
5517 struct channel *res = &s->res;
5518 struct htx *htx = htx_from_buf(&res->buf);
5519 struct htx_sl *sl;
5520 struct ist code, body;
5521 int status;
5522 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5523 size_t data;
5524
5525 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5526 status = 401;
5527 code = ist("401");
5528 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5529 "You need a valid user and password to access this content.\n"
5530 "</body></html>\n");
5531 }
5532 else {
5533 status = 407;
5534 code = ist("407");
5535 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5536 "You need a valid user and password to access this content.\n"
5537 "</body></html>\n");
5538 }
5539
5540 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5541 ist("HTTP/1.1"), code, ist("Unauthorized"));
5542 if (!sl)
5543 goto fail;
5544 sl->info.res.status = status;
5545 s->txn->status = status;
5546
5547 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5548 goto fail;
5549
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005550 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5551 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005552 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005553 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5554 goto fail;
5555 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5556 goto fail;
5557 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005558 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005559 if (!htx_add_endof(htx, HTX_BLK_EOH))
5560 goto fail;
5561
5562 while (body.len) {
5563 size_t sent = htx_add_data(htx, body);
5564 if (!sent)
5565 goto fail;
5566 body.ptr += sent;
5567 body.len -= sent;
5568 }
5569
5570 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005571 goto fail;
5572
5573 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005574 c_adv(res, data);
5575 res->total += data;
5576
5577 channel_auto_read(&s->req);
5578 channel_abort(&s->req);
5579 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005580 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005581
5582 res->wex = tick_add_ifset(now_ms, res->wto);
5583 channel_auto_read(res);
5584 channel_auto_close(res);
5585 channel_shutr_now(res);
5586 return 0;
5587
5588 fail:
5589 /* If an error occurred, remove the incomplete HTTP response from the
5590 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005591 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005592 return -1;
5593}
5594
Christopher Faulet0f226952018-10-22 09:29:56 +02005595/*
5596 * Capture headers from message <htx> according to header list <cap_hdr>, and
5597 * fill the <cap> pointers appropriately.
5598 */
5599static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5600{
5601 struct cap_hdr *h;
5602 int32_t pos;
5603
Christopher Fauleta3f15502019-05-13 15:27:23 +02005604 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005605 struct htx_blk *blk = htx_get_blk(htx, pos);
5606 enum htx_blk_type type = htx_get_blk_type(blk);
5607 struct ist n, v;
5608
5609 if (type == HTX_BLK_EOH)
5610 break;
5611 if (type != HTX_BLK_HDR)
5612 continue;
5613
5614 n = htx_get_blk_name(htx, blk);
5615
5616 for (h = cap_hdr; h; h = h->next) {
5617 if (h->namelen && (h->namelen == n.len) &&
5618 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5619 if (cap[h->index] == NULL)
5620 cap[h->index] =
5621 pool_alloc(h->pool);
5622
5623 if (cap[h->index] == NULL) {
5624 ha_alert("HTTP capture : out of memory.\n");
5625 break;
5626 }
5627
5628 v = htx_get_blk_value(htx, blk);
5629 if (v.len > h->len)
5630 v.len = h->len;
5631
5632 memcpy(cap[h->index], v.ptr, v.len);
5633 cap[h->index][v.len]=0;
5634 }
5635 }
5636 }
5637}
5638
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005639/* Delete a value in a header between delimiters <from> and <next>. The header
5640 * itself is delimited by <start> and <end> pointers. The number of characters
5641 * displaced is returned, and the pointer to the first delimiter is updated if
5642 * required. The function tries as much as possible to respect the following
5643 * principles :
5644 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5645 * in which case <next> is simply removed
5646 * - set exactly one space character after the new first delimiter, unless there
5647 * are not enough characters in the block being moved to do so.
5648 * - remove unneeded spaces before the previous delimiter and after the new
5649 * one.
5650 *
5651 * It is the caller's responsibility to ensure that :
5652 * - <from> points to a valid delimiter or <start> ;
5653 * - <next> points to a valid delimiter or <end> ;
5654 * - there are non-space chars before <from>.
5655 */
5656static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5657{
5658 char *prev = *from;
5659
5660 if (prev == start) {
5661 /* We're removing the first value. eat the semicolon, if <next>
5662 * is lower than <end> */
5663 if (next < end)
5664 next++;
5665
5666 while (next < end && HTTP_IS_SPHT(*next))
5667 next++;
5668 }
5669 else {
5670 /* Remove useless spaces before the old delimiter. */
5671 while (HTTP_IS_SPHT(*(prev-1)))
5672 prev--;
5673 *from = prev;
5674
5675 /* copy the delimiter and if possible a space if we're
5676 * not at the end of the line.
5677 */
5678 if (next < end) {
5679 *prev++ = *next++;
5680 if (prev + 1 < next)
5681 *prev++ = ' ';
5682 while (next < end && HTTP_IS_SPHT(*next))
5683 next++;
5684 }
5685 }
5686 memmove(prev, next, end - next);
5687 return (prev - next);
5688}
5689
Christopher Faulet0f226952018-10-22 09:29:56 +02005690
5691/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005692 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005693 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005694static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005695{
5696 struct ist dst = ist2(str, 0);
5697
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005698 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005699 goto end;
5700 if (dst.len + 1 > len)
5701 goto end;
5702 dst.ptr[dst.len++] = ' ';
5703
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 goto end;
5706 if (dst.len + 1 > len)
5707 goto end;
5708 dst.ptr[dst.len++] = ' ';
5709
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005710 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005711 end:
5712 return dst.len;
5713}
5714
Christopher Fauletf0523542018-10-24 11:06:58 +02005715/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005716 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005717 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005718static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005719{
5720 struct ist dst = ist2(str, 0);
5721
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005722 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005723 goto end;
5724 if (dst.len + 1 > len)
5725 goto end;
5726 dst.ptr[dst.len++] = ' ';
5727
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005728 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005729 goto end;
5730 if (dst.len + 1 > len)
5731 goto end;
5732 dst.ptr[dst.len++] = ' ';
5733
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005734 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005735 end:
5736 return dst.len;
5737}
5738
5739
Christopher Faulet0f226952018-10-22 09:29:56 +02005740/*
5741 * Print a debug line with a start line.
5742 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005743static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005744{
5745 struct session *sess = strm_sess(s);
5746 int max;
5747
5748 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5749 dir,
5750 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5751 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5752
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005753 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005754 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005755 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005756 trash.area[trash.data++] = ' ';
5757
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005758 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005759 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005760 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005761 trash.area[trash.data++] = ' ';
5762
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005763 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005764 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005765 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005766 trash.area[trash.data++] = '\n';
5767
5768 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5769}
5770
5771/*
5772 * Print a debug line with a header.
5773 */
5774static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5775{
5776 struct session *sess = strm_sess(s);
5777 int max;
5778
5779 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5780 dir,
5781 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5782 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5783
5784 max = n.len;
5785 UBOUND(max, trash.size - trash.data - 3);
5786 chunk_memcat(&trash, n.ptr, max);
5787 trash.area[trash.data++] = ':';
5788 trash.area[trash.data++] = ' ';
5789
5790 max = v.len;
5791 UBOUND(max, trash.size - trash.data - 1);
5792 chunk_memcat(&trash, v.ptr, max);
5793 trash.area[trash.data++] = '\n';
5794
5795 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5796}
5797
5798
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005799__attribute__((constructor))
5800static void __htx_protocol_init(void)
5801{
5802}
5803
5804
5805/*
5806 * Local variables:
5807 * c-indent-level: 8
5808 * c-basic-offset: 8
5809 * End:
5810 */