blob: ea1e20f178314fa6e2ef8c152718a32d4711a19a [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulet9768c262018-10-22 09:34:31 +0200150 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 stream_inc_http_req_ctr(s);
152 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100153 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100155 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200156
Christopher Faulet9768c262018-10-22 09:34:31 +0200157 txn->status = 400;
158 msg->err_state = msg->msg_state;
159 msg->msg_state = HTTP_MSG_ERROR;
160 htx_reply_and_close(s, txn->status, NULL);
161 req->analysers &= AN_REQ_FLT_END;
162
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (!(s->flags & SF_FINST_MASK))
164 s->flags |= SF_FINST_R;
165 return 0;
166 }
167
Christopher Faulet9768c262018-10-22 09:34:31 +0200168 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200169 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
170 if (!(s->flags & SF_ERR_MASK))
171 s->flags |= SF_ERR_CLITO;
172
173 if (txn->flags & TX_WAIT_NEXT_RQ)
174 goto failed_keep_alive;
175
176 if (sess->fe->options & PR_O_IGNORE_PRB)
177 goto failed_keep_alive;
178
Christopher Faulet9768c262018-10-22 09:34:31 +0200179 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200180 stream_inc_http_req_ctr(s);
181 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100184 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200185
Christopher Faulet9768c262018-10-22 09:34:31 +0200186 txn->status = 408;
187 msg->err_state = msg->msg_state;
188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100189 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200190 req->analysers &= AN_REQ_FLT_END;
191
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (!(s->flags & SF_FINST_MASK))
193 s->flags |= SF_FINST_R;
194 return 0;
195 }
196
Christopher Faulet9768c262018-10-22 09:34:31 +0200197 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200198 else if (req->flags & CF_SHUTR) {
199 if (!(s->flags & SF_ERR_MASK))
200 s->flags |= SF_ERR_CLICL;
201
202 if (txn->flags & TX_WAIT_NEXT_RQ)
203 goto failed_keep_alive;
204
205 if (sess->fe->options & PR_O_IGNORE_PRB)
206 goto failed_keep_alive;
207
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 stream_inc_http_err_ctr(s);
209 stream_inc_http_req_ctr(s);
210 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100213 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200214
Christopher Faulet9768c262018-10-22 09:34:31 +0200215 txn->status = 400;
216 msg->err_state = msg->msg_state;
217 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100218 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200219 req->analysers &= AN_REQ_FLT_END;
220
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (!(s->flags & SF_FINST_MASK))
222 s->flags |= SF_FINST_R;
223 return 0;
224 }
225
226 channel_dont_connect(req);
227 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
228 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100229
Christopher Faulet9768c262018-10-22 09:34:31 +0200230 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
232 /* We need more data, we have to re-enable quick-ack in case we
233 * previously disabled it, otherwise we might cause the client
234 * to delay next data.
235 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet47365272018-10-31 17:40:50 +0100239 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 /* If the client starts to talk, let's fall back to
241 * request timeout processing.
242 */
243 txn->flags &= ~TX_WAIT_NEXT_RQ;
244 req->analyse_exp = TICK_ETERNITY;
245 }
246
247 /* just set the request timeout once at the beginning of the request */
248 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
251 else
252 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
253 }
254
255 /* we're not ready yet */
256 return 0;
257
258 failed_keep_alive:
259 /* Here we process low-level errors for keep-alive requests. In
260 * short, if the request is not the first one and it experiences
261 * a timeout, read error or shutdown, we just silently close so
262 * that the client can try again.
263 */
264 txn->status = 0;
265 msg->msg_state = HTTP_MSG_RQBEFORE;
266 req->analysers &= AN_REQ_FLT_END;
267 s->logs.logwait = 0;
268 s->logs.level = 0;
269 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200270 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200271 return 0;
272 }
273
Christopher Faulet9768c262018-10-22 09:34:31 +0200274 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200275 stream_inc_http_req_ctr(s);
276 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 /* kill the pending keep-alive timeout */
279 txn->flags &= ~TX_WAIT_NEXT_RQ;
280 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281
Christopher Faulet29f17582019-05-23 11:03:26 +0200282 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200283 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100284
Christopher Faulet9768c262018-10-22 09:34:31 +0200285 /* 0: we might have to print this header in debug mode */
286 if (unlikely((global.mode & MODE_DEBUG) &&
287 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
288 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200289
Christopher Faulet03599112018-11-27 11:21:21 +0100290 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200291
Christopher Fauleta3f15502019-05-13 15:27:23 +0200292 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 struct htx_blk *blk = htx_get_blk(htx, pos);
294 enum htx_blk_type type = htx_get_blk_type(blk);
295
296 if (type == HTX_BLK_EOH)
297 break;
298 if (type != HTX_BLK_HDR)
299 continue;
300
301 htx_debug_hdr("clihdr", s,
302 htx_get_blk_name(htx, blk),
303 htx_get_blk_value(htx, blk));
304 }
305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306
307 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100308 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200309 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100310 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200312 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100313 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100314 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100315 if (sl->flags & HTX_SL_F_BODYLESS)
316 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /* we can make use of server redirect on GET and HEAD */
319 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
320 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 goto return_bad_req;
324 }
325
326 /*
327 * 2: check if the URI matches the monitor_uri.
328 * We have to do this for every request which gets in, because
329 * the monitor-uri is defined by the frontend.
330 */
331 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet943ab4d2020-02-18 14:51:51 +0100332 isteq(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /*
334 * We have found the monitor URI
335 */
336 struct acl_cond *cond;
337
338 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200340
341 /* Check if we want to fail this monitor request or not */
342 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
343 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
344
345 ret = acl_pass(ret);
346 if (cond->pol == ACL_COND_UNLESS)
347 ret = !ret;
348
349 if (ret) {
350 /* we fail this request, let's return 503 service unavail */
351 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100352 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200353 if (!(s->flags & SF_ERR_MASK))
354 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
355 goto return_prx_cond;
356 }
357 }
358
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800359 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366
367 /*
368 * 3: Maybe we have to copy the original REQURI for the logs ?
369 * Note: we cannot log anymore if the request has been
370 * classified as invalid.
371 */
372 if (unlikely(s->logs.logwait & LW_REQ)) {
373 /* we have a complete HTTP request that we must log */
374 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulet9768c262018-10-22 09:34:31 +0200377 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
378 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200379
380 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
381 s->do_log(s);
382 } else {
383 ha_alert("HTTP logging : out of memory.\n");
384 }
385 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387 /* if the frontend has "option http-use-proxy-header", we'll check if
388 * we have what looks like a proxied connection instead of a connection,
389 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
390 * Note that this is *not* RFC-compliant, however browsers and proxies
391 * happen to do that despite being non-standard :-(
392 * We consider that a request not beginning with either '/' or '*' is
393 * a proxied connection, which covers both "scheme://location" and
394 * CONNECT ip:port.
395 */
396 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100397 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 txn->flags |= TX_USE_PX_CONN;
399
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400 /* 5: we may need to capture headers */
401 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200402 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100404 /* by default, close the stream at the end of the transaction. */
405 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100441 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100444 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
Olivier Houchard629693f2020-01-23 14:57:36 +0100527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_SSL_WAIT_HS))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Faulet4629d082019-07-04 11:27:15 +0200543 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100548 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200556 htx_handle_stats(s, req);
557 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
567 /* evaluate the req* rules except reqadd */
568 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200569 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200570 goto return_bad_req;
571
572 if (txn->flags & TX_CLDENY)
573 goto deny;
574
575 if (txn->flags & TX_CLTARPIT) {
576 deny_status = HTTP_ERR_500;
577 goto tarpit;
578 }
579 }
580
581 /* add request headers from the rule sets in the same order */
582 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200583 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200584 if (wl->cond) {
585 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
586 ret = acl_pass(ret);
587 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
588 ret = !ret;
589 if (!ret)
590 continue;
591 }
592
Christopher Fauletff2759f2018-10-24 11:13:16 +0200593 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
594 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 goto return_bad_req;
596 }
597
Christopher Faulet2571bc62019-03-01 11:44:26 +0100598 /* Proceed with the applets now. */
599 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100601 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100603 if (htx_handle_expect_hdr(s, htx, msg) == -1)
604 goto return_bad_req;
605
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
607 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
608 if (!(s->flags & SF_FINST_MASK))
609 s->flags |= SF_FINST_R;
610
611 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
612 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
613 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
614 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100615
616 req->flags |= CF_SEND_DONTWAIT;
617 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100666 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100685 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100698 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100704 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100766 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100775 struct htx_sl *sl;
776 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100784 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200793 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100794 uri = htx_sl_req_uri(sl);
795 path = http_get_path(uri);
796 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797 goto return_bad_req;
798
799 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 * uri.ptr and path.ptr (excluded). If it was not found, we need
801 * to replace from all the uri by a single "/".
802 *
803 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100804 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau3284dd22019-07-18 16:17:15 +0200808 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 }
810
811 /*
812 * 7: Now we can work with the cookies.
813 * Note that doing so might move headers in the request, but
814 * the fields will stay coherent and the URI will not move.
815 * This should only be performed in the backend.
816 */
817 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100818 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819
820 /* add unique-id if "header-unique-id" is specified */
821
822 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
823 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
824 goto return_bad_req;
825 s->unique_id[0] = '\0';
826 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
827 }
828
829 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200830 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
831 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
832
833 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 }
836
837 /*
838 * 9: add X-Forwarded-For if either the frontend or the backend
839 * asks for it.
840 */
841 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200842 struct http_hdr_ctx ctx = { .blk = NULL };
843 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
844 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
845
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200848 /* The header is set to be added only if none is present
849 * and we found it, so don't do anything.
850 */
851 }
852 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
853 /* Add an X-Forwarded-For header unless the source IP is
854 * in the 'except' network range.
855 */
856 if ((!sess->fe->except_mask.s_addr ||
857 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
858 != sess->fe->except_net.s_addr) &&
859 (!s->be->except_mask.s_addr ||
860 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
861 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863
864 /* Note: we rely on the backend to get the header name to be used for
865 * x-forwarded-for, because the header is really meant for the backends.
866 * However, if the backend did not specify any option, we have to rely
867 * on the frontend's header name.
868 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
870 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200871 goto return_bad_req;
872 }
873 }
874 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
875 /* FIXME: for the sake of completeness, we should also support
876 * 'except' here, although it is mostly useless in this case.
877 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200879
Christopher Faulete0768eb2018-10-03 16:38:02 +0200880 inet_ntop(AF_INET6,
881 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
882 pn, sizeof(pn));
883
884 /* Note: we rely on the backend to get the header name to be used for
885 * x-forwarded-for, because the header is really meant for the backends.
886 * However, if the backend did not specify any option, we have to rely
887 * on the frontend's header name.
888 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200889 chunk_printf(&trash, "%s", pn);
890 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 goto return_bad_req;
892 }
893 }
894
895 /*
896 * 10: add X-Original-To if either the frontend or the backend
897 * asks for it.
898 */
899 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
900
901 /* FIXME: don't know if IPv6 can handle that case too. */
902 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
903 /* Add an X-Original-To header unless the destination IP is
904 * in the 'except' network range.
905 */
906 conn_get_to_addr(cli_conn);
907
908 if (cli_conn->addr.to.ss_family == AF_INET &&
909 ((!sess->fe->except_mask_to.s_addr ||
910 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
911 != sess->fe->except_to.s_addr) &&
912 (!s->be->except_mask_to.s_addr ||
913 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
914 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200915 struct ist hdr;
916 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200917
918 /* Note: we rely on the backend to get the header name to be used for
919 * x-original-to, because the header is really meant for the backends.
920 * However, if the backend did not specify any option, we have to rely
921 * on the frontend's header name.
922 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200923 if (s->be->orgto_hdr_len)
924 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
925 else
926 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200927
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
929 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200930 goto return_bad_req;
931 }
932 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 }
934
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 /* If we have no server assigned yet and we're balancing on url_param
936 * with a POST request, we may be interested in checking the body for
937 * that parameter. This will be done in another analyser.
938 */
939 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100940 s->txn->meth == HTTP_METH_POST &&
941 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100948
Christopher Faulete0768eb2018-10-03 16:38:02 +0200949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200955 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957
958 /*************************************************************
959 * OK, that's finished for the headers. We have done what we *
960 * could. Let's switch to the DATA state. *
961 ************************************************************/
962 req->analyse_exp = TICK_ETERNITY;
963 req->analysers &= ~an_bit;
964
965 s->logs.tv_request = now;
966 /* OK let's go on with the BODY now */
967 return 1;
968
969 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200970 txn->req.err_state = txn->req.msg_state;
971 txn->req.msg_state = HTTP_MSG_ERROR;
972 txn->status = 400;
973 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100974 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100978 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_R;
984 return 0;
985}
986
987/* This function is an analyser which processes the HTTP tarpit. It always
988 * returns zero, at the beginning because it prevents any other processing
989 * from occurring, and at the end because it terminates the request.
990 */
991int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
992{
993 struct http_txn *txn = s->txn;
994
995 /* This connection is being tarpitted. The CLIENT side has
996 * already set the connect expiration date to the right
997 * timeout. We just have to check that the client is still
998 * there and that the timeout has not expired.
999 */
1000 channel_dont_connect(req);
1001 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1002 !tick_is_expired(req->analyse_exp, now_ms))
1003 return 0;
1004
1005 /* We will set the queue timer to the time spent, just for
1006 * logging purposes. We fake a 500 server error, so that the
1007 * attacker will not suspect his connection has been tarpitted.
1008 * It will not cause trouble to the logs because we can exclude
1009 * the tarpitted connections by filtering on the 'PT' status flags.
1010 */
1011 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1012
Christopher Fauletef9a1692020-02-21 10:20:46 +01001013 htx_reply_and_close(s, txn->status, (!(req->flags & CF_READ_ERROR) ? htx_error_message(s) : NULL));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001066 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1067 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 }
1069
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001070 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1073 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001075 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001076 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 goto http_end;
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1081 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001082 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
1084 if (!(s->flags & SF_ERR_MASK))
1085 s->flags |= SF_ERR_CLITO;
1086 if (!(s->flags & SF_FINST_MASK))
1087 s->flags |= SF_FINST_D;
1088 goto return_err_msg;
1089 }
1090
1091 /* we get here if we need to wait for more data */
1092 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1093 /* Not enough data. We'll re-use the http-request
1094 * timeout here. Ideally, we should set the timeout
1095 * relative to the accept() date. We just set the
1096 * request timeout once at the beginning of the
1097 * request.
1098 */
1099 channel_dont_connect(req);
1100 if (!tick_isset(req->analyse_exp))
1101 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1102 return 0;
1103 }
1104
1105 http_end:
1106 /* The situation will not evolve, so let's give up on the analysis. */
1107 s->logs.tv_request = now; /* update the request timer to reflect full request */
1108 req->analysers &= ~an_bit;
1109 req->analyse_exp = TICK_ETERNITY;
1110 return 1;
1111
1112 return_bad_req: /* let's centralize all bad requests */
1113 txn->req.err_state = txn->req.msg_state;
1114 txn->req.msg_state = HTTP_MSG_ERROR;
1115 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001116 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001117
1118 if (!(s->flags & SF_ERR_MASK))
1119 s->flags |= SF_ERR_PRXCOND;
1120 if (!(s->flags & SF_FINST_MASK))
1121 s->flags |= SF_FINST_R;
1122
1123 return_err_msg:
1124 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128 return 0;
1129}
1130
1131/* This function is an analyser which forwards request body (including chunk
1132 * sizes if any). It is called as soon as we must forward, even if we forward
1133 * zero byte. The only situation where it must not be called is when we're in
1134 * tunnel mode and we want to forward till the close. It's used both to forward
1135 * remaining data and to resync after end of body. It expects the msg_state to
1136 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1137 * read more data, or 1 once we can go on with next request or end the stream.
1138 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1139 * bytes of pending data + the headers if not already done.
1140 */
1141int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1142{
1143 struct session *sess = s->sess;
1144 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001145 struct http_msg *msg = &txn->req;
1146 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001147 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001148 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001149
1150 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1151 now_ms, __FUNCTION__,
1152 s,
1153 req,
1154 req->rex, req->wex,
1155 req->flags,
1156 ci_data(req),
1157 req->analysers);
1158
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001159 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1162 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1163 /* Output closed while we were sending data. We must abort and
1164 * wake the other side up.
1165 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001166 /* Don't abort yet if we had L7 retries activated and it
1167 * was a write error, we may recover.
1168 */
1169 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1170 (s->si[1].flags & SI_FL_L7_RETRY))
1171 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001172 msg->err_state = msg->msg_state;
1173 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001174 htx_end_request(s);
1175 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 return 1;
1177 }
1178
1179 /* Note that we don't have to send 100-continue back because we don't
1180 * need the data to complete our job, and it's up to the server to
1181 * decide whether to return 100, 417 or anything else in return of
1182 * an "Expect: 100-continue" header.
1183 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001184 if (msg->msg_state == HTTP_MSG_BODY)
1185 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 /* Some post-connect processing might want us to refrain from starting to
1188 * forward data. Currently, the only reason for this is "balance url_param"
1189 * whichs need to parse/process the request after we've enabled forwarding.
1190 */
1191 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1192 if (!(s->res.flags & CF_READ_ATTACHED)) {
1193 channel_auto_connect(req);
1194 req->flags |= CF_WAKE_CONNECT;
1195 channel_dont_close(req); /* don't fail on early shutr */
1196 goto waiting;
1197 }
1198 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1199 }
1200
1201 /* in most states, we should abort in case of early close */
1202 channel_auto_close(req);
1203
1204 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001205 if (req->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001206 if (req->flags & CF_EOI)
1207 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01001208 }
1209 else {
1210 /* We can't process the buffer's contents yet */
1211 req->flags |= CF_WAKE_WRITE;
1212 goto missing_data_or_waiting;
1213 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001214 }
1215
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001216 if (msg->msg_state >= HTTP_MSG_ENDING)
1217 goto ending;
1218
1219 if (txn->meth == HTTP_METH_CONNECT) {
1220 msg->msg_state = HTTP_MSG_ENDING;
1221 goto ending;
1222 }
1223
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 /* Forward input data. We get it by removing all outgoing data not
1225 * forwarded yet from HTX data size. If there are some data filters, we
1226 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 if (HAS_REQ_DATA_FILTERS(s)) {
1229 ret = flt_http_payload(s, msg, htx->data);
1230 if (ret < 0)
1231 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001232 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001233 }
1234 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001235 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001236 if (msg->flags & HTTP_MSGF_XFER_LEN)
1237 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001238 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001239
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001240 if (htx->data != co_data(req))
1241 goto missing_data_or_waiting;
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001242
Christopher Faulet9768c262018-10-22 09:34:31 +02001243 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001244 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1245 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001246 */
1247 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1248 goto missing_data_or_waiting;
1249
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001250 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02001251
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001252 ending:
1253 /* other states, ENDING...TUNNEL */
1254 if (msg->msg_state >= HTTP_MSG_DONE)
1255 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001256
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001257 if (HAS_REQ_DATA_FILTERS(s)) {
1258 ret = flt_http_end(s, msg);
1259 if (ret <= 0) {
1260 if (!ret)
1261 goto missing_data_or_waiting;
1262 goto return_bad_req;
1263 }
1264 }
1265
Christopher Fauletbe7c5522019-11-15 16:31:46 +01001266 if (txn->meth == HTTP_METH_CONNECT)
1267 msg->msg_state = HTTP_MSG_TUNNEL;
1268 else {
1269 msg->msg_state = HTTP_MSG_DONE;
1270 req->to_forward = 0;
1271 }
1272
1273 done:
1274 /* we don't want to forward closes on DONE except in tunnel mode. */
1275 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1276 channel_dont_close(req);
1277
Christopher Fauletf2824e62018-10-01 12:12:37 +02001278 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001279 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001280 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1282 if (req->flags & CF_SHUTW) {
1283 /* request errors are most likely due to the
1284 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001285 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001287 goto return_bad_req;
1288 }
1289 return 1;
1290 }
1291
1292 /* If "option abortonclose" is set on the backend, we want to monitor
1293 * the client's connection and forward any shutdown notification to the
1294 * server, which will decide whether to close or to go on processing the
1295 * request. We only do that in tunnel mode, and not in other modes since
1296 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001297 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001298 channel_auto_read(req);
1299 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1300 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1301 s->si[1].flags |= SI_FL_NOLINGER;
1302 channel_auto_close(req);
1303 }
1304 else if (s->txn->meth == HTTP_METH_POST) {
1305 /* POST requests may require to read extra CRLF sent by broken
1306 * browsers and which could cause an RST to be sent upon close
1307 * on some systems (eg: Linux). */
1308 channel_auto_read(req);
1309 }
1310 return 0;
1311
1312 missing_data_or_waiting:
1313 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001314 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001316
1317 waiting:
1318 /* waiting for the last bits to leave the buffer */
1319 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001320 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321
Christopher Faulet47365272018-10-31 17:40:50 +01001322 if (htx->flags & HTX_FL_PARSING_ERROR)
1323 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001324
Christopher Faulete0768eb2018-10-03 16:38:02 +02001325 /* When TE: chunked is used, we need to get there again to parse remaining
1326 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1327 * And when content-length is used, we never want to let the possible
1328 * shutdown be forwarded to the other side, as the state machine will
1329 * take care of it once the client responds. It's also important to
1330 * prevent TIME_WAITs from accumulating on the backend side, and for
1331 * HTTP/2 where the last frame comes with a shutdown.
1332 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001333 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001334 channel_dont_close(req);
1335
1336 /* We know that more data are expected, but we couldn't send more that
1337 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1338 * system knows it must not set a PUSH on this first part. Interactive
1339 * modes are already handled by the stream sock layer. We must not do
1340 * this in content-length mode because it could present the MSG_MORE
1341 * flag with the last block of forwarded data, which would cause an
1342 * additional delay to be observed by the receiver.
1343 */
1344 if (msg->flags & HTTP_MSGF_TE_CHNK)
1345 req->flags |= CF_EXPECT_MORE;
1346
1347 return 0;
1348
Christopher Faulet93e02d82019-03-08 14:18:50 +01001349 return_cli_abort:
1350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1351 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1352 if (objt_server(s->target))
1353 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1354 if (!(s->flags & SF_ERR_MASK))
1355 s->flags |= SF_ERR_CLICL;
1356 status = 400;
1357 goto return_error;
1358
1359 return_srv_abort:
1360 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1361 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1362 if (objt_server(s->target))
1363 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1364 if (!(s->flags & SF_ERR_MASK))
1365 s->flags |= SF_ERR_SRVCL;
1366 status = 502;
1367 goto return_error;
1368
1369 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001370 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001372 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001374 s->flags |= SF_ERR_CLICL;
1375 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001376
Christopher Faulet93e02d82019-03-08 14:18:50 +01001377 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 txn->req.err_state = txn->req.msg_state;
1379 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001380 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001382 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001384 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001385 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 }
1387 req->analysers &= AN_REQ_FLT_END;
1388 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001389 if (!(s->flags & SF_FINST_MASK))
1390 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 return 0;
1392}
1393
Olivier Houcharda254a372019-04-05 15:30:12 +02001394/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1395/* Returns 0 if we can attempt to retry, -1 otherwise */
1396static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1397{
1398 struct channel *req, *res;
1399 int co_data;
1400
1401 si->conn_retries--;
1402 if (si->conn_retries < 0)
1403 return -1;
1404
Willy Tarreau223995e2019-05-04 10:38:31 +02001405 if (objt_server(s->target))
1406 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1407 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1408
Olivier Houcharda254a372019-04-05 15:30:12 +02001409 req = &s->req;
1410 res = &s->res;
1411 /* Remove any write error from the request, and read error from the response */
1412 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1413 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1414 res->analysers = 0;
1415 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchardc86a9662020-05-12 22:18:14 +02001416 s->flags &= ~SF_ADDR_SET;
Olivier Houchard530249c2019-07-12 16:16:59 +02001417 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001418 si->exp = TICK_ETERNITY;
1419 res->rex = TICK_ETERNITY;
1420 res->to_forward = 0;
1421 res->analyse_exp = TICK_ETERNITY;
1422 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001423 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001424 si_release_endpoint(&s->si[1]);
1425 b_free(&req->buf);
1426 /* Swap the L7 buffer with the channel buffer */
1427 /* We know we stored the co_data as b_data, so get it there */
1428 co_data = b_data(&si->l7_buffer);
1429 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1430 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1431
1432 co_set_data(req, co_data);
1433 b_reset(&res->buf);
1434 co_set_data(res, 0);
1435 return 0;
1436}
1437
Christopher Faulete0768eb2018-10-03 16:38:02 +02001438/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1439 * processing can continue on next analysers, or zero if it either needs more
1440 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1441 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1442 * when it has nothing left to do, and may remove any analyser when it wants to
1443 * abort.
1444 */
1445int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1446{
Christopher Faulet9768c262018-10-22 09:34:31 +02001447 /*
1448 * We will analyze a complete HTTP response to check the its syntax.
1449 *
1450 * Once the start line and all headers are received, we may perform a
1451 * capture of the error (if any), and we will set a few fields. We also
1452 * logging and finally headers capture.
1453 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 struct session *sess = s->sess;
1455 struct http_txn *txn = s->txn;
1456 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001457 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001458 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001459 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001460 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 int n;
1462
1463 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1464 now_ms, __FUNCTION__,
1465 s,
1466 rep,
1467 rep->rex, rep->wex,
1468 rep->flags,
1469 ci_data(rep),
1470 rep->analysers);
1471
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001472 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473
Willy Tarreau4236f032019-03-05 10:43:32 +01001474 /* Parsing errors are caught here */
1475 if (htx->flags & HTX_FL_PARSING_ERROR)
1476 goto return_bad_res;
1477
Christopher Faulete0768eb2018-10-03 16:38:02 +02001478 /*
1479 * Now we quickly check if we have found a full valid response.
1480 * If not so, we check the FD and buffer states before leaving.
1481 * A full response is indicated by the fact that we have seen
1482 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1483 * responses are checked first.
1484 *
1485 * Depending on whether the client is still there or not, we
1486 * may send an error response back or not. Note that normally
1487 * we should only check for HTTP status there, and check I/O
1488 * errors somewhere else.
1489 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001490 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001491 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001492 /* 1: have we encountered a read error ? */
1493 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001494 struct connection *conn = NULL;
1495
Olivier Houchard865d8392019-05-03 22:46:27 +02001496 if (objt_cs(s->si[1].end))
1497 conn = objt_cs(s->si[1].end)->conn;
1498
1499 if (si_b->flags & SI_FL_L7_RETRY &&
1500 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001501 /* If we arrive here, then CF_READ_ERROR was
1502 * set by si_cs_recv() because we matched a
1503 * status, overwise it would have removed
1504 * the SI_FL_L7_RETRY flag, so it's ok not
1505 * to check s->be->retry_type.
1506 */
1507 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1508 return 0;
1509 }
1510
Olivier Houchard6db16992019-05-17 15:40:49 +02001511 if (txn->flags & TX_NOT_FIRST)
1512 goto abort_keep_alive;
1513
Olivier Houcharda798bf52019-03-08 18:52:00 +01001514 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001516 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001517 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 }
1519
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001521 s->req.analysers &= AN_REQ_FLT_END;
1522 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 txn->status = 502;
1524
1525 /* Check to see if the server refused the early data.
1526 * If so, just send a 425
1527 */
Willy Tarreau1b4cc2e2020-06-23 05:58:20 +02001528 if (conn && conn->err_code == CO_ER_SSL_EARLY_FAILED) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001529 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001530 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001531 do_l7_retry(s, si_b) == 0)
1532 return 0;
1533 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 }
1535
1536 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_SRVCL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001548 if ((si_b->flags & SI_FL_L7_RETRY) &&
1549 (s->be->retry_type & PR_RE_TIMEOUT)) {
1550 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1551 return 0;
1552 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001553 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001555 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001556 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 }
1558
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001560 s->req.analysers &= AN_REQ_FLT_END;
1561 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562 txn->status = 504;
1563 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565
1566 if (!(s->flags & SF_ERR_MASK))
1567 s->flags |= SF_ERR_SRVTO;
1568 if (!(s->flags & SF_FINST_MASK))
1569 s->flags |= SF_FINST_H;
1570 return 0;
1571 }
1572
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001575 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1576 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001578 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579
1580 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001581 s->req.analysers &= AN_REQ_FLT_END;
1582 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001584 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585
1586 if (!(s->flags & SF_ERR_MASK))
1587 s->flags |= SF_ERR_CLICL;
1588 if (!(s->flags & SF_FINST_MASK))
1589 s->flags |= SF_FINST_H;
1590
1591 /* process_stream() will take care of the error */
1592 return 0;
1593 }
1594
Christopher Faulet9768c262018-10-22 09:34:31 +02001595 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001597 if ((si_b->flags & SI_FL_L7_RETRY) &&
1598 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1599 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1600 return 0;
1601 }
1602
Olivier Houchard6db16992019-05-17 15:40:49 +02001603 if (txn->flags & TX_NOT_FIRST)
1604 goto abort_keep_alive;
1605
Olivier Houcharda798bf52019-03-08 18:52:00 +01001606 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001608 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001609 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610 }
1611
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001613 s->req.analysers &= AN_REQ_FLT_END;
1614 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 txn->status = 502;
1616 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001617 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618
1619 if (!(s->flags & SF_ERR_MASK))
1620 s->flags |= SF_ERR_SRVCL;
1621 if (!(s->flags & SF_FINST_MASK))
1622 s->flags |= SF_FINST_H;
1623 return 0;
1624 }
1625
Christopher Faulet9768c262018-10-22 09:34:31 +02001626 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 goto abort_keep_alive;
1630
Olivier Houcharda798bf52019-03-08 18:52:00 +01001631 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001632 rep->analysers &= AN_RES_FLT_END;
Christopher Faulet8868ac32020-04-01 08:14:16 +02001633 s->req.analysers &= AN_REQ_FLT_END;
1634 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635
1636 if (!(s->flags & SF_ERR_MASK))
1637 s->flags |= SF_ERR_CLICL;
1638 if (!(s->flags & SF_FINST_MASK))
1639 s->flags |= SF_FINST_H;
1640
1641 /* process_stream() will take care of the error */
1642 return 0;
1643 }
1644
1645 channel_dont_close(rep);
1646 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1647 return 0;
1648 }
1649
1650 /* More interesting part now : we know that we have a complete
1651 * response which at least looks like HTTP. We have an indicator
1652 * of each header's length, so we can parse them quickly.
1653 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001654 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001655 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001656 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001657
Christopher Faulet9768c262018-10-22 09:34:31 +02001658 /* 0: we might have to print this header in debug mode */
1659 if (unlikely((global.mode & MODE_DEBUG) &&
1660 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1661 int32_t pos;
1662
Christopher Faulet03599112018-11-27 11:21:21 +01001663 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001664
Christopher Fauleta3f15502019-05-13 15:27:23 +02001665 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001666 struct htx_blk *blk = htx_get_blk(htx, pos);
1667 enum htx_blk_type type = htx_get_blk_type(blk);
1668
1669 if (type == HTX_BLK_EOH)
1670 break;
1671 if (type != HTX_BLK_HDR)
1672 continue;
1673
1674 htx_debug_hdr("srvhdr", s,
1675 htx_get_blk_name(htx, blk),
1676 htx_get_blk_value(htx, blk));
1677 }
1678 }
1679
Christopher Faulet03599112018-11-27 11:21:21 +01001680 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001681 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001682 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001683 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001684 if (sl->flags & HTX_SL_F_XFER_LEN) {
1685 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001686 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001687 if (sl->flags & HTX_SL_F_BODYLESS)
1688 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001689 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001690
1691 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692 if (n < 1 || n > 5)
1693 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001694
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695 /* when the client triggers a 4xx from the server, it's most often due
1696 * to a missing object or permission. These events should be tracked
1697 * because if they happen often, it may indicate a brute force or a
1698 * vulnerability scan.
1699 */
1700 if (n == 4)
1701 stream_inc_http_err_ctr(s);
1702
1703 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001704 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 /* Adjust server's health based on status code. Note: status codes 501
1707 * and 505 are triggered on demand by client request, so we must not
1708 * count them as server failures.
1709 */
1710 if (objt_server(s->target)) {
1711 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001712 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001714 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 }
1716
1717 /*
1718 * We may be facing a 100-continue response, or any other informational
1719 * 1xx response which is non-final, in which case this is not the right
1720 * response, and we're waiting for the next one. Let's allow this response
1721 * to go to the client and wait for the next one. There's an exception for
1722 * 101 which is used later in the code to switch protocols.
1723 */
1724 if (txn->status < 200 &&
1725 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001726 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001727 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001728 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001729 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001730 txn->status = 0;
1731 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet5761e7d2020-08-31 11:07:07 +02001732 rep->flags |= CF_SEND_DONTWAIT; /* Send ASAP informational messages */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001733 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001734 }
1735
1736 /*
1737 * 2: check for cacheability.
1738 */
1739
1740 switch (txn->status) {
1741 case 200:
1742 case 203:
1743 case 204:
1744 case 206:
1745 case 300:
1746 case 301:
1747 case 404:
1748 case 405:
1749 case 410:
1750 case 414:
1751 case 501:
1752 break;
1753 default:
1754 /* RFC7231#6.1:
1755 * Responses with status codes that are defined as
1756 * cacheable by default (e.g., 200, 203, 204, 206,
1757 * 300, 301, 404, 405, 410, 414, and 501 in this
1758 * specification) can be reused by a cache with
1759 * heuristic expiration unless otherwise indicated
1760 * by the method definition or explicit cache
1761 * controls [RFC7234]; all other status codes are
1762 * not cacheable by default.
1763 */
1764 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1765 break;
1766 }
1767
1768 /*
1769 * 3: we may need to capture headers
1770 */
1771 s->logs.logwait &= ~LW_RESP;
1772 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001773 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001774
Christopher Faulet9768c262018-10-22 09:34:31 +02001775 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1777 txn->status == 101)) {
1778 /* Either we've established an explicit tunnel, or we're
1779 * switching the protocol. In both cases, we're very unlikely
1780 * to understand the next protocols. We have to switch to tunnel
1781 * mode, so that we transfer the request and responses then let
1782 * this protocol pass unmodified. When we later implement specific
1783 * parsers for such protocols, we'll want to check the Upgrade
1784 * header which contains information about that protocol for
1785 * responses with status 101 (eg: see RFC2817 about TLS).
1786 */
1787 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001788 }
1789
Christopher Faulet61608322018-11-23 16:23:45 +01001790 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1791 * 407 (Proxy-Authenticate) responses and set the connection to private
1792 */
1793 srv_conn = cs_conn(objt_cs(s->si[1].end));
1794 if (srv_conn) {
1795 struct ist hdr;
1796 struct http_hdr_ctx ctx;
1797
1798 if (txn->status == 401)
1799 hdr = ist("WWW-Authenticate");
1800 else if (txn->status == 407)
1801 hdr = ist("Proxy-Authenticate");
1802 else
1803 goto end;
1804
1805 ctx.blk = NULL;
1806 while (http_find_header(htx, hdr, &ctx, 0)) {
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001807 /* If www-authenticate contains "Negotiate", "Nego2", or "NTLM",
1808 * possibly followed by blanks and a base64 string, the connection
1809 * is private. Since it's a mess to deal with, we only check for
1810 * values starting with "NTLM" or "Nego". Note that often multiple
1811 * headers are sent by the server there.
1812 */
1813 if ((ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "Nego", 4) == 0) ||
Willy Tarreaud3be89b2020-05-07 19:10:15 +02001814 (ctx.value.len >= 4 && strncasecmp(ctx.value.ptr, "NTLM", 4) == 0)) {
Olivier Houchard250031e2019-05-29 15:01:50 +02001815 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001816 srv_conn->flags |= CO_FL_PRIVATE;
Willy Tarreaud22b28e2020-05-07 19:27:02 +02001817 break;
Olivier Houchard250031e2019-05-29 15:01:50 +02001818 }
Christopher Faulet61608322018-11-23 16:23:45 +01001819 }
1820 }
1821
1822 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001823 /* we want to have the response time before we start processing it */
1824 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1825
1826 /* end of job, return OK */
1827 rep->analysers &= ~an_bit;
1828 rep->analyse_exp = TICK_ETERNITY;
1829 channel_auto_close(rep);
1830 return 1;
1831
Christopher Faulet47365272018-10-31 17:40:50 +01001832 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001833 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001834 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001835 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001836 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001837 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001838 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001839 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001840 do_l7_retry(s, si_b) == 0)
1841 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001842 txn->status = 502;
1843 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001844 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001845 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001846 s->req.analysers &= AN_REQ_FLT_END;
1847 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001848
1849 if (!(s->flags & SF_ERR_MASK))
1850 s->flags |= SF_ERR_PRXCOND;
1851 if (!(s->flags & SF_FINST_MASK))
1852 s->flags |= SF_FINST_H;
1853 return 0;
1854
Christopher Faulete0768eb2018-10-03 16:38:02 +02001855 abort_keep_alive:
1856 /* A keep-alive request to the server failed on a network error.
1857 * The client is required to retry. We need to close without returning
1858 * any other information so that the client retries.
1859 */
1860 txn->status = 0;
1861 rep->analysers &= AN_RES_FLT_END;
1862 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001863 s->logs.logwait = 0;
1864 s->logs.level = 0;
1865 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001866 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 return 0;
1868}
1869
1870/* This function performs all the processing enabled for the current response.
1871 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1872 * and updates s->res.analysers. It might make sense to explode it into several
1873 * other functions. It works like process_request (see indications above).
1874 */
1875int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1876{
1877 struct session *sess = s->sess;
1878 struct http_txn *txn = s->txn;
1879 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001880 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001881 struct proxy *cur_proxy;
1882 struct cond_wordlist *wl;
1883 enum rule_result ret = HTTP_RULE_RES_CONT;
1884
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001885 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1886 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001887
Christopher Faulete0768eb2018-10-03 16:38:02 +02001888 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1889 now_ms, __FUNCTION__,
1890 s,
1891 rep,
1892 rep->rex, rep->wex,
1893 rep->flags,
1894 ci_data(rep),
1895 rep->analysers);
1896
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001897 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001898
1899 /* The stats applet needs to adjust the Connection header but we don't
1900 * apply any filter there.
1901 */
1902 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1903 rep->analysers &= ~an_bit;
1904 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001905 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001906 }
1907
1908 /*
1909 * We will have to evaluate the filters.
1910 * As opposed to version 1.2, now they will be evaluated in the
1911 * filters order and not in the header order. This means that
1912 * each filter has to be validated among all headers.
1913 *
1914 * Filters are tried with ->be first, then with ->fe if it is
1915 * different from ->be.
1916 *
1917 * Maybe we are in resume condiion. In this case I choose the
1918 * "struct proxy" which contains the rule list matching the resume
1919 * pointer. If none of theses "struct proxy" match, I initialise
1920 * the process with the first one.
1921 *
1922 * In fact, I check only correspondance betwwen the current list
1923 * pointer and the ->fe rule list. If it doesn't match, I initialize
1924 * the loop with the ->be.
1925 */
1926 if (s->current_rule_list == &sess->fe->http_res_rules)
1927 cur_proxy = sess->fe;
1928 else
1929 cur_proxy = s->be;
1930 while (1) {
1931 struct proxy *rule_set = cur_proxy;
1932
1933 /* evaluate http-response rules */
1934 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001935 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001936
1937 if (ret == HTTP_RULE_RES_BADREQ)
1938 goto return_srv_prx_502;
1939
1940 if (ret == HTTP_RULE_RES_DONE) {
1941 rep->analysers &= ~an_bit;
1942 rep->analyse_exp = TICK_ETERNITY;
1943 return 1;
1944 }
1945 }
1946
1947 /* we need to be called again. */
1948 if (ret == HTTP_RULE_RES_YIELD) {
1949 channel_dont_close(rep);
1950 return 0;
1951 }
1952
1953 /* try headers filters */
1954 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001955 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1956 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001957 }
1958
1959 /* has the response been denied ? */
1960 if (txn->flags & TX_SVDENY) {
1961 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001962 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001963
Olivier Houcharda798bf52019-03-08 18:52:00 +01001964 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1965 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001967 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968 goto return_srv_prx_502;
1969 }
1970
1971 /* add response headers from the rule sets in the same order */
1972 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001973 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001974 if (txn->status < 200 && txn->status != 101)
1975 break;
1976 if (wl->cond) {
1977 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1978 ret = acl_pass(ret);
1979 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1980 ret = !ret;
1981 if (!ret)
1982 continue;
1983 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001984
1985 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1986 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001987 goto return_bad_resp;
1988 }
1989
1990 /* check whether we're already working on the frontend */
1991 if (cur_proxy == sess->fe)
1992 break;
1993 cur_proxy = sess->fe;
1994 }
1995
1996 /* After this point, this anayzer can't return yield, so we can
1997 * remove the bit corresponding to this analyzer from the list.
1998 *
1999 * Note that the intermediate returns and goto found previously
2000 * reset the analyzers.
2001 */
2002 rep->analysers &= ~an_bit;
2003 rep->analyse_exp = TICK_ETERNITY;
2004
2005 /* OK that's all we can do for 1xx responses */
2006 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02002007 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002008
2009 /*
2010 * Now check for a server cookie.
2011 */
2012 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002013 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002014
2015 /*
2016 * Check for cache-control or pragma headers if required.
2017 */
2018 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2019 check_response_for_cacheability(s, rep);
2020
2021 /*
2022 * Add server cookie in the response if needed
2023 */
2024 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2025 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2026 (!(s->flags & SF_DIRECT) ||
2027 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2028 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2029 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2030 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2031 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2032 !(s->flags & SF_IGNORE_PRST)) {
2033 /* the server is known, it's not the one the client requested, or the
2034 * cookie's last seen date needs to be refreshed. We have to
2035 * insert a set-cookie here, except if we want to insert only on POST
2036 * requests and this one isn't. Note that servers which don't have cookies
2037 * (eg: some backup servers) will return a full cookie removal request.
2038 */
2039 if (!objt_server(s->target)->cookie) {
2040 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002041 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002042 s->be->cookie_name);
2043 }
2044 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002045 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002046
2047 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2048 /* emit last_date, which is mandatory */
2049 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2050 s30tob64((date.tv_sec+3) >> 2,
2051 trash.area + trash.data);
2052 trash.data += 5;
2053
2054 if (s->be->cookie_maxlife) {
2055 /* emit first_date, which is either the original one or
2056 * the current date.
2057 */
2058 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2059 s30tob64(txn->cookie_first_date ?
2060 txn->cookie_first_date >> 2 :
2061 (date.tv_sec+3) >> 2,
2062 trash.area + trash.data);
2063 trash.data += 5;
2064 }
2065 }
2066 chunk_appendf(&trash, "; path=/");
2067 }
2068
2069 if (s->be->cookie_domain)
2070 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2071
2072 if (s->be->ck_opts & PR_CK_HTTPONLY)
2073 chunk_appendf(&trash, "; HttpOnly");
2074
2075 if (s->be->ck_opts & PR_CK_SECURE)
2076 chunk_appendf(&trash, "; Secure");
2077
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002078 if (s->be->cookie_attrs)
2079 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2080
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002081 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082 goto return_bad_resp;
2083
2084 txn->flags &= ~TX_SCK_MASK;
2085 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2086 /* the server did not change, only the date was updated */
2087 txn->flags |= TX_SCK_UPDATED;
2088 else
2089 txn->flags |= TX_SCK_INSERTED;
2090
2091 /* Here, we will tell an eventual cache on the client side that we don't
2092 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2093 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2094 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2095 */
2096 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2097
2098 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2099
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002100 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101 goto return_bad_resp;
2102 }
2103 }
2104
2105 /*
2106 * Check if result will be cacheable with a cookie.
2107 * We'll block the response if security checks have caught
2108 * nasty things such as a cacheable cookie.
2109 */
2110 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2111 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2112 (s->be->options & PR_O_CHK_CACHE)) {
2113 /* we're in presence of a cacheable response containing
2114 * a set-cookie header. We'll block it as requested by
2115 * the 'checkcache' option, and send an alert.
2116 */
2117 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002118 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002119
Olivier Houcharda798bf52019-03-08 18:52:00 +01002120 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2121 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002122 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002123 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002124
2125 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2126 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2127 send_log(s->be, LOG_ALERT,
2128 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2129 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2130 goto return_srv_prx_502;
2131 }
2132
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002133 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002134 /* Always enter in the body analyzer */
2135 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2136 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2137
2138 /* if the user wants to log as soon as possible, without counting
2139 * bytes from the server, then this is the right moment. We have
2140 * to temporarily assign bytes_out to log what we currently have.
2141 */
2142 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2143 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002144 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002145 s->do_log(s);
2146 s->logs.bytes_out = 0;
2147 }
2148 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002149
2150 return_bad_resp:
2151 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002152 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002153 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002154 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002155 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002156
2157 return_srv_prx_502:
2158 rep->analysers &= AN_RES_FLT_END;
2159 txn->status = 502;
2160 s->logs.t_data = -1; /* was not a valid response */
2161 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002162 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002163 if (!(s->flags & SF_ERR_MASK))
2164 s->flags |= SF_ERR_PRXCOND;
2165 if (!(s->flags & SF_FINST_MASK))
2166 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002167
2168 s->req.analysers &= AN_REQ_FLT_END;
2169 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002170 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002171}
2172
2173/* This function is an analyser which forwards response body (including chunk
2174 * sizes if any). It is called as soon as we must forward, even if we forward
2175 * zero byte. The only situation where it must not be called is when we're in
2176 * tunnel mode and we want to forward till the close. It's used both to forward
2177 * remaining data and to resync after end of body. It expects the msg_state to
2178 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2179 * read more data, or 1 once we can go on with next request or end the stream.
2180 *
2181 * It is capable of compressing response data both in content-length mode and
2182 * in chunked mode. The state machines follows different flows depending on
2183 * whether content-length and chunked modes are used, since there are no
2184 * trailers in content-length :
2185 *
2186 * chk-mode cl-mode
2187 * ,----- BODY -----.
2188 * / \
2189 * V size > 0 V chk-mode
2190 * .--> SIZE -------------> DATA -------------> CRLF
2191 * | | size == 0 | last byte |
2192 * | v final crlf v inspected |
2193 * | TRAILERS -----------> DONE |
2194 * | |
2195 * `----------------------------------------------'
2196 *
2197 * Compression only happens in the DATA state, and must be flushed in final
2198 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2199 * is performed at once on final states for all bytes parsed, or when leaving
2200 * on missing data.
2201 */
2202int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2203{
2204 struct session *sess = s->sess;
2205 struct http_txn *txn = s->txn;
2206 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002208 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002209
2210 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2211 now_ms, __FUNCTION__,
2212 s,
2213 res,
2214 res->rex, res->wex,
2215 res->flags,
2216 ci_data(res),
2217 res->analysers);
2218
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002219 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220
2221 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002222 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002223 /* Output closed while we were sending data. We must abort and
2224 * wake the other side up.
2225 */
2226 msg->err_state = msg->msg_state;
2227 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002228 htx_end_response(s);
2229 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 return 1;
2231 }
2232
Christopher Faulet9768c262018-10-22 09:34:31 +02002233 if (msg->msg_state == HTTP_MSG_BODY)
2234 msg->msg_state = HTTP_MSG_DATA;
2235
Christopher Faulete0768eb2018-10-03 16:38:02 +02002236 /* in most states, we should abort in case of early close */
2237 channel_auto_close(res);
2238
Christopher Faulete0768eb2018-10-03 16:38:02 +02002239 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002240 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002241 if (res->flags & CF_EOI)
2242 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002243 }
2244 else {
2245 /* We can't process the buffer's contents yet */
2246 res->flags |= CF_WAKE_WRITE;
2247 goto missing_data_or_waiting;
2248 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002249 }
2250
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002251 if (msg->msg_state >= HTTP_MSG_ENDING)
2252 goto ending;
2253
2254 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2255 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2256 msg->msg_state = HTTP_MSG_ENDING;
2257 goto ending;
2258 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002259
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002260 /* Forward input data. We get it by removing all outgoing data not
2261 * forwarded yet from HTX data size. If there are some data filters, we
2262 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002263 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002264 if (HAS_RSP_DATA_FILTERS(s)) {
2265 ret = flt_http_payload(s, msg, htx->data);
2266 if (ret < 0)
2267 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002268 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002269 }
2270 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002271 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002272 if (msg->flags & HTTP_MSGF_XFER_LEN)
2273 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002274 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002275
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002276 if (htx->data != co_data(res))
2277 goto missing_data_or_waiting;
2278
2279 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2280 msg->msg_state = HTTP_MSG_ENDING;
2281 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002282 }
2283
Christopher Faulet9768c262018-10-22 09:34:31 +02002284 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002285 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2286 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002287 */
2288 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2289 goto missing_data_or_waiting;
2290
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002291 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002292
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002293 ending:
2294 /* other states, ENDING...TUNNEL */
2295 if (msg->msg_state >= HTTP_MSG_DONE)
2296 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002297
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002298 if (HAS_RSP_DATA_FILTERS(s)) {
2299 ret = flt_http_end(s, msg);
2300 if (ret <= 0) {
2301 if (!ret)
2302 goto missing_data_or_waiting;
2303 goto return_bad_res;
2304 }
2305 }
2306
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002307 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2308 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2309 msg->msg_state = HTTP_MSG_TUNNEL;
2310 goto ending;
2311 }
2312 else {
2313 msg->msg_state = HTTP_MSG_DONE;
2314 res->to_forward = 0;
2315 }
2316
2317 done:
2318
2319 channel_dont_close(res);
2320
Christopher Fauletf2824e62018-10-01 12:12:37 +02002321 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002322 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002324 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2325 if (res->flags & CF_SHUTW) {
2326 /* response errors are most likely due to the
2327 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002328 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002329 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 goto return_bad_res;
2331 }
2332 return 1;
2333 }
2334 return 0;
2335
2336 missing_data_or_waiting:
2337 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002338 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002339
Christopher Faulet47365272018-10-31 17:40:50 +01002340 if (htx->flags & HTX_FL_PARSING_ERROR)
2341 goto return_bad_res;
2342
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343 /* stop waiting for data if the input is closed before the end. If the
2344 * client side was already closed, it means that the client has aborted,
2345 * so we don't want to count this as a server abort. Otherwise it's a
2346 * server abort.
2347 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002348 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002349 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002350 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002351 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002352 if (htx_is_empty(htx))
2353 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002354 }
2355
Christopher Faulete0768eb2018-10-03 16:38:02 +02002356 /* When TE: chunked is used, we need to get there again to parse
2357 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002358 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2359 * are filters registered on the stream, we don't want to forward a
2360 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002361 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002362 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363 channel_dont_close(res);
2364
2365 /* We know that more data are expected, but we couldn't send more that
2366 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2367 * system knows it must not set a PUSH on this first part. Interactive
2368 * modes are already handled by the stream sock layer. We must not do
2369 * this in content-length mode because it could present the MSG_MORE
2370 * flag with the last block of forwarded data, which would cause an
2371 * additional delay to be observed by the receiver.
2372 */
2373 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2374 res->flags |= CF_EXPECT_MORE;
2375
2376 /* the stream handler will take care of timeouts and errors */
2377 return 0;
2378
Christopher Faulet93e02d82019-03-08 14:18:50 +01002379 return_srv_abort:
2380 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2381 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002382 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002383 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2384 if (!(s->flags & SF_ERR_MASK))
2385 s->flags |= SF_ERR_SRVCL;
2386 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002387
Christopher Faulet93e02d82019-03-08 14:18:50 +01002388 return_cli_abort:
2389 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2390 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002391 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002392 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2393 if (!(s->flags & SF_ERR_MASK))
2394 s->flags |= SF_ERR_CLICL;
2395 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002396
Christopher Faulet93e02d82019-03-08 14:18:50 +01002397 return_bad_res:
2398 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2399 if (objt_server(s->target)) {
2400 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2401 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2402 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002403 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002404 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002405
Christopher Faulet93e02d82019-03-08 14:18:50 +01002406 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002407 txn->rsp.err_state = txn->rsp.msg_state;
2408 txn->rsp.msg_state = HTTP_MSG_ERROR;
2409 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002410 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002411 res->analysers &= AN_RES_FLT_END;
2412 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 +02002413 if (!(s->flags & SF_FINST_MASK))
2414 s->flags |= SF_FINST_D;
2415 return 0;
2416}
2417
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420 * as too large a request to build a valid response.
2421 */
2422int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2423{
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 struct channel *req = &s->req;
2425 struct channel *res = &s->res;
2426 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002427 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002429 struct ist status, reason, location;
2430 unsigned int flags;
2431 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002432 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002433
2434 chunk = alloc_trash_chunk();
2435 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002437
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 /*
2439 * Create the location
2440 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002441 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 case REDIRECT_TYPE_SCHEME: {
2444 struct http_hdr_ctx ctx;
2445 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 host = ist("");
2448 ctx.blk = NULL;
2449 if (http_find_header(htx, ist("Host"), &ctx, 0))
2450 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451
Christopher Faulet297fbb42019-05-13 14:41:27 +02002452 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002453 path = http_get_path(htx_sl_req_uri(sl));
2454 /* build message using path */
2455 if (path.ptr) {
2456 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2457 int qs = 0;
2458 while (qs < path.len) {
2459 if (*(path.ptr + qs) == '?') {
2460 path.len = qs;
2461 break;
2462 }
2463 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002465 }
2466 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002467 else
2468 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002469
Christopher Faulet99daf282018-11-28 22:58:13 +01002470 if (rule->rdr_str) { /* this is an old "redirect" rule */
2471 /* add scheme */
2472 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2473 goto fail;
2474 }
2475 else {
2476 /* add scheme with executing log format */
2477 chunk->data += build_logline(s, chunk->area + chunk->data,
2478 chunk->size - chunk->data,
2479 &rule->rdr_fmt);
2480 }
2481 /* add "://" + host + path */
2482 if (!chunk_memcat(chunk, "://", 3) ||
2483 !chunk_memcat(chunk, host.ptr, host.len) ||
2484 !chunk_memcat(chunk, path.ptr, path.len))
2485 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002486
Christopher Faulet99daf282018-11-28 22:58:13 +01002487 /* append a slash at the end of the location if needed and missing */
2488 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2489 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2490 if (chunk->data + 1 >= chunk->size)
2491 goto fail;
2492 chunk->area[chunk->data++] = '/';
2493 }
2494 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002495 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002496
Christopher Faulet99daf282018-11-28 22:58:13 +01002497 case REDIRECT_TYPE_PREFIX: {
2498 struct ist path;
2499
Christopher Faulet297fbb42019-05-13 14:41:27 +02002500 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002501 path = http_get_path(htx_sl_req_uri(sl));
2502 /* build message using path */
2503 if (path.ptr) {
2504 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2505 int qs = 0;
2506 while (qs < path.len) {
2507 if (*(path.ptr + qs) == '?') {
2508 path.len = qs;
2509 break;
2510 }
2511 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002512 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002513 }
2514 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002515 else
2516 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002517
Christopher Faulet99daf282018-11-28 22:58:13 +01002518 if (rule->rdr_str) { /* this is an old "redirect" rule */
2519 /* add prefix. Note that if prefix == "/", we don't want to
2520 * add anything, otherwise it makes it hard for the user to
2521 * configure a self-redirection.
2522 */
2523 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2524 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2525 goto fail;
2526 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002527 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002528 else {
2529 /* add prefix with executing log format */
2530 chunk->data += build_logline(s, chunk->area + chunk->data,
2531 chunk->size - chunk->data,
2532 &rule->rdr_fmt);
2533 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002534
Christopher Faulet99daf282018-11-28 22:58:13 +01002535 /* add path */
2536 if (!chunk_memcat(chunk, path.ptr, path.len))
2537 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002538
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 /* append a slash at the end of the location if needed and missing */
2540 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2541 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2542 if (chunk->data + 1 >= chunk->size)
2543 goto fail;
2544 chunk->area[chunk->data++] = '/';
2545 }
2546 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002547 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002548 case REDIRECT_TYPE_LOCATION:
2549 default:
2550 if (rule->rdr_str) { /* this is an old "redirect" rule */
2551 /* add location */
2552 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2553 goto fail;
2554 }
2555 else {
2556 /* add location with executing log format */
2557 chunk->data += build_logline(s, chunk->area + chunk->data,
2558 chunk->size - chunk->data,
2559 &rule->rdr_fmt);
2560 }
2561 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002562 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002563 location = ist2(chunk->area, chunk->data);
2564
2565 /*
2566 * Create the 30x response
2567 */
2568 switch (rule->code) {
2569 case 308:
2570 status = ist("308");
2571 reason = ist("Permanent Redirect");
2572 break;
2573 case 307:
2574 status = ist("307");
2575 reason = ist("Temporary Redirect");
2576 break;
2577 case 303:
2578 status = ist("303");
2579 reason = ist("See Other");
2580 break;
2581 case 301:
2582 status = ist("301");
2583 reason = ist("Moved Permanently");
2584 break;
2585 case 302:
2586 default:
2587 status = ist("302");
2588 reason = ist("Found");
2589 break;
2590 }
2591
Christopher Faulet08e66462019-05-23 16:44:59 +02002592 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2593 close = 1;
2594
Christopher Faulet99daf282018-11-28 22:58:13 +01002595 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002596 /* Trim any possible response */
2597 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002598 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2599 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2600 if (!sl)
2601 goto fail;
2602 sl->info.res.status = rule->code;
2603 s->txn->status = rule->code;
2604
Christopher Faulet08e66462019-05-23 16:44:59 +02002605 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2606 goto fail;
2607
2608 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002609 !htx_add_header(htx, ist("Location"), location))
2610 goto fail;
2611
2612 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2613 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2614 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002615 }
2616
2617 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002618 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2619 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002620 }
2621
Christopher Faulet99daf282018-11-28 22:58:13 +01002622 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2623 goto fail;
2624
Kevin Zhu0fd70882020-01-07 09:42:55 +01002625 htx_to_buf(htx, &res->buf);
2626
Christopher Faulet99daf282018-11-28 22:58:13 +01002627 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002628 c_adv(res, data);
2629 res->total += data;
2630
2631 channel_auto_read(req);
2632 channel_abort(req);
2633 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002634 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002635
2636 res->wex = tick_add_ifset(now_ms, res->wto);
2637 channel_auto_read(res);
2638 channel_auto_close(res);
2639 channel_shutr_now(res);
Christopher Faulet7d84db32020-01-28 09:18:10 +01002640 if (rule->flags & REDIRECT_FLAG_FROM_REQ) {
2641 /* let's log the request time */
2642 s->logs.tv_request = now;
2643 req->analysers &= AN_REQ_FLT_END;
Christopher Faulet99daf282018-11-28 22:58:13 +01002644
Christopher Faulet7d84db32020-01-28 09:18:10 +01002645 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
2646 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
2647 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002648
2649 if (!(s->flags & SF_ERR_MASK))
2650 s->flags |= SF_ERR_LOCAL;
2651 if (!(s->flags & SF_FINST_MASK))
Christopher Faulet7d84db32020-01-28 09:18:10 +01002652 s->flags |= ((rule->flags & REDIRECT_FLAG_FROM_REQ) ? SF_FINST_R : SF_FINST_H);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002653
Christopher Faulet99daf282018-11-28 22:58:13 +01002654 free_trash_chunk(chunk);
2655 return 1;
2656
2657 fail:
2658 /* If an error occurred, remove the incomplete HTTP response from the
2659 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002660 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002661 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002662 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002663}
2664
Christopher Faulet72333522018-10-24 11:25:02 +02002665int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2666 struct ist name, const char *str, struct my_regex *re, int action)
2667{
2668 struct http_hdr_ctx ctx;
2669 struct buffer *output = get_trash_chunk();
2670
2671 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2672 ctx.blk = NULL;
2673 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2674 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2675 continue;
2676
2677 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2678 if (output->data == -1)
2679 return -1;
2680 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2681 return -1;
2682 }
2683 return 0;
2684}
2685
2686static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2687 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2688{
2689 struct buffer *replace;
2690 int ret = -1;
2691
2692 replace = alloc_trash_chunk();
2693 if (!replace)
2694 goto leave;
2695
2696 replace->data = build_logline(s, replace->area, replace->size, fmt);
2697 if (replace->data >= replace->size - 1)
2698 goto leave;
2699
2700 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2701
2702 leave:
2703 free_trash_chunk(replace);
2704 return ret;
2705}
2706
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002707
2708/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2709 * on success and -1 on error. The response channel is updated accordingly.
2710 */
2711static int htx_reply_103_early_hints(struct channel *res)
2712{
2713 struct htx *htx = htx_from_buf(&res->buf);
2714 size_t data;
2715
Christopher Faulet9869f932019-06-26 14:23:54 +02002716 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002717 /* If an error occurred during an Early-hint rule,
2718 * remove the incomplete HTTP 103 response from the
2719 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002720 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002721 return -1;
2722 }
2723
2724 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002725 c_adv(res, data);
2726 res->total += data;
2727 return 0;
2728}
2729
Christopher Faulet6eb92892018-11-15 16:39:29 +01002730/*
2731 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2732 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002733 * If <early_hints> is 0, it is starts a new response by adding the start
2734 * line. If an error occurred -1 is returned. On success 0 is returned. The
2735 * channel is not updated here. It must be done calling the function
2736 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002737 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002738static 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 +01002739{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002740 struct channel *res = &s->res;
2741 struct htx *htx = htx_from_buf(&res->buf);
2742 struct buffer *value = alloc_trash_chunk();
2743
Christopher Faulet6eb92892018-11-15 16:39:29 +01002744 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002745 struct htx_sl *sl;
2746 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2747 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2748
2749 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2750 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2751 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002752 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002753 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002754 }
2755
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002756 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2757 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002758 goto fail;
2759
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002760 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002761 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002762
2763 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002764 /* If an error occurred during an Early-hint rule, remove the incomplete
2765 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002766 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002767 free_trash_chunk(value);
2768 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002769}
2770
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002771/* This function executes one of the set-{method,path,query,uri} actions. It
2772 * takes the string from the variable 'replace' with length 'len', then modifies
2773 * the relevant part of the request line accordingly. Then it updates various
2774 * pointers to the next elements which were moved, and the total buffer length.
2775 * It finds the action to be performed in p[2], previously filled by function
2776 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2777 * error, though this can be revisited when this code is finally exploited.
2778 *
2779 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2780 * query string and 3 to replace uri.
2781 *
2782 * In query string case, the mark question '?' must be set at the start of the
2783 * string by the caller, event if the replacement query string is empty.
2784 */
2785int htx_req_replace_stline(int action, const char *replace, int len,
2786 struct proxy *px, struct stream *s)
2787{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002788 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002789
2790 switch (action) {
2791 case 0: // method
2792 if (!http_replace_req_meth(htx, ist2(replace, len)))
2793 return -1;
2794 break;
2795
2796 case 1: // path
2797 if (!http_replace_req_path(htx, ist2(replace, len)))
2798 return -1;
2799 break;
2800
2801 case 2: // query
2802 if (!http_replace_req_query(htx, ist2(replace, len)))
2803 return -1;
2804 break;
2805
2806 case 3: // uri
2807 if (!http_replace_req_uri(htx, ist2(replace, len)))
2808 return -1;
2809 break;
2810
2811 default:
2812 return -1;
2813 }
2814 return 0;
2815}
2816
2817/* This function replace the HTTP status code and the associated message. The
2818 * variable <status> contains the new status code. This function never fails.
2819 */
2820void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2821{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002822 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002823 char *res;
2824
2825 chunk_reset(&trash);
2826 res = ultoa_o(status, trash.area, trash.size);
2827 trash.data = res - trash.area;
2828
2829 /* Do we have a custom reason format string? */
2830 if (reason == NULL)
2831 reason = http_get_reason(status);
2832
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002833 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002834 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2835}
2836
Christopher Faulet3e964192018-10-24 11:39:23 +02002837/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2838 * transaction <txn>. Returns the verdict of the first rule that prevents
2839 * further processing of the request (auth, deny, ...), and defaults to
2840 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2841 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2842 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2843 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2844 * status.
2845 */
2846static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2847 struct stream *s, int *deny_status)
2848{
2849 struct session *sess = strm_sess(s);
2850 struct http_txn *txn = s->txn;
2851 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002852 struct act_rule *rule;
2853 struct http_hdr_ctx ctx;
2854 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002855 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2856 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002857 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002858
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002859 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002860
2861 /* If "the current_rule_list" match the executed rule list, we are in
2862 * resume condition. If a resume is needed it is always in the action
2863 * and never in the ACL or converters. In this case, we initialise the
2864 * current rule, and go to the action execution point.
2865 */
2866 if (s->current_rule) {
2867 rule = s->current_rule;
2868 s->current_rule = NULL;
2869 if (s->current_rule_list == rules)
2870 goto resume_execution;
2871 }
2872 s->current_rule_list = rules;
2873
2874 list_for_each_entry(rule, rules, list) {
2875 /* check optional condition */
2876 if (rule->cond) {
2877 int ret;
2878
2879 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2880 ret = acl_pass(ret);
2881
2882 if (rule->cond->pol == ACL_COND_UNLESS)
2883 ret = !ret;
2884
2885 if (!ret) /* condition not matched */
2886 continue;
2887 }
2888
2889 act_flags |= ACT_FLAG_FIRST;
2890 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002891 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2892 early_hints = 0;
2893 if (htx_reply_103_early_hints(&s->res) == -1) {
2894 rule_ret = HTTP_RULE_RES_BADREQ;
2895 goto end;
2896 }
2897 }
2898
Christopher Faulet3e964192018-10-24 11:39:23 +02002899 switch (rule->action) {
2900 case ACT_ACTION_ALLOW:
2901 rule_ret = HTTP_RULE_RES_STOP;
2902 goto end;
2903
2904 case ACT_ACTION_DENY:
2905 if (deny_status)
2906 *deny_status = rule->deny_status;
2907 rule_ret = HTTP_RULE_RES_DENY;
2908 goto end;
2909
2910 case ACT_HTTP_REQ_TARPIT:
2911 txn->flags |= TX_CLTARPIT;
2912 if (deny_status)
2913 *deny_status = rule->deny_status;
2914 rule_ret = HTTP_RULE_RES_DENY;
2915 goto end;
2916
2917 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002918 /* Auth might be performed on regular http-req rules as well as on stats */
2919 auth_realm = rule->arg.auth.realm;
2920 if (!auth_realm) {
2921 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2922 auth_realm = STATS_DEFAULT_REALM;
2923 else
2924 auth_realm = px->id;
2925 }
2926 /* send 401/407 depending on whether we use a proxy or not. We still
2927 * count one error, because normal browsing won't significantly
2928 * increase the counter but brute force attempts will.
2929 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002930 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002931 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2932 rule_ret = HTTP_RULE_RES_BADREQ;
2933 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002934 goto end;
2935
2936 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002937 rule_ret = HTTP_RULE_RES_DONE;
2938 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2939 rule_ret = HTTP_RULE_RES_BADREQ;
2940 goto end;
2941
2942 case ACT_HTTP_SET_NICE:
2943 s->task->nice = rule->arg.nice;
2944 break;
2945
2946 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002947 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002948 break;
2949
2950 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002951 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002952 break;
2953
2954 case ACT_HTTP_SET_LOGL:
2955 s->logs.level = rule->arg.loglevel;
2956 break;
2957
2958 case ACT_HTTP_REPLACE_HDR:
2959 case ACT_HTTP_REPLACE_VAL:
2960 if (htx_transform_header(s, &s->req, htx,
2961 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2962 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002963 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002964 rule_ret = HTTP_RULE_RES_BADREQ;
2965 goto end;
2966 }
2967 break;
2968
2969 case ACT_HTTP_DEL_HDR:
2970 /* remove all occurrences of the header */
2971 ctx.blk = NULL;
2972 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2973 http_remove_header(htx, &ctx);
2974 break;
2975
2976 case ACT_HTTP_SET_HDR:
2977 case ACT_HTTP_ADD_HDR: {
2978 /* The scope of the trash buffer must be limited to this function. The
2979 * build_logline() function can execute a lot of other function which
2980 * can use the trash buffer. So for limiting the scope of this global
2981 * buffer, we build first the header value using build_logline, and
2982 * after we store the header name.
2983 */
2984 struct buffer *replace;
2985 struct ist n, v;
2986
2987 replace = alloc_trash_chunk();
2988 if (!replace) {
2989 rule_ret = HTTP_RULE_RES_BADREQ;
2990 goto end;
2991 }
2992
2993 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2994 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2995 v = ist2(replace->area, replace->data);
2996
2997 if (rule->action == ACT_HTTP_SET_HDR) {
2998 /* remove all occurrences of the header */
2999 ctx.blk = NULL;
3000 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3001 http_remove_header(htx, &ctx);
3002 }
3003
3004 if (!http_add_header(htx, n, v)) {
3005 static unsigned char rate_limit = 0;
3006
3007 if ((rate_limit++ & 255) == 0) {
3008 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);
3009 }
3010
Olivier Houcharda798bf52019-03-08 18:52:00 +01003011 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003012 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003013 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003014 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003015 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003016 }
3017 free_trash_chunk(replace);
3018 break;
3019 }
3020
3021 case ACT_HTTP_DEL_ACL:
3022 case ACT_HTTP_DEL_MAP: {
3023 struct pat_ref *ref;
3024 struct buffer *key;
3025
3026 /* collect reference */
3027 ref = pat_ref_lookup(rule->arg.map.ref);
3028 if (!ref)
3029 continue;
3030
3031 /* allocate key */
3032 key = alloc_trash_chunk();
3033 if (!key) {
3034 rule_ret = HTTP_RULE_RES_BADREQ;
3035 goto end;
3036 }
3037
3038 /* collect key */
3039 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3040 key->area[key->data] = '\0';
3041
3042 /* perform update */
3043 /* returned code: 1=ok, 0=ko */
3044 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3045 pat_ref_delete(ref, key->area);
3046 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3047
3048 free_trash_chunk(key);
3049 break;
3050 }
3051
3052 case ACT_HTTP_ADD_ACL: {
3053 struct pat_ref *ref;
3054 struct buffer *key;
3055
3056 /* collect reference */
3057 ref = pat_ref_lookup(rule->arg.map.ref);
3058 if (!ref)
3059 continue;
3060
3061 /* allocate key */
3062 key = alloc_trash_chunk();
3063 if (!key) {
3064 rule_ret = HTTP_RULE_RES_BADREQ;
3065 goto end;
3066 }
3067
3068 /* collect key */
3069 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3070 key->area[key->data] = '\0';
3071
3072 /* perform update */
3073 /* add entry only if it does not already exist */
3074 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3075 if (pat_ref_find_elt(ref, key->area) == NULL)
3076 pat_ref_add(ref, key->area, NULL, NULL);
3077 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3078
3079 free_trash_chunk(key);
3080 break;
3081 }
3082
3083 case ACT_HTTP_SET_MAP: {
3084 struct pat_ref *ref;
3085 struct buffer *key, *value;
3086
3087 /* collect reference */
3088 ref = pat_ref_lookup(rule->arg.map.ref);
3089 if (!ref)
3090 continue;
3091
3092 /* allocate key */
3093 key = alloc_trash_chunk();
3094 if (!key) {
3095 rule_ret = HTTP_RULE_RES_BADREQ;
3096 goto end;
3097 }
3098
3099 /* allocate value */
3100 value = alloc_trash_chunk();
3101 if (!value) {
3102 free_trash_chunk(key);
3103 rule_ret = HTTP_RULE_RES_BADREQ;
3104 goto end;
3105 }
3106
3107 /* collect key */
3108 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3109 key->area[key->data] = '\0';
3110
3111 /* collect value */
3112 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3113 value->area[value->data] = '\0';
3114
3115 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003116 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003117 if (pat_ref_find_elt(ref, key->area) != NULL)
3118 /* update entry if it exists */
3119 pat_ref_set(ref, key->area, value->area, NULL);
3120 else
3121 /* insert a new entry */
3122 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003123 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003124 free_trash_chunk(key);
3125 free_trash_chunk(value);
3126 break;
3127 }
3128
3129 case ACT_HTTP_EARLY_HINT:
3130 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3131 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003132 early_hints = htx_add_early_hint_header(s, early_hints,
3133 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003134 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003135 if (early_hints == -1) {
3136 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003137 goto end;
3138 }
3139 break;
3140
3141 case ACT_CUSTOM:
3142 if ((s->req.flags & CF_READ_ERROR) ||
3143 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003144 (px->options & PR_O_ABRT_CLOSE)))
3145 act_flags |= ACT_FLAG_FINAL;
3146
3147 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3148 case ACT_RET_ERR:
3149 case ACT_RET_CONT:
3150 break;
3151 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003152 rule_ret = HTTP_RULE_RES_STOP;
3153 goto end;
3154 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003155 rule_ret = HTTP_RULE_RES_DONE;
3156 goto end;
3157 case ACT_RET_YIELD:
3158 s->current_rule = rule;
3159 rule_ret = HTTP_RULE_RES_YIELD;
3160 goto end;
3161 }
3162 break;
3163
3164 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3165 /* Note: only the first valid tracking parameter of each
3166 * applies.
3167 */
3168
3169 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3170 struct stktable *t;
3171 struct stksess *ts;
3172 struct stktable_key *key;
3173 void *ptr1, *ptr2;
3174
3175 t = rule->arg.trk_ctr.table.t;
3176 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3177 rule->arg.trk_ctr.expr, NULL);
3178
3179 if (key && (ts = stktable_get_entry(t, key))) {
3180 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3181
3182 /* let's count a new HTTP request as it's the first time we do it */
3183 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3184 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3185 if (ptr1 || ptr2) {
3186 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3187
3188 if (ptr1)
3189 stktable_data_cast(ptr1, http_req_cnt)++;
3190
3191 if (ptr2)
3192 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3193 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3194
3195 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3196
3197 /* If data was modified, we need to touch to re-schedule sync */
3198 stktable_touch_local(t, ts, 0);
3199 }
3200
3201 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3202 if (sess->fe != s->be)
3203 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3204 }
3205 }
3206 break;
3207
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003208 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003209 default:
3210 break;
3211 }
3212 }
3213
3214 end:
3215 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003216 if (htx_reply_103_early_hints(&s->res) == -1)
3217 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003218 }
3219
3220 /* we reached the end of the rules, nothing to report */
3221 return rule_ret;
3222}
3223
3224/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3225 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3226 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3227 * is returned, the process can continue the evaluation of next rule list. If
3228 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3229 * is returned, it means the operation could not be processed and a server error
3230 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3231 * deny rule. If *YIELD is returned, the caller must call again the function
3232 * with the same context.
3233 */
3234static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3235 struct stream *s)
3236{
3237 struct session *sess = strm_sess(s);
3238 struct http_txn *txn = s->txn;
3239 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003240 struct act_rule *rule;
3241 struct http_hdr_ctx ctx;
3242 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3243 int act_flags = 0;
3244
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003245 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003246
3247 /* If "the current_rule_list" match the executed rule list, we are in
3248 * resume condition. If a resume is needed it is always in the action
3249 * and never in the ACL or converters. In this case, we initialise the
3250 * current rule, and go to the action execution point.
3251 */
3252 if (s->current_rule) {
3253 rule = s->current_rule;
3254 s->current_rule = NULL;
3255 if (s->current_rule_list == rules)
3256 goto resume_execution;
3257 }
3258 s->current_rule_list = rules;
3259
3260 list_for_each_entry(rule, rules, list) {
3261 /* check optional condition */
3262 if (rule->cond) {
3263 int ret;
3264
3265 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3266 ret = acl_pass(ret);
3267
3268 if (rule->cond->pol == ACL_COND_UNLESS)
3269 ret = !ret;
3270
3271 if (!ret) /* condition not matched */
3272 continue;
3273 }
3274
3275 act_flags |= ACT_FLAG_FIRST;
3276resume_execution:
3277 switch (rule->action) {
3278 case ACT_ACTION_ALLOW:
3279 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3280 goto end;
3281
3282 case ACT_ACTION_DENY:
3283 txn->flags |= TX_SVDENY;
3284 rule_ret = HTTP_RULE_RES_STOP;
3285 goto end;
3286
3287 case ACT_HTTP_SET_NICE:
3288 s->task->nice = rule->arg.nice;
3289 break;
3290
3291 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003292 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003293 break;
3294
3295 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003296 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003297 break;
3298
3299 case ACT_HTTP_SET_LOGL:
3300 s->logs.level = rule->arg.loglevel;
3301 break;
3302
3303 case ACT_HTTP_REPLACE_HDR:
3304 case ACT_HTTP_REPLACE_VAL:
3305 if (htx_transform_header(s, &s->res, htx,
3306 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3307 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003308 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003309 rule_ret = HTTP_RULE_RES_BADREQ;
3310 goto end;
3311 }
3312 break;
3313
3314 case ACT_HTTP_DEL_HDR:
3315 /* remove all occurrences of the header */
3316 ctx.blk = NULL;
3317 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3318 http_remove_header(htx, &ctx);
3319 break;
3320
3321 case ACT_HTTP_SET_HDR:
3322 case ACT_HTTP_ADD_HDR: {
3323 struct buffer *replace;
3324 struct ist n, v;
3325
3326 replace = alloc_trash_chunk();
3327 if (!replace) {
3328 rule_ret = HTTP_RULE_RES_BADREQ;
3329 goto end;
3330 }
3331
3332 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3333 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3334 v = ist2(replace->area, replace->data);
3335
3336 if (rule->action == ACT_HTTP_SET_HDR) {
3337 /* remove all occurrences of the header */
3338 ctx.blk = NULL;
3339 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3340 http_remove_header(htx, &ctx);
3341 }
3342
3343 if (!http_add_header(htx, n, v)) {
3344 static unsigned char rate_limit = 0;
3345
3346 if ((rate_limit++ & 255) == 0) {
3347 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);
3348 }
3349
Olivier Houcharda798bf52019-03-08 18:52:00 +01003350 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003351 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003352 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003353 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003354 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003355 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003356 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003357 }
3358 free_trash_chunk(replace);
3359 break;
3360 }
3361
3362 case ACT_HTTP_DEL_ACL:
3363 case ACT_HTTP_DEL_MAP: {
3364 struct pat_ref *ref;
3365 struct buffer *key;
3366
3367 /* collect reference */
3368 ref = pat_ref_lookup(rule->arg.map.ref);
3369 if (!ref)
3370 continue;
3371
3372 /* allocate key */
3373 key = alloc_trash_chunk();
3374 if (!key) {
3375 rule_ret = HTTP_RULE_RES_BADREQ;
3376 goto end;
3377 }
3378
3379 /* collect key */
3380 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3381 key->area[key->data] = '\0';
3382
3383 /* perform update */
3384 /* returned code: 1=ok, 0=ko */
3385 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3386 pat_ref_delete(ref, key->area);
3387 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3388
3389 free_trash_chunk(key);
3390 break;
3391 }
3392
3393 case ACT_HTTP_ADD_ACL: {
3394 struct pat_ref *ref;
3395 struct buffer *key;
3396
3397 /* collect reference */
3398 ref = pat_ref_lookup(rule->arg.map.ref);
3399 if (!ref)
3400 continue;
3401
3402 /* allocate key */
3403 key = alloc_trash_chunk();
3404 if (!key) {
3405 rule_ret = HTTP_RULE_RES_BADREQ;
3406 goto end;
3407 }
3408
3409 /* collect key */
3410 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3411 key->area[key->data] = '\0';
3412
3413 /* perform update */
3414 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003415 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003416 if (pat_ref_find_elt(ref, key->area) == NULL)
3417 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003418 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003419 free_trash_chunk(key);
3420 break;
3421 }
3422
3423 case ACT_HTTP_SET_MAP: {
3424 struct pat_ref *ref;
3425 struct buffer *key, *value;
3426
3427 /* collect reference */
3428 ref = pat_ref_lookup(rule->arg.map.ref);
3429 if (!ref)
3430 continue;
3431
3432 /* allocate key */
3433 key = alloc_trash_chunk();
3434 if (!key) {
3435 rule_ret = HTTP_RULE_RES_BADREQ;
3436 goto end;
3437 }
3438
3439 /* allocate value */
3440 value = alloc_trash_chunk();
3441 if (!value) {
3442 free_trash_chunk(key);
3443 rule_ret = HTTP_RULE_RES_BADREQ;
3444 goto end;
3445 }
3446
3447 /* collect key */
3448 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3449 key->area[key->data] = '\0';
3450
3451 /* collect value */
3452 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3453 value->area[value->data] = '\0';
3454
3455 /* perform update */
3456 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3457 if (pat_ref_find_elt(ref, key->area) != NULL)
3458 /* update entry if it exists */
3459 pat_ref_set(ref, key->area, value->area, NULL);
3460 else
3461 /* insert a new entry */
3462 pat_ref_add(ref, key->area, value->area, NULL);
3463 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3464 free_trash_chunk(key);
3465 free_trash_chunk(value);
3466 break;
3467 }
3468
3469 case ACT_HTTP_REDIR:
3470 rule_ret = HTTP_RULE_RES_DONE;
3471 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3472 rule_ret = HTTP_RULE_RES_BADREQ;
3473 goto end;
3474
3475 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3476 /* Note: only the first valid tracking parameter of each
3477 * applies.
3478 */
3479 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3480 struct stktable *t;
3481 struct stksess *ts;
3482 struct stktable_key *key;
3483 void *ptr;
3484
3485 t = rule->arg.trk_ctr.table.t;
3486 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3487 rule->arg.trk_ctr.expr, NULL);
3488
3489 if (key && (ts = stktable_get_entry(t, key))) {
3490 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3491
3492 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3493
3494 /* let's count a new HTTP request as it's the first time we do it */
3495 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3496 if (ptr)
3497 stktable_data_cast(ptr, http_req_cnt)++;
3498
3499 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3500 if (ptr)
3501 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3502 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3503
3504 /* When the client triggers a 4xx from the server, it's most often due
3505 * to a missing object or permission. These events should be tracked
3506 * because if they happen often, it may indicate a brute force or a
3507 * vulnerability scan. Normally this is done when receiving the response
3508 * but here we're tracking after this ought to have been done so we have
3509 * to do it on purpose.
3510 */
3511 if ((unsigned)(txn->status - 400) < 100) {
3512 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3513 if (ptr)
3514 stktable_data_cast(ptr, http_err_cnt)++;
3515
3516 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3517 if (ptr)
3518 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3519 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3520 }
3521
3522 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3523
3524 /* If data was modified, we need to touch to re-schedule sync */
3525 stktable_touch_local(t, ts, 0);
3526
3527 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3528 if (sess->fe != s->be)
3529 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3530 }
3531 }
3532 break;
3533
3534 case ACT_CUSTOM:
3535 if ((s->req.flags & CF_READ_ERROR) ||
3536 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003537 (px->options & PR_O_ABRT_CLOSE)))
3538 act_flags |= ACT_FLAG_FINAL;
3539
3540 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3541 case ACT_RET_ERR:
3542 case ACT_RET_CONT:
3543 break;
3544 case ACT_RET_STOP:
3545 rule_ret = HTTP_RULE_RES_STOP;
3546 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003547 case ACT_RET_DONE:
3548 rule_ret = HTTP_RULE_RES_DONE;
3549 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003550 case ACT_RET_YIELD:
3551 s->current_rule = rule;
3552 rule_ret = HTTP_RULE_RES_YIELD;
3553 goto end;
3554 }
3555 break;
3556
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003557 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003558 default:
3559 break;
3560 }
3561 }
3562
3563 end:
3564 /* we reached the end of the rules, nothing to report */
3565 return rule_ret;
3566}
3567
Christopher Faulet33640082018-10-24 11:53:01 +02003568/* Iterate the same filter through all request headers.
3569 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3570 * Since it can manage the switch to another backend, it updates the per-proxy
3571 * DENY stats.
3572 */
3573static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3574{
3575 struct http_txn *txn = s->txn;
3576 struct htx *htx;
3577 struct buffer *hdr = get_trash_chunk();
3578 int32_t pos;
3579
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003580 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003581
Christopher Fauleta3f15502019-05-13 15:27:23 +02003582 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003583 struct htx_blk *blk = htx_get_blk(htx, pos);
3584 enum htx_blk_type type;
3585 struct ist n, v;
3586
3587 next_hdr:
3588 type = htx_get_blk_type(blk);
3589 if (type == HTX_BLK_EOH)
3590 break;
3591 if (type != HTX_BLK_HDR)
3592 continue;
3593
3594 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3595 return 1;
3596 else if (unlikely(txn->flags & TX_CLALLOW) &&
3597 (exp->action == ACT_ALLOW ||
3598 exp->action == ACT_DENY ||
3599 exp->action == ACT_TARPIT))
3600 return 0;
3601
3602 n = htx_get_blk_name(htx, blk);
3603 v = htx_get_blk_value(htx, blk);
3604
Christopher Faulet02e771a2019-02-26 15:36:05 +01003605 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003606 hdr->area[hdr->data++] = ':';
3607 hdr->area[hdr->data++] = ' ';
3608 chunk_memcat(hdr, v.ptr, v.len);
3609
3610 /* Now we have one header in <hdr> */
3611
3612 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3613 struct http_hdr_ctx ctx;
3614 int len;
3615
3616 switch (exp->action) {
3617 case ACT_ALLOW:
3618 txn->flags |= TX_CLALLOW;
3619 goto end;
3620
3621 case ACT_DENY:
3622 txn->flags |= TX_CLDENY;
3623 goto end;
3624
3625 case ACT_TARPIT:
3626 txn->flags |= TX_CLTARPIT;
3627 goto end;
3628
3629 case ACT_REPLACE:
3630 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3631 if (len < 0)
3632 return -1;
3633
3634 http_parse_header(ist2(trash.area, len), &n, &v);
3635 ctx.blk = blk;
3636 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003637 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003638 if (!http_replace_header(htx, &ctx, n, v))
3639 return -1;
3640 if (!ctx.blk)
3641 goto end;
3642 pos = htx_get_blk_pos(htx, blk);
3643 break;
3644
3645 case ACT_REMOVE:
3646 ctx.blk = blk;
3647 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003648 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003649 if (!http_remove_header(htx, &ctx))
3650 return -1;
3651 if (!ctx.blk)
3652 goto end;
3653 pos = htx_get_blk_pos(htx, blk);
3654 goto next_hdr;
3655
3656 }
3657 }
3658 }
3659 end:
3660 return 0;
3661}
3662
3663/* Apply the filter to the request line.
3664 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3665 * or -1 if a replacement resulted in an invalid request line.
3666 * Since it can manage the switch to another backend, it updates the per-proxy
3667 * DENY stats.
3668 */
3669static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3670{
3671 struct http_txn *txn = s->txn;
3672 struct htx *htx;
3673 struct buffer *reqline = get_trash_chunk();
3674 int done;
3675
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003676 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003677
3678 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3679 return 1;
3680 else if (unlikely(txn->flags & TX_CLALLOW) &&
3681 (exp->action == ACT_ALLOW ||
3682 exp->action == ACT_DENY ||
3683 exp->action == ACT_TARPIT))
3684 return 0;
3685 else if (exp->action == ACT_REMOVE)
3686 return 0;
3687
3688 done = 0;
3689
Christopher Faulet297fbb42019-05-13 14:41:27 +02003690 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003691
3692 /* Now we have the request line between cur_ptr and cur_end */
3693 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003694 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003695 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003696 int len;
3697
3698 switch (exp->action) {
3699 case ACT_ALLOW:
3700 txn->flags |= TX_CLALLOW;
3701 done = 1;
3702 break;
3703
3704 case ACT_DENY:
3705 txn->flags |= TX_CLDENY;
3706 done = 1;
3707 break;
3708
3709 case ACT_TARPIT:
3710 txn->flags |= TX_CLTARPIT;
3711 done = 1;
3712 break;
3713
3714 case ACT_REPLACE:
3715 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3716 if (len < 0)
3717 return -1;
3718
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003719 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3720 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3721 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003722 return -1;
3723 done = 1;
3724 break;
3725 }
3726 }
3727 return done;
3728}
3729
3730/*
3731 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3732 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3733 * unparsable request. Since it can manage the switch to another backend, it
3734 * updates the per-proxy DENY stats.
3735 */
3736static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3737{
3738 struct session *sess = s->sess;
3739 struct http_txn *txn = s->txn;
3740 struct hdr_exp *exp;
3741
3742 for (exp = px->req_exp; exp; exp = exp->next) {
3743 int ret;
3744
3745 /*
3746 * The interleaving of transformations and verdicts
3747 * makes it difficult to decide to continue or stop
3748 * the evaluation.
3749 */
3750
3751 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3752 break;
3753
3754 if ((txn->flags & TX_CLALLOW) &&
3755 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3756 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3757 continue;
3758
3759 /* if this filter had a condition, evaluate it now and skip to
3760 * next filter if the condition does not match.
3761 */
3762 if (exp->cond) {
3763 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3764 ret = acl_pass(ret);
3765 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3766 ret = !ret;
3767
3768 if (!ret)
3769 continue;
3770 }
3771
3772 /* Apply the filter to the request line. */
3773 ret = htx_apply_filter_to_req_line(s, req, exp);
3774 if (unlikely(ret < 0))
3775 return -1;
3776
3777 if (likely(ret == 0)) {
3778 /* The filter did not match the request, it can be
3779 * iterated through all headers.
3780 */
3781 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3782 return -1;
3783 }
3784 }
3785 return 0;
3786}
3787
3788/* Iterate the same filter through all response headers contained in <res>.
3789 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3790 */
3791static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3792{
3793 struct http_txn *txn = s->txn;
3794 struct htx *htx;
3795 struct buffer *hdr = get_trash_chunk();
3796 int32_t pos;
3797
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003798 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003799
Christopher Fauleta3f15502019-05-13 15:27:23 +02003800 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003801 struct htx_blk *blk = htx_get_blk(htx, pos);
3802 enum htx_blk_type type;
3803 struct ist n, v;
3804
3805 next_hdr:
3806 type = htx_get_blk_type(blk);
3807 if (type == HTX_BLK_EOH)
3808 break;
3809 if (type != HTX_BLK_HDR)
3810 continue;
3811
3812 if (unlikely(txn->flags & TX_SVDENY))
3813 return 1;
3814 else if (unlikely(txn->flags & TX_SVALLOW) &&
3815 (exp->action == ACT_ALLOW ||
3816 exp->action == ACT_DENY))
3817 return 0;
3818
3819 n = htx_get_blk_name(htx, blk);
3820 v = htx_get_blk_value(htx, blk);
3821
Christopher Faulet02e771a2019-02-26 15:36:05 +01003822 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003823 hdr->area[hdr->data++] = ':';
3824 hdr->area[hdr->data++] = ' ';
3825 chunk_memcat(hdr, v.ptr, v.len);
3826
3827 /* Now we have one header in <hdr> */
3828
3829 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3830 struct http_hdr_ctx ctx;
3831 int len;
3832
3833 switch (exp->action) {
3834 case ACT_ALLOW:
3835 txn->flags |= TX_SVALLOW;
3836 goto end;
3837 break;
3838
3839 case ACT_DENY:
3840 txn->flags |= TX_SVDENY;
3841 goto end;
3842 break;
3843
3844 case ACT_REPLACE:
3845 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3846 if (len < 0)
3847 return -1;
3848
3849 http_parse_header(ist2(trash.area, len), &n, &v);
3850 ctx.blk = blk;
3851 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003852 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003853 if (!http_replace_header(htx, &ctx, n, v))
3854 return -1;
3855 if (!ctx.blk)
3856 goto end;
3857 pos = htx_get_blk_pos(htx, blk);
3858 break;
3859
3860 case ACT_REMOVE:
3861 ctx.blk = blk;
3862 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003863 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003864 if (!http_remove_header(htx, &ctx))
3865 return -1;
3866 if (!ctx.blk)
3867 goto end;
3868 pos = htx_get_blk_pos(htx, blk);
3869 goto next_hdr;
3870 }
3871 }
3872
3873 }
3874 end:
3875 return 0;
3876}
3877
3878/* Apply the filter to the status line in the response buffer <res>.
3879 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3880 * or -1 if a replacement resulted in an invalid status line.
3881 */
3882static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3883{
3884 struct http_txn *txn = s->txn;
3885 struct htx *htx;
3886 struct buffer *resline = get_trash_chunk();
3887 int done;
3888
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003889 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003890
3891 if (unlikely(txn->flags & TX_SVDENY))
3892 return 1;
3893 else if (unlikely(txn->flags & TX_SVALLOW) &&
3894 (exp->action == ACT_ALLOW ||
3895 exp->action == ACT_DENY))
3896 return 0;
3897 else if (exp->action == ACT_REMOVE)
3898 return 0;
3899
3900 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003901 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003902
3903 /* Now we have the status line between cur_ptr and cur_end */
3904 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003905 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003906 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003907 int len;
3908
3909 switch (exp->action) {
3910 case ACT_ALLOW:
3911 txn->flags |= TX_SVALLOW;
3912 done = 1;
3913 break;
3914
3915 case ACT_DENY:
3916 txn->flags |= TX_SVDENY;
3917 done = 1;
3918 break;
3919
3920 case ACT_REPLACE:
3921 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3922 if (len < 0)
3923 return -1;
3924
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003925 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3926 sl->info.res.status = strl2ui(code.ptr, code.len);
3927 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003928 return -1;
3929
3930 done = 1;
3931 return 1;
3932 }
3933 }
3934 return done;
3935}
3936
3937/*
3938 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3939 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3940 * unparsable response.
3941 */
3942static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3943{
3944 struct session *sess = s->sess;
3945 struct http_txn *txn = s->txn;
3946 struct hdr_exp *exp;
3947
3948 for (exp = px->rsp_exp; exp; exp = exp->next) {
3949 int ret;
3950
3951 /*
3952 * The interleaving of transformations and verdicts
3953 * makes it difficult to decide to continue or stop
3954 * the evaluation.
3955 */
3956
3957 if (txn->flags & TX_SVDENY)
3958 break;
3959
3960 if ((txn->flags & TX_SVALLOW) &&
3961 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3962 exp->action == ACT_PASS)) {
3963 exp = exp->next;
3964 continue;
3965 }
3966
3967 /* if this filter had a condition, evaluate it now and skip to
3968 * next filter if the condition does not match.
3969 */
3970 if (exp->cond) {
3971 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3972 ret = acl_pass(ret);
3973 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3974 ret = !ret;
3975 if (!ret)
3976 continue;
3977 }
3978
3979 /* Apply the filter to the status line. */
3980 ret = htx_apply_filter_to_sts_line(s, res, exp);
3981 if (unlikely(ret < 0))
3982 return -1;
3983
3984 if (likely(ret == 0)) {
3985 /* The filter did not match the response, it can be
3986 * iterated through all headers.
3987 */
3988 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3989 return -1;
3990 }
3991 }
3992 return 0;
3993}
3994
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003995/*
3996 * Manage client-side cookie. It can impact performance by about 2% so it is
3997 * desirable to call it only when needed. This code is quite complex because
3998 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3999 * highly recommended not to touch this part without a good reason !
4000 */
4001static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
4002{
4003 struct session *sess = s->sess;
4004 struct http_txn *txn = s->txn;
4005 struct htx *htx;
4006 struct http_hdr_ctx ctx;
4007 char *hdr_beg, *hdr_end, *del_from;
4008 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4009 int preserve_hdr;
4010
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004011 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004012 ctx.blk = NULL;
4013 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004014 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004015 del_from = NULL; /* nothing to be deleted */
4016 preserve_hdr = 0; /* assume we may kill the whole header */
4017
4018 /* Now look for cookies. Conforming to RFC2109, we have to support
4019 * attributes whose name begin with a '$', and associate them with
4020 * the right cookie, if we want to delete this cookie.
4021 * So there are 3 cases for each cookie read :
4022 * 1) it's a special attribute, beginning with a '$' : ignore it.
4023 * 2) it's a server id cookie that we *MAY* want to delete : save
4024 * some pointers on it (last semi-colon, beginning of cookie...)
4025 * 3) it's an application cookie : we *MAY* have to delete a previous
4026 * "special" cookie.
4027 * At the end of loop, if a "special" cookie remains, we may have to
4028 * remove it. If no application cookie persists in the header, we
4029 * *MUST* delete it.
4030 *
4031 * Note: RFC2965 is unclear about the processing of spaces around
4032 * the equal sign in the ATTR=VALUE form. A careful inspection of
4033 * the RFC explicitly allows spaces before it, and not within the
4034 * tokens (attrs or values). An inspection of RFC2109 allows that
4035 * too but section 10.1.3 lets one think that spaces may be allowed
4036 * after the equal sign too, resulting in some (rare) buggy
4037 * implementations trying to do that. So let's do what servers do.
4038 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4039 * allowed quoted strings in values, with any possible character
4040 * after a backslash, including control chars and delimitors, which
4041 * causes parsing to become ambiguous. Browsers also allow spaces
4042 * within values even without quotes.
4043 *
4044 * We have to keep multiple pointers in order to support cookie
4045 * removal at the beginning, middle or end of header without
4046 * corrupting the header. All of these headers are valid :
4047 *
4048 * hdr_beg hdr_end
4049 * | |
4050 * v |
4051 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4052 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4053 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4054 * | | | | | | |
4055 * | | | | | | |
4056 * | | | | | | +--> next
4057 * | | | | | +----> val_end
4058 * | | | | +-----------> val_beg
4059 * | | | +--------------> equal
4060 * | | +----------------> att_end
4061 * | +---------------------> att_beg
4062 * +--------------------------> prev
4063 *
4064 */
4065 hdr_beg = ctx.value.ptr;
4066 hdr_end = hdr_beg + ctx.value.len;
4067 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4068 /* Iterate through all cookies on this line */
4069
4070 /* find att_beg */
4071 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004072 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004073 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004074 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004075
4076 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4077 att_beg++;
4078
4079 /* find att_end : this is the first character after the last non
4080 * space before the equal. It may be equal to hdr_end.
4081 */
4082 equal = att_end = att_beg;
4083 while (equal < hdr_end) {
4084 if (*equal == '=' || *equal == ',' || *equal == ';')
4085 break;
4086 if (HTTP_IS_SPHT(*equal++))
4087 continue;
4088 att_end = equal;
4089 }
4090
4091 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4092 * is between <att_beg> and <equal>, both may be identical.
4093 */
4094 /* look for end of cookie if there is an equal sign */
4095 if (equal < hdr_end && *equal == '=') {
4096 /* look for the beginning of the value */
4097 val_beg = equal + 1;
4098 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4099 val_beg++;
4100
4101 /* find the end of the value, respecting quotes */
4102 next = http_find_cookie_value_end(val_beg, hdr_end);
4103
4104 /* make val_end point to the first white space or delimitor after the value */
4105 val_end = next;
4106 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4107 val_end--;
4108 }
4109 else
4110 val_beg = val_end = next = equal;
4111
4112 /* We have nothing to do with attributes beginning with
4113 * '$'. However, they will automatically be removed if a
4114 * header before them is removed, since they're supposed
4115 * to be linked together.
4116 */
4117 if (*att_beg == '$')
4118 continue;
4119
4120 /* Ignore cookies with no equal sign */
4121 if (equal == next) {
4122 /* This is not our cookie, so we must preserve it. But if we already
4123 * scheduled another cookie for removal, we cannot remove the
4124 * complete header, but we can remove the previous block itself.
4125 */
4126 preserve_hdr = 1;
4127 if (del_from != NULL) {
4128 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4129 val_end += delta;
4130 next += delta;
4131 hdr_end += delta;
4132 prev = del_from;
4133 del_from = NULL;
4134 }
4135 continue;
4136 }
4137
4138 /* if there are spaces around the equal sign, we need to
4139 * strip them otherwise we'll get trouble for cookie captures,
4140 * or even for rewrites. Since this happens extremely rarely,
4141 * it does not hurt performance.
4142 */
4143 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4144 int stripped_before = 0;
4145 int stripped_after = 0;
4146
4147 if (att_end != equal) {
4148 memmove(att_end, equal, hdr_end - equal);
4149 stripped_before = (att_end - equal);
4150 equal += stripped_before;
4151 val_beg += stripped_before;
4152 }
4153
4154 if (val_beg > equal + 1) {
4155 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4156 stripped_after = (equal + 1) - val_beg;
4157 val_beg += stripped_after;
4158 stripped_before += stripped_after;
4159 }
4160
4161 val_end += stripped_before;
4162 next += stripped_before;
4163 hdr_end += stripped_before;
4164 }
4165 /* now everything is as on the diagram above */
4166
4167 /* First, let's see if we want to capture this cookie. We check
4168 * that we don't already have a client side cookie, because we
4169 * can only capture one. Also as an optimisation, we ignore
4170 * cookies shorter than the declared name.
4171 */
4172 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4173 (val_end - att_beg >= sess->fe->capture_namelen) &&
4174 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4175 int log_len = val_end - att_beg;
4176
4177 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4178 ha_alert("HTTP logging : out of memory.\n");
4179 } else {
4180 if (log_len > sess->fe->capture_len)
4181 log_len = sess->fe->capture_len;
4182 memcpy(txn->cli_cookie, att_beg, log_len);
4183 txn->cli_cookie[log_len] = 0;
4184 }
4185 }
4186
4187 /* Persistence cookies in passive, rewrite or insert mode have the
4188 * following form :
4189 *
4190 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4191 *
4192 * For cookies in prefix mode, the form is :
4193 *
4194 * Cookie: NAME=SRV~VALUE
4195 */
4196 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4197 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4198 struct server *srv = s->be->srv;
4199 char *delim;
4200
4201 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4202 * have the server ID between val_beg and delim, and the original cookie between
4203 * delim+1 and val_end. Otherwise, delim==val_end :
4204 *
4205 * hdr_beg
4206 * |
4207 * v
4208 * NAME=SRV; # in all but prefix modes
4209 * NAME=SRV~OPAQUE ; # in prefix mode
4210 * || || | |+-> next
4211 * || || | +--> val_end
4212 * || || +---------> delim
4213 * || |+------------> val_beg
4214 * || +-------------> att_end = equal
4215 * |+-----------------> att_beg
4216 * +------------------> prev
4217 *
4218 */
4219 if (s->be->ck_opts & PR_CK_PFX) {
4220 for (delim = val_beg; delim < val_end; delim++)
4221 if (*delim == COOKIE_DELIM)
4222 break;
4223 }
4224 else {
4225 char *vbar1;
4226 delim = val_end;
4227 /* Now check if the cookie contains a date field, which would
4228 * appear after a vertical bar ('|') just after the server name
4229 * and before the delimiter.
4230 */
4231 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4232 if (vbar1) {
4233 /* OK, so left of the bar is the server's cookie and
4234 * right is the last seen date. It is a base64 encoded
4235 * 30-bit value representing the UNIX date since the
4236 * epoch in 4-second quantities.
4237 */
4238 int val;
4239 delim = vbar1++;
4240 if (val_end - vbar1 >= 5) {
4241 val = b64tos30(vbar1);
4242 if (val > 0)
4243 txn->cookie_last_date = val << 2;
4244 }
4245 /* look for a second vertical bar */
4246 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4247 if (vbar1 && (val_end - vbar1 > 5)) {
4248 val = b64tos30(vbar1 + 1);
4249 if (val > 0)
4250 txn->cookie_first_date = val << 2;
4251 }
4252 }
4253 }
4254
4255 /* if the cookie has an expiration date and the proxy wants to check
4256 * it, then we do that now. We first check if the cookie is too old,
4257 * then only if it has expired. We detect strict overflow because the
4258 * time resolution here is not great (4 seconds). Cookies with dates
4259 * in the future are ignored if their offset is beyond one day. This
4260 * allows an admin to fix timezone issues without expiring everyone
4261 * and at the same time avoids keeping unwanted side effects for too
4262 * long.
4263 */
4264 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4265 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4266 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4267 txn->flags &= ~TX_CK_MASK;
4268 txn->flags |= TX_CK_OLD;
4269 delim = val_beg; // let's pretend we have not found the cookie
4270 txn->cookie_first_date = 0;
4271 txn->cookie_last_date = 0;
4272 }
4273 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4274 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4275 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4276 txn->flags &= ~TX_CK_MASK;
4277 txn->flags |= TX_CK_EXPIRED;
4278 delim = val_beg; // let's pretend we have not found the cookie
4279 txn->cookie_first_date = 0;
4280 txn->cookie_last_date = 0;
4281 }
4282
4283 /* Here, we'll look for the first running server which supports the cookie.
4284 * This allows to share a same cookie between several servers, for example
4285 * to dedicate backup servers to specific servers only.
4286 * However, to prevent clients from sticking to cookie-less backup server
4287 * when they have incidentely learned an empty cookie, we simply ignore
4288 * empty cookies and mark them as invalid.
4289 * The same behaviour is applied when persistence must be ignored.
4290 */
4291 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4292 srv = NULL;
4293
4294 while (srv) {
4295 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4296 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4297 if ((srv->cur_state != SRV_ST_STOPPED) ||
4298 (s->be->options & PR_O_PERSIST) ||
4299 (s->flags & SF_FORCE_PRST)) {
4300 /* we found the server and we can use it */
4301 txn->flags &= ~TX_CK_MASK;
4302 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4303 s->flags |= SF_DIRECT | SF_ASSIGNED;
4304 s->target = &srv->obj_type;
4305 break;
4306 } else {
4307 /* we found a server, but it's down,
4308 * mark it as such and go on in case
4309 * another one is available.
4310 */
4311 txn->flags &= ~TX_CK_MASK;
4312 txn->flags |= TX_CK_DOWN;
4313 }
4314 }
4315 srv = srv->next;
4316 }
4317
4318 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4319 /* no server matched this cookie or we deliberately skipped it */
4320 txn->flags &= ~TX_CK_MASK;
4321 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4322 txn->flags |= TX_CK_UNUSED;
4323 else
4324 txn->flags |= TX_CK_INVALID;
4325 }
4326
4327 /* depending on the cookie mode, we may have to either :
4328 * - delete the complete cookie if we're in insert+indirect mode, so that
4329 * the server never sees it ;
4330 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004331 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004332 * if we're in cookie prefix mode
4333 */
4334 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4335 int delta; /* negative */
4336
4337 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4338 delta = val_beg - (delim + 1);
4339 val_end += delta;
4340 next += delta;
4341 hdr_end += delta;
4342 del_from = NULL;
4343 preserve_hdr = 1; /* we want to keep this cookie */
4344 }
4345 else if (del_from == NULL &&
4346 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4347 del_from = prev;
4348 }
4349 }
4350 else {
4351 /* This is not our cookie, so we must preserve it. But if we already
4352 * scheduled another cookie for removal, we cannot remove the
4353 * complete header, but we can remove the previous block itself.
4354 */
4355 preserve_hdr = 1;
4356
4357 if (del_from != NULL) {
4358 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4359 if (att_beg >= del_from)
4360 att_beg += delta;
4361 if (att_end >= del_from)
4362 att_end += delta;
4363 val_beg += delta;
4364 val_end += delta;
4365 next += delta;
4366 hdr_end += delta;
4367 prev = del_from;
4368 del_from = NULL;
4369 }
4370 }
4371
4372 /* continue with next cookie on this header line */
4373 att_beg = next;
4374 } /* for each cookie */
4375
4376
4377 /* There are no more cookies on this line.
4378 * We may still have one (or several) marked for deletion at the
4379 * end of the line. We must do this now in two ways :
4380 * - if some cookies must be preserved, we only delete from the
4381 * mark to the end of line ;
4382 * - if nothing needs to be preserved, simply delete the whole header
4383 */
4384 if (del_from) {
4385 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4386 }
4387 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004388 if (hdr_beg != hdr_end)
4389 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004390 else
4391 http_remove_header(htx, &ctx);
4392 }
4393 } /* for each "Cookie header */
4394}
4395
4396/*
4397 * Manage server-side cookies. It can impact performance by about 2% so it is
4398 * desirable to call it only when needed. This function is also used when we
4399 * just need to know if there is a cookie (eg: for check-cache).
4400 */
4401static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4402{
4403 struct session *sess = s->sess;
4404 struct http_txn *txn = s->txn;
4405 struct htx *htx;
4406 struct http_hdr_ctx ctx;
4407 struct server *srv;
4408 char *hdr_beg, *hdr_end;
4409 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004410 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004411
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004412 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004413
4414 ctx.blk = NULL;
4415 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004416 int is_first = 1;
4417
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004418 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4419 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4420 break;
4421 is_cookie2 = 1;
4422 }
4423
4424 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4425 * <prev> points to the colon.
4426 */
4427 txn->flags |= TX_SCK_PRESENT;
4428
4429 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4430 * check-cache is enabled) and we are not interested in checking
4431 * them. Warning, the cookie capture is declared in the frontend.
4432 */
4433 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4434 break;
4435
4436 /* OK so now we know we have to process this response cookie.
4437 * The format of the Set-Cookie header is slightly different
4438 * from the format of the Cookie header in that it does not
4439 * support the comma as a cookie delimiter (thus the header
4440 * cannot be folded) because the Expires attribute described in
4441 * the original Netscape's spec may contain an unquoted date
4442 * with a comma inside. We have to live with this because
4443 * many browsers don't support Max-Age and some browsers don't
4444 * support quoted strings. However the Set-Cookie2 header is
4445 * clean.
4446 *
4447 * We have to keep multiple pointers in order to support cookie
4448 * removal at the beginning, middle or end of header without
4449 * corrupting the header (in case of set-cookie2). A special
4450 * pointer, <scav> points to the beginning of the set-cookie-av
4451 * fields after the first semi-colon. The <next> pointer points
4452 * either to the end of line (set-cookie) or next unquoted comma
4453 * (set-cookie2). All of these headers are valid :
4454 *
4455 * hdr_beg hdr_end
4456 * | |
4457 * v |
4458 * NAME1 = VALUE 1 ; Secure; Path="/" |
4459 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4460 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4461 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4462 * | | | | | | | |
4463 * | | | | | | | +-> next
4464 * | | | | | | +------------> scav
4465 * | | | | | +--------------> val_end
4466 * | | | | +--------------------> val_beg
4467 * | | | +----------------------> equal
4468 * | | +------------------------> att_end
4469 * | +----------------------------> att_beg
4470 * +------------------------------> prev
4471 * -------------------------------> hdr_beg
4472 */
4473 hdr_beg = ctx.value.ptr;
4474 hdr_end = hdr_beg + ctx.value.len;
4475 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4476
4477 /* Iterate through all cookies on this line */
4478
4479 /* find att_beg */
4480 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004481 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004482 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004483 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004484
4485 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4486 att_beg++;
4487
4488 /* find att_end : this is the first character after the last non
4489 * space before the equal. It may be equal to hdr_end.
4490 */
4491 equal = att_end = att_beg;
4492
4493 while (equal < hdr_end) {
4494 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4495 break;
4496 if (HTTP_IS_SPHT(*equal++))
4497 continue;
4498 att_end = equal;
4499 }
4500
4501 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4502 * is between <att_beg> and <equal>, both may be identical.
4503 */
4504
4505 /* look for end of cookie if there is an equal sign */
4506 if (equal < hdr_end && *equal == '=') {
4507 /* look for the beginning of the value */
4508 val_beg = equal + 1;
4509 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4510 val_beg++;
4511
4512 /* find the end of the value, respecting quotes */
4513 next = http_find_cookie_value_end(val_beg, hdr_end);
4514
4515 /* make val_end point to the first white space or delimitor after the value */
4516 val_end = next;
4517 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4518 val_end--;
4519 }
4520 else {
4521 /* <equal> points to next comma, semi-colon or EOL */
4522 val_beg = val_end = next = equal;
4523 }
4524
4525 if (next < hdr_end) {
4526 /* Set-Cookie2 supports multiple cookies, and <next> points to
4527 * a colon or semi-colon before the end. So skip all attr-value
4528 * pairs and look for the next comma. For Set-Cookie, since
4529 * commas are permitted in values, skip to the end.
4530 */
4531 if (is_cookie2)
4532 next = http_find_hdr_value_end(next, hdr_end);
4533 else
4534 next = hdr_end;
4535 }
4536
4537 /* Now everything is as on the diagram above */
4538
4539 /* Ignore cookies with no equal sign */
4540 if (equal == val_end)
4541 continue;
4542
4543 /* If there are spaces around the equal sign, we need to
4544 * strip them otherwise we'll get trouble for cookie captures,
4545 * or even for rewrites. Since this happens extremely rarely,
4546 * it does not hurt performance.
4547 */
4548 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4549 int stripped_before = 0;
4550 int stripped_after = 0;
4551
4552 if (att_end != equal) {
4553 memmove(att_end, equal, hdr_end - equal);
4554 stripped_before = (att_end - equal);
4555 equal += stripped_before;
4556 val_beg += stripped_before;
4557 }
4558
4559 if (val_beg > equal + 1) {
4560 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4561 stripped_after = (equal + 1) - val_beg;
4562 val_beg += stripped_after;
4563 stripped_before += stripped_after;
4564 }
4565
4566 val_end += stripped_before;
4567 next += stripped_before;
4568 hdr_end += stripped_before;
4569
Christopher Faulet41dc8432019-06-18 09:49:16 +02004570 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004571 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004572 }
4573
4574 /* First, let's see if we want to capture this cookie. We check
4575 * that we don't already have a server side cookie, because we
4576 * can only capture one. Also as an optimisation, we ignore
4577 * cookies shorter than the declared name.
4578 */
4579 if (sess->fe->capture_name != NULL &&
4580 txn->srv_cookie == NULL &&
4581 (val_end - att_beg >= sess->fe->capture_namelen) &&
4582 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4583 int log_len = val_end - att_beg;
4584 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4585 ha_alert("HTTP logging : out of memory.\n");
4586 }
4587 else {
4588 if (log_len > sess->fe->capture_len)
4589 log_len = sess->fe->capture_len;
4590 memcpy(txn->srv_cookie, att_beg, log_len);
4591 txn->srv_cookie[log_len] = 0;
4592 }
4593 }
4594
4595 srv = objt_server(s->target);
4596 /* now check if we need to process it for persistence */
4597 if (!(s->flags & SF_IGNORE_PRST) &&
4598 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4599 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4600 /* assume passive cookie by default */
4601 txn->flags &= ~TX_SCK_MASK;
4602 txn->flags |= TX_SCK_FOUND;
4603
4604 /* If the cookie is in insert mode on a known server, we'll delete
4605 * this occurrence because we'll insert another one later.
4606 * We'll delete it too if the "indirect" option is set and we're in
4607 * a direct access.
4608 */
4609 if (s->be->ck_opts & PR_CK_PSV) {
4610 /* The "preserve" flag was set, we don't want to touch the
4611 * server's cookie.
4612 */
4613 }
4614 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4615 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4616 /* this cookie must be deleted */
4617 if (prev == hdr_beg && next == hdr_end) {
4618 /* whole header */
4619 http_remove_header(htx, &ctx);
4620 /* note: while both invalid now, <next> and <hdr_end>
4621 * are still equal, so the for() will stop as expected.
4622 */
4623 } else {
4624 /* just remove the value */
4625 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4626 next = prev;
4627 hdr_end += delta;
4628 }
4629 txn->flags &= ~TX_SCK_MASK;
4630 txn->flags |= TX_SCK_DELETED;
4631 /* and go on with next cookie */
4632 }
4633 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4634 /* replace bytes val_beg->val_end with the cookie name associated
4635 * with this server since we know it.
4636 */
4637 int sliding, delta;
4638
4639 ctx.value = ist2(val_beg, val_end - val_beg);
4640 ctx.lws_before = ctx.lws_after = 0;
4641 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4642 delta = srv->cklen - (val_end - val_beg);
4643 sliding = (ctx.value.ptr - val_beg);
4644 hdr_beg += sliding;
4645 val_beg += sliding;
4646 next += sliding + delta;
4647 hdr_end += sliding + delta;
4648
4649 txn->flags &= ~TX_SCK_MASK;
4650 txn->flags |= TX_SCK_REPLACED;
4651 }
4652 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4653 /* insert the cookie name associated with this server
4654 * before existing cookie, and insert a delimiter between them..
4655 */
4656 int sliding, delta;
4657 ctx.value = ist2(val_beg, 0);
4658 ctx.lws_before = ctx.lws_after = 0;
4659 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4660 delta = srv->cklen + 1;
4661 sliding = (ctx.value.ptr - val_beg);
4662 hdr_beg += sliding;
4663 val_beg += sliding;
4664 next += sliding + delta;
4665 hdr_end += sliding + delta;
4666
4667 val_beg[srv->cklen] = COOKIE_DELIM;
4668 txn->flags &= ~TX_SCK_MASK;
4669 txn->flags |= TX_SCK_REPLACED;
4670 }
4671 }
4672 /* that's done for this cookie, check the next one on the same
4673 * line when next != hdr_end (only if is_cookie2).
4674 */
4675 }
4676 }
4677}
4678
Christopher Faulet25a02f62018-10-24 12:00:25 +02004679/*
4680 * Parses the Cache-Control and Pragma request header fields to determine if
4681 * the request may be served from the cache and/or if it is cacheable. Updates
4682 * s->txn->flags.
4683 */
4684void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4685{
4686 struct http_txn *txn = s->txn;
4687 struct htx *htx;
4688 int32_t pos;
4689 int pragma_found, cc_found, i;
4690
4691 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4692 return; /* nothing more to do here */
4693
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004694 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004695 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004696 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004697 struct htx_blk *blk = htx_get_blk(htx, pos);
4698 enum htx_blk_type type = htx_get_blk_type(blk);
4699 struct ist n, v;
4700
4701 if (type == HTX_BLK_EOH)
4702 break;
4703 if (type != HTX_BLK_HDR)
4704 continue;
4705
4706 n = htx_get_blk_name(htx, blk);
4707 v = htx_get_blk_value(htx, blk);
4708
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004709 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004710 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4711 pragma_found = 1;
4712 continue;
4713 }
4714 }
4715
4716 /* Don't use the cache and don't try to store if we found the
4717 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004718 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004719 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4720 txn->flags |= TX_CACHE_IGNORE;
4721 continue;
4722 }
4723
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004724 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004725 continue;
4726
4727 /* OK, right now we know we have a cache-control header */
4728 cc_found = 1;
4729 if (!v.len) /* no info */
4730 continue;
4731
4732 i = 0;
4733 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4734 !isspace((unsigned char)*(v.ptr+i)))
4735 i++;
4736
4737 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4738 * values after max-age, max-stale nor min-fresh, we simply don't
4739 * use the cache when they're specified.
4740 */
4741 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4742 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4743 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4744 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4745 txn->flags |= TX_CACHE_IGNORE;
4746 continue;
4747 }
4748
4749 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4750 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4751 continue;
4752 }
4753 }
4754
4755 /* RFC7234#5.4:
4756 * When the Cache-Control header field is also present and
4757 * understood in a request, Pragma is ignored.
4758 * When the Cache-Control header field is not present in a
4759 * request, caches MUST consider the no-cache request
4760 * pragma-directive as having the same effect as if
4761 * "Cache-Control: no-cache" were present.
4762 */
4763 if (!cc_found && pragma_found)
4764 txn->flags |= TX_CACHE_IGNORE;
4765}
4766
4767/*
4768 * Check if response is cacheable or not. Updates s->txn->flags.
4769 */
4770void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4771{
4772 struct http_txn *txn = s->txn;
4773 struct htx *htx;
4774 int32_t pos;
4775 int i;
4776
4777 if (txn->status < 200) {
4778 /* do not try to cache interim responses! */
4779 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4780 return;
4781 }
4782
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004783 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004784 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004785 struct htx_blk *blk = htx_get_blk(htx, pos);
4786 enum htx_blk_type type = htx_get_blk_type(blk);
4787 struct ist n, v;
4788
4789 if (type == HTX_BLK_EOH)
4790 break;
4791 if (type != HTX_BLK_HDR)
4792 continue;
4793
4794 n = htx_get_blk_name(htx, blk);
4795 v = htx_get_blk_value(htx, blk);
4796
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004797 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004798 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4799 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4800 return;
4801 }
4802 }
4803
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004804 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004805 continue;
4806
4807 /* OK, right now we know we have a cache-control header */
4808 if (!v.len) /* no info */
4809 continue;
4810
4811 i = 0;
4812 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4813 !isspace((unsigned char)*(v.ptr+i)))
4814 i++;
4815
4816 /* we have a complete value between v.ptr and (v.ptr+i) */
4817 if (i < v.len && *(v.ptr + i) == '=') {
4818 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4819 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4820 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4821 continue;
4822 }
4823
4824 /* we have something of the form no-cache="set-cookie" */
4825 if ((v.len >= 21) &&
4826 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4827 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4828 txn->flags &= ~TX_CACHE_COOK;
4829 continue;
4830 }
4831
4832 /* OK, so we know that either p2 points to the end of string or to a comma */
4833 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4834 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4835 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4836 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4837 return;
4838 }
4839
4840 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4841 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4842 continue;
4843 }
4844 }
4845}
4846
Christopher Faulet64159df2018-10-24 21:15:35 +02004847/* send a server's name with an outgoing request over an established connection.
4848 * Note: this function is designed to be called once the request has been
4849 * scheduled for being forwarded. This is the reason why the number of forwarded
4850 * bytes have to be adjusted.
4851 */
4852int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4853{
4854 struct htx *htx;
4855 struct http_hdr_ctx ctx;
4856 struct ist hdr;
4857 uint32_t data;
4858
4859 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004860 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004861 data = htx->data;
4862
4863 ctx.blk = NULL;
4864 while (http_find_header(htx, hdr, &ctx, 1))
4865 http_remove_header(htx, &ctx);
4866 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4867
4868 if (co_data(&s->req)) {
4869 if (data >= htx->data)
4870 c_rew(&s->req, data - htx->data);
4871 else
4872 c_adv(&s->req, htx->data - data);
4873 }
4874 return 0;
4875}
4876
Christopher Faulet377c5a52018-10-24 21:21:30 +02004877/*
4878 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4879 * for the current backend.
4880 *
4881 * It is assumed that the request is either a HEAD, GET, or POST and that the
4882 * uri_auth field is valid.
4883 *
4884 * Returns 1 if stats should be provided, otherwise 0.
4885 */
4886static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4887{
4888 struct uri_auth *uri_auth = backend->uri_auth;
4889 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004890 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004891 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004892
4893 if (!uri_auth)
4894 return 0;
4895
4896 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4897 return 0;
4898
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004899 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004900 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004901 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004902
4903 /* check URI size */
4904 if (uri_auth->uri_len > uri.len)
4905 return 0;
4906
4907 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4908 return 0;
4909
4910 return 1;
4911}
4912
4913/* This function prepares an applet to handle the stats. It can deal with the
4914 * "100-continue" expectation, check that admin rules are met for POST requests,
4915 * and program a response message if something was unexpected. It cannot fail
4916 * and always relies on the stats applet to complete the job. It does not touch
4917 * analysers nor counters, which are left to the caller. It does not touch
4918 * s->target which is supposed to already point to the stats applet. The caller
4919 * is expected to have already assigned an appctx to the stream.
4920 */
4921static int htx_handle_stats(struct stream *s, struct channel *req)
4922{
4923 struct stats_admin_rule *stats_admin_rule;
4924 struct stream_interface *si = &s->si[1];
4925 struct session *sess = s->sess;
4926 struct http_txn *txn = s->txn;
4927 struct http_msg *msg = &txn->req;
4928 struct uri_auth *uri_auth = s->be->uri_auth;
4929 const char *h, *lookup, *end;
4930 struct appctx *appctx;
4931 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004932 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004933
4934 appctx = si_appctx(si);
4935 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4936 appctx->st1 = appctx->st2 = 0;
4937 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4938 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4939 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4940 appctx->ctx.stats.flags |= STAT_CHUNKED;
4941
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004942 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004943 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004944 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4945 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004946
4947 for (h = lookup; h <= end - 3; h++) {
4948 if (memcmp(h, ";up", 3) == 0) {
4949 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4950 break;
4951 }
4952 }
4953
4954 if (uri_auth->refresh) {
4955 for (h = lookup; h <= end - 10; h++) {
4956 if (memcmp(h, ";norefresh", 10) == 0) {
4957 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4958 break;
4959 }
4960 }
4961 }
4962
4963 for (h = lookup; h <= end - 4; h++) {
4964 if (memcmp(h, ";csv", 4) == 0) {
4965 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4966 break;
4967 }
4968 }
4969
4970 for (h = lookup; h <= end - 6; h++) {
4971 if (memcmp(h, ";typed", 6) == 0) {
4972 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4973 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4974 break;
4975 }
4976 }
4977
4978 for (h = lookup; h <= end - 8; h++) {
4979 if (memcmp(h, ";st=", 4) == 0) {
4980 int i;
4981 h += 4;
4982 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4983 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4984 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4985 appctx->ctx.stats.st_code = i;
4986 break;
4987 }
4988 }
4989 break;
4990 }
4991 }
4992
4993 appctx->ctx.stats.scope_str = 0;
4994 appctx->ctx.stats.scope_len = 0;
4995 for (h = lookup; h <= end - 8; h++) {
4996 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4997 int itx = 0;
4998 const char *h2;
4999 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
5000 const char *err;
5001
5002 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
5003 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01005004 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
5005 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005006 if (*h == ';' || *h == '&' || *h == ' ')
5007 break;
5008 itx++;
5009 h++;
5010 }
5011
5012 if (itx > STAT_SCOPE_TXT_MAXLEN)
5013 itx = STAT_SCOPE_TXT_MAXLEN;
5014 appctx->ctx.stats.scope_len = itx;
5015
5016 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
5017 memcpy(scope_txt, h2, itx);
5018 scope_txt[itx] = '\0';
5019 err = invalid_char(scope_txt);
5020 if (err) {
5021 /* bad char in search text => clear scope */
5022 appctx->ctx.stats.scope_str = 0;
5023 appctx->ctx.stats.scope_len = 0;
5024 }
5025 break;
5026 }
5027 }
5028
5029 /* now check whether we have some admin rules for this request */
5030 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5031 int ret = 1;
5032
5033 if (stats_admin_rule->cond) {
5034 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5035 ret = acl_pass(ret);
5036 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5037 ret = !ret;
5038 }
5039
5040 if (ret) {
5041 /* no rule, or the rule matches */
5042 appctx->ctx.stats.flags |= STAT_ADMIN;
5043 break;
5044 }
5045 }
5046
Christopher Faulet5d45e382019-02-27 15:15:23 +01005047 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5048 appctx->st0 = STAT_HTTP_HEAD;
5049 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005050 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005051 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005052 if (msg->msg_state < HTTP_MSG_DATA)
5053 req->analysers |= AN_REQ_HTTP_BODY;
5054 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005055 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005056 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005057 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5058 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5059 appctx->st0 = STAT_HTTP_LAST;
5060 }
5061 }
5062 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005063 /* Unsupported method */
5064 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5065 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5066 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005067 }
5068
5069 s->task->nice = -32; /* small boost for HTTP statistics */
5070 return 1;
5071}
5072
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005073void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5074{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005075 struct channel *req = &s->req;
5076 struct channel *res = &s->res;
5077 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005078 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005079 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005080 struct ist path, location;
5081 unsigned int flags;
5082 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005083
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005084 /*
5085 * Create the location
5086 */
5087 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005088
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005089 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005090 /* special prefix "/" means don't change URL */
5091 srv = __objt_server(s->target);
5092 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5093 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5094 return;
5095 }
5096
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005097 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005098 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005099 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005100 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005101 if (!path.ptr)
5102 return;
5103
5104 if (!chunk_memcat(&trash, path.ptr, path.len))
5105 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005106 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005107
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005108 /*
5109 * Create the 302 respone
5110 */
5111 htx = htx_from_buf(&res->buf);
5112 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5113 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5114 ist("HTTP/1.1"), ist("302"), ist("Found"));
5115 if (!sl)
5116 goto fail;
5117 sl->info.res.status = 302;
5118 s->txn->status = 302;
5119
5120 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5121 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5122 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5123 !htx_add_header(htx, ist("Location"), location))
5124 goto fail;
5125
5126 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5127 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005128
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005129 /*
5130 * Send the message
5131 */
5132 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005133 c_adv(res, data);
5134 res->total += data;
5135
5136 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005137 si_shutr(si);
5138 si_shutw(si);
5139 si->err_type = SI_ET_NONE;
5140 si->state = SI_ST_CLO;
5141
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005142 channel_auto_read(req);
5143 channel_abort(req);
5144 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005145 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005146 channel_auto_read(res);
5147 channel_auto_close(res);
5148
5149 if (!(s->flags & SF_ERR_MASK))
5150 s->flags |= SF_ERR_LOCAL;
5151 if (!(s->flags & SF_FINST_MASK))
5152 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005153
5154 /* FIXME: we should increase a counter of redirects per server and per backend. */
5155 srv_inc_sess_ctr(srv);
5156 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005157 return;
5158
5159 fail:
5160 /* If an error occurred, remove the incomplete HTTP response from the
5161 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005162 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005163}
5164
Christopher Fauletf2824e62018-10-01 12:12:37 +02005165/* This function terminates the request because it was completly analyzed or
5166 * because an error was triggered during the body forwarding.
5167 */
5168static void htx_end_request(struct stream *s)
5169{
5170 struct channel *chn = &s->req;
5171 struct http_txn *txn = s->txn;
5172
5173 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5174 now_ms, __FUNCTION__, s,
5175 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5176 s->req.analysers, s->res.analysers);
5177
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005178 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5179 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005180 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005181 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005182 goto end;
5183 }
5184
5185 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5186 return;
5187
5188 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005189 /* No need to read anymore, the request was completely parsed.
5190 * We can shut the read side unless we want to abort_on_close,
5191 * or we have a POST request. The issue with POST requests is
5192 * that some browsers still send a CRLF after the request, and
5193 * this CRLF must be read so that it does not remain in the kernel
5194 * buffers, otherwise a close could cause an RST on some systems
5195 * (eg: Linux).
5196 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005197 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005198 channel_dont_read(chn);
5199
5200 /* if the server closes the connection, we want to immediately react
5201 * and close the socket to save packets and syscalls.
5202 */
5203 s->si[1].flags |= SI_FL_NOHALF;
5204
5205 /* In any case we've finished parsing the request so we must
5206 * disable Nagle when sending data because 1) we're not going
5207 * to shut this side, and 2) the server is waiting for us to
5208 * send pending data.
5209 */
5210 chn->flags |= CF_NEVER_WAIT;
5211
Christopher Fauletd01ce402019-01-02 17:44:13 +01005212 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5213 /* The server has not finished to respond, so we
5214 * don't want to move in order not to upset it.
5215 */
5216 return;
5217 }
5218
Christopher Fauletf2824e62018-10-01 12:12:37 +02005219 /* When we get here, it means that both the request and the
5220 * response have finished receiving. Depending on the connection
5221 * mode, we'll have to wait for the last bytes to leave in either
5222 * direction, and sometimes for a close to be effective.
5223 */
5224 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5225 /* Tunnel mode will not have any analyser so it needs to
5226 * poll for reads.
5227 */
5228 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005229 if (b_data(&chn->buf))
5230 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005231 txn->req.msg_state = HTTP_MSG_TUNNEL;
5232 }
5233 else {
5234 /* we're not expecting any new data to come for this
5235 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 *
5237 * However, there is an exception if the response
5238 * length is undefined. In this case, we need to wait
5239 * the close from the server. The response will be
5240 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005241 */
5242 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5243 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005244 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005245
5246 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5247 channel_shutr_now(chn);
5248 channel_shutw_now(chn);
5249 }
5250 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005251 goto check_channel_flags;
5252 }
5253
5254 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5255 http_msg_closing:
5256 /* nothing else to forward, just waiting for the output buffer
5257 * to be empty and for the shutw_now to take effect.
5258 */
5259 if (channel_is_empty(chn)) {
5260 txn->req.msg_state = HTTP_MSG_CLOSED;
5261 goto http_msg_closed;
5262 }
5263 else if (chn->flags & CF_SHUTW) {
5264 txn->req.err_state = txn->req.msg_state;
5265 txn->req.msg_state = HTTP_MSG_ERROR;
5266 goto end;
5267 }
5268 return;
5269 }
5270
5271 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5272 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005273 /* if we don't know whether the server will close, we need to hard close */
5274 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5275 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005276 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005277 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005278 channel_dont_read(chn);
5279 goto end;
5280 }
5281
5282 check_channel_flags:
5283 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5284 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5285 /* if we've just closed an output, let's switch */
5286 txn->req.msg_state = HTTP_MSG_CLOSING;
5287 goto http_msg_closing;
5288 }
5289
5290 end:
5291 chn->analysers &= AN_REQ_FLT_END;
5292 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5293 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5294 channel_auto_close(chn);
5295 channel_auto_read(chn);
5296}
5297
5298
5299/* This function terminates the response because it was completly analyzed or
5300 * because an error was triggered during the body forwarding.
5301 */
5302static void htx_end_response(struct stream *s)
5303{
5304 struct channel *chn = &s->res;
5305 struct http_txn *txn = s->txn;
5306
5307 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5308 now_ms, __FUNCTION__, s,
5309 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5310 s->req.analysers, s->res.analysers);
5311
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005312 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5313 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005314 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005315 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005316 goto end;
5317 }
5318
5319 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5320 return;
5321
5322 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5323 /* In theory, we don't need to read anymore, but we must
5324 * still monitor the server connection for a possible close
5325 * while the request is being uploaded, so we don't disable
5326 * reading.
5327 */
5328 /* channel_dont_read(chn); */
5329
5330 if (txn->req.msg_state < HTTP_MSG_DONE) {
5331 /* The client seems to still be sending data, probably
5332 * because we got an error response during an upload.
5333 * We have the choice of either breaking the connection
5334 * or letting it pass through. Let's do the later.
5335 */
5336 return;
5337 }
5338
5339 /* When we get here, it means that both the request and the
5340 * response have finished receiving. Depending on the connection
5341 * mode, we'll have to wait for the last bytes to leave in either
5342 * direction, and sometimes for a close to be effective.
5343 */
5344 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5345 channel_auto_read(chn);
5346 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005347 if (b_data(&chn->buf))
5348 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005349 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5350 }
5351 else {
5352 /* we're not expecting any new data to come for this
5353 * transaction, so we can close it.
5354 */
5355 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5356 channel_shutr_now(chn);
5357 channel_shutw_now(chn);
5358 }
5359 }
5360 goto check_channel_flags;
5361 }
5362
5363 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5364 http_msg_closing:
5365 /* nothing else to forward, just waiting for the output buffer
5366 * to be empty and for the shutw_now to take effect.
5367 */
5368 if (channel_is_empty(chn)) {
5369 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5370 goto http_msg_closed;
5371 }
5372 else if (chn->flags & CF_SHUTW) {
5373 txn->rsp.err_state = txn->rsp.msg_state;
5374 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005375 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005376 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005377 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005378 goto end;
5379 }
5380 return;
5381 }
5382
5383 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5384 http_msg_closed:
5385 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005386 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005387 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005388 goto end;
5389 }
5390
5391 check_channel_flags:
5392 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5393 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5394 /* if we've just closed an output, let's switch */
5395 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5396 goto http_msg_closing;
5397 }
5398
5399 end:
5400 chn->analysers &= AN_RES_FLT_END;
5401 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5402 chn->analysers |= AN_RES_FLT_XFER_DATA;
5403 channel_auto_close(chn);
5404 channel_auto_read(chn);
5405}
5406
Christopher Faulet0f226952018-10-22 09:29:56 +02005407void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5408 int finst, const struct buffer *msg)
5409{
5410 channel_auto_read(si_oc(si));
5411 channel_abort(si_oc(si));
5412 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005413 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005414 channel_auto_close(si_ic(si));
5415 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005416
5417 /* <msg> is an HTX structure. So we copy it in the response's
5418 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005419 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005420 struct channel *chn = si_ic(si);
5421 struct htx *htx;
5422
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005423 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005424 chn->buf.data = msg->data;
5425 memcpy(chn->buf.area, msg->area, msg->data);
5426 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005427 if (s->txn->meth == HTTP_METH_HEAD)
5428 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005429 c_adv(chn, htx->data);
5430 chn->total += htx->data;
5431 }
5432 if (!(s->flags & SF_ERR_MASK))
5433 s->flags |= err;
5434 if (!(s->flags & SF_FINST_MASK))
5435 s->flags |= finst;
5436}
5437
5438void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5439{
5440 channel_auto_read(&s->req);
5441 channel_abort(&s->req);
5442 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005443 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5444 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005445
5446 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005447
5448 /* <msg> is an HTX structure. So we copy it in the response's
5449 * channel */
5450 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005451 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005452 struct channel *chn = &s->res;
5453 struct htx *htx;
5454
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005455 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005456 chn->buf.data = msg->data;
5457 memcpy(chn->buf.area, msg->area, msg->data);
5458 htx = htx_from_buf(&chn->buf);
Christopher Faulete6ee4652020-10-19 18:01:38 +02005459 if (s->txn->meth == HTTP_METH_HEAD)
5460 htx_skip_msg_payload(htx);
Christopher Faulet0f226952018-10-22 09:29:56 +02005461 c_adv(chn, htx->data);
5462 chn->total += htx->data;
5463 }
5464
5465 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5466 channel_auto_read(&s->res);
5467 channel_auto_close(&s->res);
5468 channel_shutr_now(&s->res);
5469}
5470
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005471struct buffer *htx_error_message(struct stream *s)
5472{
5473 const int msgnum = http_get_status_idx(s->txn->status);
5474
5475 if (s->be->errmsg[msgnum].area)
5476 return &s->be->errmsg[msgnum];
5477 else if (strm_fe(s)->errmsg[msgnum].area)
5478 return &strm_fe(s)->errmsg[msgnum];
5479 else
5480 return &htx_err_chunks[msgnum];
5481}
5482
5483
Christopher Faulet4a28a532019-03-01 11:19:40 +01005484/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5485 * on success and -1 on error.
5486 */
5487static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5488{
5489 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5490 * then we must send an HTTP/1.1 100 Continue intermediate response.
5491 */
5492 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5493 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5494 struct ist hdr = { .ptr = "Expect", .len = 6 };
5495 struct http_hdr_ctx ctx;
5496
5497 ctx.blk = NULL;
5498 /* Expect is allowed in 1.1, look for it */
5499 if (http_find_header(htx, hdr, &ctx, 0) &&
5500 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5501 if (htx_reply_100_continue(s) == -1)
5502 return -1;
5503 http_remove_header(htx, &ctx);
5504 }
5505 }
5506 return 0;
5507}
5508
Christopher Faulet23a3c792018-11-28 10:01:23 +01005509/* Send a 100-Continue response to the client. It returns 0 on success and -1
5510 * on error. The response channel is updated accordingly.
5511 */
5512static int htx_reply_100_continue(struct stream *s)
5513{
5514 struct channel *res = &s->res;
5515 struct htx *htx = htx_from_buf(&res->buf);
5516 struct htx_sl *sl;
5517 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5518 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5519 size_t data;
5520
5521 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5522 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5523 if (!sl)
5524 goto fail;
5525 sl->info.res.status = 100;
5526
Christopher Faulet9869f932019-06-26 14:23:54 +02005527 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005528 goto fail;
5529
5530 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005531 c_adv(res, data);
5532 res->total += data;
5533 return 0;
5534
5535 fail:
5536 /* If an error occurred, remove the incomplete HTTP response from the
5537 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005538 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005539 return -1;
5540}
5541
Christopher Faulet12c51e22018-11-28 15:59:42 +01005542
5543/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5544 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5545 * error. The response channel is updated accordingly.
5546 */
5547static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5548{
5549 struct channel *res = &s->res;
5550 struct htx *htx = htx_from_buf(&res->buf);
5551 struct htx_sl *sl;
5552 struct ist code, body;
5553 int status;
5554 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5555 size_t data;
5556
5557 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5558 status = 401;
5559 code = ist("401");
5560 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5561 "You need a valid user and password to access this content.\n"
5562 "</body></html>\n");
5563 }
5564 else {
5565 status = 407;
5566 code = ist("407");
5567 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5568 "You need a valid user and password to access this content.\n"
5569 "</body></html>\n");
5570 }
5571
5572 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5573 ist("HTTP/1.1"), code, ist("Unauthorized"));
5574 if (!sl)
5575 goto fail;
5576 sl->info.res.status = status;
5577 s->txn->status = status;
5578
5579 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5580 goto fail;
5581
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005582 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5583 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005584 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005585 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5586 goto fail;
5587 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5588 goto fail;
5589 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005590 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005591 if (!htx_add_endof(htx, HTX_BLK_EOH))
5592 goto fail;
5593
Christopher Faulete6ee4652020-10-19 18:01:38 +02005594 if (s->txn->meth == HTTP_METH_HEAD)
5595 body.len = 0;
5596
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005597 while (body.len) {
5598 size_t sent = htx_add_data(htx, body);
5599 if (!sent)
5600 goto fail;
5601 body.ptr += sent;
5602 body.len -= sent;
5603 }
5604
5605 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005606 goto fail;
5607
5608 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005609 c_adv(res, data);
5610 res->total += data;
5611
5612 channel_auto_read(&s->req);
5613 channel_abort(&s->req);
5614 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005615 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005616
5617 res->wex = tick_add_ifset(now_ms, res->wto);
5618 channel_auto_read(res);
5619 channel_auto_close(res);
5620 channel_shutr_now(res);
5621 return 0;
5622
5623 fail:
5624 /* If an error occurred, remove the incomplete HTTP response from the
5625 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005626 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005627 return -1;
5628}
5629
Christopher Faulet0f226952018-10-22 09:29:56 +02005630/*
5631 * Capture headers from message <htx> according to header list <cap_hdr>, and
5632 * fill the <cap> pointers appropriately.
5633 */
5634static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5635{
5636 struct cap_hdr *h;
5637 int32_t pos;
5638
Christopher Fauleta3f15502019-05-13 15:27:23 +02005639 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005640 struct htx_blk *blk = htx_get_blk(htx, pos);
5641 enum htx_blk_type type = htx_get_blk_type(blk);
5642 struct ist n, v;
5643
5644 if (type == HTX_BLK_EOH)
5645 break;
5646 if (type != HTX_BLK_HDR)
5647 continue;
5648
5649 n = htx_get_blk_name(htx, blk);
5650
5651 for (h = cap_hdr; h; h = h->next) {
5652 if (h->namelen && (h->namelen == n.len) &&
5653 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5654 if (cap[h->index] == NULL)
5655 cap[h->index] =
5656 pool_alloc(h->pool);
5657
5658 if (cap[h->index] == NULL) {
5659 ha_alert("HTTP capture : out of memory.\n");
5660 break;
5661 }
5662
5663 v = htx_get_blk_value(htx, blk);
5664 if (v.len > h->len)
5665 v.len = h->len;
5666
5667 memcpy(cap[h->index], v.ptr, v.len);
5668 cap[h->index][v.len]=0;
5669 }
5670 }
5671 }
5672}
5673
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005674/* Delete a value in a header between delimiters <from> and <next>. The header
5675 * itself is delimited by <start> and <end> pointers. The number of characters
5676 * displaced is returned, and the pointer to the first delimiter is updated if
5677 * required. The function tries as much as possible to respect the following
5678 * principles :
5679 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5680 * in which case <next> is simply removed
5681 * - set exactly one space character after the new first delimiter, unless there
5682 * are not enough characters in the block being moved to do so.
5683 * - remove unneeded spaces before the previous delimiter and after the new
5684 * one.
5685 *
5686 * It is the caller's responsibility to ensure that :
5687 * - <from> points to a valid delimiter or <start> ;
5688 * - <next> points to a valid delimiter or <end> ;
5689 * - there are non-space chars before <from>.
5690 */
5691static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5692{
5693 char *prev = *from;
5694
5695 if (prev == start) {
5696 /* We're removing the first value. eat the semicolon, if <next>
5697 * is lower than <end> */
5698 if (next < end)
5699 next++;
5700
5701 while (next < end && HTTP_IS_SPHT(*next))
5702 next++;
5703 }
5704 else {
5705 /* Remove useless spaces before the old delimiter. */
5706 while (HTTP_IS_SPHT(*(prev-1)))
5707 prev--;
5708 *from = prev;
5709
5710 /* copy the delimiter and if possible a space if we're
5711 * not at the end of the line.
5712 */
5713 if (next < end) {
5714 *prev++ = *next++;
5715 if (prev + 1 < next)
5716 *prev++ = ' ';
5717 while (next < end && HTTP_IS_SPHT(*next))
5718 next++;
5719 }
5720 }
5721 memmove(prev, next, end - next);
5722 return (prev - next);
5723}
5724
Christopher Faulet0f226952018-10-22 09:29:56 +02005725
5726/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005727 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005728 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005729static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005730{
5731 struct ist dst = ist2(str, 0);
5732
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005733 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005734 goto end;
5735 if (dst.len + 1 > len)
5736 goto end;
5737 dst.ptr[dst.len++] = ' ';
5738
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005739 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005740 goto end;
5741 if (dst.len + 1 > len)
5742 goto end;
5743 dst.ptr[dst.len++] = ' ';
5744
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005745 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005746 end:
5747 return dst.len;
5748}
5749
Christopher Fauletf0523542018-10-24 11:06:58 +02005750/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005751 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005752 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005753static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005754{
5755 struct ist dst = ist2(str, 0);
5756
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005757 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005758 goto end;
5759 if (dst.len + 1 > len)
5760 goto end;
5761 dst.ptr[dst.len++] = ' ';
5762
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005763 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005764 goto end;
5765 if (dst.len + 1 > len)
5766 goto end;
5767 dst.ptr[dst.len++] = ' ';
5768
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005769 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005770 end:
5771 return dst.len;
5772}
5773
5774
Christopher Faulet0f226952018-10-22 09:29:56 +02005775/*
5776 * Print a debug line with a start line.
5777 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005778static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005779{
5780 struct session *sess = strm_sess(s);
5781 int max;
5782
5783 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5784 dir,
5785 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5786 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5787
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005788 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005789 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005790 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005791 trash.area[trash.data++] = ' ';
5792
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005793 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005794 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005795 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005796 trash.area[trash.data++] = ' ';
5797
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005798 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005799 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005800 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005801 trash.area[trash.data++] = '\n';
5802
5803 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5804}
5805
5806/*
5807 * Print a debug line with a header.
5808 */
5809static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5810{
5811 struct session *sess = strm_sess(s);
5812 int max;
5813
5814 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5815 dir,
5816 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5817 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5818
5819 max = n.len;
5820 UBOUND(max, trash.size - trash.data - 3);
5821 chunk_memcat(&trash, n.ptr, max);
5822 trash.area[trash.data++] = ':';
5823 trash.area[trash.data++] = ' ';
5824
5825 max = v.len;
5826 UBOUND(max, trash.size - trash.data - 1);
5827 chunk_memcat(&trash, v.ptr, max);
5828 trash.area[trash.data++] = '\n';
5829
5830 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5831}
5832
5833
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005834__attribute__((constructor))
5835static void __htx_protocol_init(void)
5836{
5837}
5838
5839
5840/*
5841 * Local variables:
5842 * c-indent-level: 8
5843 * c-basic-offset: 8
5844 * End:
5845 */