blob: 7b913c57475908a3a1a2f0c7b32e034217b39fb9 [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulet9768c262018-10-22 09:34:31 +0200150 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 stream_inc_http_req_ctr(s);
152 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100153 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100155 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200156
Christopher Faulet9768c262018-10-22 09:34:31 +0200157 txn->status = 400;
158 msg->err_state = msg->msg_state;
159 msg->msg_state = HTTP_MSG_ERROR;
160 htx_reply_and_close(s, txn->status, NULL);
161 req->analysers &= AN_REQ_FLT_END;
162
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (!(s->flags & SF_FINST_MASK))
164 s->flags |= SF_FINST_R;
165 return 0;
166 }
167
Christopher Faulet9768c262018-10-22 09:34:31 +0200168 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200169 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
170 if (!(s->flags & SF_ERR_MASK))
171 s->flags |= SF_ERR_CLITO;
172
173 if (txn->flags & TX_WAIT_NEXT_RQ)
174 goto failed_keep_alive;
175
176 if (sess->fe->options & PR_O_IGNORE_PRB)
177 goto failed_keep_alive;
178
Christopher Faulet9768c262018-10-22 09:34:31 +0200179 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200180 stream_inc_http_req_ctr(s);
181 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100184 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200185
Christopher Faulet9768c262018-10-22 09:34:31 +0200186 txn->status = 408;
187 msg->err_state = msg->msg_state;
188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100189 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200190 req->analysers &= AN_REQ_FLT_END;
191
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (!(s->flags & SF_FINST_MASK))
193 s->flags |= SF_FINST_R;
194 return 0;
195 }
196
Christopher Faulet9768c262018-10-22 09:34:31 +0200197 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200198 else if (req->flags & CF_SHUTR) {
199 if (!(s->flags & SF_ERR_MASK))
200 s->flags |= SF_ERR_CLICL;
201
202 if (txn->flags & TX_WAIT_NEXT_RQ)
203 goto failed_keep_alive;
204
205 if (sess->fe->options & PR_O_IGNORE_PRB)
206 goto failed_keep_alive;
207
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 stream_inc_http_err_ctr(s);
209 stream_inc_http_req_ctr(s);
210 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100213 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200214
Christopher Faulet9768c262018-10-22 09:34:31 +0200215 txn->status = 400;
216 msg->err_state = msg->msg_state;
217 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100218 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200219 req->analysers &= AN_REQ_FLT_END;
220
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (!(s->flags & SF_FINST_MASK))
222 s->flags |= SF_FINST_R;
223 return 0;
224 }
225
226 channel_dont_connect(req);
227 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
228 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100229
Christopher Faulet9768c262018-10-22 09:34:31 +0200230 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
232 /* We need more data, we have to re-enable quick-ack in case we
233 * previously disabled it, otherwise we might cause the client
234 * to delay next data.
235 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet47365272018-10-31 17:40:50 +0100239 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 /* If the client starts to talk, let's fall back to
241 * request timeout processing.
242 */
243 txn->flags &= ~TX_WAIT_NEXT_RQ;
244 req->analyse_exp = TICK_ETERNITY;
245 }
246
247 /* just set the request timeout once at the beginning of the request */
248 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
251 else
252 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
253 }
254
255 /* we're not ready yet */
256 return 0;
257
258 failed_keep_alive:
259 /* Here we process low-level errors for keep-alive requests. In
260 * short, if the request is not the first one and it experiences
261 * a timeout, read error or shutdown, we just silently close so
262 * that the client can try again.
263 */
264 txn->status = 0;
265 msg->msg_state = HTTP_MSG_RQBEFORE;
266 req->analysers &= AN_REQ_FLT_END;
267 s->logs.logwait = 0;
268 s->logs.level = 0;
269 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200270 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200271 return 0;
272 }
273
Christopher Faulet9768c262018-10-22 09:34:31 +0200274 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200275 stream_inc_http_req_ctr(s);
276 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 /* kill the pending keep-alive timeout */
279 txn->flags &= ~TX_WAIT_NEXT_RQ;
280 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281
Christopher Faulet29f17582019-05-23 11:03:26 +0200282 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200283 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100284
Christopher Faulet9768c262018-10-22 09:34:31 +0200285 /* 0: we might have to print this header in debug mode */
286 if (unlikely((global.mode & MODE_DEBUG) &&
287 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
288 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200289
Christopher Faulet03599112018-11-27 11:21:21 +0100290 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200291
Christopher Fauleta3f15502019-05-13 15:27:23 +0200292 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 struct htx_blk *blk = htx_get_blk(htx, pos);
294 enum htx_blk_type type = htx_get_blk_type(blk);
295
296 if (type == HTX_BLK_EOH)
297 break;
298 if (type != HTX_BLK_HDR)
299 continue;
300
301 htx_debug_hdr("clihdr", s,
302 htx_get_blk_name(htx, blk),
303 htx_get_blk_value(htx, blk));
304 }
305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306
307 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100308 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200309 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100310 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200312 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100313 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100314 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100315 if (sl->flags & HTX_SL_F_BODYLESS)
316 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /* we can make use of server redirect on GET and HEAD */
319 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
320 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 goto return_bad_req;
324 }
325
326 /*
327 * 2: check if the URI matches the monitor_uri.
328 * We have to do this for every request which gets in, because
329 * the monitor-uri is defined by the frontend.
330 */
331 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet943ab4d2020-02-18 14:51:51 +0100332 isteq(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /*
334 * We have found the monitor URI
335 */
336 struct acl_cond *cond;
337
338 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200340
341 /* Check if we want to fail this monitor request or not */
342 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
343 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
344
345 ret = acl_pass(ret);
346 if (cond->pol == ACL_COND_UNLESS)
347 ret = !ret;
348
349 if (ret) {
350 /* we fail this request, let's return 503 service unavail */
351 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100352 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200353 if (!(s->flags & SF_ERR_MASK))
354 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
355 goto return_prx_cond;
356 }
357 }
358
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800359 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366
367 /*
368 * 3: Maybe we have to copy the original REQURI for the logs ?
369 * Note: we cannot log anymore if the request has been
370 * classified as invalid.
371 */
372 if (unlikely(s->logs.logwait & LW_REQ)) {
373 /* we have a complete HTTP request that we must log */
374 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulet9768c262018-10-22 09:34:31 +0200377 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
378 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200379
380 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
381 s->do_log(s);
382 } else {
383 ha_alert("HTTP logging : out of memory.\n");
384 }
385 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387 /* if the frontend has "option http-use-proxy-header", we'll check if
388 * we have what looks like a proxied connection instead of a connection,
389 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
390 * Note that this is *not* RFC-compliant, however browsers and proxies
391 * happen to do that despite being non-standard :-(
392 * We consider that a request not beginning with either '/' or '*' is
393 * a proxied connection, which covers both "scheme://location" and
394 * CONNECT ip:port.
395 */
396 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100397 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 txn->flags |= TX_USE_PX_CONN;
399
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400 /* 5: we may need to capture headers */
401 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200402 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100404 /* by default, close the stream at the end of the transaction. */
405 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100441 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100444 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
Olivier Houchard629693f2020-01-23 14:57:36 +0100527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Faulet4629d082019-07-04 11:27:15 +0200543 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100548 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200556 htx_handle_stats(s, req);
557 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
567 /* evaluate the req* rules except reqadd */
568 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200569 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200570 goto return_bad_req;
571
572 if (txn->flags & TX_CLDENY)
573 goto deny;
574
575 if (txn->flags & TX_CLTARPIT) {
576 deny_status = HTTP_ERR_500;
577 goto tarpit;
578 }
579 }
580
581 /* add request headers from the rule sets in the same order */
582 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200583 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200584 if (wl->cond) {
585 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
586 ret = acl_pass(ret);
587 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
588 ret = !ret;
589 if (!ret)
590 continue;
591 }
592
Christopher Fauletff2759f2018-10-24 11:13:16 +0200593 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
594 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 goto return_bad_req;
596 }
597
Christopher Faulet2571bc62019-03-01 11:44:26 +0100598 /* Proceed with the applets now. */
599 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100601 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100603 if (htx_handle_expect_hdr(s, htx, msg) == -1)
604 goto return_bad_req;
605
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
607 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
608 if (!(s->flags & SF_FINST_MASK))
609 s->flags |= SF_FINST_R;
610
611 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
612 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
613 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
614 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100615
616 req->flags |= CF_SEND_DONTWAIT;
617 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100666 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100685 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100698 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100704 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100766 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100775 struct htx_sl *sl;
776 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100784 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200793 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100794 uri = htx_sl_req_uri(sl);
795 path = http_get_path(uri);
796 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797 goto return_bad_req;
798
799 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 * uri.ptr and path.ptr (excluded). If it was not found, we need
801 * to replace from all the uri by a single "/".
802 *
803 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100804 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau3284dd22019-07-18 16:17:15 +0200808 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 }
810
811 /*
812 * 7: Now we can work with the cookies.
813 * Note that doing so might move headers in the request, but
814 * the fields will stay coherent and the URI will not move.
815 * This should only be performed in the backend.
816 */
817 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100818 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819
820 /* add unique-id if "header-unique-id" is specified */
821
822 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
823 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
824 goto return_bad_req;
825 s->unique_id[0] = '\0';
826 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
827 }
828
829 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200830 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
831 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
832
833 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 }
836
837 /*
838 * 9: add X-Forwarded-For if either the frontend or the backend
839 * asks for it.
840 */
841 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200842 struct http_hdr_ctx ctx = { .blk = NULL };
843 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
844 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
845
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200848 /* The header is set to be added only if none is present
849 * and we found it, so don't do anything.
850 */
851 }
852 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
853 /* Add an X-Forwarded-For header unless the source IP is
854 * in the 'except' network range.
855 */
856 if ((!sess->fe->except_mask.s_addr ||
857 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
858 != sess->fe->except_net.s_addr) &&
859 (!s->be->except_mask.s_addr ||
860 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
861 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863
864 /* Note: we rely on the backend to get the header name to be used for
865 * x-forwarded-for, because the header is really meant for the backends.
866 * However, if the backend did not specify any option, we have to rely
867 * on the frontend's header name.
868 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
870 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200871 goto return_bad_req;
872 }
873 }
874 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
875 /* FIXME: for the sake of completeness, we should also support
876 * 'except' here, although it is mostly useless in this case.
877 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200879
Christopher Faulete0768eb2018-10-03 16:38:02 +0200880 inet_ntop(AF_INET6,
881 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
882 pn, sizeof(pn));
883
884 /* Note: we rely on the backend to get the header name to be used for
885 * x-forwarded-for, because the header is really meant for the backends.
886 * However, if the backend did not specify any option, we have to rely
887 * on the frontend's header name.
888 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200889 chunk_printf(&trash, "%s", pn);
890 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 goto return_bad_req;
892 }
893 }
894
895 /*
896 * 10: add X-Original-To if either the frontend or the backend
897 * asks for it.
898 */
899 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
900
901 /* FIXME: don't know if IPv6 can handle that case too. */
Christopher Faulet8fc16fb2021-02-26 12:45:56 +0100902 if (cli_conn && cli_conn->addr.to.ss_family == AF_INET) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200903 /* Add an X-Original-To header unless the destination IP is
904 * in the 'except' network range.
905 */
906 conn_get_to_addr(cli_conn);
907
908 if (cli_conn->addr.to.ss_family == AF_INET &&
909 ((!sess->fe->except_mask_to.s_addr ||
910 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
911 != sess->fe->except_to.s_addr) &&
912 (!s->be->except_mask_to.s_addr ||
913 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
914 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200915 struct ist hdr;
916 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200917
918 /* Note: we rely on the backend to get the header name to be used for
919 * x-original-to, because the header is really meant for the backends.
920 * However, if the backend did not specify any option, we have to rely
921 * on the frontend's header name.
922 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200923 if (s->be->orgto_hdr_len)
924 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
925 else
926 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200927
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
929 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200930 goto return_bad_req;
931 }
932 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 }
934
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 /* If we have no server assigned yet and we're balancing on url_param
936 * with a POST request, we may be interested in checking the body for
937 * that parameter. This will be done in another analyser.
938 */
939 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100940 s->txn->meth == HTTP_METH_POST &&
941 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100948
Christopher Faulete0768eb2018-10-03 16:38:02 +0200949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200955 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957
958 /*************************************************************
959 * OK, that's finished for the headers. We have done what we *
960 * could. Let's switch to the DATA state. *
961 ************************************************************/
962 req->analyse_exp = TICK_ETERNITY;
963 req->analysers &= ~an_bit;
964
965 s->logs.tv_request = now;
966 /* OK let's go on with the BODY now */
967 return 1;
968
969 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200970 txn->req.err_state = txn->req.msg_state;
971 txn->req.msg_state = HTTP_MSG_ERROR;
972 txn->status = 400;
973 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100974 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100978 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_R;
984 return 0;
985}
986
987/* This function is an analyser which processes the HTTP tarpit. It always
988 * returns zero, at the beginning because it prevents any other processing
989 * from occurring, and at the end because it terminates the request.
990 */
991int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
992{
993 struct http_txn *txn = s->txn;
994
995 /* This connection is being tarpitted. The CLIENT side has
996 * already set the connect expiration date to the right
997 * timeout. We just have to check that the client is still
998 * there and that the timeout has not expired.
999 */
1000 channel_dont_connect(req);
1001 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1002 !tick_is_expired(req->analyse_exp, now_ms))
1003 return 0;
1004
1005 /* We will set the queue timer to the time spent, just for
1006 * logging purposes. We fake a 500 server error, so that the
1007 * attacker will not suspect his connection has been tarpitted.
1008 * It will not cause trouble to the logs because we can exclude
1009 * the tarpitted connections by filtering on the 'PT' status flags.
1010 */
1011 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1012
Christopher Fauletef9a1692020-02-21 10:20:46 +01001013 htx_reply_and_close(s, txn->status, (!(req->flags & CF_READ_ERROR) ? htx_error_message(s) : NULL));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Faulet1c8288d2020-11-16 16:03:35 +01001056 /* CONNECT requests have no body */
1057 if (txn->meth == HTTP_METH_CONNECT)
1058 goto http_end;
1059
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001060 if (msg->msg_state < HTTP_MSG_BODY)
1061 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001062
Christopher Faulete0768eb2018-10-03 16:38:02 +02001063 /* We have to parse the HTTP request body to find any required data.
1064 * "balance url_param check_post" should have been the only way to get
1065 * into this. We were brought here after HTTP header analysis, so all
1066 * related structures are ready.
1067 */
1068
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001070 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1071 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072 }
1073
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001074 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001076 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1077 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001078 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001079 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001080 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001081 goto http_end;
1082
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001083 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1085 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001086 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087
1088 if (!(s->flags & SF_ERR_MASK))
1089 s->flags |= SF_ERR_CLITO;
1090 if (!(s->flags & SF_FINST_MASK))
1091 s->flags |= SF_FINST_D;
1092 goto return_err_msg;
1093 }
1094
1095 /* we get here if we need to wait for more data */
1096 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1097 /* Not enough data. We'll re-use the http-request
1098 * timeout here. Ideally, we should set the timeout
1099 * relative to the accept() date. We just set the
1100 * request timeout once at the beginning of the
1101 * request.
1102 */
1103 channel_dont_connect(req);
1104 if (!tick_isset(req->analyse_exp))
1105 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1106 return 0;
1107 }
1108
1109 http_end:
1110 /* The situation will not evolve, so let's give up on the analysis. */
1111 s->logs.tv_request = now; /* update the request timer to reflect full request */
1112 req->analysers &= ~an_bit;
1113 req->analyse_exp = TICK_ETERNITY;
1114 return 1;
1115
1116 return_bad_req: /* let's centralize all bad requests */
1117 txn->req.err_state = txn->req.msg_state;
1118 txn->req.msg_state = HTTP_MSG_ERROR;
1119 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001120 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001121
1122 if (!(s->flags & SF_ERR_MASK))
1123 s->flags |= SF_ERR_PRXCOND;
1124 if (!(s->flags & SF_FINST_MASK))
1125 s->flags |= SF_FINST_R;
1126
1127 return_err_msg:
1128 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001129 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001130 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001131 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001132 return 0;
1133}
1134
1135/* This function is an analyser which forwards request body (including chunk
1136 * sizes if any). It is called as soon as we must forward, even if we forward
1137 * zero byte. The only situation where it must not be called is when we're in
1138 * tunnel mode and we want to forward till the close. It's used both to forward
1139 * remaining data and to resync after end of body. It expects the msg_state to
1140 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1141 * read more data, or 1 once we can go on with next request or end the stream.
1142 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1143 * bytes of pending data + the headers if not already done.
1144 */
1145int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1146{
1147 struct session *sess = s->sess;
1148 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001149 struct http_msg *msg = &txn->req;
1150 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001151 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001152 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001153
1154 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1155 now_ms, __FUNCTION__,
1156 s,
1157 req,
1158 req->rex, req->wex,
1159 req->flags,
1160 ci_data(req),
1161 req->analysers);
1162
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001163 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001164
1165 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1166 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1167 /* Output closed while we were sending data. We must abort and
1168 * wake the other side up.
1169 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001170 /* Don't abort yet if we had L7 retries activated and it
1171 * was a write error, we may recover.
1172 */
1173 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1174 (s->si[1].flags & SI_FL_L7_RETRY))
1175 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 msg->err_state = msg->msg_state;
1177 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001178 htx_end_request(s);
1179 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001180 return 1;
1181 }
1182
1183 /* Note that we don't have to send 100-continue back because we don't
1184 * need the data to complete our job, and it's up to the server to
1185 * decide whether to return 100, 417 or anything else in return of
1186 * an "Expect: 100-continue" header.
1187 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001188 if (msg->msg_state == HTTP_MSG_BODY)
1189 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001190
1191 /* Some post-connect processing might want us to refrain from starting to
1192 * forward data. Currently, the only reason for this is "balance url_param"
1193 * whichs need to parse/process the request after we've enabled forwarding.
1194 */
1195 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1196 if (!(s->res.flags & CF_READ_ATTACHED)) {
1197 channel_auto_connect(req);
1198 req->flags |= CF_WAKE_CONNECT;
1199 channel_dont_close(req); /* don't fail on early shutr */
1200 goto waiting;
1201 }
1202 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1203 }
1204
1205 /* in most states, we should abort in case of early close */
1206 channel_auto_close(req);
1207
1208 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001209 if (req->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001210 if (req->flags & CF_EOI)
1211 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01001212 }
1213 else {
1214 /* We can't process the buffer's contents yet */
1215 req->flags |= CF_WAKE_WRITE;
1216 goto missing_data_or_waiting;
1217 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001218 }
1219
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001220 if (msg->msg_state >= HTTP_MSG_ENDING)
1221 goto ending;
1222
1223 if (txn->meth == HTTP_METH_CONNECT) {
1224 msg->msg_state = HTTP_MSG_ENDING;
1225 goto ending;
1226 }
1227
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 /* Forward input data. We get it by removing all outgoing data not
1229 * forwarded yet from HTX data size. If there are some data filters, we
1230 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001231 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001232 if (HAS_REQ_DATA_FILTERS(s)) {
1233 ret = flt_http_payload(s, msg, htx->data);
1234 if (ret < 0)
1235 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001236 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001237 }
1238 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001239 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001240 if (msg->flags & HTTP_MSGF_XFER_LEN)
1241 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001242 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001244 if (htx->data != co_data(req))
1245 goto missing_data_or_waiting;
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001246
Christopher Faulet9768c262018-10-22 09:34:31 +02001247 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001248 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1249 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001250 */
1251 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1252 goto missing_data_or_waiting;
1253
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001254 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02001255
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001256 ending:
1257 /* other states, ENDING...TUNNEL */
1258 if (msg->msg_state >= HTTP_MSG_DONE)
1259 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001260
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001261 if (HAS_REQ_DATA_FILTERS(s)) {
1262 ret = flt_http_end(s, msg);
1263 if (ret <= 0) {
1264 if (!ret)
1265 goto missing_data_or_waiting;
1266 goto return_bad_req;
1267 }
1268 }
1269
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001270 if (txn->meth == HTTP_METH_CONNECT)
1271 msg->msg_state = HTTP_MSG_TUNNEL;
1272 else {
1273 msg->msg_state = HTTP_MSG_DONE;
1274 req->to_forward = 0;
1275 }
1276
1277 done:
1278 /* we don't want to forward closes on DONE except in tunnel mode. */
1279 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1280 channel_dont_close(req);
1281
Christopher Fauletf2824e62018-10-01 12:12:37 +02001282 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001283 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001284 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001285 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1286 if (req->flags & CF_SHUTW) {
1287 /* request errors are most likely due to the
1288 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001289 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001290 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001291 goto return_bad_req;
1292 }
1293 return 1;
1294 }
1295
1296 /* If "option abortonclose" is set on the backend, we want to monitor
1297 * the client's connection and forward any shutdown notification to the
1298 * server, which will decide whether to close or to go on processing the
1299 * request. We only do that in tunnel mode, and not in other modes since
1300 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001301 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001302 channel_auto_read(req);
1303 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1304 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1305 s->si[1].flags |= SI_FL_NOLINGER;
1306 channel_auto_close(req);
1307 }
1308 else if (s->txn->meth == HTTP_METH_POST) {
1309 /* POST requests may require to read extra CRLF sent by broken
1310 * browsers and which could cause an RST to be sent upon close
1311 * on some systems (eg: Linux). */
1312 channel_auto_read(req);
1313 }
1314 return 0;
1315
1316 missing_data_or_waiting:
1317 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001318 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001319 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001320
1321 waiting:
1322 /* waiting for the last bits to leave the buffer */
1323 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001324 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001325
Christopher Faulet47365272018-10-31 17:40:50 +01001326 if (htx->flags & HTX_FL_PARSING_ERROR)
1327 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001328
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 /* When TE: chunked is used, we need to get there again to parse remaining
1330 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1331 * And when content-length is used, we never want to let the possible
1332 * shutdown be forwarded to the other side, as the state machine will
1333 * take care of it once the client responds. It's also important to
1334 * prevent TIME_WAITs from accumulating on the backend side, and for
1335 * HTTP/2 where the last frame comes with a shutdown.
1336 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001337 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001338 channel_dont_close(req);
1339
1340 /* We know that more data are expected, but we couldn't send more that
1341 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1342 * system knows it must not set a PUSH on this first part. Interactive
1343 * modes are already handled by the stream sock layer. We must not do
1344 * this in content-length mode because it could present the MSG_MORE
1345 * flag with the last block of forwarded data, which would cause an
1346 * additional delay to be observed by the receiver.
1347 */
1348 if (msg->flags & HTTP_MSGF_TE_CHNK)
1349 req->flags |= CF_EXPECT_MORE;
1350
1351 return 0;
1352
Christopher Faulet93e02d82019-03-08 14:18:50 +01001353 return_cli_abort:
1354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1355 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1356 if (objt_server(s->target))
1357 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1358 if (!(s->flags & SF_ERR_MASK))
1359 s->flags |= SF_ERR_CLICL;
1360 status = 400;
1361 goto return_error;
1362
1363 return_srv_abort:
1364 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1365 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1366 if (objt_server(s->target))
1367 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1368 if (!(s->flags & SF_ERR_MASK))
1369 s->flags |= SF_ERR_SRVCL;
1370 status = 502;
1371 goto return_error;
1372
1373 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001374 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001376 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001378 s->flags |= SF_ERR_CLICL;
1379 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001380
Christopher Faulet93e02d82019-03-08 14:18:50 +01001381 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001382 txn->req.err_state = txn->req.msg_state;
1383 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001384 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001385 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001386 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001387 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001388 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001389 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001390 }
1391 req->analysers &= AN_REQ_FLT_END;
1392 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 +01001393 if (!(s->flags & SF_FINST_MASK))
1394 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 return 0;
1396}
1397
Olivier Houcharda254a372019-04-05 15:30:12 +02001398/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1399/* Returns 0 if we can attempt to retry, -1 otherwise */
1400static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1401{
1402 struct channel *req, *res;
1403 int co_data;
1404
1405 si->conn_retries--;
1406 if (si->conn_retries < 0)
1407 return -1;
1408
Willy Tarreau223995e2019-05-04 10:38:31 +02001409 if (objt_server(s->target))
1410 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1411 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1412
Olivier Houcharda254a372019-04-05 15:30:12 +02001413 req = &s->req;
1414 res = &s->res;
1415 /* Remove any write error from the request, and read error from the response */
1416 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1417 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1418 res->analysers = 0;
1419 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchardc86a9662020-05-12 22:18:14 +02001420 s->flags &= ~SF_ADDR_SET;
Olivier Houchard530249c2019-07-12 16:16:59 +02001421 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001422 si->exp = TICK_ETERNITY;
1423 res->rex = TICK_ETERNITY;
1424 res->to_forward = 0;
1425 res->analyse_exp = TICK_ETERNITY;
1426 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001427 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001428 si_release_endpoint(&s->si[1]);
1429 b_free(&req->buf);
1430 /* Swap the L7 buffer with the channel buffer */
1431 /* We know we stored the co_data as b_data, so get it there */
1432 co_data = b_data(&si->l7_buffer);
1433 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1434 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1435
1436 co_set_data(req, co_data);
1437 b_reset(&res->buf);
1438 co_set_data(res, 0);
1439 return 0;
1440}
1441
Christopher Faulete0768eb2018-10-03 16:38:02 +02001442/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1443 * processing can continue on next analysers, or zero if it either needs more
1444 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1445 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1446 * when it has nothing left to do, and may remove any analyser when it wants to
1447 * abort.
1448 */
1449int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1450{
Christopher Faulet9768c262018-10-22 09:34:31 +02001451 /*
1452 * We will analyze a complete HTTP response to check the its syntax.
1453 *
1454 * Once the start line and all headers are received, we may perform a
1455 * capture of the error (if any), and we will set a few fields. We also
1456 * logging and finally headers capture.
1457 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001458 struct session *sess = s->sess;
1459 struct http_txn *txn = s->txn;
1460 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001461 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001462 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001463 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001464 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001465 int n;
1466
1467 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1468 now_ms, __FUNCTION__,
1469 s,
1470 rep,
1471 rep->rex, rep->wex,
1472 rep->flags,
1473 ci_data(rep),
1474 rep->analysers);
1475
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001476 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477
Willy Tarreau4236f032019-03-05 10:43:32 +01001478 /* Parsing errors are caught here */
1479 if (htx->flags & HTX_FL_PARSING_ERROR)
1480 goto return_bad_res;
1481
Christopher Faulete0768eb2018-10-03 16:38:02 +02001482 /*
1483 * Now we quickly check if we have found a full valid response.
1484 * If not so, we check the FD and buffer states before leaving.
1485 * A full response is indicated by the fact that we have seen
1486 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1487 * responses are checked first.
1488 *
1489 * Depending on whether the client is still there or not, we
1490 * may send an error response back or not. Note that normally
1491 * we should only check for HTTP status there, and check I/O
1492 * errors somewhere else.
1493 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001494 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001495 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001496 /* 1: have we encountered a read error ? */
1497 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001498 struct connection *conn = NULL;
1499
Olivier Houchard865d8392019-05-03 22:46:27 +02001500 if (objt_cs(s->si[1].end))
1501 conn = objt_cs(s->si[1].end)->conn;
1502
1503 if (si_b->flags & SI_FL_L7_RETRY &&
1504 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001505 /* If we arrive here, then CF_READ_ERROR was
1506 * set by si_cs_recv() because we matched a
1507 * status, overwise it would have removed
1508 * the SI_FL_L7_RETRY flag, so it's ok not
1509 * to check s->be->retry_type.
1510 */
1511 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1512 return 0;
1513 }
1514
Olivier Houchard6db16992019-05-17 15:40:49 +02001515 if (txn->flags & TX_NOT_FIRST)
1516 goto abort_keep_alive;
1517
Olivier Houcharda798bf52019-03-08 18:52:00 +01001518 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001520 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001521 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522 }
1523
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001525 s->req.analysers &= AN_REQ_FLT_END;
1526 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 txn->status = 502;
1528
1529 /* Check to see if the server refused the early data.
1530 * If so, just send a 425
1531 */
Willy Tarreau1b4cc2e2020-06-23 05:58:20 +02001532 if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001533 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001534 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001535 do_l7_retry(s, si_b) == 0)
1536 return 0;
1537 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 }
1539
1540 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001541 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001542
1543 if (!(s->flags & SF_ERR_MASK))
1544 s->flags |= SF_ERR_SRVCL;
1545 if (!(s->flags & SF_FINST_MASK))
1546 s->flags |= SF_FINST_H;
1547 return 0;
1548 }
1549
Christopher Faulet9768c262018-10-22 09:34:31 +02001550 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001552 if ((si_b->flags & SI_FL_L7_RETRY) &&
1553 (s->be->retry_type & PR_RE_TIMEOUT)) {
1554 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1555 return 0;
1556 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001559 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001560 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 }
1562
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001564 s->req.analysers &= AN_REQ_FLT_END;
1565 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001566 txn->status = 504;
1567 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001568 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569
1570 if (!(s->flags & SF_ERR_MASK))
1571 s->flags |= SF_ERR_SRVTO;
1572 if (!(s->flags & SF_FINST_MASK))
1573 s->flags |= SF_FINST_H;
1574 return 0;
1575 }
1576
Christopher Faulet9768c262018-10-22 09:34:31 +02001577 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001579 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1580 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001581 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001582 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583
1584 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001585 s->req.analysers &= AN_REQ_FLT_END;
1586 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587 txn->status = 400;
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_CLICL;
1592 if (!(s->flags & SF_FINST_MASK))
1593 s->flags |= SF_FINST_H;
1594
1595 /* process_stream() will take care of the error */
1596 return 0;
1597 }
1598
Christopher Faulet9768c262018-10-22 09:34:31 +02001599 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001601 if ((si_b->flags & SI_FL_L7_RETRY) &&
1602 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1603 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1604 return 0;
1605 }
1606
Olivier Houchard6db16992019-05-17 15:40:49 +02001607 if (txn->flags & TX_NOT_FIRST)
1608 goto abort_keep_alive;
1609
Olivier Houcharda798bf52019-03-08 18:52:00 +01001610 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001611 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001612 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001613 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614 }
1615
Christopher Faulete0768eb2018-10-03 16:38:02 +02001616 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001617 s->req.analysers &= AN_REQ_FLT_END;
1618 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001619 txn->status = 502;
1620 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001621 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622
1623 if (!(s->flags & SF_ERR_MASK))
1624 s->flags |= SF_ERR_SRVCL;
1625 if (!(s->flags & SF_FINST_MASK))
1626 s->flags |= SF_FINST_H;
1627 return 0;
1628 }
1629
Christopher Faulet9768c262018-10-22 09:34:31 +02001630 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001632 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001633 goto abort_keep_alive;
1634
Olivier Houcharda798bf52019-03-08 18:52:00 +01001635 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001636 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001637 s->req.analysers &= AN_REQ_FLT_END;
1638 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639
1640 if (!(s->flags & SF_ERR_MASK))
1641 s->flags |= SF_ERR_CLICL;
1642 if (!(s->flags & SF_FINST_MASK))
1643 s->flags |= SF_FINST_H;
1644
1645 /* process_stream() will take care of the error */
1646 return 0;
1647 }
1648
1649 channel_dont_close(rep);
1650 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1651 return 0;
1652 }
1653
1654 /* More interesting part now : we know that we have a complete
1655 * response which at least looks like HTTP. We have an indicator
1656 * of each header's length, so we can parse them quickly.
1657 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001658 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001659 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001660 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001661
Christopher Faulet9768c262018-10-22 09:34:31 +02001662 /* 0: we might have to print this header in debug mode */
1663 if (unlikely((global.mode & MODE_DEBUG) &&
1664 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1665 int32_t pos;
1666
Christopher Faulet03599112018-11-27 11:21:21 +01001667 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001668
Christopher Fauleta3f15502019-05-13 15:27:23 +02001669 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001670 struct htx_blk *blk = htx_get_blk(htx, pos);
1671 enum htx_blk_type type = htx_get_blk_type(blk);
1672
1673 if (type == HTX_BLK_EOH)
1674 break;
1675 if (type != HTX_BLK_HDR)
1676 continue;
1677
1678 htx_debug_hdr("srvhdr", s,
1679 htx_get_blk_name(htx, blk),
1680 htx_get_blk_value(htx, blk));
1681 }
1682 }
1683
Christopher Faulet03599112018-11-27 11:21:21 +01001684 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001685 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001686 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001687 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001688 if (sl->flags & HTX_SL_F_XFER_LEN) {
1689 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001690 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001691 if (sl->flags & HTX_SL_F_BODYLESS)
1692 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001693 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001694
1695 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001696 if (n < 1 || n > 5)
1697 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001698
Christopher Faulete0768eb2018-10-03 16:38:02 +02001699 /* when the client triggers a 4xx from the server, it's most often due
1700 * to a missing object or permission. These events should be tracked
1701 * because if they happen often, it may indicate a brute force or a
1702 * vulnerability scan.
1703 */
1704 if (n == 4)
1705 stream_inc_http_err_ctr(s);
1706
1707 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001708 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001709
Christopher Faulete0768eb2018-10-03 16:38:02 +02001710 /* Adjust server's health based on status code. Note: status codes 501
1711 * and 505 are triggered on demand by client request, so we must not
1712 * count them as server failures.
1713 */
1714 if (objt_server(s->target)) {
1715 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001716 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001718 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001719 }
1720
1721 /*
1722 * We may be facing a 100-continue response, or any other informational
1723 * 1xx response which is non-final, in which case this is not the right
1724 * response, and we're waiting for the next one. Let's allow this response
1725 * to go to the client and wait for the next one. There's an exception for
1726 * 101 which is used later in the code to switch protocols.
1727 */
1728 if (txn->status < 200 &&
1729 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001730 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001731 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001732 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001733 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001734 txn->status = 0;
1735 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet5761e7d2020-08-31 11:07:07 +02001736 rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001737 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001738 }
1739
1740 /*
1741 * 2: check for cacheability.
1742 */
1743
1744 switch (txn->status) {
1745 case 200:
1746 case 203:
1747 case 204:
1748 case 206:
1749 case 300:
1750 case 301:
1751 case 404:
1752 case 405:
1753 case 410:
1754 case 414:
1755 case 501:
1756 break;
1757 default:
1758 /* RFC7231#6.1:
1759 * Responses with status codes that are defined as
1760 * cacheable by default (e.g., 200, 203, 204, 206,
1761 * 300, 301, 404, 405, 410, 414, and 501 in this
1762 * specification) can be reused by a cache with
1763 * heuristic expiration unless otherwise indicated
1764 * by the method definition or explicit cache
1765 * controls [RFC7234]; all other status codes are
1766 * not cacheable by default.
1767 */
1768 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1769 break;
1770 }
1771
1772 /*
1773 * 3: we may need to capture headers
1774 */
1775 s->logs.logwait &= ~LW_RESP;
1776 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001777 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001778
Christopher Faulet9768c262018-10-22 09:34:31 +02001779 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001780 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1781 txn->status == 101)) {
1782 /* Either we've established an explicit tunnel, or we're
1783 * switching the protocol. In both cases, we're very unlikely
1784 * to understand the next protocols. We have to switch to tunnel
1785 * mode, so that we transfer the request and responses then let
1786 * this protocol pass unmodified. When we later implement specific
1787 * parsers for such protocols, we'll want to check the Upgrade
1788 * header which contains information about that protocol for
1789 * responses with status 101 (eg: see RFC2817 about TLS).
1790 */
1791 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001792 }
1793
Christopher Faulet61608322018-11-23 16:23:45 +01001794 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1795 * 407 (Proxy-Authenticate) responses and set the connection to private
1796 */
1797 srv_conn = cs_conn(objt_cs(s->si[1].end));
1798 if (srv_conn) {
1799 struct ist hdr;
1800 struct http_hdr_ctx ctx;
1801
1802 if (txn->status == 401)
1803 hdr = ist("WWW-Authenticate");
1804 else if (txn->status == 407)
1805 hdr = ist("Proxy-Authenticate");
1806 else
1807 goto end;
1808
1809 ctx.blk = NULL;
1810 while (http_find_header(htx, hdr, &ctx, 0)) {
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001811 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1812 * possibly followed by blanks and a base64 string, the connection
1813 * is private. Since it's a mess to deal with, we only check for
1814 * values starting with "NTLM" or "Nego". Note that often multiple
1815 * headers are sent by the server there.
1816 */
1817 if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
Willy Tarreaud3be89b2020-05-07 19:10:15 +02001818 (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001819 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001820 srv_conn->flags |= CO_FL_PRIVATE;
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001821 break;
Olivier Houchard250031e2019-05-29 15:01:50 +02001822 }
Christopher Faulet61608322018-11-23 16:23:45 +01001823 }
1824 }
1825
1826 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001827 /* we want to have the response time before we start processing it */
1828 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1829
1830 /* end of job, return OK */
1831 rep->analysers &= ~an_bit;
1832 rep->analyse_exp = TICK_ETERNITY;
1833 channel_auto_close(rep);
1834 return 1;
1835
Christopher Faulet47365272018-10-31 17:40:50 +01001836 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001837 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001838 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001839 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001840 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001841 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001842 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001843 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001844 do_l7_retry(s, si_b) == 0)
1845 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001846 txn->status = 502;
1847 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001848 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001849 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001850 s->req.analysers &= AN_REQ_FLT_END;
1851 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001852
1853 if (!(s->flags & SF_ERR_MASK))
1854 s->flags |= SF_ERR_PRXCOND;
1855 if (!(s->flags & SF_FINST_MASK))
1856 s->flags |= SF_FINST_H;
1857 return 0;
1858
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859 abort_keep_alive:
1860 /* A keep-alive request to the server failed on a network error.
1861 * The client is required to retry. We need to close without returning
1862 * any other information so that the client retries.
1863 */
1864 txn->status = 0;
1865 rep->analysers &= AN_RES_FLT_END;
1866 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 s->logs.logwait = 0;
1868 s->logs.level = 0;
1869 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001870 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 return 0;
1872}
1873
1874/* This function performs all the processing enabled for the current response.
1875 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1876 * and updates s->res.analysers. It might make sense to explode it into several
1877 * other functions. It works like process_request (see indications above).
1878 */
1879int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1880{
1881 struct session *sess = s->sess;
1882 struct http_txn *txn = s->txn;
1883 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001884 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001885 struct proxy *cur_proxy;
1886 struct cond_wordlist *wl;
1887 enum rule_result ret = HTTP_RULE_RES_CONT;
1888
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001889 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1890 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001891
Christopher Faulete0768eb2018-10-03 16:38:02 +02001892 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1893 now_ms, __FUNCTION__,
1894 s,
1895 rep,
1896 rep->rex, rep->wex,
1897 rep->flags,
1898 ci_data(rep),
1899 rep->analysers);
1900
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001901 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001902
1903 /* The stats applet needs to adjust the Connection header but we don't
1904 * apply any filter there.
1905 */
1906 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1907 rep->analysers &= ~an_bit;
1908 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001909 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001910 }
1911
1912 /*
1913 * We will have to evaluate the filters.
1914 * As opposed to version 1.2, now they will be evaluated in the
1915 * filters order and not in the header order. This means that
1916 * each filter has to be validated among all headers.
1917 *
1918 * Filters are tried with ->be first, then with ->fe if it is
1919 * different from ->be.
1920 *
1921 * Maybe we are in resume condiion. In this case I choose the
1922 * "struct proxy" which contains the rule list matching the resume
1923 * pointer. If none of theses "struct proxy" match, I initialise
1924 * the process with the first one.
1925 *
1926 * In fact, I check only correspondance betwwen the current list
1927 * pointer and the ->fe rule list. If it doesn't match, I initialize
1928 * the loop with the ->be.
1929 */
1930 if (s->current_rule_list == &sess->fe->http_res_rules)
1931 cur_proxy = sess->fe;
1932 else
1933 cur_proxy = s->be;
1934 while (1) {
1935 struct proxy *rule_set = cur_proxy;
1936
1937 /* evaluate http-response rules */
1938 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001939 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001940
1941 if (ret == HTTP_RULE_RES_BADREQ)
1942 goto return_srv_prx_502;
1943
1944 if (ret == HTTP_RULE_RES_DONE) {
1945 rep->analysers &= ~an_bit;
1946 rep->analyse_exp = TICK_ETERNITY;
1947 return 1;
1948 }
1949 }
1950
1951 /* we need to be called again. */
1952 if (ret == HTTP_RULE_RES_YIELD) {
1953 channel_dont_close(rep);
1954 return 0;
1955 }
1956
1957 /* try headers filters */
1958 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001959 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1960 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001961 }
1962
1963 /* has the response been denied ? */
1964 if (txn->flags & TX_SVDENY) {
1965 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001966 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967
Olivier Houcharda798bf52019-03-08 18:52:00 +01001968 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1969 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001970 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001971 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001972 goto return_srv_prx_502;
1973 }
1974
1975 /* add response headers from the rule sets in the same order */
1976 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001977 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001978 if (txn->status < 200 && txn->status != 101)
1979 break;
1980 if (wl->cond) {
1981 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1982 ret = acl_pass(ret);
1983 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1984 ret = !ret;
1985 if (!ret)
1986 continue;
1987 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001988
1989 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1990 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001991 goto return_bad_resp;
1992 }
1993
1994 /* check whether we're already working on the frontend */
1995 if (cur_proxy == sess->fe)
1996 break;
1997 cur_proxy = sess->fe;
1998 }
1999
2000 /* After this point, this anayzer can't return yield, so we can
2001 * remove the bit corresponding to this analyzer from the list.
2002 *
2003 * Note that the intermediate returns and goto found previously
2004 * reset the analyzers.
2005 */
2006 rep->analysers &= ~an_bit;
2007 rep->analyse_exp = TICK_ETERNITY;
2008
2009 /* OK that's all we can do for 1xx responses */
2010 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002011 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002012
2013 /*
2014 * Now check for a server cookie.
2015 */
2016 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002017 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002018
2019 /*
2020 * Check for cache-control or pragma headers if required.
2021 */
2022 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2023 check_response_for_cacheability(s, rep);
2024
2025 /*
2026 * Add server cookie in the response if needed
2027 */
2028 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2029 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2030 (!(s->flags & SF_DIRECT) ||
2031 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2032 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2033 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2034 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2035 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2036 !(s->flags & SF_IGNORE_PRST)) {
2037 /* the server is known, it's not the one the client requested, or the
2038 * cookie's last seen date needs to be refreshed. We have to
2039 * insert a set-cookie here, except if we want to insert only on POST
2040 * requests and this one isn't. Note that servers which don't have cookies
2041 * (eg: some backup servers) will return a full cookie removal request.
2042 */
2043 if (!objt_server(s->target)->cookie) {
2044 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002045 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002046 s->be->cookie_name);
2047 }
2048 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002049 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002050
2051 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2052 /* emit last_date, which is mandatory */
2053 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2054 s30tob64((date.tv_sec+3) >> 2,
2055 trash.area + trash.data);
2056 trash.data += 5;
2057
2058 if (s->be->cookie_maxlife) {
2059 /* emit first_date, which is either the original one or
2060 * the current date.
2061 */
2062 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2063 s30tob64(txn->cookie_first_date ?
2064 txn->cookie_first_date >> 2 :
2065 (date.tv_sec+3) >> 2,
2066 trash.area + trash.data);
2067 trash.data += 5;
2068 }
2069 }
2070 chunk_appendf(&trash, "; path=/");
2071 }
2072
2073 if (s->be->cookie_domain)
2074 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2075
2076 if (s->be->ck_opts & PR_CK_HTTPONLY)
2077 chunk_appendf(&trash, "; HttpOnly");
2078
2079 if (s->be->ck_opts & PR_CK_SECURE)
2080 chunk_appendf(&trash, "; Secure");
2081
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002082 if (s->be->cookie_attrs)
2083 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2084
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002085 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002086 goto return_bad_resp;
2087
2088 txn->flags &= ~TX_SCK_MASK;
2089 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2090 /* the server did not change, only the date was updated */
2091 txn->flags |= TX_SCK_UPDATED;
2092 else
2093 txn->flags |= TX_SCK_INSERTED;
2094
2095 /* Here, we will tell an eventual cache on the client side that we don't
2096 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2097 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2098 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2099 */
2100 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2101
2102 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2103
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002104 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002105 goto return_bad_resp;
2106 }
2107 }
2108
2109 /*
2110 * Check if result will be cacheable with a cookie.
2111 * We'll block the response if security checks have caught
2112 * nasty things such as a cacheable cookie.
2113 */
2114 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2115 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2116 (s->be->options & PR_O_CHK_CACHE)) {
2117 /* we're in presence of a cacheable response containing
2118 * a set-cookie header. We'll block it as requested by
2119 * the 'checkcache' option, and send an alert.
2120 */
2121 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002122 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123
Olivier Houcharda798bf52019-03-08 18:52:00 +01002124 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002127 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002128
2129 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2130 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2131 send_log(s->be, LOG_ALERT,
2132 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2133 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2134 goto return_srv_prx_502;
2135 }
2136
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002137 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002138 /* Always enter in the body analyzer */
2139 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2140 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2141
2142 /* if the user wants to log as soon as possible, without counting
2143 * bytes from the server, then this is the right moment. We have
2144 * to temporarily assign bytes_out to log what we currently have.
2145 */
2146 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2147 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002148 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 s->do_log(s);
2150 s->logs.bytes_out = 0;
2151 }
2152 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002153
2154 return_bad_resp:
2155 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002156 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002157 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002158 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002159 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002160
2161 return_srv_prx_502:
2162 rep->analysers &= AN_RES_FLT_END;
2163 txn->status = 502;
2164 s->logs.t_data = -1; /* was not a valid response */
2165 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002166 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002167 if (!(s->flags & SF_ERR_MASK))
2168 s->flags |= SF_ERR_PRXCOND;
2169 if (!(s->flags & SF_FINST_MASK))
2170 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002171
2172 s->req.analysers &= AN_REQ_FLT_END;
2173 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002174 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002175}
2176
2177/* This function is an analyser which forwards response body (including chunk
2178 * sizes if any). It is called as soon as we must forward, even if we forward
2179 * zero byte. The only situation where it must not be called is when we're in
2180 * tunnel mode and we want to forward till the close. It's used both to forward
2181 * remaining data and to resync after end of body. It expects the msg_state to
2182 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2183 * read more data, or 1 once we can go on with next request or end the stream.
2184 *
2185 * It is capable of compressing response data both in content-length mode and
2186 * in chunked mode. The state machines follows different flows depending on
2187 * whether content-length and chunked modes are used, since there are no
2188 * trailers in content-length :
2189 *
2190 * chk-mode cl-mode
2191 * ,----- BODY -----.
2192 * / \
2193 * V size > 0 V chk-mode
2194 * .--> SIZE -------------> DATA -------------> CRLF
2195 * | | size == 0 | last byte |
2196 * | v final crlf v inspected |
2197 * | TRAILERS -----------> DONE |
2198 * | |
2199 * `----------------------------------------------'
2200 *
2201 * Compression only happens in the DATA state, and must be flushed in final
2202 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2203 * is performed at once on final states for all bytes parsed, or when leaving
2204 * on missing data.
2205 */
2206int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2207{
2208 struct session *sess = s->sess;
2209 struct http_txn *txn = s->txn;
2210 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002211 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002212 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213
2214 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2215 now_ms, __FUNCTION__,
2216 s,
2217 res,
2218 res->rex, res->wex,
2219 res->flags,
2220 ci_data(res),
2221 res->analysers);
2222
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002223 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224
2225 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002226 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002227 /* Output closed while we were sending data. We must abort and
2228 * wake the other side up.
2229 */
2230 msg->err_state = msg->msg_state;
2231 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002232 htx_end_response(s);
2233 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 return 1;
2235 }
2236
Christopher Faulet9768c262018-10-22 09:34:31 +02002237 if (msg->msg_state == HTTP_MSG_BODY)
2238 msg->msg_state = HTTP_MSG_DATA;
2239
Christopher Faulete0768eb2018-10-03 16:38:02 +02002240 /* in most states, we should abort in case of early close */
2241 channel_auto_close(res);
2242
Christopher Faulete0768eb2018-10-03 16:38:02 +02002243 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002244 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002245 if (res->flags & CF_EOI)
2246 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002247 }
2248 else {
2249 /* We can't process the buffer's contents yet */
2250 res->flags |= CF_WAKE_WRITE;
2251 goto missing_data_or_waiting;
2252 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253 }
2254
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002255 if (msg->msg_state >= HTTP_MSG_ENDING)
2256 goto ending;
2257
2258 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2259 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2260 msg->msg_state = HTTP_MSG_ENDING;
2261 goto ending;
2262 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002263
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002264 /* Forward input data. We get it by removing all outgoing data not
2265 * forwarded yet from HTX data size. If there are some data filters, we
2266 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002267 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002268 if (HAS_RSP_DATA_FILTERS(s)) {
2269 ret = flt_http_payload(s, msg, htx->data);
2270 if (ret < 0)
2271 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002272 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002273 }
2274 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002275 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002276 if (msg->flags & HTTP_MSGF_XFER_LEN)
2277 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002278 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002279
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002280 if (htx->data != co_data(res))
2281 goto missing_data_or_waiting;
2282
2283 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2284 msg->msg_state = HTTP_MSG_ENDING;
2285 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 }
2287
Christopher Faulet9768c262018-10-22 09:34:31 +02002288 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002289 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2290 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002291 */
2292 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2293 goto missing_data_or_waiting;
2294
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002295 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002296
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002297 ending:
2298 /* other states, ENDING...TUNNEL */
2299 if (msg->msg_state >= HTTP_MSG_DONE)
2300 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002301
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002302 if (HAS_RSP_DATA_FILTERS(s)) {
2303 ret = flt_http_end(s, msg);
2304 if (ret <= 0) {
2305 if (!ret)
2306 goto missing_data_or_waiting;
2307 goto return_bad_res;
2308 }
2309 }
2310
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002311 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2312 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2313 msg->msg_state = HTTP_MSG_TUNNEL;
2314 goto ending;
2315 }
2316 else {
2317 msg->msg_state = HTTP_MSG_DONE;
2318 res->to_forward = 0;
2319 }
2320
2321 done:
2322
2323 channel_dont_close(res);
2324
Christopher Fauletf2824e62018-10-01 12:12:37 +02002325 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2329 if (res->flags & CF_SHUTW) {
2330 /* response errors are most likely due to the
2331 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002332 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002334 goto return_bad_res;
2335 }
2336 return 1;
2337 }
2338 return 0;
2339
2340 missing_data_or_waiting:
2341 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002342 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343
Christopher Faulet47365272018-10-31 17:40:50 +01002344 if (htx->flags & HTX_FL_PARSING_ERROR)
2345 goto return_bad_res;
2346
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347 /* stop waiting for data if the input is closed before the end. If the
2348 * client side was already closed, it means that the client has aborted,
2349 * so we don't want to count this as a server abort. Otherwise it's a
2350 * server abort.
2351 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002352 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002353 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002354 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002355 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002356 if (htx_is_empty(htx))
2357 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 }
2359
Christopher Faulete0768eb2018-10-03 16:38:02 +02002360 /* When TE: chunked is used, we need to get there again to parse
2361 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002362 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2363 * are filters registered on the stream, we don't want to forward a
2364 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002365 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002366 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002367 channel_dont_close(res);
2368
2369 /* We know that more data are expected, but we couldn't send more that
2370 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2371 * system knows it must not set a PUSH on this first part. Interactive
2372 * modes are already handled by the stream sock layer. We must not do
2373 * this in content-length mode because it could present the MSG_MORE
2374 * flag with the last block of forwarded data, which would cause an
2375 * additional delay to be observed by the receiver.
2376 */
2377 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2378 res->flags |= CF_EXPECT_MORE;
2379
2380 /* the stream handler will take care of timeouts and errors */
2381 return 0;
2382
Christopher Faulet93e02d82019-03-08 14:18:50 +01002383 return_srv_abort:
2384 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2385 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002386 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002387 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2388 if (!(s->flags & SF_ERR_MASK))
2389 s->flags |= SF_ERR_SRVCL;
2390 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002391
Christopher Faulet93e02d82019-03-08 14:18:50 +01002392 return_cli_abort:
2393 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2394 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002395 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002396 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2397 if (!(s->flags & SF_ERR_MASK))
2398 s->flags |= SF_ERR_CLICL;
2399 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002400
Christopher Faulet93e02d82019-03-08 14:18:50 +01002401 return_bad_res:
2402 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2403 if (objt_server(s->target)) {
2404 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2405 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2406 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002407 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002408 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002409
Christopher Faulet93e02d82019-03-08 14:18:50 +01002410 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002411 txn->rsp.err_state = txn->rsp.msg_state;
2412 txn->rsp.msg_state = HTTP_MSG_ERROR;
2413 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002414 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002415 res->analysers &= AN_RES_FLT_END;
2416 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 +02002417 if (!(s->flags & SF_FINST_MASK))
2418 s->flags |= SF_FINST_D;
2419 return 0;
2420}
2421
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002424 * as too large a request to build a valid response.
2425 */
2426int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2427{
Christopher Faulet99daf282018-11-28 22:58:13 +01002428 struct channel *req = &s->req;
2429 struct channel *res = &s->res;
2430 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002431 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 struct ist status, reason, location;
2434 unsigned int flags;
2435 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002436 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002437
2438 chunk = alloc_trash_chunk();
2439 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002440 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441
Christopher Faulet99daf282018-11-28 22:58:13 +01002442 /*
2443 * Create the location
2444 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002445 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 case REDIRECT_TYPE_SCHEME: {
2448 struct http_hdr_ctx ctx;
2449 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450
Christopher Faulet99daf282018-11-28 22:58:13 +01002451 host = ist("");
2452 ctx.blk = NULL;
2453 if (http_find_header(htx, ist("Host"), &ctx, 0))
2454 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002455
Christopher Faulet297fbb42019-05-13 14:41:27 +02002456 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002457 path = http_get_path(htx_sl_req_uri(sl));
2458 /* build message using path */
2459 if (path.ptr) {
2460 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2461 int qs = 0;
2462 while (qs < path.len) {
2463 if (*(path.ptr + qs) == '?') {
2464 path.len = qs;
2465 break;
2466 }
2467 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002469 }
2470 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002471 else
2472 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473
Christopher Faulet99daf282018-11-28 22:58:13 +01002474 if (rule->rdr_str) { /* this is an old "redirect" rule */
2475 /* add scheme */
2476 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2477 goto fail;
2478 }
2479 else {
2480 /* add scheme with executing log format */
2481 chunk->data += build_logline(s, chunk->area + chunk->data,
2482 chunk->size - chunk->data,
2483 &rule->rdr_fmt);
2484 }
2485 /* add "://" + host + path */
2486 if (!chunk_memcat(chunk, "://", 3) ||
2487 !chunk_memcat(chunk, host.ptr, host.len) ||
2488 !chunk_memcat(chunk, path.ptr, path.len))
2489 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002490
Christopher Faulet99daf282018-11-28 22:58:13 +01002491 /* append a slash at the end of the location if needed and missing */
2492 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2493 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2494 if (chunk->data + 1 >= chunk->size)
2495 goto fail;
2496 chunk->area[chunk->data++] = '/';
2497 }
2498 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002499 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002500
Christopher Faulet99daf282018-11-28 22:58:13 +01002501 case REDIRECT_TYPE_PREFIX: {
2502 struct ist path;
2503
Christopher Faulet297fbb42019-05-13 14:41:27 +02002504 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 path = http_get_path(htx_sl_req_uri(sl));
2506 /* build message using path */
2507 if (path.ptr) {
2508 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2509 int qs = 0;
2510 while (qs < path.len) {
2511 if (*(path.ptr + qs) == '?') {
2512 path.len = qs;
2513 break;
2514 }
2515 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002516 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002517 }
2518 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002519 else
2520 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002521
Christopher Faulet99daf282018-11-28 22:58:13 +01002522 if (rule->rdr_str) { /* this is an old "redirect" rule */
2523 /* add prefix. Note that if prefix == "/", we don't want to
2524 * add anything, otherwise it makes it hard for the user to
2525 * configure a self-redirection.
2526 */
2527 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2528 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2529 goto fail;
2530 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002531 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 else {
2533 /* add prefix with executing log format */
2534 chunk->data += build_logline(s, chunk->area + chunk->data,
2535 chunk->size - chunk->data,
2536 &rule->rdr_fmt);
2537 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002538
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 /* add path */
2540 if (!chunk_memcat(chunk, path.ptr, path.len))
2541 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002542
Christopher Faulet99daf282018-11-28 22:58:13 +01002543 /* append a slash at the end of the location if needed and missing */
2544 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2545 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2546 if (chunk->data + 1 >= chunk->size)
2547 goto fail;
2548 chunk->area[chunk->data++] = '/';
2549 }
2550 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002551 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 case REDIRECT_TYPE_LOCATION:
2553 default:
2554 if (rule->rdr_str) { /* this is an old "redirect" rule */
2555 /* add location */
2556 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2557 goto fail;
2558 }
2559 else {
2560 /* add location with executing log format */
2561 chunk->data += build_logline(s, chunk->area + chunk->data,
2562 chunk->size - chunk->data,
2563 &rule->rdr_fmt);
2564 }
2565 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002566 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002567 location = ist2(chunk->area, chunk->data);
2568
2569 /*
2570 * Create the 30x response
2571 */
2572 switch (rule->code) {
2573 case 308:
2574 status = ist("308");
2575 reason = ist("Permanent Redirect");
2576 break;
2577 case 307:
2578 status = ist("307");
2579 reason = ist("Temporary Redirect");
2580 break;
2581 case 303:
2582 status = ist("303");
2583 reason = ist("See Other");
2584 break;
2585 case 301:
2586 status = ist("301");
2587 reason = ist("Moved Permanently");
2588 break;
2589 case 302:
2590 default:
2591 status = ist("302");
2592 reason = ist("Found");
2593 break;
2594 }
2595
Christopher Faulet08e66462019-05-23 16:44:59 +02002596 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2597 close = 1;
2598
Christopher Faulet99daf282018-11-28 22:58:13 +01002599 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002600 /* Trim any possible response */
2601 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002602 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2603 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2604 if (!sl)
2605 goto fail;
2606 sl->info.res.status = rule->code;
2607 s->txn->status = rule->code;
2608
Christopher Faulet08e66462019-05-23 16:44:59 +02002609 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2610 goto fail;
2611
2612 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002613 !htx_add_header(htx, ist("Location"), location))
2614 goto fail;
2615
2616 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2617 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2618 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002619 }
2620
2621 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002622 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2623 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002624 }
2625
Christopher Faulet99daf282018-11-28 22:58:13 +01002626 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2627 goto fail;
2628
Kevin Zhu0fd70882020-01-07 09:42:55 +01002629 htx_to_buf(htx, &res->buf);
2630
Christopher Faulet99daf282018-11-28 22:58:13 +01002631 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002632 c_adv(res, data);
2633 res->total += data;
2634
2635 channel_auto_read(req);
2636 channel_abort(req);
2637 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002638 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002639
2640 res->wex = tick_add_ifset(now_ms, res->wto);
2641 channel_auto_read(res);
2642 channel_auto_close(res);
2643 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002644 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2645 /* let's log the request time */
2646 s->logs.tv_request = now;
2647 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002648
Christopher Faulet7d84db32020-01-28 09:18:10 +01002649 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2650 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2651 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002652
2653 if (!(s->flags & SF_ERR_MASK))
2654 s->flags |= SF_ERR_LOCAL;
2655 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002656 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002657
Christopher Faulet99daf282018-11-28 22:58:13 +01002658 free_trash_chunk(chunk);
2659 return 1;
2660
2661 fail:
2662 /* If an error occurred, remove the incomplete HTTP response from the
2663 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002664 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002665 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002666 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002667}
2668
Christopher Faulet72333522018-10-24 11:25:02 +02002669int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2670 struct ist name, const char *str, struct my_regex *re, int action)
2671{
2672 struct http_hdr_ctx ctx;
2673 struct buffer *output = get_trash_chunk();
2674
2675 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2676 ctx.blk = NULL;
2677 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2678 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2679 continue;
2680
2681 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2682 if (output->data == -1)
2683 return -1;
2684 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2685 return -1;
2686 }
2687 return 0;
2688}
2689
2690static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2691 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2692{
2693 struct buffer *replace;
2694 int ret = -1;
2695
2696 replace = alloc_trash_chunk();
2697 if (!replace)
2698 goto leave;
2699
2700 replace->data = build_logline(s, replace->area, replace->size, fmt);
2701 if (replace->data >= replace->size - 1)
2702 goto leave;
2703
2704 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2705
2706 leave:
2707 free_trash_chunk(replace);
2708 return ret;
2709}
2710
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002711
2712/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2713 * on success and -1 on error. The response channel is updated accordingly.
2714 */
2715static int htx_reply_103_early_hints(struct channel *res)
2716{
2717 struct htx *htx = htx_from_buf(&res->buf);
2718 size_t data;
2719
Christopher Faulet9869f932019-06-26 14:23:54 +02002720 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002721 /* If an error occurred during an Early-hint rule,
2722 * remove the incomplete HTTP 103 response from the
2723 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002724 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002725 return -1;
2726 }
2727
2728 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002729 c_adv(res, data);
2730 res->total += data;
2731 return 0;
2732}
2733
Christopher Faulet6eb92892018-11-15 16:39:29 +01002734/*
2735 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2736 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002737 * If <early_hints> is 0, it is starts a new response by adding the start
2738 * line. If an error occurred -1 is returned. On success 0 is returned. The
2739 * channel is not updated here. It must be done calling the function
2740 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002741 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002742static 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 +01002743{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002744 struct channel *res = &s->res;
2745 struct htx *htx = htx_from_buf(&res->buf);
2746 struct buffer *value = alloc_trash_chunk();
2747
Christopher Faulet6eb92892018-11-15 16:39:29 +01002748 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002749 struct htx_sl *sl;
2750 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2751 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2752
2753 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2754 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2755 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002756 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002757 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002758 }
2759
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002760 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2761 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002762 goto fail;
2763
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002764 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002765 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002766
2767 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002768 /* If an error occurred during an Early-hint rule, remove the incomplete
2769 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002770 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002771 free_trash_chunk(value);
2772 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002773}
2774
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002775/* This function executes one of the set-{method,path,query,uri} actions. It
2776 * takes the string from the variable 'replace' with length 'len', then modifies
2777 * the relevant part of the request line accordingly. Then it updates various
2778 * pointers to the next elements which were moved, and the total buffer length.
2779 * It finds the action to be performed in p[2], previously filled by function
2780 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2781 * error, though this can be revisited when this code is finally exploited.
2782 *
2783 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2784 * query string and 3 to replace uri.
2785 *
2786 * In query string case, the mark question '?' must be set at the start of the
2787 * string by the caller, event if the replacement query string is empty.
2788 */
2789int htx_req_replace_stline(int action, const char *replace, int len,
2790 struct proxy *px, struct stream *s)
2791{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002792 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002793
2794 switch (action) {
2795 case 0: // method
2796 if (!http_replace_req_meth(htx, ist2(replace, len)))
2797 return -1;
2798 break;
2799
2800 case 1: // path
2801 if (!http_replace_req_path(htx, ist2(replace, len)))
2802 return -1;
2803 break;
2804
2805 case 2: // query
2806 if (!http_replace_req_query(htx, ist2(replace, len)))
2807 return -1;
2808 break;
2809
2810 case 3: // uri
2811 if (!http_replace_req_uri(htx, ist2(replace, len)))
2812 return -1;
2813 break;
2814
2815 default:
2816 return -1;
2817 }
2818 return 0;
2819}
2820
2821/* This function replace the HTTP status code and the associated message. The
2822 * variable <status> contains the new status code. This function never fails.
2823 */
2824void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2825{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002826 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002827 char *res;
2828
2829 chunk_reset(&trash);
2830 res = ultoa_o(status, trash.area, trash.size);
2831 trash.data = res - trash.area;
2832
2833 /* Do we have a custom reason format string? */
2834 if (reason == NULL)
2835 reason = http_get_reason(status);
2836
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002837 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002838 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2839}
2840
Christopher Faulet3e964192018-10-24 11:39:23 +02002841/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2842 * transaction <txn>. Returns the verdict of the first rule that prevents
2843 * further processing of the request (auth, deny, ...), and defaults to
2844 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2845 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2846 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2847 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2848 * status.
2849 */
2850static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2851 struct stream *s, int *deny_status)
2852{
2853 struct session *sess = strm_sess(s);
2854 struct http_txn *txn = s->txn;
2855 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002856 struct act_rule *rule;
2857 struct http_hdr_ctx ctx;
2858 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002859 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2860 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002861 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002862
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002863 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002864
2865 /* If "the current_rule_list" match the executed rule list, we are in
2866 * resume condition. If a resume is needed it is always in the action
2867 * and never in the ACL or converters. In this case, we initialise the
2868 * current rule, and go to the action execution point.
2869 */
2870 if (s->current_rule) {
2871 rule = s->current_rule;
2872 s->current_rule = NULL;
2873 if (s->current_rule_list == rules)
2874 goto resume_execution;
2875 }
2876 s->current_rule_list = rules;
2877
2878 list_for_each_entry(rule, rules, list) {
2879 /* check optional condition */
2880 if (rule->cond) {
2881 int ret;
2882
2883 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2884 ret = acl_pass(ret);
2885
2886 if (rule->cond->pol == ACL_COND_UNLESS)
2887 ret = !ret;
2888
2889 if (!ret) /* condition not matched */
2890 continue;
2891 }
2892
2893 act_flags |= ACT_FLAG_FIRST;
2894 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002895 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2896 early_hints = 0;
2897 if (htx_reply_103_early_hints(&s->res) == -1) {
2898 rule_ret = HTTP_RULE_RES_BADREQ;
2899 goto end;
2900 }
2901 }
2902
Christopher Faulet3e964192018-10-24 11:39:23 +02002903 switch (rule->action) {
2904 case ACT_ACTION_ALLOW:
2905 rule_ret = HTTP_RULE_RES_STOP;
2906 goto end;
2907
2908 case ACT_ACTION_DENY:
2909 if (deny_status)
2910 *deny_status = rule->deny_status;
2911 rule_ret = HTTP_RULE_RES_DENY;
2912 goto end;
2913
2914 case ACT_HTTP_REQ_TARPIT:
2915 txn->flags |= TX_CLTARPIT;
2916 if (deny_status)
2917 *deny_status = rule->deny_status;
2918 rule_ret = HTTP_RULE_RES_DENY;
2919 goto end;
2920
2921 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002922 /* Auth might be performed on regular http-req rules as well as on stats */
2923 auth_realm = rule->arg.auth.realm;
2924 if (!auth_realm) {
2925 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2926 auth_realm = STATS_DEFAULT_REALM;
2927 else
2928 auth_realm = px->id;
2929 }
2930 /* send 401/407 depending on whether we use a proxy or not. We still
2931 * count one error, because normal browsing won't significantly
2932 * increase the counter but brute force attempts will.
2933 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002934 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002935 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2936 rule_ret = HTTP_RULE_RES_BADREQ;
2937 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002938 goto end;
2939
2940 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002941 rule_ret = HTTP_RULE_RES_DONE;
2942 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2943 rule_ret = HTTP_RULE_RES_BADREQ;
2944 goto end;
2945
2946 case ACT_HTTP_SET_NICE:
2947 s->task->nice = rule->arg.nice;
2948 break;
2949
2950 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002951 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002952 break;
2953
2954 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002955 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002956 break;
2957
2958 case ACT_HTTP_SET_LOGL:
2959 s->logs.level = rule->arg.loglevel;
2960 break;
2961
2962 case ACT_HTTP_REPLACE_HDR:
2963 case ACT_HTTP_REPLACE_VAL:
2964 if (htx_transform_header(s, &s->req, htx,
2965 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2966 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002967 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002968 rule_ret = HTTP_RULE_RES_BADREQ;
2969 goto end;
2970 }
2971 break;
2972
2973 case ACT_HTTP_DEL_HDR:
2974 /* remove all occurrences of the header */
2975 ctx.blk = NULL;
2976 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2977 http_remove_header(htx, &ctx);
2978 break;
2979
2980 case ACT_HTTP_SET_HDR:
2981 case ACT_HTTP_ADD_HDR: {
2982 /* The scope of the trash buffer must be limited to this function. The
2983 * build_logline() function can execute a lot of other function which
2984 * can use the trash buffer. So for limiting the scope of this global
2985 * buffer, we build first the header value using build_logline, and
2986 * after we store the header name.
2987 */
2988 struct buffer *replace;
2989 struct ist n, v;
2990
2991 replace = alloc_trash_chunk();
2992 if (!replace) {
2993 rule_ret = HTTP_RULE_RES_BADREQ;
2994 goto end;
2995 }
2996
2997 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2998 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2999 v = ist2(replace->area, replace->data);
3000
3001 if (rule->action == ACT_HTTP_SET_HDR) {
3002 /* remove all occurrences of the header */
3003 ctx.blk = NULL;
3004 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3005 http_remove_header(htx, &ctx);
3006 }
3007
3008 if (!http_add_header(htx, n, v)) {
3009 static unsigned char rate_limit = 0;
3010
3011 if ((rate_limit++ & 255) == 0) {
3012 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);
3013 }
3014
Olivier Houcharda798bf52019-03-08 18:52:00 +01003015 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003016 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003017 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003018 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003019 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003020 }
3021 free_trash_chunk(replace);
3022 break;
3023 }
3024
3025 case ACT_HTTP_DEL_ACL:
3026 case ACT_HTTP_DEL_MAP: {
3027 struct pat_ref *ref;
3028 struct buffer *key;
3029
3030 /* collect reference */
3031 ref = pat_ref_lookup(rule->arg.map.ref);
3032 if (!ref)
3033 continue;
3034
3035 /* allocate key */
3036 key = alloc_trash_chunk();
3037 if (!key) {
3038 rule_ret = HTTP_RULE_RES_BADREQ;
3039 goto end;
3040 }
3041
3042 /* collect key */
3043 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3044 key->area[key->data] = '\0';
3045
3046 /* perform update */
3047 /* returned code: 1=ok, 0=ko */
3048 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3049 pat_ref_delete(ref, key->area);
3050 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3051
3052 free_trash_chunk(key);
3053 break;
3054 }
3055
3056 case ACT_HTTP_ADD_ACL: {
3057 struct pat_ref *ref;
3058 struct buffer *key;
3059
3060 /* collect reference */
3061 ref = pat_ref_lookup(rule->arg.map.ref);
3062 if (!ref)
3063 continue;
3064
3065 /* allocate key */
3066 key = alloc_trash_chunk();
3067 if (!key) {
3068 rule_ret = HTTP_RULE_RES_BADREQ;
3069 goto end;
3070 }
3071
3072 /* collect key */
3073 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3074 key->area[key->data] = '\0';
3075
3076 /* perform update */
3077 /* add entry only if it does not already exist */
3078 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3079 if (pat_ref_find_elt(ref, key->area) == NULL)
3080 pat_ref_add(ref, key->area, NULL, NULL);
3081 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3082
3083 free_trash_chunk(key);
3084 break;
3085 }
3086
3087 case ACT_HTTP_SET_MAP: {
3088 struct pat_ref *ref;
3089 struct buffer *key, *value;
3090
3091 /* collect reference */
3092 ref = pat_ref_lookup(rule->arg.map.ref);
3093 if (!ref)
3094 continue;
3095
3096 /* allocate key */
3097 key = alloc_trash_chunk();
3098 if (!key) {
3099 rule_ret = HTTP_RULE_RES_BADREQ;
3100 goto end;
3101 }
3102
3103 /* allocate value */
3104 value = alloc_trash_chunk();
3105 if (!value) {
3106 free_trash_chunk(key);
3107 rule_ret = HTTP_RULE_RES_BADREQ;
3108 goto end;
3109 }
3110
3111 /* collect key */
3112 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3113 key->area[key->data] = '\0';
3114
3115 /* collect value */
3116 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3117 value->area[value->data] = '\0';
3118
3119 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003120 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003121 if (pat_ref_find_elt(ref, key->area) != NULL)
3122 /* update entry if it exists */
3123 pat_ref_set(ref, key->area, value->area, NULL);
3124 else
3125 /* insert a new entry */
3126 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003127 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003128 free_trash_chunk(key);
3129 free_trash_chunk(value);
3130 break;
3131 }
3132
3133 case ACT_HTTP_EARLY_HINT:
3134 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3135 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003136 early_hints = htx_add_early_hint_header(s, early_hints,
3137 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003138 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003139 if (early_hints == -1) {
3140 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003141 goto end;
3142 }
3143 break;
3144
3145 case ACT_CUSTOM:
3146 if ((s->req.flags & CF_READ_ERROR) ||
3147 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003148 (px->options & PR_O_ABRT_CLOSE)))
3149 act_flags |= ACT_FLAG_FINAL;
3150
3151 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3152 case ACT_RET_ERR:
3153 case ACT_RET_CONT:
3154 break;
3155 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003156 rule_ret = HTTP_RULE_RES_STOP;
3157 goto end;
3158 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003159 rule_ret = HTTP_RULE_RES_DONE;
3160 goto end;
3161 case ACT_RET_YIELD:
3162 s->current_rule = rule;
3163 rule_ret = HTTP_RULE_RES_YIELD;
3164 goto end;
3165 }
3166 break;
3167
3168 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3169 /* Note: only the first valid tracking parameter of each
3170 * applies.
3171 */
3172
3173 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3174 struct stktable *t;
3175 struct stksess *ts;
3176 struct stktable_key *key;
3177 void *ptr1, *ptr2;
3178
3179 t = rule->arg.trk_ctr.table.t;
3180 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3181 rule->arg.trk_ctr.expr, NULL);
3182
3183 if (key && (ts = stktable_get_entry(t, key))) {
3184 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3185
3186 /* let's count a new HTTP request as it's the first time we do it */
3187 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3188 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3189 if (ptr1 || ptr2) {
3190 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3191
3192 if (ptr1)
3193 stktable_data_cast(ptr1, http_req_cnt)++;
3194
3195 if (ptr2)
3196 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3197 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3198
3199 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3200
3201 /* If data was modified, we need to touch to re-schedule sync */
3202 stktable_touch_local(t, ts, 0);
3203 }
3204
3205 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3206 if (sess->fe != s->be)
3207 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3208 }
3209 }
3210 break;
3211
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003212 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003213 default:
3214 break;
3215 }
3216 }
3217
3218 end:
3219 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003220 if (htx_reply_103_early_hints(&s->res) == -1)
3221 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 }
3223
3224 /* we reached the end of the rules, nothing to report */
3225 return rule_ret;
3226}
3227
3228/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3229 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3230 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3231 * is returned, the process can continue the evaluation of next rule list. If
3232 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3233 * is returned, it means the operation could not be processed and a server error
3234 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3235 * deny rule. If *YIELD is returned, the caller must call again the function
3236 * with the same context.
3237 */
3238static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3239 struct stream *s)
3240{
3241 struct session *sess = strm_sess(s);
3242 struct http_txn *txn = s->txn;
3243 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003244 struct act_rule *rule;
3245 struct http_hdr_ctx ctx;
3246 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3247 int act_flags = 0;
3248
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003249 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003250
3251 /* If "the current_rule_list" match the executed rule list, we are in
3252 * resume condition. If a resume is needed it is always in the action
3253 * and never in the ACL or converters. In this case, we initialise the
3254 * current rule, and go to the action execution point.
3255 */
3256 if (s->current_rule) {
3257 rule = s->current_rule;
3258 s->current_rule = NULL;
3259 if (s->current_rule_list == rules)
3260 goto resume_execution;
3261 }
3262 s->current_rule_list = rules;
3263
3264 list_for_each_entry(rule, rules, list) {
3265 /* check optional condition */
3266 if (rule->cond) {
3267 int ret;
3268
3269 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3270 ret = acl_pass(ret);
3271
3272 if (rule->cond->pol == ACL_COND_UNLESS)
3273 ret = !ret;
3274
3275 if (!ret) /* condition not matched */
3276 continue;
3277 }
3278
3279 act_flags |= ACT_FLAG_FIRST;
3280resume_execution:
3281 switch (rule->action) {
3282 case ACT_ACTION_ALLOW:
3283 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3284 goto end;
3285
3286 case ACT_ACTION_DENY:
3287 txn->flags |= TX_SVDENY;
3288 rule_ret = HTTP_RULE_RES_STOP;
3289 goto end;
3290
3291 case ACT_HTTP_SET_NICE:
3292 s->task->nice = rule->arg.nice;
3293 break;
3294
3295 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003296 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003297 break;
3298
3299 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003300 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003301 break;
3302
3303 case ACT_HTTP_SET_LOGL:
3304 s->logs.level = rule->arg.loglevel;
3305 break;
3306
3307 case ACT_HTTP_REPLACE_HDR:
3308 case ACT_HTTP_REPLACE_VAL:
3309 if (htx_transform_header(s, &s->res, htx,
3310 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3311 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003312 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003313 rule_ret = HTTP_RULE_RES_BADREQ;
3314 goto end;
3315 }
3316 break;
3317
3318 case ACT_HTTP_DEL_HDR:
3319 /* remove all occurrences of the header */
3320 ctx.blk = NULL;
3321 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3322 http_remove_header(htx, &ctx);
3323 break;
3324
3325 case ACT_HTTP_SET_HDR:
3326 case ACT_HTTP_ADD_HDR: {
3327 struct buffer *replace;
3328 struct ist n, v;
3329
3330 replace = alloc_trash_chunk();
3331 if (!replace) {
3332 rule_ret = HTTP_RULE_RES_BADREQ;
3333 goto end;
3334 }
3335
3336 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3337 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3338 v = ist2(replace->area, replace->data);
3339
3340 if (rule->action == ACT_HTTP_SET_HDR) {
3341 /* remove all occurrences of the header */
3342 ctx.blk = NULL;
3343 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3344 http_remove_header(htx, &ctx);
3345 }
3346
3347 if (!http_add_header(htx, n, v)) {
3348 static unsigned char rate_limit = 0;
3349
3350 if ((rate_limit++ & 255) == 0) {
3351 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);
3352 }
3353
Olivier Houcharda798bf52019-03-08 18:52:00 +01003354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003355 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003356 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003357 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003358 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003359 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003360 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003361 }
3362 free_trash_chunk(replace);
3363 break;
3364 }
3365
3366 case ACT_HTTP_DEL_ACL:
3367 case ACT_HTTP_DEL_MAP: {
3368 struct pat_ref *ref;
3369 struct buffer *key;
3370
3371 /* collect reference */
3372 ref = pat_ref_lookup(rule->arg.map.ref);
3373 if (!ref)
3374 continue;
3375
3376 /* allocate key */
3377 key = alloc_trash_chunk();
3378 if (!key) {
3379 rule_ret = HTTP_RULE_RES_BADREQ;
3380 goto end;
3381 }
3382
3383 /* collect key */
3384 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3385 key->area[key->data] = '\0';
3386
3387 /* perform update */
3388 /* returned code: 1=ok, 0=ko */
3389 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3390 pat_ref_delete(ref, key->area);
3391 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3392
3393 free_trash_chunk(key);
3394 break;
3395 }
3396
3397 case ACT_HTTP_ADD_ACL: {
3398 struct pat_ref *ref;
3399 struct buffer *key;
3400
3401 /* collect reference */
3402 ref = pat_ref_lookup(rule->arg.map.ref);
3403 if (!ref)
3404 continue;
3405
3406 /* allocate key */
3407 key = alloc_trash_chunk();
3408 if (!key) {
3409 rule_ret = HTTP_RULE_RES_BADREQ;
3410 goto end;
3411 }
3412
3413 /* collect key */
3414 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3415 key->area[key->data] = '\0';
3416
3417 /* perform update */
3418 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003419 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003420 if (pat_ref_find_elt(ref, key->area) == NULL)
3421 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003422 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003423 free_trash_chunk(key);
3424 break;
3425 }
3426
3427 case ACT_HTTP_SET_MAP: {
3428 struct pat_ref *ref;
3429 struct buffer *key, *value;
3430
3431 /* collect reference */
3432 ref = pat_ref_lookup(rule->arg.map.ref);
3433 if (!ref)
3434 continue;
3435
3436 /* allocate key */
3437 key = alloc_trash_chunk();
3438 if (!key) {
3439 rule_ret = HTTP_RULE_RES_BADREQ;
3440 goto end;
3441 }
3442
3443 /* allocate value */
3444 value = alloc_trash_chunk();
3445 if (!value) {
3446 free_trash_chunk(key);
3447 rule_ret = HTTP_RULE_RES_BADREQ;
3448 goto end;
3449 }
3450
3451 /* collect key */
3452 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3453 key->area[key->data] = '\0';
3454
3455 /* collect value */
3456 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3457 value->area[value->data] = '\0';
3458
3459 /* perform update */
3460 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3461 if (pat_ref_find_elt(ref, key->area) != NULL)
3462 /* update entry if it exists */
3463 pat_ref_set(ref, key->area, value->area, NULL);
3464 else
3465 /* insert a new entry */
3466 pat_ref_add(ref, key->area, value->area, NULL);
3467 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3468 free_trash_chunk(key);
3469 free_trash_chunk(value);
3470 break;
3471 }
3472
3473 case ACT_HTTP_REDIR:
3474 rule_ret = HTTP_RULE_RES_DONE;
3475 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3476 rule_ret = HTTP_RULE_RES_BADREQ;
3477 goto end;
3478
3479 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3480 /* Note: only the first valid tracking parameter of each
3481 * applies.
3482 */
3483 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3484 struct stktable *t;
3485 struct stksess *ts;
3486 struct stktable_key *key;
3487 void *ptr;
3488
3489 t = rule->arg.trk_ctr.table.t;
3490 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3491 rule->arg.trk_ctr.expr, NULL);
3492
3493 if (key && (ts = stktable_get_entry(t, key))) {
3494 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3495
3496 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3497
3498 /* let's count a new HTTP request as it's the first time we do it */
3499 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3500 if (ptr)
3501 stktable_data_cast(ptr, http_req_cnt)++;
3502
3503 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3504 if (ptr)
3505 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3506 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3507
3508 /* When the client triggers a 4xx from the server, it's most often due
3509 * to a missing object or permission. These events should be tracked
3510 * because if they happen often, it may indicate a brute force or a
3511 * vulnerability scan. Normally this is done when receiving the response
3512 * but here we're tracking after this ought to have been done so we have
3513 * to do it on purpose.
3514 */
3515 if ((unsigned)(txn->status - 400) < 100) {
3516 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3517 if (ptr)
3518 stktable_data_cast(ptr, http_err_cnt)++;
3519
3520 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3521 if (ptr)
3522 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3523 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3524 }
3525
3526 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3527
3528 /* If data was modified, we need to touch to re-schedule sync */
3529 stktable_touch_local(t, ts, 0);
3530
3531 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3532 if (sess->fe != s->be)
3533 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3534 }
3535 }
3536 break;
3537
3538 case ACT_CUSTOM:
3539 if ((s->req.flags & CF_READ_ERROR) ||
3540 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003541 (px->options & PR_O_ABRT_CLOSE)))
3542 act_flags |= ACT_FLAG_FINAL;
3543
3544 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3545 case ACT_RET_ERR:
3546 case ACT_RET_CONT:
3547 break;
3548 case ACT_RET_STOP:
3549 rule_ret = HTTP_RULE_RES_STOP;
3550 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003551 case ACT_RET_DONE:
3552 rule_ret = HTTP_RULE_RES_DONE;
3553 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003554 case ACT_RET_YIELD:
3555 s->current_rule = rule;
3556 rule_ret = HTTP_RULE_RES_YIELD;
3557 goto end;
3558 }
3559 break;
3560
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003561 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003562 default:
3563 break;
3564 }
3565 }
3566
3567 end:
3568 /* we reached the end of the rules, nothing to report */
3569 return rule_ret;
3570}
3571
Christopher Faulet33640082018-10-24 11:53:01 +02003572/* Iterate the same filter through all request headers.
3573 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3574 * Since it can manage the switch to another backend, it updates the per-proxy
3575 * DENY stats.
3576 */
3577static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3578{
3579 struct http_txn *txn = s->txn;
3580 struct htx *htx;
3581 struct buffer *hdr = get_trash_chunk();
3582 int32_t pos;
3583
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003584 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003585
Christopher Fauleta3f15502019-05-13 15:27:23 +02003586 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003587 struct htx_blk *blk = htx_get_blk(htx, pos);
3588 enum htx_blk_type type;
3589 struct ist n, v;
3590
3591 next_hdr:
3592 type = htx_get_blk_type(blk);
3593 if (type == HTX_BLK_EOH)
3594 break;
3595 if (type != HTX_BLK_HDR)
3596 continue;
3597
3598 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3599 return 1;
3600 else if (unlikely(txn->flags & TX_CLALLOW) &&
3601 (exp->action == ACT_ALLOW ||
3602 exp->action == ACT_DENY ||
3603 exp->action == ACT_TARPIT))
3604 return 0;
3605
3606 n = htx_get_blk_name(htx, blk);
3607 v = htx_get_blk_value(htx, blk);
3608
Christopher Faulet02e771a2019-02-26 15:36:05 +01003609 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003610 hdr->area[hdr->data++] = ':';
3611 hdr->area[hdr->data++] = ' ';
3612 chunk_memcat(hdr, v.ptr, v.len);
3613
3614 /* Now we have one header in <hdr> */
3615
3616 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3617 struct http_hdr_ctx ctx;
3618 int len;
3619
3620 switch (exp->action) {
3621 case ACT_ALLOW:
3622 txn->flags |= TX_CLALLOW;
3623 goto end;
3624
3625 case ACT_DENY:
3626 txn->flags |= TX_CLDENY;
3627 goto end;
3628
3629 case ACT_TARPIT:
3630 txn->flags |= TX_CLTARPIT;
3631 goto end;
3632
3633 case ACT_REPLACE:
3634 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3635 if (len < 0)
3636 return -1;
3637
3638 http_parse_header(ist2(trash.area, len), &n, &v);
3639 ctx.blk = blk;
3640 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003641 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003642 if (!http_replace_header(htx, &ctx, n, v))
3643 return -1;
3644 if (!ctx.blk)
3645 goto end;
3646 pos = htx_get_blk_pos(htx, blk);
3647 break;
3648
3649 case ACT_REMOVE:
3650 ctx.blk = blk;
3651 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003652 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003653 if (!http_remove_header(htx, &ctx))
3654 return -1;
3655 if (!ctx.blk)
3656 goto end;
3657 pos = htx_get_blk_pos(htx, blk);
3658 goto next_hdr;
3659
3660 }
3661 }
3662 }
3663 end:
3664 return 0;
3665}
3666
3667/* Apply the filter to the request line.
3668 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3669 * or -1 if a replacement resulted in an invalid request line.
3670 * Since it can manage the switch to another backend, it updates the per-proxy
3671 * DENY stats.
3672 */
3673static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3674{
3675 struct http_txn *txn = s->txn;
3676 struct htx *htx;
3677 struct buffer *reqline = get_trash_chunk();
3678 int done;
3679
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003680 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003681
3682 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3683 return 1;
3684 else if (unlikely(txn->flags & TX_CLALLOW) &&
3685 (exp->action == ACT_ALLOW ||
3686 exp->action == ACT_DENY ||
3687 exp->action == ACT_TARPIT))
3688 return 0;
3689 else if (exp->action == ACT_REMOVE)
3690 return 0;
3691
3692 done = 0;
3693
Christopher Faulet297fbb42019-05-13 14:41:27 +02003694 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003695
3696 /* Now we have the request line between cur_ptr and cur_end */
3697 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003698 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003699 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003700 int len;
3701
3702 switch (exp->action) {
3703 case ACT_ALLOW:
3704 txn->flags |= TX_CLALLOW;
3705 done = 1;
3706 break;
3707
3708 case ACT_DENY:
3709 txn->flags |= TX_CLDENY;
3710 done = 1;
3711 break;
3712
3713 case ACT_TARPIT:
3714 txn->flags |= TX_CLTARPIT;
3715 done = 1;
3716 break;
3717
3718 case ACT_REPLACE:
3719 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3720 if (len < 0)
3721 return -1;
3722
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003723 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3724 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3725 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003726 return -1;
3727 done = 1;
3728 break;
3729 }
3730 }
3731 return done;
3732}
3733
3734/*
3735 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3736 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3737 * unparsable request. Since it can manage the switch to another backend, it
3738 * updates the per-proxy DENY stats.
3739 */
3740static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3741{
3742 struct session *sess = s->sess;
3743 struct http_txn *txn = s->txn;
3744 struct hdr_exp *exp;
3745
3746 for (exp = px->req_exp; exp; exp = exp->next) {
3747 int ret;
3748
3749 /*
3750 * The interleaving of transformations and verdicts
3751 * makes it difficult to decide to continue or stop
3752 * the evaluation.
3753 */
3754
3755 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3756 break;
3757
3758 if ((txn->flags & TX_CLALLOW) &&
3759 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3760 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3761 continue;
3762
3763 /* if this filter had a condition, evaluate it now and skip to
3764 * next filter if the condition does not match.
3765 */
3766 if (exp->cond) {
3767 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3768 ret = acl_pass(ret);
3769 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3770 ret = !ret;
3771
3772 if (!ret)
3773 continue;
3774 }
3775
3776 /* Apply the filter to the request line. */
3777 ret = htx_apply_filter_to_req_line(s, req, exp);
3778 if (unlikely(ret < 0))
3779 return -1;
3780
3781 if (likely(ret == 0)) {
3782 /* The filter did not match the request, it can be
3783 * iterated through all headers.
3784 */
3785 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3786 return -1;
3787 }
3788 }
3789 return 0;
3790}
3791
3792/* Iterate the same filter through all response headers contained in <res>.
3793 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3794 */
3795static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3796{
3797 struct http_txn *txn = s->txn;
3798 struct htx *htx;
3799 struct buffer *hdr = get_trash_chunk();
3800 int32_t pos;
3801
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003802 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003803
Christopher Fauleta3f15502019-05-13 15:27:23 +02003804 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003805 struct htx_blk *blk = htx_get_blk(htx, pos);
3806 enum htx_blk_type type;
3807 struct ist n, v;
3808
3809 next_hdr:
3810 type = htx_get_blk_type(blk);
3811 if (type == HTX_BLK_EOH)
3812 break;
3813 if (type != HTX_BLK_HDR)
3814 continue;
3815
3816 if (unlikely(txn->flags & TX_SVDENY))
3817 return 1;
3818 else if (unlikely(txn->flags & TX_SVALLOW) &&
3819 (exp->action == ACT_ALLOW ||
3820 exp->action == ACT_DENY))
3821 return 0;
3822
3823 n = htx_get_blk_name(htx, blk);
3824 v = htx_get_blk_value(htx, blk);
3825
Christopher Faulet02e771a2019-02-26 15:36:05 +01003826 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003827 hdr->area[hdr->data++] = ':';
3828 hdr->area[hdr->data++] = ' ';
3829 chunk_memcat(hdr, v.ptr, v.len);
3830
3831 /* Now we have one header in <hdr> */
3832
3833 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3834 struct http_hdr_ctx ctx;
3835 int len;
3836
3837 switch (exp->action) {
3838 case ACT_ALLOW:
3839 txn->flags |= TX_SVALLOW;
3840 goto end;
3841 break;
3842
3843 case ACT_DENY:
3844 txn->flags |= TX_SVDENY;
3845 goto end;
3846 break;
3847
3848 case ACT_REPLACE:
3849 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3850 if (len < 0)
3851 return -1;
3852
3853 http_parse_header(ist2(trash.area, len), &n, &v);
3854 ctx.blk = blk;
3855 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003856 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003857 if (!http_replace_header(htx, &ctx, n, v))
3858 return -1;
3859 if (!ctx.blk)
3860 goto end;
3861 pos = htx_get_blk_pos(htx, blk);
3862 break;
3863
3864 case ACT_REMOVE:
3865 ctx.blk = blk;
3866 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003867 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003868 if (!http_remove_header(htx, &ctx))
3869 return -1;
3870 if (!ctx.blk)
3871 goto end;
3872 pos = htx_get_blk_pos(htx, blk);
3873 goto next_hdr;
3874 }
3875 }
3876
3877 }
3878 end:
3879 return 0;
3880}
3881
3882/* Apply the filter to the status line in the response buffer <res>.
3883 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3884 * or -1 if a replacement resulted in an invalid status line.
3885 */
3886static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3887{
3888 struct http_txn *txn = s->txn;
3889 struct htx *htx;
3890 struct buffer *resline = get_trash_chunk();
3891 int done;
3892
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003893 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003894
3895 if (unlikely(txn->flags & TX_SVDENY))
3896 return 1;
3897 else if (unlikely(txn->flags & TX_SVALLOW) &&
3898 (exp->action == ACT_ALLOW ||
3899 exp->action == ACT_DENY))
3900 return 0;
3901 else if (exp->action == ACT_REMOVE)
3902 return 0;
3903
3904 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003905 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003906
3907 /* Now we have the status line between cur_ptr and cur_end */
3908 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003909 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003910 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003911 int len;
3912
3913 switch (exp->action) {
3914 case ACT_ALLOW:
3915 txn->flags |= TX_SVALLOW;
3916 done = 1;
3917 break;
3918
3919 case ACT_DENY:
3920 txn->flags |= TX_SVDENY;
3921 done = 1;
3922 break;
3923
3924 case ACT_REPLACE:
3925 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3926 if (len < 0)
3927 return -1;
3928
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003929 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3930 sl->info.res.status = strl2ui(code.ptr, code.len);
3931 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003932 return -1;
3933
3934 done = 1;
3935 return 1;
3936 }
3937 }
3938 return done;
3939}
3940
3941/*
3942 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3943 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3944 * unparsable response.
3945 */
3946static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3947{
3948 struct session *sess = s->sess;
3949 struct http_txn *txn = s->txn;
3950 struct hdr_exp *exp;
3951
3952 for (exp = px->rsp_exp; exp; exp = exp->next) {
3953 int ret;
3954
3955 /*
3956 * The interleaving of transformations and verdicts
3957 * makes it difficult to decide to continue or stop
3958 * the evaluation.
3959 */
3960
3961 if (txn->flags & TX_SVDENY)
3962 break;
3963
3964 if ((txn->flags & TX_SVALLOW) &&
3965 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3966 exp->action == ACT_PASS)) {
3967 exp = exp->next;
3968 continue;
3969 }
3970
3971 /* if this filter had a condition, evaluate it now and skip to
3972 * next filter if the condition does not match.
3973 */
3974 if (exp->cond) {
3975 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3976 ret = acl_pass(ret);
3977 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3978 ret = !ret;
3979 if (!ret)
3980 continue;
3981 }
3982
3983 /* Apply the filter to the status line. */
3984 ret = htx_apply_filter_to_sts_line(s, res, exp);
3985 if (unlikely(ret < 0))
3986 return -1;
3987
3988 if (likely(ret == 0)) {
3989 /* The filter did not match the response, it can be
3990 * iterated through all headers.
3991 */
3992 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3993 return -1;
3994 }
3995 }
3996 return 0;
3997}
3998
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003999/*
4000 * Manage client-side cookie. It can impact performance by about 2% so it is
4001 * desirable to call it only when needed. This code is quite complex because
4002 * of the multiple very crappy and ambiguous syntaxes we have to support. it
4003 * highly recommended not to touch this part without a good reason !
4004 */
4005static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
4006{
4007 struct session *sess = s->sess;
4008 struct http_txn *txn = s->txn;
4009 struct htx *htx;
4010 struct http_hdr_ctx ctx;
4011 char *hdr_beg, *hdr_end, *del_from;
4012 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4013 int preserve_hdr;
4014
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004015 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004016 ctx.blk = NULL;
4017 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004018 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004019 del_from = NULL; /* nothing to be deleted */
4020 preserve_hdr = 0; /* assume we may kill the whole header */
4021
4022 /* Now look for cookies. Conforming to RFC2109, we have to support
4023 * attributes whose name begin with a '$', and associate them with
4024 * the right cookie, if we want to delete this cookie.
4025 * So there are 3 cases for each cookie read :
4026 * 1) it's a special attribute, beginning with a '$' : ignore it.
4027 * 2) it's a server id cookie that we *MAY* want to delete : save
4028 * some pointers on it (last semi-colon, beginning of cookie...)
4029 * 3) it's an application cookie : we *MAY* have to delete a previous
4030 * "special" cookie.
4031 * At the end of loop, if a "special" cookie remains, we may have to
4032 * remove it. If no application cookie persists in the header, we
4033 * *MUST* delete it.
4034 *
4035 * Note: RFC2965 is unclear about the processing of spaces around
4036 * the equal sign in the ATTR=VALUE form. A careful inspection of
4037 * the RFC explicitly allows spaces before it, and not within the
4038 * tokens (attrs or values). An inspection of RFC2109 allows that
4039 * too but section 10.1.3 lets one think that spaces may be allowed
4040 * after the equal sign too, resulting in some (rare) buggy
4041 * implementations trying to do that. So let's do what servers do.
4042 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4043 * allowed quoted strings in values, with any possible character
4044 * after a backslash, including control chars and delimitors, which
4045 * causes parsing to become ambiguous. Browsers also allow spaces
4046 * within values even without quotes.
4047 *
4048 * We have to keep multiple pointers in order to support cookie
4049 * removal at the beginning, middle or end of header without
4050 * corrupting the header. All of these headers are valid :
4051 *
4052 * hdr_beg hdr_end
4053 * | |
4054 * v |
4055 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4056 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4057 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4058 * | | | | | | |
4059 * | | | | | | |
4060 * | | | | | | +--> next
4061 * | | | | | +----> val_end
4062 * | | | | +-----------> val_beg
4063 * | | | +--------------> equal
4064 * | | +----------------> att_end
4065 * | +---------------------> att_beg
4066 * +--------------------------> prev
4067 *
4068 */
4069 hdr_beg = ctx.value.ptr;
4070 hdr_end = hdr_beg + ctx.value.len;
4071 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4072 /* Iterate through all cookies on this line */
4073
4074 /* find att_beg */
4075 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004076 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004077 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004078 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004079
4080 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4081 att_beg++;
4082
4083 /* find att_end : this is the first character after the last non
4084 * space before the equal. It may be equal to hdr_end.
4085 */
4086 equal = att_end = att_beg;
4087 while (equal < hdr_end) {
4088 if (*equal == '=' || *equal == ',' || *equal == ';')
4089 break;
4090 if (HTTP_IS_SPHT(*equal++))
4091 continue;
4092 att_end = equal;
4093 }
4094
4095 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4096 * is between <att_beg> and <equal>, both may be identical.
4097 */
4098 /* look for end of cookie if there is an equal sign */
4099 if (equal < hdr_end && *equal == '=') {
4100 /* look for the beginning of the value */
4101 val_beg = equal + 1;
4102 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4103 val_beg++;
4104
4105 /* find the end of the value, respecting quotes */
4106 next = http_find_cookie_value_end(val_beg, hdr_end);
4107
4108 /* make val_end point to the first white space or delimitor after the value */
4109 val_end = next;
4110 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4111 val_end--;
4112 }
4113 else
4114 val_beg = val_end = next = equal;
4115
4116 /* We have nothing to do with attributes beginning with
4117 * '$'. However, they will automatically be removed if a
4118 * header before them is removed, since they're supposed
4119 * to be linked together.
4120 */
4121 if (*att_beg == '$')
4122 continue;
4123
4124 /* Ignore cookies with no equal sign */
4125 if (equal == next) {
4126 /* This is not our cookie, so we must preserve it. But if we already
4127 * scheduled another cookie for removal, we cannot remove the
4128 * complete header, but we can remove the previous block itself.
4129 */
4130 preserve_hdr = 1;
4131 if (del_from != NULL) {
4132 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4133 val_end += delta;
4134 next += delta;
4135 hdr_end += delta;
4136 prev = del_from;
4137 del_from = NULL;
4138 }
4139 continue;
4140 }
4141
4142 /* if there are spaces around the equal sign, we need to
4143 * strip them otherwise we'll get trouble for cookie captures,
4144 * or even for rewrites. Since this happens extremely rarely,
4145 * it does not hurt performance.
4146 */
4147 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4148 int stripped_before = 0;
4149 int stripped_after = 0;
4150
4151 if (att_end != equal) {
4152 memmove(att_end, equal, hdr_end - equal);
4153 stripped_before = (att_end - equal);
4154 equal += stripped_before;
4155 val_beg += stripped_before;
4156 }
4157
4158 if (val_beg > equal + 1) {
4159 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4160 stripped_after = (equal + 1) - val_beg;
4161 val_beg += stripped_after;
4162 stripped_before += stripped_after;
4163 }
4164
4165 val_end += stripped_before;
4166 next += stripped_before;
4167 hdr_end += stripped_before;
4168 }
4169 /* now everything is as on the diagram above */
4170
4171 /* First, let's see if we want to capture this cookie. We check
4172 * that we don't already have a client side cookie, because we
4173 * can only capture one. Also as an optimisation, we ignore
4174 * cookies shorter than the declared name.
4175 */
4176 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4177 (val_end - att_beg >= sess->fe->capture_namelen) &&
4178 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4179 int log_len = val_end - att_beg;
4180
4181 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4182 ha_alert("HTTP logging : out of memory.\n");
4183 } else {
4184 if (log_len > sess->fe->capture_len)
4185 log_len = sess->fe->capture_len;
4186 memcpy(txn->cli_cookie, att_beg, log_len);
4187 txn->cli_cookie[log_len] = 0;
4188 }
4189 }
4190
4191 /* Persistence cookies in passive, rewrite or insert mode have the
4192 * following form :
4193 *
4194 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4195 *
4196 * For cookies in prefix mode, the form is :
4197 *
4198 * Cookie: NAME=SRV~VALUE
4199 */
4200 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4201 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4202 struct server *srv = s->be->srv;
4203 char *delim;
4204
4205 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4206 * have the server ID between val_beg and delim, and the original cookie between
4207 * delim+1 and val_end. Otherwise, delim==val_end :
4208 *
4209 * hdr_beg
4210 * |
4211 * v
4212 * NAME=SRV; # in all but prefix modes
4213 * NAME=SRV~OPAQUE ; # in prefix mode
4214 * || || | |+-> next
4215 * || || | +--> val_end
4216 * || || +---------> delim
4217 * || |+------------> val_beg
4218 * || +-------------> att_end = equal
4219 * |+-----------------> att_beg
4220 * +------------------> prev
4221 *
4222 */
4223 if (s->be->ck_opts & PR_CK_PFX) {
4224 for (delim = val_beg; delim < val_end; delim++)
4225 if (*delim == COOKIE_DELIM)
4226 break;
4227 }
4228 else {
4229 char *vbar1;
4230 delim = val_end;
4231 /* Now check if the cookie contains a date field, which would
4232 * appear after a vertical bar ('|') just after the server name
4233 * and before the delimiter.
4234 */
4235 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4236 if (vbar1) {
4237 /* OK, so left of the bar is the server's cookie and
4238 * right is the last seen date. It is a base64 encoded
4239 * 30-bit value representing the UNIX date since the
4240 * epoch in 4-second quantities.
4241 */
4242 int val;
4243 delim = vbar1++;
4244 if (val_end - vbar1 >= 5) {
4245 val = b64tos30(vbar1);
4246 if (val > 0)
4247 txn->cookie_last_date = val << 2;
4248 }
4249 /* look for a second vertical bar */
4250 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4251 if (vbar1 && (val_end - vbar1 > 5)) {
4252 val = b64tos30(vbar1 + 1);
4253 if (val > 0)
4254 txn->cookie_first_date = val << 2;
4255 }
4256 }
4257 }
4258
4259 /* if the cookie has an expiration date and the proxy wants to check
4260 * it, then we do that now. We first check if the cookie is too old,
4261 * then only if it has expired. We detect strict overflow because the
4262 * time resolution here is not great (4 seconds). Cookies with dates
4263 * in the future are ignored if their offset is beyond one day. This
4264 * allows an admin to fix timezone issues without expiring everyone
4265 * and at the same time avoids keeping unwanted side effects for too
4266 * long.
4267 */
4268 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4269 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4270 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4271 txn->flags &= ~TX_CK_MASK;
4272 txn->flags |= TX_CK_OLD;
4273 delim = val_beg; // let's pretend we have not found the cookie
4274 txn->cookie_first_date = 0;
4275 txn->cookie_last_date = 0;
4276 }
4277 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4278 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4279 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4280 txn->flags &= ~TX_CK_MASK;
4281 txn->flags |= TX_CK_EXPIRED;
4282 delim = val_beg; // let's pretend we have not found the cookie
4283 txn->cookie_first_date = 0;
4284 txn->cookie_last_date = 0;
4285 }
4286
4287 /* Here, we'll look for the first running server which supports the cookie.
4288 * This allows to share a same cookie between several servers, for example
4289 * to dedicate backup servers to specific servers only.
4290 * However, to prevent clients from sticking to cookie-less backup server
4291 * when they have incidentely learned an empty cookie, we simply ignore
4292 * empty cookies and mark them as invalid.
4293 * The same behaviour is applied when persistence must be ignored.
4294 */
4295 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4296 srv = NULL;
4297
4298 while (srv) {
4299 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4300 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4301 if ((srv->cur_state != SRV_ST_STOPPED) ||
4302 (s->be->options & PR_O_PERSIST) ||
4303 (s->flags & SF_FORCE_PRST)) {
4304 /* we found the server and we can use it */
4305 txn->flags &= ~TX_CK_MASK;
4306 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4307 s->flags |= SF_DIRECT | SF_ASSIGNED;
4308 s->target = &srv->obj_type;
4309 break;
4310 } else {
4311 /* we found a server, but it's down,
4312 * mark it as such and go on in case
4313 * another one is available.
4314 */
4315 txn->flags &= ~TX_CK_MASK;
4316 txn->flags |= TX_CK_DOWN;
4317 }
4318 }
4319 srv = srv->next;
4320 }
4321
4322 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4323 /* no server matched this cookie or we deliberately skipped it */
4324 txn->flags &= ~TX_CK_MASK;
4325 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4326 txn->flags |= TX_CK_UNUSED;
4327 else
4328 txn->flags |= TX_CK_INVALID;
4329 }
4330
4331 /* depending on the cookie mode, we may have to either :
4332 * - delete the complete cookie if we're in insert+indirect mode, so that
4333 * the server never sees it ;
4334 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004335 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004336 * if we're in cookie prefix mode
4337 */
4338 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4339 int delta; /* negative */
4340
4341 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4342 delta = val_beg - (delim + 1);
4343 val_end += delta;
4344 next += delta;
4345 hdr_end += delta;
4346 del_from = NULL;
4347 preserve_hdr = 1; /* we want to keep this cookie */
4348 }
4349 else if (del_from == NULL &&
4350 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4351 del_from = prev;
4352 }
4353 }
4354 else {
4355 /* This is not our cookie, so we must preserve it. But if we already
4356 * scheduled another cookie for removal, we cannot remove the
4357 * complete header, but we can remove the previous block itself.
4358 */
4359 preserve_hdr = 1;
4360
4361 if (del_from != NULL) {
4362 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4363 if (att_beg >= del_from)
4364 att_beg += delta;
4365 if (att_end >= del_from)
4366 att_end += delta;
4367 val_beg += delta;
4368 val_end += delta;
4369 next += delta;
4370 hdr_end += delta;
4371 prev = del_from;
4372 del_from = NULL;
4373 }
4374 }
4375
4376 /* continue with next cookie on this header line */
4377 att_beg = next;
4378 } /* for each cookie */
4379
4380
4381 /* There are no more cookies on this line.
4382 * We may still have one (or several) marked for deletion at the
4383 * end of the line. We must do this now in two ways :
4384 * - if some cookies must be preserved, we only delete from the
4385 * mark to the end of line ;
4386 * - if nothing needs to be preserved, simply delete the whole header
4387 */
4388 if (del_from) {
4389 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4390 }
4391 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004392 if (hdr_beg != hdr_end)
4393 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004394 else
4395 http_remove_header(htx, &ctx);
4396 }
4397 } /* for each "Cookie header */
4398}
4399
4400/*
4401 * Manage server-side cookies. It can impact performance by about 2% so it is
4402 * desirable to call it only when needed. This function is also used when we
4403 * just need to know if there is a cookie (eg: for check-cache).
4404 */
4405static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4406{
4407 struct session *sess = s->sess;
4408 struct http_txn *txn = s->txn;
4409 struct htx *htx;
4410 struct http_hdr_ctx ctx;
4411 struct server *srv;
4412 char *hdr_beg, *hdr_end;
4413 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004414 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004415
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004416 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004417
4418 ctx.blk = NULL;
4419 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004420 int is_first = 1;
4421
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004422 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4423 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4424 break;
4425 is_cookie2 = 1;
4426 }
4427
4428 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4429 * <prev> points to the colon.
4430 */
4431 txn->flags |= TX_SCK_PRESENT;
4432
4433 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4434 * check-cache is enabled) and we are not interested in checking
4435 * them. Warning, the cookie capture is declared in the frontend.
4436 */
4437 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4438 break;
4439
4440 /* OK so now we know we have to process this response cookie.
4441 * The format of the Set-Cookie header is slightly different
4442 * from the format of the Cookie header in that it does not
4443 * support the comma as a cookie delimiter (thus the header
4444 * cannot be folded) because the Expires attribute described in
4445 * the original Netscape's spec may contain an unquoted date
4446 * with a comma inside. We have to live with this because
4447 * many browsers don't support Max-Age and some browsers don't
4448 * support quoted strings. However the Set-Cookie2 header is
4449 * clean.
4450 *
4451 * We have to keep multiple pointers in order to support cookie
4452 * removal at the beginning, middle or end of header without
4453 * corrupting the header (in case of set-cookie2). A special
4454 * pointer, <scav> points to the beginning of the set-cookie-av
4455 * fields after the first semi-colon. The <next> pointer points
4456 * either to the end of line (set-cookie) or next unquoted comma
4457 * (set-cookie2). All of these headers are valid :
4458 *
4459 * hdr_beg hdr_end
4460 * | |
4461 * v |
4462 * NAME1 = VALUE 1 ; Secure; Path="/" |
4463 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4464 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4465 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4466 * | | | | | | | |
4467 * | | | | | | | +-> next
4468 * | | | | | | +------------> scav
4469 * | | | | | +--------------> val_end
4470 * | | | | +--------------------> val_beg
4471 * | | | +----------------------> equal
4472 * | | +------------------------> att_end
4473 * | +----------------------------> att_beg
4474 * +------------------------------> prev
4475 * -------------------------------> hdr_beg
4476 */
4477 hdr_beg = ctx.value.ptr;
4478 hdr_end = hdr_beg + ctx.value.len;
4479 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4480
4481 /* Iterate through all cookies on this line */
4482
4483 /* find att_beg */
4484 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004485 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004486 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004487 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004488
4489 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4490 att_beg++;
4491
4492 /* find att_end : this is the first character after the last non
4493 * space before the equal. It may be equal to hdr_end.
4494 */
4495 equal = att_end = att_beg;
4496
4497 while (equal < hdr_end) {
4498 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4499 break;
4500 if (HTTP_IS_SPHT(*equal++))
4501 continue;
4502 att_end = equal;
4503 }
4504
4505 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4506 * is between <att_beg> and <equal>, both may be identical.
4507 */
4508
4509 /* look for end of cookie if there is an equal sign */
4510 if (equal < hdr_end && *equal == '=') {
4511 /* look for the beginning of the value */
4512 val_beg = equal + 1;
4513 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4514 val_beg++;
4515
4516 /* find the end of the value, respecting quotes */
4517 next = http_find_cookie_value_end(val_beg, hdr_end);
4518
4519 /* make val_end point to the first white space or delimitor after the value */
4520 val_end = next;
4521 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4522 val_end--;
4523 }
4524 else {
4525 /* <equal> points to next comma, semi-colon or EOL */
4526 val_beg = val_end = next = equal;
4527 }
4528
4529 if (next < hdr_end) {
4530 /* Set-Cookie2 supports multiple cookies, and <next> points to
4531 * a colon or semi-colon before the end. So skip all attr-value
4532 * pairs and look for the next comma. For Set-Cookie, since
4533 * commas are permitted in values, skip to the end.
4534 */
4535 if (is_cookie2)
4536 next = http_find_hdr_value_end(next, hdr_end);
4537 else
4538 next = hdr_end;
4539 }
4540
4541 /* Now everything is as on the diagram above */
4542
4543 /* Ignore cookies with no equal sign */
4544 if (equal == val_end)
4545 continue;
4546
4547 /* If there are spaces around the equal sign, we need to
4548 * strip them otherwise we'll get trouble for cookie captures,
4549 * or even for rewrites. Since this happens extremely rarely,
4550 * it does not hurt performance.
4551 */
4552 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4553 int stripped_before = 0;
4554 int stripped_after = 0;
4555
4556 if (att_end != equal) {
4557 memmove(att_end, equal, hdr_end - equal);
4558 stripped_before = (att_end - equal);
4559 equal += stripped_before;
4560 val_beg += stripped_before;
4561 }
4562
4563 if (val_beg > equal + 1) {
4564 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4565 stripped_after = (equal + 1) - val_beg;
4566 val_beg += stripped_after;
4567 stripped_before += stripped_after;
4568 }
4569
4570 val_end += stripped_before;
4571 next += stripped_before;
4572 hdr_end += stripped_before;
4573
Christopher Faulet41dc8432019-06-18 09:49:16 +02004574 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004575 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004576 }
4577
4578 /* First, let's see if we want to capture this cookie. We check
4579 * that we don't already have a server side cookie, because we
4580 * can only capture one. Also as an optimisation, we ignore
4581 * cookies shorter than the declared name.
4582 */
4583 if (sess->fe->capture_name != NULL &&
4584 txn->srv_cookie == NULL &&
4585 (val_end - att_beg >= sess->fe->capture_namelen) &&
4586 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4587 int log_len = val_end - att_beg;
4588 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4589 ha_alert("HTTP logging : out of memory.\n");
4590 }
4591 else {
4592 if (log_len > sess->fe->capture_len)
4593 log_len = sess->fe->capture_len;
4594 memcpy(txn->srv_cookie, att_beg, log_len);
4595 txn->srv_cookie[log_len] = 0;
4596 }
4597 }
4598
4599 srv = objt_server(s->target);
4600 /* now check if we need to process it for persistence */
4601 if (!(s->flags & SF_IGNORE_PRST) &&
4602 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4603 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4604 /* assume passive cookie by default */
4605 txn->flags &= ~TX_SCK_MASK;
4606 txn->flags |= TX_SCK_FOUND;
4607
4608 /* If the cookie is in insert mode on a known server, we'll delete
4609 * this occurrence because we'll insert another one later.
4610 * We'll delete it too if the "indirect" option is set and we're in
4611 * a direct access.
4612 */
4613 if (s->be->ck_opts & PR_CK_PSV) {
4614 /* The "preserve" flag was set, we don't want to touch the
4615 * server's cookie.
4616 */
4617 }
4618 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4619 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4620 /* this cookie must be deleted */
4621 if (prev == hdr_beg && next == hdr_end) {
4622 /* whole header */
4623 http_remove_header(htx, &ctx);
4624 /* note: while both invalid now, <next> and <hdr_end>
4625 * are still equal, so the for() will stop as expected.
4626 */
4627 } else {
4628 /* just remove the value */
4629 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4630 next = prev;
4631 hdr_end += delta;
4632 }
4633 txn->flags &= ~TX_SCK_MASK;
4634 txn->flags |= TX_SCK_DELETED;
4635 /* and go on with next cookie */
4636 }
4637 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4638 /* replace bytes val_beg->val_end with the cookie name associated
4639 * with this server since we know it.
4640 */
4641 int sliding, delta;
4642
4643 ctx.value = ist2(val_beg, val_end - val_beg);
4644 ctx.lws_before = ctx.lws_after = 0;
4645 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4646 delta = srv->cklen - (val_end - val_beg);
4647 sliding = (ctx.value.ptr - val_beg);
4648 hdr_beg += sliding;
4649 val_beg += sliding;
4650 next += sliding + delta;
4651 hdr_end += sliding + delta;
4652
4653 txn->flags &= ~TX_SCK_MASK;
4654 txn->flags |= TX_SCK_REPLACED;
4655 }
4656 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4657 /* insert the cookie name associated with this server
4658 * before existing cookie, and insert a delimiter between them..
4659 */
4660 int sliding, delta;
4661 ctx.value = ist2(val_beg, 0);
4662 ctx.lws_before = ctx.lws_after = 0;
4663 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4664 delta = srv->cklen + 1;
4665 sliding = (ctx.value.ptr - val_beg);
4666 hdr_beg += sliding;
4667 val_beg += sliding;
4668 next += sliding + delta;
4669 hdr_end += sliding + delta;
4670
4671 val_beg[srv->cklen] = COOKIE_DELIM;
4672 txn->flags &= ~TX_SCK_MASK;
4673 txn->flags |= TX_SCK_REPLACED;
4674 }
4675 }
4676 /* that's done for this cookie, check the next one on the same
4677 * line when next != hdr_end (only if is_cookie2).
4678 */
4679 }
4680 }
4681}
4682
Christopher Faulet25a02f62018-10-24 12:00:25 +02004683/*
4684 * Parses the Cache-Control and Pragma request header fields to determine if
4685 * the request may be served from the cache and/or if it is cacheable. Updates
4686 * s->txn->flags.
4687 */
4688void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4689{
4690 struct http_txn *txn = s->txn;
4691 struct htx *htx;
4692 int32_t pos;
4693 int pragma_found, cc_found, i;
4694
4695 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4696 return; /* nothing more to do here */
4697
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004698 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004699 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004700 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004701 struct htx_blk *blk = htx_get_blk(htx, pos);
4702 enum htx_blk_type type = htx_get_blk_type(blk);
4703 struct ist n, v;
4704
4705 if (type == HTX_BLK_EOH)
4706 break;
4707 if (type != HTX_BLK_HDR)
4708 continue;
4709
4710 n = htx_get_blk_name(htx, blk);
4711 v = htx_get_blk_value(htx, blk);
4712
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004713 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004714 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4715 pragma_found = 1;
4716 continue;
4717 }
4718 }
4719
4720 /* Don't use the cache and don't try to store if we found the
4721 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004722 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 txn->flags |= TX_CACHE_IGNORE;
4725 continue;
4726 }
4727
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004728 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004729 continue;
4730
4731 /* OK, right now we know we have a cache-control header */
4732 cc_found = 1;
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). We don't check the
4742 * values after max-age, max-stale nor min-fresh, we simply don't
4743 * use the cache when they're specified.
4744 */
4745 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4746 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4747 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4748 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4749 txn->flags |= TX_CACHE_IGNORE;
4750 continue;
4751 }
4752
4753 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4754 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4755 continue;
4756 }
4757 }
4758
4759 /* RFC7234#5.4:
4760 * When the Cache-Control header field is also present and
4761 * understood in a request, Pragma is ignored.
4762 * When the Cache-Control header field is not present in a
4763 * request, caches MUST consider the no-cache request
4764 * pragma-directive as having the same effect as if
4765 * "Cache-Control: no-cache" were present.
4766 */
4767 if (!cc_found && pragma_found)
4768 txn->flags |= TX_CACHE_IGNORE;
4769}
4770
4771/*
4772 * Check if response is cacheable or not. Updates s->txn->flags.
4773 */
4774void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4775{
4776 struct http_txn *txn = s->txn;
4777 struct htx *htx;
4778 int32_t pos;
4779 int i;
4780
4781 if (txn->status < 200) {
4782 /* do not try to cache interim responses! */
4783 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4784 return;
4785 }
4786
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004787 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004788 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004789 struct htx_blk *blk = htx_get_blk(htx, pos);
4790 enum htx_blk_type type = htx_get_blk_type(blk);
4791 struct ist n, v;
4792
4793 if (type == HTX_BLK_EOH)
4794 break;
4795 if (type != HTX_BLK_HDR)
4796 continue;
4797
4798 n = htx_get_blk_name(htx, blk);
4799 v = htx_get_blk_value(htx, blk);
4800
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004801 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004802 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4803 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4804 return;
4805 }
4806 }
4807
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004808 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004809 continue;
4810
4811 /* OK, right now we know we have a cache-control header */
4812 if (!v.len) /* no info */
4813 continue;
4814
4815 i = 0;
4816 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4817 !isspace((unsigned char)*(v.ptr+i)))
4818 i++;
4819
4820 /* we have a complete value between v.ptr and (v.ptr+i) */
4821 if (i < v.len && *(v.ptr + i) == '=') {
4822 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4823 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4824 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4825 continue;
4826 }
4827
4828 /* we have something of the form no-cache="set-cookie" */
4829 if ((v.len >= 21) &&
4830 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4831 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4832 txn->flags &= ~TX_CACHE_COOK;
4833 continue;
4834 }
4835
4836 /* OK, so we know that either p2 points to the end of string or to a comma */
4837 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4838 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4839 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4840 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4841 return;
4842 }
4843
4844 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4845 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4846 continue;
4847 }
4848 }
4849}
4850
Christopher Faulet64159df2018-10-24 21:15:35 +02004851/* send a server's name with an outgoing request over an established connection.
4852 * Note: this function is designed to be called once the request has been
4853 * scheduled for being forwarded. This is the reason why the number of forwarded
4854 * bytes have to be adjusted.
4855 */
4856int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4857{
4858 struct htx *htx;
4859 struct http_hdr_ctx ctx;
4860 struct ist hdr;
4861 uint32_t data;
4862
4863 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004864 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004865 data = htx->data;
4866
4867 ctx.blk = NULL;
4868 while (http_find_header(htx, hdr, &ctx, 1))
4869 http_remove_header(htx, &ctx);
4870 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4871
4872 if (co_data(&s->req)) {
4873 if (data >= htx->data)
4874 c_rew(&s->req, data - htx->data);
4875 else
4876 c_adv(&s->req, htx->data - data);
4877 }
4878 return 0;
4879}
4880
Christopher Faulet377c5a52018-10-24 21:21:30 +02004881/*
4882 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4883 * for the current backend.
4884 *
4885 * It is assumed that the request is either a HEAD, GET, or POST and that the
4886 * uri_auth field is valid.
4887 *
4888 * Returns 1 if stats should be provided, otherwise 0.
4889 */
4890static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4891{
4892 struct uri_auth *uri_auth = backend->uri_auth;
4893 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004894 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004895 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004896
4897 if (!uri_auth)
4898 return 0;
4899
4900 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4901 return 0;
4902
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004903 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004904 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004905 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004906
4907 /* check URI size */
4908 if (uri_auth->uri_len > uri.len)
4909 return 0;
4910
4911 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4912 return 0;
4913
4914 return 1;
4915}
4916
4917/* This function prepares an applet to handle the stats. It can deal with the
4918 * "100-continue" expectation, check that admin rules are met for POST requests,
4919 * and program a response message if something was unexpected. It cannot fail
4920 * and always relies on the stats applet to complete the job. It does not touch
4921 * analysers nor counters, which are left to the caller. It does not touch
4922 * s->target which is supposed to already point to the stats applet. The caller
4923 * is expected to have already assigned an appctx to the stream.
4924 */
4925static int htx_handle_stats(struct stream *s, struct channel *req)
4926{
4927 struct stats_admin_rule *stats_admin_rule;
4928 struct stream_interface *si = &s->si[1];
4929 struct session *sess = s->sess;
4930 struct http_txn *txn = s->txn;
4931 struct http_msg *msg = &txn->req;
4932 struct uri_auth *uri_auth = s->be->uri_auth;
4933 const char *h, *lookup, *end;
4934 struct appctx *appctx;
4935 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004936 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004937
4938 appctx = si_appctx(si);
4939 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4940 appctx->st1 = appctx->st2 = 0;
4941 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4942 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4943 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4944 appctx->ctx.stats.flags |= STAT_CHUNKED;
4945
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004946 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004947 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004948 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4949 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004950
4951 for (h = lookup; h <= end - 3; h++) {
4952 if (memcmp(h, ";up", 3) == 0) {
4953 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4954 break;
4955 }
4956 }
4957
4958 if (uri_auth->refresh) {
4959 for (h = lookup; h <= end - 10; h++) {
4960 if (memcmp(h, ";norefresh", 10) == 0) {
4961 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4962 break;
4963 }
4964 }
4965 }
4966
4967 for (h = lookup; h <= end - 4; h++) {
4968 if (memcmp(h, ";csv", 4) == 0) {
4969 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4970 break;
4971 }
4972 }
4973
4974 for (h = lookup; h <= end - 6; h++) {
4975 if (memcmp(h, ";typed", 6) == 0) {
4976 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4977 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4978 break;
4979 }
4980 }
4981
4982 for (h = lookup; h <= end - 8; h++) {
4983 if (memcmp(h, ";st=", 4) == 0) {
4984 int i;
4985 h += 4;
4986 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4987 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4988 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4989 appctx->ctx.stats.st_code = i;
4990 break;
4991 }
4992 }
4993 break;
4994 }
4995 }
4996
4997 appctx->ctx.stats.scope_str = 0;
4998 appctx->ctx.stats.scope_len = 0;
4999 for (h = lookup; h <= end - 8; h++) {
5000 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
5001 int itx = 0;
5002 const char *h2;
5003 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
5004 const char *err;
5005
5006 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
5007 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01005008 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
5009 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005010 if (*h == ';' || *h == '&' || *h == ' ')
5011 break;
5012 itx++;
5013 h++;
5014 }
5015
5016 if (itx > STAT_SCOPE_TXT_MAXLEN)
5017 itx = STAT_SCOPE_TXT_MAXLEN;
5018 appctx->ctx.stats.scope_len = itx;
5019
5020 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5021 memcpy(scope_txt, h2, itx);
5022 scope_txt[itx] = '\0';
5023 err = invalid_char(scope_txt);
5024 if (err) {
5025 /* bad char in search text => clear scope */
5026 appctx->ctx.stats.scope_str = 0;
5027 appctx->ctx.stats.scope_len = 0;
5028 }
5029 break;
5030 }
5031 }
5032
5033 /* now check whether we have some admin rules for this request */
5034 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5035 int ret = 1;
5036
5037 if (stats_admin_rule->cond) {
5038 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5039 ret = acl_pass(ret);
5040 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5041 ret = !ret;
5042 }
5043
5044 if (ret) {
5045 /* no rule, or the rule matches */
5046 appctx->ctx.stats.flags |= STAT_ADMIN;
5047 break;
5048 }
5049 }
5050
Christopher Faulet5d45e382019-02-27 15:15:23 +01005051 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5052 appctx->st0 = STAT_HTTP_HEAD;
5053 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005054 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005055 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005056 if (msg->msg_state < HTTP_MSG_DATA)
5057 req->analysers |= AN_REQ_HTTP_BODY;
5058 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005059 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005060 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005061 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5062 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5063 appctx->st0 = STAT_HTTP_LAST;
5064 }
5065 }
5066 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005067 /* Unsupported method */
5068 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5069 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5070 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005071 }
5072
5073 s->task->nice = -32; /* small boost for HTTP statistics */
5074 return 1;
5075}
5076
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005077void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5078{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005079 struct channel *req = &s->req;
5080 struct channel *res = &s->res;
5081 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005082 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005083 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005084 struct ist path, location;
5085 unsigned int flags;
5086 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005087
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005088 /*
5089 * Create the location
5090 */
5091 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005092
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005093 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005094 /* special prefix "/" means don't change URL */
5095 srv = __objt_server(s->target);
5096 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5097 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5098 return;
5099 }
5100
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005101 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005102 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005103 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005104 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005105 if (!path.ptr)
5106 return;
5107
5108 if (!chunk_memcat(&trash, path.ptr, path.len))
5109 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005110 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005111
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005112 /*
5113 * Create the 302 respone
5114 */
5115 htx = htx_from_buf(&res->buf);
5116 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5117 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5118 ist("HTTP/1.1"), ist("302"), ist("Found"));
5119 if (!sl)
5120 goto fail;
5121 sl->info.res.status = 302;
5122 s->txn->status = 302;
5123
5124 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5125 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5126 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5127 !htx_add_header(htx, ist("Location"), location))
5128 goto fail;
5129
5130 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5131 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005132
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005133 /*
5134 * Send the message
5135 */
5136 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005137 c_adv(res, data);
5138 res->total += data;
5139
5140 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005141 si_shutr(si);
5142 si_shutw(si);
5143 si->err_type = SI_ET_NONE;
5144 si->state = SI_ST_CLO;
5145
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005146 channel_auto_read(req);
5147 channel_abort(req);
5148 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005149 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005150 channel_auto_read(res);
5151 channel_auto_close(res);
5152
5153 if (!(s->flags & SF_ERR_MASK))
5154 s->flags |= SF_ERR_LOCAL;
5155 if (!(s->flags & SF_FINST_MASK))
5156 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005157
5158 /* FIXME: we should increase a counter of redirects per server and per backend. */
5159 srv_inc_sess_ctr(srv);
5160 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005161 return;
5162
5163 fail:
5164 /* If an error occurred, remove the incomplete HTTP response from the
5165 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005166 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005167}
5168
Christopher Fauletf2824e62018-10-01 12:12:37 +02005169/* This function terminates the request because it was completly analyzed or
5170 * because an error was triggered during the body forwarding.
5171 */
5172static void htx_end_request(struct stream *s)
5173{
5174 struct channel *chn = &s->req;
5175 struct http_txn *txn = s->txn;
5176
5177 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5178 now_ms, __FUNCTION__, s,
5179 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5180 s->req.analysers, s->res.analysers);
5181
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005182 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5183 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005184 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005185 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005186 goto end;
5187 }
5188
5189 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5190 return;
5191
5192 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005193 /* No need to read anymore, the request was completely parsed.
5194 * We can shut the read side unless we want to abort_on_close,
5195 * or we have a POST request. The issue with POST requests is
5196 * that some browsers still send a CRLF after the request, and
5197 * this CRLF must be read so that it does not remain in the kernel
5198 * buffers, otherwise a close could cause an RST on some systems
5199 * (eg: Linux).
5200 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005201 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005202 channel_dont_read(chn);
5203
5204 /* if the server closes the connection, we want to immediately react
5205 * and close the socket to save packets and syscalls.
5206 */
5207 s->si[1].flags |= SI_FL_NOHALF;
5208
5209 /* In any case we've finished parsing the request so we must
5210 * disable Nagle when sending data because 1) we're not going
5211 * to shut this side, and 2) the server is waiting for us to
5212 * send pending data.
5213 */
5214 chn->flags |= CF_NEVER_WAIT;
5215
Christopher Fauletd01ce402019-01-02 17:44:13 +01005216 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5217 /* The server has not finished to respond, so we
5218 * don't want to move in order not to upset it.
5219 */
5220 return;
5221 }
5222
Christopher Fauletf2824e62018-10-01 12:12:37 +02005223 /* When we get here, it means that both the request and the
5224 * response have finished receiving. Depending on the connection
5225 * mode, we'll have to wait for the last bytes to leave in either
5226 * direction, and sometimes for a close to be effective.
5227 */
5228 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5229 /* Tunnel mode will not have any analyser so it needs to
5230 * poll for reads.
5231 */
5232 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005233 if (b_data(&chn->buf))
5234 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005235 txn->req.msg_state = HTTP_MSG_TUNNEL;
5236 }
5237 else {
5238 /* we're not expecting any new data to come for this
5239 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005240 *
5241 * However, there is an exception if the response
5242 * length is undefined. In this case, we need to wait
5243 * the close from the server. The response will be
5244 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005245 */
5246 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5247 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005248 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005249
5250 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5251 channel_shutr_now(chn);
5252 channel_shutw_now(chn);
5253 }
5254 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005255 goto check_channel_flags;
5256 }
5257
5258 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5259 http_msg_closing:
5260 /* nothing else to forward, just waiting for the output buffer
5261 * to be empty and for the shutw_now to take effect.
5262 */
5263 if (channel_is_empty(chn)) {
5264 txn->req.msg_state = HTTP_MSG_CLOSED;
5265 goto http_msg_closed;
5266 }
5267 else if (chn->flags & CF_SHUTW) {
5268 txn->req.err_state = txn->req.msg_state;
5269 txn->req.msg_state = HTTP_MSG_ERROR;
5270 goto end;
5271 }
5272 return;
5273 }
5274
5275 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5276 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005277 /* if we don't know whether the server will close, we need to hard close */
5278 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5279 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005280 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005281 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005282 channel_dont_read(chn);
5283 goto end;
5284 }
5285
5286 check_channel_flags:
5287 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5288 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5289 /* if we've just closed an output, let's switch */
5290 txn->req.msg_state = HTTP_MSG_CLOSING;
5291 goto http_msg_closing;
5292 }
5293
5294 end:
5295 chn->analysers &= AN_REQ_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005296 if (txn->req.msg_state == HTTP_MSG_TUNNEL) {
5297 chn->flags |= CF_NEVER_WAIT;
5298 if (HAS_REQ_DATA_FILTERS(s))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 chn->analysers |= AN_REQ_FLT_XFER_DATA;
Christopher Faulet86c82202020-12-15 13:32:55 +01005300 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005301 channel_auto_close(chn);
5302 channel_auto_read(chn);
5303}
5304
5305
5306/* This function terminates the response because it was completly analyzed or
5307 * because an error was triggered during the body forwarding.
5308 */
5309static void htx_end_response(struct stream *s)
5310{
5311 struct channel *chn = &s->res;
5312 struct http_txn *txn = s->txn;
5313
5314 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5315 now_ms, __FUNCTION__, s,
5316 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5317 s->req.analysers, s->res.analysers);
5318
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005319 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5320 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005321 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005322 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005323 goto end;
5324 }
5325
5326 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5327 return;
5328
5329 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5330 /* In theory, we don't need to read anymore, but we must
5331 * still monitor the server connection for a possible close
5332 * while the request is being uploaded, so we don't disable
5333 * reading.
5334 */
5335 /* channel_dont_read(chn); */
5336
5337 if (txn->req.msg_state < HTTP_MSG_DONE) {
5338 /* The client seems to still be sending data, probably
5339 * because we got an error response during an upload.
5340 * We have the choice of either breaking the connection
5341 * or letting it pass through. Let's do the later.
5342 */
5343 return;
5344 }
5345
5346 /* When we get here, it means that both the request and the
5347 * response have finished receiving. Depending on the connection
5348 * mode, we'll have to wait for the last bytes to leave in either
5349 * direction, and sometimes for a close to be effective.
5350 */
5351 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5352 channel_auto_read(chn);
5353 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005354 if (b_data(&chn->buf))
5355 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005356 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5357 }
5358 else {
5359 /* we're not expecting any new data to come for this
5360 * transaction, so we can close it.
5361 */
5362 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5363 channel_shutr_now(chn);
5364 channel_shutw_now(chn);
5365 }
5366 }
5367 goto check_channel_flags;
5368 }
5369
5370 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5371 http_msg_closing:
5372 /* nothing else to forward, just waiting for the output buffer
5373 * to be empty and for the shutw_now to take effect.
5374 */
5375 if (channel_is_empty(chn)) {
5376 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5377 goto http_msg_closed;
5378 }
5379 else if (chn->flags & CF_SHUTW) {
5380 txn->rsp.err_state = txn->rsp.msg_state;
5381 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005382 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005383 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005384 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005385 goto end;
5386 }
5387 return;
5388 }
5389
5390 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5391 http_msg_closed:
5392 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005393 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005394 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005395 goto end;
5396 }
5397
5398 check_channel_flags:
5399 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5400 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5401 /* if we've just closed an output, let's switch */
5402 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5403 goto http_msg_closing;
5404 }
5405
5406 end:
5407 chn->analysers &= AN_RES_FLT_END;
Christopher Faulet86c82202020-12-15 13:32:55 +01005408 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) {
5409 chn->flags |= CF_NEVER_WAIT;
5410 if (HAS_RSP_DATA_FILTERS(s))
5411 chn->analysers |= AN_RES_FLT_XFER_DATA;
5412 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005413 channel_auto_close(chn);
5414 channel_auto_read(chn);
5415}
5416
Christopher Faulet0f226952018-10-22 09:29:56 +02005417void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5418 int finst, const struct buffer *msg)
5419{
5420 channel_auto_read(si_oc(si));
5421 channel_abort(si_oc(si));
5422 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005423 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005424 channel_auto_close(si_ic(si));
5425 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005426
5427 /* <msg> is an HTX structure. So we copy it in the response's
5428 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005429 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005430 struct channel *chn = si_ic(si);
5431 struct htx *htx;
5432
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005433 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005434 chn->buf.data = msg->data;
5435 memcpy(chn->buf.area, msg->area, msg->data);
5436 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005437 if (s->txn->meth == HTTP_METH_HEAD)
5438 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005439 c_adv(chn, htx->data);
5440 chn->total += htx->data;
5441 }
5442 if (!(s->flags & SF_ERR_MASK))
5443 s->flags |= err;
5444 if (!(s->flags & SF_FINST_MASK))
5445 s->flags |= finst;
5446}
5447
5448void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5449{
5450 channel_auto_read(&s->req);
5451 channel_abort(&s->req);
5452 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005453 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5454 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005455
5456 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005457
5458 /* <msg> is an HTX structure. So we copy it in the response's
5459 * channel */
5460 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005461 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005462 struct channel *chn = &s->res;
5463 struct htx *htx;
5464
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005465 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005466 chn->buf.data = msg->data;
5467 memcpy(chn->buf.area, msg->area, msg->data);
5468 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005469 if (s->txn->meth == HTTP_METH_HEAD)
5470 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005471 c_adv(chn, htx->data);
5472 chn->total += htx->data;
5473 }
5474
5475 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5476 channel_auto_read(&s->res);
5477 channel_auto_close(&s->res);
5478 channel_shutr_now(&s->res);
5479}
5480
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005481struct buffer *htx_error_message(struct stream *s)
5482{
5483 const int msgnum = http_get_status_idx(s->txn->status);
5484
5485 if (s->be->errmsg[msgnum].area)
5486 return &s->be->errmsg[msgnum];
5487 else if (strm_fe(s)->errmsg[msgnum].area)
5488 return &strm_fe(s)->errmsg[msgnum];
5489 else
5490 return &htx_err_chunks[msgnum];
5491}
5492
5493
Christopher Faulet4a28a532019-03-01 11:19:40 +01005494/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5495 * on success and -1 on error.
5496 */
5497static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5498{
5499 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5500 * then we must send an HTTP/1.1 100 Continue intermediate response.
5501 */
5502 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5503 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5504 struct ist hdr = { .ptr = "Expect", .len = 6 };
5505 struct http_hdr_ctx ctx;
5506
5507 ctx.blk = NULL;
5508 /* Expect is allowed in 1.1, look for it */
5509 if (http_find_header(htx, hdr, &ctx, 0) &&
5510 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5511 if (htx_reply_100_continue(s) == -1)
5512 return -1;
5513 http_remove_header(htx, &ctx);
5514 }
5515 }
5516 return 0;
5517}
5518
Christopher Faulet23a3c792018-11-28 10:01:23 +01005519/* Send a 100-Continue response to the client. It returns 0 on success and -1
5520 * on error. The response channel is updated accordingly.
5521 */
5522static int htx_reply_100_continue(struct stream *s)
5523{
5524 struct channel *res = &s->res;
5525 struct htx *htx = htx_from_buf(&res->buf);
5526 struct htx_sl *sl;
5527 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5528 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5529 size_t data;
5530
5531 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5532 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5533 if (!sl)
5534 goto fail;
5535 sl->info.res.status = 100;
5536
Christopher Faulet9869f932019-06-26 14:23:54 +02005537 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005538 goto fail;
5539
5540 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005541 c_adv(res, data);
5542 res->total += data;
5543 return 0;
5544
5545 fail:
5546 /* If an error occurred, remove the incomplete HTTP response from the
5547 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005548 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005549 return -1;
5550}
5551
Christopher Faulet12c51e22018-11-28 15:59:42 +01005552
5553/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5554 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5555 * error. The response channel is updated accordingly.
5556 */
5557static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5558{
5559 struct channel *res = &s->res;
5560 struct htx *htx = htx_from_buf(&res->buf);
5561 struct htx_sl *sl;
5562 struct ist code, body;
5563 int status;
5564 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5565 size_t data;
5566
5567 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5568 status = 401;
5569 code = ist("401");
5570 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5571 "You need a valid user and password to access this content.\n"
5572 "</body></html>\n");
5573 }
5574 else {
5575 status = 407;
5576 code = ist("407");
5577 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5578 "You need a valid user and password to access this content.\n"
5579 "</body></html>\n");
5580 }
5581
5582 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5583 ist("HTTP/1.1"), code, ist("Unauthorized"));
5584 if (!sl)
5585 goto fail;
5586 sl->info.res.status = status;
5587 s->txn->status = status;
5588
5589 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5590 goto fail;
5591
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005592 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5593 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005594 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005595 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5596 goto fail;
5597 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5598 goto fail;
5599 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005600 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005601 if (!htx_add_endof(htx, HTX_BLK_EOH))
5602 goto fail;
5603
Christopher Faulete6ee4652020-10-19 18:01:38 +02005604 if (s->txn->meth == HTTP_METH_HEAD)
5605 body.len = 0;
5606
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005607 while (body.len) {
5608 size_t sent = htx_add_data(htx, body);
5609 if (!sent)
5610 goto fail;
5611 body.ptr += sent;
5612 body.len -= sent;
5613 }
5614
5615 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005616 goto fail;
5617
5618 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005619 c_adv(res, data);
5620 res->total += data;
5621
5622 channel_auto_read(&s->req);
5623 channel_abort(&s->req);
5624 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005625 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005626
5627 res->wex = tick_add_ifset(now_ms, res->wto);
5628 channel_auto_read(res);
5629 channel_auto_close(res);
5630 channel_shutr_now(res);
5631 return 0;
5632
5633 fail:
5634 /* If an error occurred, remove the incomplete HTTP response from the
5635 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005636 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005637 return -1;
5638}
5639
Christopher Faulet0f226952018-10-22 09:29:56 +02005640/*
5641 * Capture headers from message <htx> according to header list <cap_hdr>, and
5642 * fill the <cap> pointers appropriately.
5643 */
5644static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5645{
5646 struct cap_hdr *h;
5647 int32_t pos;
5648
Christopher Fauleta3f15502019-05-13 15:27:23 +02005649 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005650 struct htx_blk *blk = htx_get_blk(htx, pos);
5651 enum htx_blk_type type = htx_get_blk_type(blk);
5652 struct ist n, v;
5653
5654 if (type == HTX_BLK_EOH)
5655 break;
5656 if (type != HTX_BLK_HDR)
5657 continue;
5658
5659 n = htx_get_blk_name(htx, blk);
5660
5661 for (h = cap_hdr; h; h = h->next) {
5662 if (h->namelen && (h->namelen == n.len) &&
5663 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5664 if (cap[h->index] == NULL)
5665 cap[h->index] =
5666 pool_alloc(h->pool);
5667
5668 if (cap[h->index] == NULL) {
5669 ha_alert("HTTP capture : out of memory.\n");
5670 break;
5671 }
5672
5673 v = htx_get_blk_value(htx, blk);
5674 if (v.len > h->len)
5675 v.len = h->len;
5676
5677 memcpy(cap[h->index], v.ptr, v.len);
5678 cap[h->index][v.len]=0;
5679 }
5680 }
5681 }
5682}
5683
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005684/* Delete a value in a header between delimiters <from> and <next>. The header
5685 * itself is delimited by <start> and <end> pointers. The number of characters
5686 * displaced is returned, and the pointer to the first delimiter is updated if
5687 * required. The function tries as much as possible to respect the following
5688 * principles :
5689 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5690 * in which case <next> is simply removed
5691 * - set exactly one space character after the new first delimiter, unless there
5692 * are not enough characters in the block being moved to do so.
5693 * - remove unneeded spaces before the previous delimiter and after the new
5694 * one.
5695 *
5696 * It is the caller's responsibility to ensure that :
5697 * - <from> points to a valid delimiter or <start> ;
5698 * - <next> points to a valid delimiter or <end> ;
5699 * - there are non-space chars before <from>.
5700 */
5701static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5702{
5703 char *prev = *from;
5704
5705 if (prev == start) {
5706 /* We're removing the first value. eat the semicolon, if <next>
5707 * is lower than <end> */
5708 if (next < end)
5709 next++;
5710
5711 while (next < end && HTTP_IS_SPHT(*next))
5712 next++;
5713 }
5714 else {
5715 /* Remove useless spaces before the old delimiter. */
5716 while (HTTP_IS_SPHT(*(prev-1)))
5717 prev--;
5718 *from = prev;
5719
5720 /* copy the delimiter and if possible a space if we're
5721 * not at the end of the line.
5722 */
5723 if (next < end) {
5724 *prev++ = *next++;
5725 if (prev + 1 < next)
5726 *prev++ = ' ';
5727 while (next < end && HTTP_IS_SPHT(*next))
5728 next++;
5729 }
5730 }
5731 memmove(prev, next, end - next);
5732 return (prev - next);
5733}
5734
Christopher Faulet0f226952018-10-22 09:29:56 +02005735
5736/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005737 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005738 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005739static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005740{
5741 struct ist dst = ist2(str, 0);
5742
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005743 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005744 goto end;
5745 if (dst.len + 1 > len)
5746 goto end;
5747 dst.ptr[dst.len++] = ' ';
5748
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005749 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005750 goto end;
5751 if (dst.len + 1 > len)
5752 goto end;
5753 dst.ptr[dst.len++] = ' ';
5754
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005755 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005756 end:
5757 return dst.len;
5758}
5759
Christopher Fauletf0523542018-10-24 11:06:58 +02005760/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005761 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005762 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005763static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005764{
5765 struct ist dst = ist2(str, 0);
5766
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005767 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005768 goto end;
5769 if (dst.len + 1 > len)
5770 goto end;
5771 dst.ptr[dst.len++] = ' ';
5772
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005773 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005774 goto end;
5775 if (dst.len + 1 > len)
5776 goto end;
5777 dst.ptr[dst.len++] = ' ';
5778
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005779 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005780 end:
5781 return dst.len;
5782}
5783
5784
Christopher Faulet0f226952018-10-22 09:29:56 +02005785/*
5786 * Print a debug line with a start line.
5787 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005788static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005789{
5790 struct session *sess = strm_sess(s);
5791 int max;
5792
5793 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5794 dir,
5795 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5796 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5797
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005798 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005799 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005800 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005801 trash.area[trash.data++] = ' ';
5802
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005803 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005804 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005805 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005806 trash.area[trash.data++] = ' ';
5807
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005808 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005809 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005810 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005811 trash.area[trash.data++] = '\n';
5812
5813 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5814}
5815
5816/*
5817 * Print a debug line with a header.
5818 */
5819static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5820{
5821 struct session *sess = strm_sess(s);
5822 int max;
5823
5824 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5825 dir,
5826 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5827 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5828
5829 max = n.len;
5830 UBOUND(max, trash.size - trash.data - 3);
5831 chunk_memcat(&trash, n.ptr, max);
5832 trash.area[trash.data++] = ':';
5833 trash.area[trash.data++] = ' ';
5834
5835 max = v.len;
5836 UBOUND(max, trash.size - trash.data - 1);
5837 chunk_memcat(&trash, v.ptr, max);
5838 trash.area[trash.data++] = '\n';
5839
5840 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5841}
5842
5843
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005844__attribute__((constructor))
5845static void __htx_protocol_init(void)
5846{
5847}
5848
5849
5850/*
5851 * Local variables:
5852 * c-indent-level: 8
5853 * c-basic-offset: 8
5854 * End:
5855 */