blob: 2a4c654f5b57970739c54251b5d7d318d1e1d7e4 [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 Houchard530249c2019-07-12 16:16:59 +02001416 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001417 si->exp = TICK_ETERNITY;
1418 res->rex = TICK_ETERNITY;
1419 res->to_forward = 0;
1420 res->analyse_exp = TICK_ETERNITY;
1421 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001422 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001423 si_release_endpoint(&s->si[1]);
1424 b_free(&req->buf);
1425 /* Swap the L7 buffer with the channel buffer */
1426 /* We know we stored the co_data as b_data, so get it there */
1427 co_data = b_data(&si->l7_buffer);
1428 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1429 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1430
1431 co_set_data(req, co_data);
1432 b_reset(&res->buf);
1433 co_set_data(res, 0);
1434 return 0;
1435}
1436
Christopher Faulete0768eb2018-10-03 16:38:02 +02001437/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1438 * processing can continue on next analysers, or zero if it either needs more
1439 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1440 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1441 * when it has nothing left to do, and may remove any analyser when it wants to
1442 * abort.
1443 */
1444int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1445{
Christopher Faulet9768c262018-10-22 09:34:31 +02001446 /*
1447 * We will analyze a complete HTTP response to check the its syntax.
1448 *
1449 * Once the start line and all headers are received, we may perform a
1450 * capture of the error (if any), and we will set a few fields. We also
1451 * logging and finally headers capture.
1452 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001453 struct session *sess = s->sess;
1454 struct http_txn *txn = s->txn;
1455 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001456 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001457 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001458 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001459 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 int n;
1461
1462 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1463 now_ms, __FUNCTION__,
1464 s,
1465 rep,
1466 rep->rex, rep->wex,
1467 rep->flags,
1468 ci_data(rep),
1469 rep->analysers);
1470
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001471 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001472
Willy Tarreau4236f032019-03-05 10:43:32 +01001473 /* Parsing errors are caught here */
1474 if (htx->flags & HTX_FL_PARSING_ERROR)
1475 goto return_bad_res;
1476
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477 /*
1478 * Now we quickly check if we have found a full valid response.
1479 * If not so, we check the FD and buffer states before leaving.
1480 * A full response is indicated by the fact that we have seen
1481 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1482 * responses are checked first.
1483 *
1484 * Depending on whether the client is still there or not, we
1485 * may send an error response back or not. Note that normally
1486 * we should only check for HTTP status there, and check I/O
1487 * errors somewhere else.
1488 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001489 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001490 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001491 /* 1: have we encountered a read error ? */
1492 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001493 struct connection *conn = NULL;
1494
Olivier Houchard865d8392019-05-03 22:46:27 +02001495 if (objt_cs(s->si[1].end))
1496 conn = objt_cs(s->si[1].end)->conn;
1497
1498 if (si_b->flags & SI_FL_L7_RETRY &&
1499 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001500 /* If we arrive here, then CF_READ_ERROR was
1501 * set by si_cs_recv() because we matched a
1502 * status, overwise it would have removed
1503 * the SI_FL_L7_RETRY flag, so it's ok not
1504 * to check s->be->retry_type.
1505 */
1506 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1507 return 0;
1508 }
1509
Olivier Houchard6db16992019-05-17 15:40:49 +02001510 if (txn->flags & TX_NOT_FIRST)
1511 goto abort_keep_alive;
1512
Olivier Houcharda798bf52019-03-08 18:52:00 +01001513 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001515 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001516 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001517 }
1518
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 rep->analysers &= AN_RES_FLT_END;
1520 txn->status = 502;
1521
1522 /* Check to see if the server refused the early data.
1523 * If so, just send a 425
1524 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001525 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1526 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001527 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001528 do_l7_retry(s, si_b) == 0)
1529 return 0;
1530 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 }
1532
1533 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001534 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535
1536 if (!(s->flags & SF_ERR_MASK))
1537 s->flags |= SF_ERR_SRVCL;
1538 if (!(s->flags & SF_FINST_MASK))
1539 s->flags |= SF_FINST_H;
1540 return 0;
1541 }
1542
Christopher Faulet9768c262018-10-22 09:34:31 +02001543 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001545 if ((si_b->flags & SI_FL_L7_RETRY) &&
1546 (s->be->retry_type & PR_RE_TIMEOUT)) {
1547 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1548 return 0;
1549 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001550 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001552 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001553 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 }
1555
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 rep->analysers &= AN_RES_FLT_END;
1557 txn->status = 504;
1558 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001559 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560
1561 if (!(s->flags & SF_ERR_MASK))
1562 s->flags |= SF_ERR_SRVTO;
1563 if (!(s->flags & SF_FINST_MASK))
1564 s->flags |= SF_FINST_H;
1565 return 0;
1566 }
1567
Christopher Faulet9768c262018-10-22 09:34:31 +02001568 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001570 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1571 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001573 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574
1575 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001577 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578
1579 if (!(s->flags & SF_ERR_MASK))
1580 s->flags |= SF_ERR_CLICL;
1581 if (!(s->flags & SF_FINST_MASK))
1582 s->flags |= SF_FINST_H;
1583
1584 /* process_stream() will take care of the error */
1585 return 0;
1586 }
1587
Christopher Faulet9768c262018-10-22 09:34:31 +02001588 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001589 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001590 if ((si_b->flags & SI_FL_L7_RETRY) &&
1591 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1592 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1593 return 0;
1594 }
1595
Olivier Houchard6db16992019-05-17 15:40:49 +02001596 if (txn->flags & TX_NOT_FIRST)
1597 goto abort_keep_alive;
1598
Olivier Houcharda798bf52019-03-08 18:52:00 +01001599 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001601 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001602 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603 }
1604
Christopher Faulete0768eb2018-10-03 16:38:02 +02001605 rep->analysers &= AN_RES_FLT_END;
1606 txn->status = 502;
1607 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001608 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001609
1610 if (!(s->flags & SF_ERR_MASK))
1611 s->flags |= SF_ERR_SRVCL;
1612 if (!(s->flags & SF_FINST_MASK))
1613 s->flags |= SF_FINST_H;
1614 return 0;
1615 }
1616
Christopher Faulet9768c262018-10-22 09:34:31 +02001617 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001619 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620 goto abort_keep_alive;
1621
Olivier Houcharda798bf52019-03-08 18:52:00 +01001622 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624
1625 if (!(s->flags & SF_ERR_MASK))
1626 s->flags |= SF_ERR_CLICL;
1627 if (!(s->flags & SF_FINST_MASK))
1628 s->flags |= SF_FINST_H;
1629
1630 /* process_stream() will take care of the error */
1631 return 0;
1632 }
1633
1634 channel_dont_close(rep);
1635 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1636 return 0;
1637 }
1638
1639 /* More interesting part now : we know that we have a complete
1640 * response which at least looks like HTTP. We have an indicator
1641 * of each header's length, so we can parse them quickly.
1642 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001643 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001644 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001645 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001646
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 /* 0: we might have to print this header in debug mode */
1648 if (unlikely((global.mode & MODE_DEBUG) &&
1649 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1650 int32_t pos;
1651
Christopher Faulet03599112018-11-27 11:21:21 +01001652 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001653
Christopher Fauleta3f15502019-05-13 15:27:23 +02001654 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001655 struct htx_blk *blk = htx_get_blk(htx, pos);
1656 enum htx_blk_type type = htx_get_blk_type(blk);
1657
1658 if (type == HTX_BLK_EOH)
1659 break;
1660 if (type != HTX_BLK_HDR)
1661 continue;
1662
1663 htx_debug_hdr("srvhdr", s,
1664 htx_get_blk_name(htx, blk),
1665 htx_get_blk_value(htx, blk));
1666 }
1667 }
1668
Christopher Faulet03599112018-11-27 11:21:21 +01001669 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001670 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001671 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001672 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001673 if (sl->flags & HTX_SL_F_XFER_LEN) {
1674 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001675 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001676 if (sl->flags & HTX_SL_F_BODYLESS)
1677 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001678 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001679
1680 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001681 if (n < 1 || n > 5)
1682 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001683
Christopher Faulete0768eb2018-10-03 16:38:02 +02001684 /* when the client triggers a 4xx from the server, it's most often due
1685 * to a missing object or permission. These events should be tracked
1686 * because if they happen often, it may indicate a brute force or a
1687 * vulnerability scan.
1688 */
1689 if (n == 4)
1690 stream_inc_http_err_ctr(s);
1691
1692 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001693 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001694
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695 /* Adjust server's health based on status code. Note: status codes 501
1696 * and 505 are triggered on demand by client request, so we must not
1697 * count them as server failures.
1698 */
1699 if (objt_server(s->target)) {
1700 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001701 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001703 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001704 }
1705
1706 /*
1707 * We may be facing a 100-continue response, or any other informational
1708 * 1xx response which is non-final, in which case this is not the right
1709 * response, and we're waiting for the next one. Let's allow this response
1710 * to go to the client and wait for the next one. There's an exception for
1711 * 101 which is used later in the code to switch protocols.
1712 */
1713 if (txn->status < 200 &&
1714 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001715 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001716 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001718 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001719 txn->status = 0;
1720 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001721 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001722 }
1723
1724 /*
1725 * 2: check for cacheability.
1726 */
1727
1728 switch (txn->status) {
1729 case 200:
1730 case 203:
1731 case 204:
1732 case 206:
1733 case 300:
1734 case 301:
1735 case 404:
1736 case 405:
1737 case 410:
1738 case 414:
1739 case 501:
1740 break;
1741 default:
1742 /* RFC7231#6.1:
1743 * Responses with status codes that are defined as
1744 * cacheable by default (e.g., 200, 203, 204, 206,
1745 * 300, 301, 404, 405, 410, 414, and 501 in this
1746 * specification) can be reused by a cache with
1747 * heuristic expiration unless otherwise indicated
1748 * by the method definition or explicit cache
1749 * controls [RFC7234]; all other status codes are
1750 * not cacheable by default.
1751 */
1752 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1753 break;
1754 }
1755
1756 /*
1757 * 3: we may need to capture headers
1758 */
1759 s->logs.logwait &= ~LW_RESP;
1760 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001761 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001762
Christopher Faulet9768c262018-10-22 09:34:31 +02001763 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001764 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1765 txn->status == 101)) {
1766 /* Either we've established an explicit tunnel, or we're
1767 * switching the protocol. In both cases, we're very unlikely
1768 * to understand the next protocols. We have to switch to tunnel
1769 * mode, so that we transfer the request and responses then let
1770 * this protocol pass unmodified. When we later implement specific
1771 * parsers for such protocols, we'll want to check the Upgrade
1772 * header which contains information about that protocol for
1773 * responses with status 101 (eg: see RFC2817 about TLS).
1774 */
1775 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776 }
1777
Christopher Faulet61608322018-11-23 16:23:45 +01001778 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1779 * 407 (Proxy-Authenticate) responses and set the connection to private
1780 */
1781 srv_conn = cs_conn(objt_cs(s->si[1].end));
1782 if (srv_conn) {
1783 struct ist hdr;
1784 struct http_hdr_ctx ctx;
1785
1786 if (txn->status == 401)
1787 hdr = ist("WWW-Authenticate");
1788 else if (txn->status == 407)
1789 hdr = ist("Proxy-Authenticate");
1790 else
1791 goto end;
1792
1793 ctx.blk = NULL;
1794 while (http_find_header(htx, hdr, &ctx, 0)) {
1795 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001796 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1797 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001798 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001799 }
Christopher Faulet61608322018-11-23 16:23:45 +01001800 }
1801 }
1802
1803 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 /* we want to have the response time before we start processing it */
1805 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1806
1807 /* end of job, return OK */
1808 rep->analysers &= ~an_bit;
1809 rep->analyse_exp = TICK_ETERNITY;
1810 channel_auto_close(rep);
1811 return 1;
1812
Christopher Faulet47365272018-10-31 17:40:50 +01001813 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001814 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001815 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001816 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001817 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001818 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001819 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001820 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001821 do_l7_retry(s, si_b) == 0)
1822 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001823 txn->status = 502;
1824 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001825 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001826 rep->analysers &= AN_RES_FLT_END;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01001827 s->req.analysers &= AN_REQ_FLT_END;
1828 rep->analyse_exp = TICK_ETERNITY;
Christopher Faulet47365272018-10-31 17:40:50 +01001829
1830 if (!(s->flags & SF_ERR_MASK))
1831 s->flags |= SF_ERR_PRXCOND;
1832 if (!(s->flags & SF_FINST_MASK))
1833 s->flags |= SF_FINST_H;
1834 return 0;
1835
Christopher Faulete0768eb2018-10-03 16:38:02 +02001836 abort_keep_alive:
1837 /* A keep-alive request to the server failed on a network error.
1838 * The client is required to retry. We need to close without returning
1839 * any other information so that the client retries.
1840 */
1841 txn->status = 0;
1842 rep->analysers &= AN_RES_FLT_END;
1843 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001844 s->logs.logwait = 0;
1845 s->logs.level = 0;
1846 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001847 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001848 return 0;
1849}
1850
1851/* This function performs all the processing enabled for the current response.
1852 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1853 * and updates s->res.analysers. It might make sense to explode it into several
1854 * other functions. It works like process_request (see indications above).
1855 */
1856int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1857{
1858 struct session *sess = s->sess;
1859 struct http_txn *txn = s->txn;
1860 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001861 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001862 struct proxy *cur_proxy;
1863 struct cond_wordlist *wl;
1864 enum rule_result ret = HTTP_RULE_RES_CONT;
1865
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001866 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1867 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001868
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1870 now_ms, __FUNCTION__,
1871 s,
1872 rep,
1873 rep->rex, rep->wex,
1874 rep->flags,
1875 ci_data(rep),
1876 rep->analysers);
1877
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001878 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879
1880 /* The stats applet needs to adjust the Connection header but we don't
1881 * apply any filter there.
1882 */
1883 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1884 rep->analysers &= ~an_bit;
1885 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001886 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001887 }
1888
1889 /*
1890 * We will have to evaluate the filters.
1891 * As opposed to version 1.2, now they will be evaluated in the
1892 * filters order and not in the header order. This means that
1893 * each filter has to be validated among all headers.
1894 *
1895 * Filters are tried with ->be first, then with ->fe if it is
1896 * different from ->be.
1897 *
1898 * Maybe we are in resume condiion. In this case I choose the
1899 * "struct proxy" which contains the rule list matching the resume
1900 * pointer. If none of theses "struct proxy" match, I initialise
1901 * the process with the first one.
1902 *
1903 * In fact, I check only correspondance betwwen the current list
1904 * pointer and the ->fe rule list. If it doesn't match, I initialize
1905 * the loop with the ->be.
1906 */
1907 if (s->current_rule_list == &sess->fe->http_res_rules)
1908 cur_proxy = sess->fe;
1909 else
1910 cur_proxy = s->be;
1911 while (1) {
1912 struct proxy *rule_set = cur_proxy;
1913
1914 /* evaluate http-response rules */
1915 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001916 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001917
1918 if (ret == HTTP_RULE_RES_BADREQ)
1919 goto return_srv_prx_502;
1920
1921 if (ret == HTTP_RULE_RES_DONE) {
1922 rep->analysers &= ~an_bit;
1923 rep->analyse_exp = TICK_ETERNITY;
1924 return 1;
1925 }
1926 }
1927
1928 /* we need to be called again. */
1929 if (ret == HTTP_RULE_RES_YIELD) {
1930 channel_dont_close(rep);
1931 return 0;
1932 }
1933
1934 /* try headers filters */
1935 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001936 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1937 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001938 }
1939
1940 /* has the response been denied ? */
1941 if (txn->flags & TX_SVDENY) {
1942 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001943 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001944
Olivier Houcharda798bf52019-03-08 18:52:00 +01001945 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1946 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001947 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001948 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001949 goto return_srv_prx_502;
1950 }
1951
1952 /* add response headers from the rule sets in the same order */
1953 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001954 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001955 if (txn->status < 200 && txn->status != 101)
1956 break;
1957 if (wl->cond) {
1958 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1959 ret = acl_pass(ret);
1960 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1961 ret = !ret;
1962 if (!ret)
1963 continue;
1964 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001965
1966 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1967 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968 goto return_bad_resp;
1969 }
1970
1971 /* check whether we're already working on the frontend */
1972 if (cur_proxy == sess->fe)
1973 break;
1974 cur_proxy = sess->fe;
1975 }
1976
1977 /* After this point, this anayzer can't return yield, so we can
1978 * remove the bit corresponding to this analyzer from the list.
1979 *
1980 * Note that the intermediate returns and goto found previously
1981 * reset the analyzers.
1982 */
1983 rep->analysers &= ~an_bit;
1984 rep->analyse_exp = TICK_ETERNITY;
1985
1986 /* OK that's all we can do for 1xx responses */
1987 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001988 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001989
1990 /*
1991 * Now check for a server cookie.
1992 */
1993 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001994 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001995
1996 /*
1997 * Check for cache-control or pragma headers if required.
1998 */
1999 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2000 check_response_for_cacheability(s, rep);
2001
2002 /*
2003 * Add server cookie in the response if needed
2004 */
2005 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2006 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2007 (!(s->flags & SF_DIRECT) ||
2008 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2009 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2010 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2011 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2012 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2013 !(s->flags & SF_IGNORE_PRST)) {
2014 /* the server is known, it's not the one the client requested, or the
2015 * cookie's last seen date needs to be refreshed. We have to
2016 * insert a set-cookie here, except if we want to insert only on POST
2017 * requests and this one isn't. Note that servers which don't have cookies
2018 * (eg: some backup servers) will return a full cookie removal request.
2019 */
2020 if (!objt_server(s->target)->cookie) {
2021 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002022 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002023 s->be->cookie_name);
2024 }
2025 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002026 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002027
2028 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2029 /* emit last_date, which is mandatory */
2030 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2031 s30tob64((date.tv_sec+3) >> 2,
2032 trash.area + trash.data);
2033 trash.data += 5;
2034
2035 if (s->be->cookie_maxlife) {
2036 /* emit first_date, which is either the original one or
2037 * the current date.
2038 */
2039 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2040 s30tob64(txn->cookie_first_date ?
2041 txn->cookie_first_date >> 2 :
2042 (date.tv_sec+3) >> 2,
2043 trash.area + trash.data);
2044 trash.data += 5;
2045 }
2046 }
2047 chunk_appendf(&trash, "; path=/");
2048 }
2049
2050 if (s->be->cookie_domain)
2051 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2052
2053 if (s->be->ck_opts & PR_CK_HTTPONLY)
2054 chunk_appendf(&trash, "; HttpOnly");
2055
2056 if (s->be->ck_opts & PR_CK_SECURE)
2057 chunk_appendf(&trash, "; Secure");
2058
Christopher Fauletdb2cdbb2020-01-21 11:06:48 +01002059 if (s->be->cookie_attrs)
2060 chunk_appendf(&trash, "; %s", s->be->cookie_attrs);
2061
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002063 goto return_bad_resp;
2064
2065 txn->flags &= ~TX_SCK_MASK;
2066 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2067 /* the server did not change, only the date was updated */
2068 txn->flags |= TX_SCK_UPDATED;
2069 else
2070 txn->flags |= TX_SCK_INSERTED;
2071
2072 /* Here, we will tell an eventual cache on the client side that we don't
2073 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2074 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2075 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2076 */
2077 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2078
2079 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2080
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002081 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082 goto return_bad_resp;
2083 }
2084 }
2085
2086 /*
2087 * Check if result will be cacheable with a cookie.
2088 * We'll block the response if security checks have caught
2089 * nasty things such as a cacheable cookie.
2090 */
2091 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2092 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2093 (s->be->options & PR_O_CHK_CACHE)) {
2094 /* we're in presence of a cacheable response containing
2095 * a set-cookie header. We'll block it as requested by
2096 * the 'checkcache' option, and send an alert.
2097 */
2098 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002099 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002100
Olivier Houcharda798bf52019-03-08 18:52:00 +01002101 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2102 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002103 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002104 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002105
2106 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2107 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2108 send_log(s->be, LOG_ALERT,
2109 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2110 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2111 goto return_srv_prx_502;
2112 }
2113
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002114 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002115 /* Always enter in the body analyzer */
2116 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2117 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2118
2119 /* if the user wants to log as soon as possible, without counting
2120 * bytes from the server, then this is the right moment. We have
2121 * to temporarily assign bytes_out to log what we currently have.
2122 */
2123 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2124 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002125 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 s->do_log(s);
2127 s->logs.bytes_out = 0;
2128 }
2129 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002130
2131 return_bad_resp:
2132 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002133 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002134 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002135 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002136 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002137
2138 return_srv_prx_502:
2139 rep->analysers &= AN_RES_FLT_END;
2140 txn->status = 502;
2141 s->logs.t_data = -1; /* was not a valid response */
2142 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002143 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002144 if (!(s->flags & SF_ERR_MASK))
2145 s->flags |= SF_ERR_PRXCOND;
2146 if (!(s->flags & SF_FINST_MASK))
2147 s->flags |= SF_FINST_H;
Christopher Fauletf6df2b42020-03-02 16:21:01 +01002148
2149 s->req.analysers &= AN_REQ_FLT_END;
2150 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002151 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002152}
2153
2154/* This function is an analyser which forwards response body (including chunk
2155 * sizes if any). It is called as soon as we must forward, even if we forward
2156 * zero byte. The only situation where it must not be called is when we're in
2157 * tunnel mode and we want to forward till the close. It's used both to forward
2158 * remaining data and to resync after end of body. It expects the msg_state to
2159 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2160 * read more data, or 1 once we can go on with next request or end the stream.
2161 *
2162 * It is capable of compressing response data both in content-length mode and
2163 * in chunked mode. The state machines follows different flows depending on
2164 * whether content-length and chunked modes are used, since there are no
2165 * trailers in content-length :
2166 *
2167 * chk-mode cl-mode
2168 * ,----- BODY -----.
2169 * / \
2170 * V size > 0 V chk-mode
2171 * .--> SIZE -------------> DATA -------------> CRLF
2172 * | | size == 0 | last byte |
2173 * | v final crlf v inspected |
2174 * | TRAILERS -----------> DONE |
2175 * | |
2176 * `----------------------------------------------'
2177 *
2178 * Compression only happens in the DATA state, and must be flushed in final
2179 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2180 * is performed at once on final states for all bytes parsed, or when leaving
2181 * on missing data.
2182 */
2183int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2184{
2185 struct session *sess = s->sess;
2186 struct http_txn *txn = s->txn;
2187 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002188 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002189 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190
2191 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2192 now_ms, __FUNCTION__,
2193 s,
2194 res,
2195 res->rex, res->wex,
2196 res->flags,
2197 ci_data(res),
2198 res->analysers);
2199
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002200 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002201
2202 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002203 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 /* Output closed while we were sending data. We must abort and
2205 * wake the other side up.
2206 */
2207 msg->err_state = msg->msg_state;
2208 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002209 htx_end_response(s);
2210 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 return 1;
2212 }
2213
Christopher Faulet9768c262018-10-22 09:34:31 +02002214 if (msg->msg_state == HTTP_MSG_BODY)
2215 msg->msg_state = HTTP_MSG_DATA;
2216
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217 /* in most states, we should abort in case of early close */
2218 channel_auto_close(res);
2219
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002221 if (res->to_forward == CHN_INFINITE_FORWARD) {
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002222 if (res->flags & CF_EOI)
2223 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet66af0b22019-03-22 14:54:52 +01002224 }
2225 else {
2226 /* We can't process the buffer's contents yet */
2227 res->flags |= CF_WAKE_WRITE;
2228 goto missing_data_or_waiting;
2229 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 }
2231
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002232 if (msg->msg_state >= HTTP_MSG_ENDING)
2233 goto ending;
2234
2235 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2236 (!(msg->flags & HTTP_MSGF_XFER_LEN) && !HAS_RSP_DATA_FILTERS(s))) {
2237 msg->msg_state = HTTP_MSG_ENDING;
2238 goto ending;
2239 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002240
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002241 /* Forward input data. We get it by removing all outgoing data not
2242 * forwarded yet from HTX data size. If there are some data filters, we
2243 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002244 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002245 if (HAS_RSP_DATA_FILTERS(s)) {
2246 ret = flt_http_payload(s, msg, htx->data);
2247 if (ret < 0)
2248 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002249 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002250 }
2251 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002252 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002253 if (msg->flags & HTTP_MSGF_XFER_LEN)
2254 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002255 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002256
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002257 if (htx->data != co_data(res))
2258 goto missing_data_or_waiting;
2259
2260 if (!(msg->flags & HTTP_MSGF_XFER_LEN) && res->flags & CF_SHUTR) {
2261 msg->msg_state = HTTP_MSG_ENDING;
2262 goto ending;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 }
2264
Christopher Faulet9768c262018-10-22 09:34:31 +02002265 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002266 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2267 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002268 */
2269 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2270 goto missing_data_or_waiting;
2271
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002272 msg->msg_state = HTTP_MSG_ENDING;
Christopher Faulet9768c262018-10-22 09:34:31 +02002273
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002274 ending:
2275 /* other states, ENDING...TUNNEL */
2276 if (msg->msg_state >= HTTP_MSG_DONE)
2277 goto done;
Christopher Faulet9768c262018-10-22 09:34:31 +02002278
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002279 if (HAS_RSP_DATA_FILTERS(s)) {
2280 ret = flt_http_end(s, msg);
2281 if (ret <= 0) {
2282 if (!ret)
2283 goto missing_data_or_waiting;
2284 goto return_bad_res;
2285 }
2286 }
2287
Christopher Fauletbe7c5522019-11-15 16:31:46 +01002288 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2289 !(msg->flags & HTTP_MSGF_XFER_LEN)) {
2290 msg->msg_state = HTTP_MSG_TUNNEL;
2291 goto ending;
2292 }
2293 else {
2294 msg->msg_state = HTTP_MSG_DONE;
2295 res->to_forward = 0;
2296 }
2297
2298 done:
2299
2300 channel_dont_close(res);
2301
Christopher Fauletf2824e62018-10-01 12:12:37 +02002302 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002303 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002304 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2306 if (res->flags & CF_SHUTW) {
2307 /* response errors are most likely due to the
2308 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002309 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002310 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002311 goto return_bad_res;
2312 }
2313 return 1;
2314 }
2315 return 0;
2316
2317 missing_data_or_waiting:
2318 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002319 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002320
Christopher Faulet47365272018-10-31 17:40:50 +01002321 if (htx->flags & HTX_FL_PARSING_ERROR)
2322 goto return_bad_res;
2323
Christopher Faulete0768eb2018-10-03 16:38:02 +02002324 /* stop waiting for data if the input is closed before the end. If the
2325 * client side was already closed, it means that the client has aborted,
2326 * so we don't want to count this as a server abort. Otherwise it's a
2327 * server abort.
2328 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002329 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002330 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002331 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002333 if (htx_is_empty(htx))
2334 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335 }
2336
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337 /* When TE: chunked is used, we need to get there again to parse
2338 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002339 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2340 * are filters registered on the stream, we don't want to forward a
2341 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002343 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002344 channel_dont_close(res);
2345
2346 /* We know that more data are expected, but we couldn't send more that
2347 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2348 * system knows it must not set a PUSH on this first part. Interactive
2349 * modes are already handled by the stream sock layer. We must not do
2350 * this in content-length mode because it could present the MSG_MORE
2351 * flag with the last block of forwarded data, which would cause an
2352 * additional delay to be observed by the receiver.
2353 */
2354 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2355 res->flags |= CF_EXPECT_MORE;
2356
2357 /* the stream handler will take care of timeouts and errors */
2358 return 0;
2359
Christopher Faulet93e02d82019-03-08 14:18:50 +01002360 return_srv_abort:
2361 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2362 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002363 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002364 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2365 if (!(s->flags & SF_ERR_MASK))
2366 s->flags |= SF_ERR_SRVCL;
2367 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002368
Christopher Faulet93e02d82019-03-08 14:18:50 +01002369 return_cli_abort:
2370 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2371 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002372 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002373 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2374 if (!(s->flags & SF_ERR_MASK))
2375 s->flags |= SF_ERR_CLICL;
2376 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002377
Christopher Faulet93e02d82019-03-08 14:18:50 +01002378 return_bad_res:
2379 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2380 if (objt_server(s->target)) {
2381 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2382 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2383 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002384 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002385 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002386
Christopher Faulet93e02d82019-03-08 14:18:50 +01002387 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002388 txn->rsp.err_state = txn->rsp.msg_state;
2389 txn->rsp.msg_state = HTTP_MSG_ERROR;
2390 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002391 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002392 res->analysers &= AN_RES_FLT_END;
2393 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 +02002394 if (!(s->flags & SF_FINST_MASK))
2395 s->flags |= SF_FINST_D;
2396 return 0;
2397}
2398
Christopher Fauletf2824e62018-10-01 12:12:37 +02002399/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002400 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 * as too large a request to build a valid response.
2402 */
2403int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2404{
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 struct channel *req = &s->req;
2406 struct channel *res = &s->res;
2407 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002408 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002410 struct ist status, reason, location;
2411 unsigned int flags;
2412 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002413 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414
2415 chunk = alloc_trash_chunk();
2416 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002417 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 /*
2420 * Create the location
2421 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002422 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 case REDIRECT_TYPE_SCHEME: {
2425 struct http_hdr_ctx ctx;
2426 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427
Christopher Faulet99daf282018-11-28 22:58:13 +01002428 host = ist("");
2429 ctx.blk = NULL;
2430 if (http_find_header(htx, ist("Host"), &ctx, 0))
2431 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet297fbb42019-05-13 14:41:27 +02002433 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002434 path = http_get_path(htx_sl_req_uri(sl));
2435 /* build message using path */
2436 if (path.ptr) {
2437 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2438 int qs = 0;
2439 while (qs < path.len) {
2440 if (*(path.ptr + qs) == '?') {
2441 path.len = qs;
2442 break;
2443 }
2444 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002445 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446 }
2447 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002448 else
2449 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450
Christopher Faulet99daf282018-11-28 22:58:13 +01002451 if (rule->rdr_str) { /* this is an old "redirect" rule */
2452 /* add scheme */
2453 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2454 goto fail;
2455 }
2456 else {
2457 /* add scheme with executing log format */
2458 chunk->data += build_logline(s, chunk->area + chunk->data,
2459 chunk->size - chunk->data,
2460 &rule->rdr_fmt);
2461 }
2462 /* add "://" + host + path */
2463 if (!chunk_memcat(chunk, "://", 3) ||
2464 !chunk_memcat(chunk, host.ptr, host.len) ||
2465 !chunk_memcat(chunk, path.ptr, path.len))
2466 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002467
Christopher Faulet99daf282018-11-28 22:58:13 +01002468 /* append a slash at the end of the location if needed and missing */
2469 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2470 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2471 if (chunk->data + 1 >= chunk->size)
2472 goto fail;
2473 chunk->area[chunk->data++] = '/';
2474 }
2475 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002476 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002477
Christopher Faulet99daf282018-11-28 22:58:13 +01002478 case REDIRECT_TYPE_PREFIX: {
2479 struct ist path;
2480
Christopher Faulet297fbb42019-05-13 14:41:27 +02002481 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002482 path = http_get_path(htx_sl_req_uri(sl));
2483 /* build message using path */
2484 if (path.ptr) {
2485 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2486 int qs = 0;
2487 while (qs < path.len) {
2488 if (*(path.ptr + qs) == '?') {
2489 path.len = qs;
2490 break;
2491 }
2492 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002493 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002494 }
2495 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002496 else
2497 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002498
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 if (rule->rdr_str) { /* this is an old "redirect" rule */
2500 /* add prefix. Note that if prefix == "/", we don't want to
2501 * add anything, otherwise it makes it hard for the user to
2502 * configure a self-redirection.
2503 */
2504 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2505 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2506 goto fail;
2507 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 else {
2510 /* add prefix with executing log format */
2511 chunk->data += build_logline(s, chunk->area + chunk->data,
2512 chunk->size - chunk->data,
2513 &rule->rdr_fmt);
2514 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002515
Christopher Faulet99daf282018-11-28 22:58:13 +01002516 /* add path */
2517 if (!chunk_memcat(chunk, path.ptr, path.len))
2518 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002519
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 /* append a slash at the end of the location if needed and missing */
2521 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2522 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2523 if (chunk->data + 1 >= chunk->size)
2524 goto fail;
2525 chunk->area[chunk->data++] = '/';
2526 }
2527 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002528 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002529 case REDIRECT_TYPE_LOCATION:
2530 default:
2531 if (rule->rdr_str) { /* this is an old "redirect" rule */
2532 /* add location */
2533 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2534 goto fail;
2535 }
2536 else {
2537 /* add location with executing log format */
2538 chunk->data += build_logline(s, chunk->area + chunk->data,
2539 chunk->size - chunk->data,
2540 &rule->rdr_fmt);
2541 }
2542 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002543 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002544 location = ist2(chunk->area, chunk->data);
2545
2546 /*
2547 * Create the 30x response
2548 */
2549 switch (rule->code) {
2550 case 308:
2551 status = ist("308");
2552 reason = ist("Permanent Redirect");
2553 break;
2554 case 307:
2555 status = ist("307");
2556 reason = ist("Temporary Redirect");
2557 break;
2558 case 303:
2559 status = ist("303");
2560 reason = ist("See Other");
2561 break;
2562 case 301:
2563 status = ist("301");
2564 reason = ist("Moved Permanently");
2565 break;
2566 case 302:
2567 default:
2568 status = ist("302");
2569 reason = ist("Found");
2570 break;
2571 }
2572
Christopher Faulet08e66462019-05-23 16:44:59 +02002573 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2574 close = 1;
2575
Christopher Faulet99daf282018-11-28 22:58:13 +01002576 htx = htx_from_buf(&res->buf);
Kevin Zhu0fd70882020-01-07 09:42:55 +01002577 /* Trim any possible response */
2578 channel_htx_truncate(&s->res, htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002579 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2580 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2581 if (!sl)
2582 goto fail;
2583 sl->info.res.status = rule->code;
2584 s->txn->status = rule->code;
2585
Christopher Faulet08e66462019-05-23 16:44:59 +02002586 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2587 goto fail;
2588
2589 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002590 !htx_add_header(htx, ist("Location"), location))
2591 goto fail;
2592
2593 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2594 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2595 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002596 }
2597
2598 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002599 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2600 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002601 }
2602
Christopher Faulet99daf282018-11-28 22:58:13 +01002603 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2604 goto fail;
2605
Kevin Zhu0fd70882020-01-07 09:42:55 +01002606 htx_to_buf(htx, &res->buf);
2607
Christopher Fauletf2824e62018-10-01 12:12:37 +02002608 /* let's log the request time */
2609 s->logs.tv_request = now;
2610
Christopher Faulet99daf282018-11-28 22:58:13 +01002611 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002612 c_adv(res, data);
2613 res->total += data;
2614
2615 channel_auto_read(req);
2616 channel_abort(req);
2617 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002618 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002619
2620 res->wex = tick_add_ifset(now_ms, res->wto);
2621 channel_auto_read(res);
2622 channel_auto_close(res);
2623 channel_shutr_now(res);
2624
2625 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002626
2627 if (!(s->flags & SF_ERR_MASK))
2628 s->flags |= SF_ERR_LOCAL;
2629 if (!(s->flags & SF_FINST_MASK))
2630 s->flags |= SF_FINST_R;
2631
Christopher Faulet99daf282018-11-28 22:58:13 +01002632 free_trash_chunk(chunk);
2633 return 1;
2634
2635 fail:
2636 /* If an error occurred, remove the incomplete HTTP response from the
2637 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002638 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002639 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002640 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002641}
2642
Christopher Faulet72333522018-10-24 11:25:02 +02002643int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2644 struct ist name, const char *str, struct my_regex *re, int action)
2645{
2646 struct http_hdr_ctx ctx;
2647 struct buffer *output = get_trash_chunk();
2648
2649 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2650 ctx.blk = NULL;
2651 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2652 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2653 continue;
2654
2655 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2656 if (output->data == -1)
2657 return -1;
2658 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2659 return -1;
2660 }
2661 return 0;
2662}
2663
2664static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2665 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2666{
2667 struct buffer *replace;
2668 int ret = -1;
2669
2670 replace = alloc_trash_chunk();
2671 if (!replace)
2672 goto leave;
2673
2674 replace->data = build_logline(s, replace->area, replace->size, fmt);
2675 if (replace->data >= replace->size - 1)
2676 goto leave;
2677
2678 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2679
2680 leave:
2681 free_trash_chunk(replace);
2682 return ret;
2683}
2684
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002685
2686/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2687 * on success and -1 on error. The response channel is updated accordingly.
2688 */
2689static int htx_reply_103_early_hints(struct channel *res)
2690{
2691 struct htx *htx = htx_from_buf(&res->buf);
2692 size_t data;
2693
Christopher Faulet9869f932019-06-26 14:23:54 +02002694 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002695 /* If an error occurred during an Early-hint rule,
2696 * remove the incomplete HTTP 103 response from the
2697 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002698 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002699 return -1;
2700 }
2701
2702 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002703 c_adv(res, data);
2704 res->total += data;
2705 return 0;
2706}
2707
Christopher Faulet6eb92892018-11-15 16:39:29 +01002708/*
2709 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2710 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002711 * If <early_hints> is 0, it is starts a new response by adding the start
2712 * line. If an error occurred -1 is returned. On success 0 is returned. The
2713 * channel is not updated here. It must be done calling the function
2714 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002715 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002716static 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 +01002717{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002718 struct channel *res = &s->res;
2719 struct htx *htx = htx_from_buf(&res->buf);
2720 struct buffer *value = alloc_trash_chunk();
2721
Christopher Faulet6eb92892018-11-15 16:39:29 +01002722 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002723 struct htx_sl *sl;
2724 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2725 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2726
2727 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2728 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2729 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002730 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002731 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002732 }
2733
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002734 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2735 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002736 goto fail;
2737
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002738 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002739 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002740
2741 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002742 /* If an error occurred during an Early-hint rule, remove the incomplete
2743 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002744 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002745 free_trash_chunk(value);
2746 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002747}
2748
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002749/* This function executes one of the set-{method,path,query,uri} actions. It
2750 * takes the string from the variable 'replace' with length 'len', then modifies
2751 * the relevant part of the request line accordingly. Then it updates various
2752 * pointers to the next elements which were moved, and the total buffer length.
2753 * It finds the action to be performed in p[2], previously filled by function
2754 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2755 * error, though this can be revisited when this code is finally exploited.
2756 *
2757 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2758 * query string and 3 to replace uri.
2759 *
2760 * In query string case, the mark question '?' must be set at the start of the
2761 * string by the caller, event if the replacement query string is empty.
2762 */
2763int htx_req_replace_stline(int action, const char *replace, int len,
2764 struct proxy *px, struct stream *s)
2765{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002766 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002767
2768 switch (action) {
2769 case 0: // method
2770 if (!http_replace_req_meth(htx, ist2(replace, len)))
2771 return -1;
2772 break;
2773
2774 case 1: // path
2775 if (!http_replace_req_path(htx, ist2(replace, len)))
2776 return -1;
2777 break;
2778
2779 case 2: // query
2780 if (!http_replace_req_query(htx, ist2(replace, len)))
2781 return -1;
2782 break;
2783
2784 case 3: // uri
2785 if (!http_replace_req_uri(htx, ist2(replace, len)))
2786 return -1;
2787 break;
2788
2789 default:
2790 return -1;
2791 }
2792 return 0;
2793}
2794
2795/* This function replace the HTTP status code and the associated message. The
2796 * variable <status> contains the new status code. This function never fails.
2797 */
2798void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2799{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002800 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002801 char *res;
2802
2803 chunk_reset(&trash);
2804 res = ultoa_o(status, trash.area, trash.size);
2805 trash.data = res - trash.area;
2806
2807 /* Do we have a custom reason format string? */
2808 if (reason == NULL)
2809 reason = http_get_reason(status);
2810
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002811 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002812 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2813}
2814
Christopher Faulet3e964192018-10-24 11:39:23 +02002815/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2816 * transaction <txn>. Returns the verdict of the first rule that prevents
2817 * further processing of the request (auth, deny, ...), and defaults to
2818 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2819 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2820 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2821 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2822 * status.
2823 */
2824static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2825 struct stream *s, int *deny_status)
2826{
2827 struct session *sess = strm_sess(s);
2828 struct http_txn *txn = s->txn;
2829 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002830 struct act_rule *rule;
2831 struct http_hdr_ctx ctx;
2832 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002833 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2834 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002835 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002836
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002837 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002838
2839 /* If "the current_rule_list" match the executed rule list, we are in
2840 * resume condition. If a resume is needed it is always in the action
2841 * and never in the ACL or converters. In this case, we initialise the
2842 * current rule, and go to the action execution point.
2843 */
2844 if (s->current_rule) {
2845 rule = s->current_rule;
2846 s->current_rule = NULL;
2847 if (s->current_rule_list == rules)
2848 goto resume_execution;
2849 }
2850 s->current_rule_list = rules;
2851
2852 list_for_each_entry(rule, rules, list) {
2853 /* check optional condition */
2854 if (rule->cond) {
2855 int ret;
2856
2857 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2858 ret = acl_pass(ret);
2859
2860 if (rule->cond->pol == ACL_COND_UNLESS)
2861 ret = !ret;
2862
2863 if (!ret) /* condition not matched */
2864 continue;
2865 }
2866
2867 act_flags |= ACT_FLAG_FIRST;
2868 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002869 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2870 early_hints = 0;
2871 if (htx_reply_103_early_hints(&s->res) == -1) {
2872 rule_ret = HTTP_RULE_RES_BADREQ;
2873 goto end;
2874 }
2875 }
2876
Christopher Faulet3e964192018-10-24 11:39:23 +02002877 switch (rule->action) {
2878 case ACT_ACTION_ALLOW:
2879 rule_ret = HTTP_RULE_RES_STOP;
2880 goto end;
2881
2882 case ACT_ACTION_DENY:
2883 if (deny_status)
2884 *deny_status = rule->deny_status;
2885 rule_ret = HTTP_RULE_RES_DENY;
2886 goto end;
2887
2888 case ACT_HTTP_REQ_TARPIT:
2889 txn->flags |= TX_CLTARPIT;
2890 if (deny_status)
2891 *deny_status = rule->deny_status;
2892 rule_ret = HTTP_RULE_RES_DENY;
2893 goto end;
2894
2895 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002896 /* Auth might be performed on regular http-req rules as well as on stats */
2897 auth_realm = rule->arg.auth.realm;
2898 if (!auth_realm) {
2899 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2900 auth_realm = STATS_DEFAULT_REALM;
2901 else
2902 auth_realm = px->id;
2903 }
2904 /* send 401/407 depending on whether we use a proxy or not. We still
2905 * count one error, because normal browsing won't significantly
2906 * increase the counter but brute force attempts will.
2907 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002908 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002909 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2910 rule_ret = HTTP_RULE_RES_BADREQ;
2911 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002912 goto end;
2913
2914 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002915 rule_ret = HTTP_RULE_RES_DONE;
2916 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2917 rule_ret = HTTP_RULE_RES_BADREQ;
2918 goto end;
2919
2920 case ACT_HTTP_SET_NICE:
2921 s->task->nice = rule->arg.nice;
2922 break;
2923
2924 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002925 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002926 break;
2927
2928 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002929 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002930 break;
2931
2932 case ACT_HTTP_SET_LOGL:
2933 s->logs.level = rule->arg.loglevel;
2934 break;
2935
2936 case ACT_HTTP_REPLACE_HDR:
2937 case ACT_HTTP_REPLACE_VAL:
2938 if (htx_transform_header(s, &s->req, htx,
2939 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2940 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002941 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 rule_ret = HTTP_RULE_RES_BADREQ;
2943 goto end;
2944 }
2945 break;
2946
2947 case ACT_HTTP_DEL_HDR:
2948 /* remove all occurrences of the header */
2949 ctx.blk = NULL;
2950 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2951 http_remove_header(htx, &ctx);
2952 break;
2953
2954 case ACT_HTTP_SET_HDR:
2955 case ACT_HTTP_ADD_HDR: {
2956 /* The scope of the trash buffer must be limited to this function. The
2957 * build_logline() function can execute a lot of other function which
2958 * can use the trash buffer. So for limiting the scope of this global
2959 * buffer, we build first the header value using build_logline, and
2960 * after we store the header name.
2961 */
2962 struct buffer *replace;
2963 struct ist n, v;
2964
2965 replace = alloc_trash_chunk();
2966 if (!replace) {
2967 rule_ret = HTTP_RULE_RES_BADREQ;
2968 goto end;
2969 }
2970
2971 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2972 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2973 v = ist2(replace->area, replace->data);
2974
2975 if (rule->action == ACT_HTTP_SET_HDR) {
2976 /* remove all occurrences of the header */
2977 ctx.blk = NULL;
2978 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2979 http_remove_header(htx, &ctx);
2980 }
2981
2982 if (!http_add_header(htx, n, v)) {
2983 static unsigned char rate_limit = 0;
2984
2985 if ((rate_limit++ & 255) == 0) {
2986 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);
2987 }
2988
Olivier Houcharda798bf52019-03-08 18:52:00 +01002989 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002990 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002991 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002992 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002993 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002994 }
2995 free_trash_chunk(replace);
2996 break;
2997 }
2998
2999 case ACT_HTTP_DEL_ACL:
3000 case ACT_HTTP_DEL_MAP: {
3001 struct pat_ref *ref;
3002 struct buffer *key;
3003
3004 /* collect reference */
3005 ref = pat_ref_lookup(rule->arg.map.ref);
3006 if (!ref)
3007 continue;
3008
3009 /* allocate key */
3010 key = alloc_trash_chunk();
3011 if (!key) {
3012 rule_ret = HTTP_RULE_RES_BADREQ;
3013 goto end;
3014 }
3015
3016 /* collect key */
3017 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3018 key->area[key->data] = '\0';
3019
3020 /* perform update */
3021 /* returned code: 1=ok, 0=ko */
3022 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3023 pat_ref_delete(ref, key->area);
3024 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3025
3026 free_trash_chunk(key);
3027 break;
3028 }
3029
3030 case ACT_HTTP_ADD_ACL: {
3031 struct pat_ref *ref;
3032 struct buffer *key;
3033
3034 /* collect reference */
3035 ref = pat_ref_lookup(rule->arg.map.ref);
3036 if (!ref)
3037 continue;
3038
3039 /* allocate key */
3040 key = alloc_trash_chunk();
3041 if (!key) {
3042 rule_ret = HTTP_RULE_RES_BADREQ;
3043 goto end;
3044 }
3045
3046 /* collect key */
3047 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3048 key->area[key->data] = '\0';
3049
3050 /* perform update */
3051 /* add entry only if it does not already exist */
3052 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3053 if (pat_ref_find_elt(ref, key->area) == NULL)
3054 pat_ref_add(ref, key->area, NULL, NULL);
3055 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3056
3057 free_trash_chunk(key);
3058 break;
3059 }
3060
3061 case ACT_HTTP_SET_MAP: {
3062 struct pat_ref *ref;
3063 struct buffer *key, *value;
3064
3065 /* collect reference */
3066 ref = pat_ref_lookup(rule->arg.map.ref);
3067 if (!ref)
3068 continue;
3069
3070 /* allocate key */
3071 key = alloc_trash_chunk();
3072 if (!key) {
3073 rule_ret = HTTP_RULE_RES_BADREQ;
3074 goto end;
3075 }
3076
3077 /* allocate value */
3078 value = alloc_trash_chunk();
3079 if (!value) {
3080 free_trash_chunk(key);
3081 rule_ret = HTTP_RULE_RES_BADREQ;
3082 goto end;
3083 }
3084
3085 /* collect key */
3086 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3087 key->area[key->data] = '\0';
3088
3089 /* collect value */
3090 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3091 value->area[value->data] = '\0';
3092
3093 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003094 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003095 if (pat_ref_find_elt(ref, key->area) != NULL)
3096 /* update entry if it exists */
3097 pat_ref_set(ref, key->area, value->area, NULL);
3098 else
3099 /* insert a new entry */
3100 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003101 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003102 free_trash_chunk(key);
3103 free_trash_chunk(value);
3104 break;
3105 }
3106
3107 case ACT_HTTP_EARLY_HINT:
3108 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3109 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003110 early_hints = htx_add_early_hint_header(s, early_hints,
3111 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003112 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003113 if (early_hints == -1) {
3114 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003115 goto end;
3116 }
3117 break;
3118
3119 case ACT_CUSTOM:
3120 if ((s->req.flags & CF_READ_ERROR) ||
3121 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003122 (px->options & PR_O_ABRT_CLOSE)))
3123 act_flags |= ACT_FLAG_FINAL;
3124
3125 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3126 case ACT_RET_ERR:
3127 case ACT_RET_CONT:
3128 break;
3129 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003130 rule_ret = HTTP_RULE_RES_STOP;
3131 goto end;
3132 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003133 rule_ret = HTTP_RULE_RES_DONE;
3134 goto end;
3135 case ACT_RET_YIELD:
3136 s->current_rule = rule;
3137 rule_ret = HTTP_RULE_RES_YIELD;
3138 goto end;
3139 }
3140 break;
3141
3142 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3143 /* Note: only the first valid tracking parameter of each
3144 * applies.
3145 */
3146
3147 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3148 struct stktable *t;
3149 struct stksess *ts;
3150 struct stktable_key *key;
3151 void *ptr1, *ptr2;
3152
3153 t = rule->arg.trk_ctr.table.t;
3154 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3155 rule->arg.trk_ctr.expr, NULL);
3156
3157 if (key && (ts = stktable_get_entry(t, key))) {
3158 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3159
3160 /* let's count a new HTTP request as it's the first time we do it */
3161 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3162 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3163 if (ptr1 || ptr2) {
3164 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3165
3166 if (ptr1)
3167 stktable_data_cast(ptr1, http_req_cnt)++;
3168
3169 if (ptr2)
3170 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3171 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3172
3173 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3174
3175 /* If data was modified, we need to touch to re-schedule sync */
3176 stktable_touch_local(t, ts, 0);
3177 }
3178
3179 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3180 if (sess->fe != s->be)
3181 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3182 }
3183 }
3184 break;
3185
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003186 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003187 default:
3188 break;
3189 }
3190 }
3191
3192 end:
3193 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003194 if (htx_reply_103_early_hints(&s->res) == -1)
3195 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003196 }
3197
3198 /* we reached the end of the rules, nothing to report */
3199 return rule_ret;
3200}
3201
3202/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3203 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3204 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3205 * is returned, the process can continue the evaluation of next rule list. If
3206 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3207 * is returned, it means the operation could not be processed and a server error
3208 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3209 * deny rule. If *YIELD is returned, the caller must call again the function
3210 * with the same context.
3211 */
3212static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3213 struct stream *s)
3214{
3215 struct session *sess = strm_sess(s);
3216 struct http_txn *txn = s->txn;
3217 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003218 struct act_rule *rule;
3219 struct http_hdr_ctx ctx;
3220 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3221 int act_flags = 0;
3222
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003223 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003224
3225 /* If "the current_rule_list" match the executed rule list, we are in
3226 * resume condition. If a resume is needed it is always in the action
3227 * and never in the ACL or converters. In this case, we initialise the
3228 * current rule, and go to the action execution point.
3229 */
3230 if (s->current_rule) {
3231 rule = s->current_rule;
3232 s->current_rule = NULL;
3233 if (s->current_rule_list == rules)
3234 goto resume_execution;
3235 }
3236 s->current_rule_list = rules;
3237
3238 list_for_each_entry(rule, rules, list) {
3239 /* check optional condition */
3240 if (rule->cond) {
3241 int ret;
3242
3243 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3244 ret = acl_pass(ret);
3245
3246 if (rule->cond->pol == ACL_COND_UNLESS)
3247 ret = !ret;
3248
3249 if (!ret) /* condition not matched */
3250 continue;
3251 }
3252
3253 act_flags |= ACT_FLAG_FIRST;
3254resume_execution:
3255 switch (rule->action) {
3256 case ACT_ACTION_ALLOW:
3257 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3258 goto end;
3259
3260 case ACT_ACTION_DENY:
3261 txn->flags |= TX_SVDENY;
3262 rule_ret = HTTP_RULE_RES_STOP;
3263 goto end;
3264
3265 case ACT_HTTP_SET_NICE:
3266 s->task->nice = rule->arg.nice;
3267 break;
3268
3269 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003270 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003271 break;
3272
3273 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003274 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003275 break;
3276
3277 case ACT_HTTP_SET_LOGL:
3278 s->logs.level = rule->arg.loglevel;
3279 break;
3280
3281 case ACT_HTTP_REPLACE_HDR:
3282 case ACT_HTTP_REPLACE_VAL:
3283 if (htx_transform_header(s, &s->res, htx,
3284 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3285 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003286 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003287 rule_ret = HTTP_RULE_RES_BADREQ;
3288 goto end;
3289 }
3290 break;
3291
3292 case ACT_HTTP_DEL_HDR:
3293 /* remove all occurrences of the header */
3294 ctx.blk = NULL;
3295 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3296 http_remove_header(htx, &ctx);
3297 break;
3298
3299 case ACT_HTTP_SET_HDR:
3300 case ACT_HTTP_ADD_HDR: {
3301 struct buffer *replace;
3302 struct ist n, v;
3303
3304 replace = alloc_trash_chunk();
3305 if (!replace) {
3306 rule_ret = HTTP_RULE_RES_BADREQ;
3307 goto end;
3308 }
3309
3310 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3311 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3312 v = ist2(replace->area, replace->data);
3313
3314 if (rule->action == ACT_HTTP_SET_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 }
3320
3321 if (!http_add_header(htx, n, v)) {
3322 static unsigned char rate_limit = 0;
3323
3324 if ((rate_limit++ & 255) == 0) {
3325 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);
3326 }
3327
Olivier Houcharda798bf52019-03-08 18:52:00 +01003328 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003329 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003330 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003331 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003332 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003333 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003334 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003335 }
3336 free_trash_chunk(replace);
3337 break;
3338 }
3339
3340 case ACT_HTTP_DEL_ACL:
3341 case ACT_HTTP_DEL_MAP: {
3342 struct pat_ref *ref;
3343 struct buffer *key;
3344
3345 /* collect reference */
3346 ref = pat_ref_lookup(rule->arg.map.ref);
3347 if (!ref)
3348 continue;
3349
3350 /* allocate key */
3351 key = alloc_trash_chunk();
3352 if (!key) {
3353 rule_ret = HTTP_RULE_RES_BADREQ;
3354 goto end;
3355 }
3356
3357 /* collect key */
3358 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3359 key->area[key->data] = '\0';
3360
3361 /* perform update */
3362 /* returned code: 1=ok, 0=ko */
3363 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3364 pat_ref_delete(ref, key->area);
3365 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3366
3367 free_trash_chunk(key);
3368 break;
3369 }
3370
3371 case ACT_HTTP_ADD_ACL: {
3372 struct pat_ref *ref;
3373 struct buffer *key;
3374
3375 /* collect reference */
3376 ref = pat_ref_lookup(rule->arg.map.ref);
3377 if (!ref)
3378 continue;
3379
3380 /* allocate key */
3381 key = alloc_trash_chunk();
3382 if (!key) {
3383 rule_ret = HTTP_RULE_RES_BADREQ;
3384 goto end;
3385 }
3386
3387 /* collect key */
3388 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3389 key->area[key->data] = '\0';
3390
3391 /* perform update */
3392 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003393 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003394 if (pat_ref_find_elt(ref, key->area) == NULL)
3395 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003396 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003397 free_trash_chunk(key);
3398 break;
3399 }
3400
3401 case ACT_HTTP_SET_MAP: {
3402 struct pat_ref *ref;
3403 struct buffer *key, *value;
3404
3405 /* collect reference */
3406 ref = pat_ref_lookup(rule->arg.map.ref);
3407 if (!ref)
3408 continue;
3409
3410 /* allocate key */
3411 key = alloc_trash_chunk();
3412 if (!key) {
3413 rule_ret = HTTP_RULE_RES_BADREQ;
3414 goto end;
3415 }
3416
3417 /* allocate value */
3418 value = alloc_trash_chunk();
3419 if (!value) {
3420 free_trash_chunk(key);
3421 rule_ret = HTTP_RULE_RES_BADREQ;
3422 goto end;
3423 }
3424
3425 /* collect key */
3426 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3427 key->area[key->data] = '\0';
3428
3429 /* collect value */
3430 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3431 value->area[value->data] = '\0';
3432
3433 /* perform update */
3434 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3435 if (pat_ref_find_elt(ref, key->area) != NULL)
3436 /* update entry if it exists */
3437 pat_ref_set(ref, key->area, value->area, NULL);
3438 else
3439 /* insert a new entry */
3440 pat_ref_add(ref, key->area, value->area, NULL);
3441 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3442 free_trash_chunk(key);
3443 free_trash_chunk(value);
3444 break;
3445 }
3446
3447 case ACT_HTTP_REDIR:
3448 rule_ret = HTTP_RULE_RES_DONE;
3449 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3450 rule_ret = HTTP_RULE_RES_BADREQ;
3451 goto end;
3452
3453 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3454 /* Note: only the first valid tracking parameter of each
3455 * applies.
3456 */
3457 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3458 struct stktable *t;
3459 struct stksess *ts;
3460 struct stktable_key *key;
3461 void *ptr;
3462
3463 t = rule->arg.trk_ctr.table.t;
3464 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3465 rule->arg.trk_ctr.expr, NULL);
3466
3467 if (key && (ts = stktable_get_entry(t, key))) {
3468 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3469
3470 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3471
3472 /* let's count a new HTTP request as it's the first time we do it */
3473 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3474 if (ptr)
3475 stktable_data_cast(ptr, http_req_cnt)++;
3476
3477 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3478 if (ptr)
3479 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3480 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3481
3482 /* When the client triggers a 4xx from the server, it's most often due
3483 * to a missing object or permission. These events should be tracked
3484 * because if they happen often, it may indicate a brute force or a
3485 * vulnerability scan. Normally this is done when receiving the response
3486 * but here we're tracking after this ought to have been done so we have
3487 * to do it on purpose.
3488 */
3489 if ((unsigned)(txn->status - 400) < 100) {
3490 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3491 if (ptr)
3492 stktable_data_cast(ptr, http_err_cnt)++;
3493
3494 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3495 if (ptr)
3496 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3497 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3498 }
3499
3500 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3501
3502 /* If data was modified, we need to touch to re-schedule sync */
3503 stktable_touch_local(t, ts, 0);
3504
3505 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3506 if (sess->fe != s->be)
3507 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3508 }
3509 }
3510 break;
3511
3512 case ACT_CUSTOM:
3513 if ((s->req.flags & CF_READ_ERROR) ||
3514 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003515 (px->options & PR_O_ABRT_CLOSE)))
3516 act_flags |= ACT_FLAG_FINAL;
3517
3518 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3519 case ACT_RET_ERR:
3520 case ACT_RET_CONT:
3521 break;
3522 case ACT_RET_STOP:
3523 rule_ret = HTTP_RULE_RES_STOP;
3524 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003525 case ACT_RET_DONE:
3526 rule_ret = HTTP_RULE_RES_DONE;
3527 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003528 case ACT_RET_YIELD:
3529 s->current_rule = rule;
3530 rule_ret = HTTP_RULE_RES_YIELD;
3531 goto end;
3532 }
3533 break;
3534
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003535 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003536 default:
3537 break;
3538 }
3539 }
3540
3541 end:
3542 /* we reached the end of the rules, nothing to report */
3543 return rule_ret;
3544}
3545
Christopher Faulet33640082018-10-24 11:53:01 +02003546/* Iterate the same filter through all request headers.
3547 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3548 * Since it can manage the switch to another backend, it updates the per-proxy
3549 * DENY stats.
3550 */
3551static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3552{
3553 struct http_txn *txn = s->txn;
3554 struct htx *htx;
3555 struct buffer *hdr = get_trash_chunk();
3556 int32_t pos;
3557
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003558 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003559
Christopher Fauleta3f15502019-05-13 15:27:23 +02003560 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003561 struct htx_blk *blk = htx_get_blk(htx, pos);
3562 enum htx_blk_type type;
3563 struct ist n, v;
3564
3565 next_hdr:
3566 type = htx_get_blk_type(blk);
3567 if (type == HTX_BLK_EOH)
3568 break;
3569 if (type != HTX_BLK_HDR)
3570 continue;
3571
3572 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3573 return 1;
3574 else if (unlikely(txn->flags & TX_CLALLOW) &&
3575 (exp->action == ACT_ALLOW ||
3576 exp->action == ACT_DENY ||
3577 exp->action == ACT_TARPIT))
3578 return 0;
3579
3580 n = htx_get_blk_name(htx, blk);
3581 v = htx_get_blk_value(htx, blk);
3582
Christopher Faulet02e771a2019-02-26 15:36:05 +01003583 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003584 hdr->area[hdr->data++] = ':';
3585 hdr->area[hdr->data++] = ' ';
3586 chunk_memcat(hdr, v.ptr, v.len);
3587
3588 /* Now we have one header in <hdr> */
3589
3590 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3591 struct http_hdr_ctx ctx;
3592 int len;
3593
3594 switch (exp->action) {
3595 case ACT_ALLOW:
3596 txn->flags |= TX_CLALLOW;
3597 goto end;
3598
3599 case ACT_DENY:
3600 txn->flags |= TX_CLDENY;
3601 goto end;
3602
3603 case ACT_TARPIT:
3604 txn->flags |= TX_CLTARPIT;
3605 goto end;
3606
3607 case ACT_REPLACE:
3608 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3609 if (len < 0)
3610 return -1;
3611
3612 http_parse_header(ist2(trash.area, len), &n, &v);
3613 ctx.blk = blk;
3614 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003615 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003616 if (!http_replace_header(htx, &ctx, n, v))
3617 return -1;
3618 if (!ctx.blk)
3619 goto end;
3620 pos = htx_get_blk_pos(htx, blk);
3621 break;
3622
3623 case ACT_REMOVE:
3624 ctx.blk = blk;
3625 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003626 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003627 if (!http_remove_header(htx, &ctx))
3628 return -1;
3629 if (!ctx.blk)
3630 goto end;
3631 pos = htx_get_blk_pos(htx, blk);
3632 goto next_hdr;
3633
3634 }
3635 }
3636 }
3637 end:
3638 return 0;
3639}
3640
3641/* Apply the filter to the request line.
3642 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3643 * or -1 if a replacement resulted in an invalid request line.
3644 * Since it can manage the switch to another backend, it updates the per-proxy
3645 * DENY stats.
3646 */
3647static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3648{
3649 struct http_txn *txn = s->txn;
3650 struct htx *htx;
3651 struct buffer *reqline = get_trash_chunk();
3652 int done;
3653
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003654 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003655
3656 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3657 return 1;
3658 else if (unlikely(txn->flags & TX_CLALLOW) &&
3659 (exp->action == ACT_ALLOW ||
3660 exp->action == ACT_DENY ||
3661 exp->action == ACT_TARPIT))
3662 return 0;
3663 else if (exp->action == ACT_REMOVE)
3664 return 0;
3665
3666 done = 0;
3667
Christopher Faulet297fbb42019-05-13 14:41:27 +02003668 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003669
3670 /* Now we have the request line between cur_ptr and cur_end */
3671 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003672 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003673 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003674 int len;
3675
3676 switch (exp->action) {
3677 case ACT_ALLOW:
3678 txn->flags |= TX_CLALLOW;
3679 done = 1;
3680 break;
3681
3682 case ACT_DENY:
3683 txn->flags |= TX_CLDENY;
3684 done = 1;
3685 break;
3686
3687 case ACT_TARPIT:
3688 txn->flags |= TX_CLTARPIT;
3689 done = 1;
3690 break;
3691
3692 case ACT_REPLACE:
3693 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3694 if (len < 0)
3695 return -1;
3696
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003697 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3698 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3699 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003700 return -1;
3701 done = 1;
3702 break;
3703 }
3704 }
3705 return done;
3706}
3707
3708/*
3709 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3710 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3711 * unparsable request. Since it can manage the switch to another backend, it
3712 * updates the per-proxy DENY stats.
3713 */
3714static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3715{
3716 struct session *sess = s->sess;
3717 struct http_txn *txn = s->txn;
3718 struct hdr_exp *exp;
3719
3720 for (exp = px->req_exp; exp; exp = exp->next) {
3721 int ret;
3722
3723 /*
3724 * The interleaving of transformations and verdicts
3725 * makes it difficult to decide to continue or stop
3726 * the evaluation.
3727 */
3728
3729 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3730 break;
3731
3732 if ((txn->flags & TX_CLALLOW) &&
3733 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3734 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3735 continue;
3736
3737 /* if this filter had a condition, evaluate it now and skip to
3738 * next filter if the condition does not match.
3739 */
3740 if (exp->cond) {
3741 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3742 ret = acl_pass(ret);
3743 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3744 ret = !ret;
3745
3746 if (!ret)
3747 continue;
3748 }
3749
3750 /* Apply the filter to the request line. */
3751 ret = htx_apply_filter_to_req_line(s, req, exp);
3752 if (unlikely(ret < 0))
3753 return -1;
3754
3755 if (likely(ret == 0)) {
3756 /* The filter did not match the request, it can be
3757 * iterated through all headers.
3758 */
3759 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3760 return -1;
3761 }
3762 }
3763 return 0;
3764}
3765
3766/* Iterate the same filter through all response headers contained in <res>.
3767 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3768 */
3769static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3770{
3771 struct http_txn *txn = s->txn;
3772 struct htx *htx;
3773 struct buffer *hdr = get_trash_chunk();
3774 int32_t pos;
3775
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003776 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003777
Christopher Fauleta3f15502019-05-13 15:27:23 +02003778 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003779 struct htx_blk *blk = htx_get_blk(htx, pos);
3780 enum htx_blk_type type;
3781 struct ist n, v;
3782
3783 next_hdr:
3784 type = htx_get_blk_type(blk);
3785 if (type == HTX_BLK_EOH)
3786 break;
3787 if (type != HTX_BLK_HDR)
3788 continue;
3789
3790 if (unlikely(txn->flags & TX_SVDENY))
3791 return 1;
3792 else if (unlikely(txn->flags & TX_SVALLOW) &&
3793 (exp->action == ACT_ALLOW ||
3794 exp->action == ACT_DENY))
3795 return 0;
3796
3797 n = htx_get_blk_name(htx, blk);
3798 v = htx_get_blk_value(htx, blk);
3799
Christopher Faulet02e771a2019-02-26 15:36:05 +01003800 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003801 hdr->area[hdr->data++] = ':';
3802 hdr->area[hdr->data++] = ' ';
3803 chunk_memcat(hdr, v.ptr, v.len);
3804
3805 /* Now we have one header in <hdr> */
3806
3807 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3808 struct http_hdr_ctx ctx;
3809 int len;
3810
3811 switch (exp->action) {
3812 case ACT_ALLOW:
3813 txn->flags |= TX_SVALLOW;
3814 goto end;
3815 break;
3816
3817 case ACT_DENY:
3818 txn->flags |= TX_SVDENY;
3819 goto end;
3820 break;
3821
3822 case ACT_REPLACE:
3823 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3824 if (len < 0)
3825 return -1;
3826
3827 http_parse_header(ist2(trash.area, len), &n, &v);
3828 ctx.blk = blk;
3829 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003830 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003831 if (!http_replace_header(htx, &ctx, n, v))
3832 return -1;
3833 if (!ctx.blk)
3834 goto end;
3835 pos = htx_get_blk_pos(htx, blk);
3836 break;
3837
3838 case ACT_REMOVE:
3839 ctx.blk = blk;
3840 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003841 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003842 if (!http_remove_header(htx, &ctx))
3843 return -1;
3844 if (!ctx.blk)
3845 goto end;
3846 pos = htx_get_blk_pos(htx, blk);
3847 goto next_hdr;
3848 }
3849 }
3850
3851 }
3852 end:
3853 return 0;
3854}
3855
3856/* Apply the filter to the status line in the response buffer <res>.
3857 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3858 * or -1 if a replacement resulted in an invalid status line.
3859 */
3860static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3861{
3862 struct http_txn *txn = s->txn;
3863 struct htx *htx;
3864 struct buffer *resline = get_trash_chunk();
3865 int done;
3866
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003867 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003868
3869 if (unlikely(txn->flags & TX_SVDENY))
3870 return 1;
3871 else if (unlikely(txn->flags & TX_SVALLOW) &&
3872 (exp->action == ACT_ALLOW ||
3873 exp->action == ACT_DENY))
3874 return 0;
3875 else if (exp->action == ACT_REMOVE)
3876 return 0;
3877
3878 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003879 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003880
3881 /* Now we have the status line between cur_ptr and cur_end */
3882 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003883 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003884 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003885 int len;
3886
3887 switch (exp->action) {
3888 case ACT_ALLOW:
3889 txn->flags |= TX_SVALLOW;
3890 done = 1;
3891 break;
3892
3893 case ACT_DENY:
3894 txn->flags |= TX_SVDENY;
3895 done = 1;
3896 break;
3897
3898 case ACT_REPLACE:
3899 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3900 if (len < 0)
3901 return -1;
3902
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003903 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3904 sl->info.res.status = strl2ui(code.ptr, code.len);
3905 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003906 return -1;
3907
3908 done = 1;
3909 return 1;
3910 }
3911 }
3912 return done;
3913}
3914
3915/*
3916 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3917 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3918 * unparsable response.
3919 */
3920static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3921{
3922 struct session *sess = s->sess;
3923 struct http_txn *txn = s->txn;
3924 struct hdr_exp *exp;
3925
3926 for (exp = px->rsp_exp; exp; exp = exp->next) {
3927 int ret;
3928
3929 /*
3930 * The interleaving of transformations and verdicts
3931 * makes it difficult to decide to continue or stop
3932 * the evaluation.
3933 */
3934
3935 if (txn->flags & TX_SVDENY)
3936 break;
3937
3938 if ((txn->flags & TX_SVALLOW) &&
3939 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3940 exp->action == ACT_PASS)) {
3941 exp = exp->next;
3942 continue;
3943 }
3944
3945 /* if this filter had a condition, evaluate it now and skip to
3946 * next filter if the condition does not match.
3947 */
3948 if (exp->cond) {
3949 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3950 ret = acl_pass(ret);
3951 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3952 ret = !ret;
3953 if (!ret)
3954 continue;
3955 }
3956
3957 /* Apply the filter to the status line. */
3958 ret = htx_apply_filter_to_sts_line(s, res, exp);
3959 if (unlikely(ret < 0))
3960 return -1;
3961
3962 if (likely(ret == 0)) {
3963 /* The filter did not match the response, it can be
3964 * iterated through all headers.
3965 */
3966 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3967 return -1;
3968 }
3969 }
3970 return 0;
3971}
3972
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003973/*
3974 * Manage client-side cookie. It can impact performance by about 2% so it is
3975 * desirable to call it only when needed. This code is quite complex because
3976 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3977 * highly recommended not to touch this part without a good reason !
3978 */
3979static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3980{
3981 struct session *sess = s->sess;
3982 struct http_txn *txn = s->txn;
3983 struct htx *htx;
3984 struct http_hdr_ctx ctx;
3985 char *hdr_beg, *hdr_end, *del_from;
3986 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3987 int preserve_hdr;
3988
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003989 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003990 ctx.blk = NULL;
3991 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02003992 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003993 del_from = NULL; /* nothing to be deleted */
3994 preserve_hdr = 0; /* assume we may kill the whole header */
3995
3996 /* Now look for cookies. Conforming to RFC2109, we have to support
3997 * attributes whose name begin with a '$', and associate them with
3998 * the right cookie, if we want to delete this cookie.
3999 * So there are 3 cases for each cookie read :
4000 * 1) it's a special attribute, beginning with a '$' : ignore it.
4001 * 2) it's a server id cookie that we *MAY* want to delete : save
4002 * some pointers on it (last semi-colon, beginning of cookie...)
4003 * 3) it's an application cookie : we *MAY* have to delete a previous
4004 * "special" cookie.
4005 * At the end of loop, if a "special" cookie remains, we may have to
4006 * remove it. If no application cookie persists in the header, we
4007 * *MUST* delete it.
4008 *
4009 * Note: RFC2965 is unclear about the processing of spaces around
4010 * the equal sign in the ATTR=VALUE form. A careful inspection of
4011 * the RFC explicitly allows spaces before it, and not within the
4012 * tokens (attrs or values). An inspection of RFC2109 allows that
4013 * too but section 10.1.3 lets one think that spaces may be allowed
4014 * after the equal sign too, resulting in some (rare) buggy
4015 * implementations trying to do that. So let's do what servers do.
4016 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
4017 * allowed quoted strings in values, with any possible character
4018 * after a backslash, including control chars and delimitors, which
4019 * causes parsing to become ambiguous. Browsers also allow spaces
4020 * within values even without quotes.
4021 *
4022 * We have to keep multiple pointers in order to support cookie
4023 * removal at the beginning, middle or end of header without
4024 * corrupting the header. All of these headers are valid :
4025 *
4026 * hdr_beg hdr_end
4027 * | |
4028 * v |
4029 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
4030 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
4031 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
4032 * | | | | | | |
4033 * | | | | | | |
4034 * | | | | | | +--> next
4035 * | | | | | +----> val_end
4036 * | | | | +-----------> val_beg
4037 * | | | +--------------> equal
4038 * | | +----------------> att_end
4039 * | +---------------------> att_beg
4040 * +--------------------------> prev
4041 *
4042 */
4043 hdr_beg = ctx.value.ptr;
4044 hdr_end = hdr_beg + ctx.value.len;
4045 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4046 /* Iterate through all cookies on this line */
4047
4048 /* find att_beg */
4049 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004050 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004051 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004052 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004053
4054 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4055 att_beg++;
4056
4057 /* find att_end : this is the first character after the last non
4058 * space before the equal. It may be equal to hdr_end.
4059 */
4060 equal = att_end = att_beg;
4061 while (equal < hdr_end) {
4062 if (*equal == '=' || *equal == ',' || *equal == ';')
4063 break;
4064 if (HTTP_IS_SPHT(*equal++))
4065 continue;
4066 att_end = equal;
4067 }
4068
4069 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4070 * is between <att_beg> and <equal>, both may be identical.
4071 */
4072 /* look for end of cookie if there is an equal sign */
4073 if (equal < hdr_end && *equal == '=') {
4074 /* look for the beginning of the value */
4075 val_beg = equal + 1;
4076 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4077 val_beg++;
4078
4079 /* find the end of the value, respecting quotes */
4080 next = http_find_cookie_value_end(val_beg, hdr_end);
4081
4082 /* make val_end point to the first white space or delimitor after the value */
4083 val_end = next;
4084 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4085 val_end--;
4086 }
4087 else
4088 val_beg = val_end = next = equal;
4089
4090 /* We have nothing to do with attributes beginning with
4091 * '$'. However, they will automatically be removed if a
4092 * header before them is removed, since they're supposed
4093 * to be linked together.
4094 */
4095 if (*att_beg == '$')
4096 continue;
4097
4098 /* Ignore cookies with no equal sign */
4099 if (equal == next) {
4100 /* This is not our cookie, so we must preserve it. But if we already
4101 * scheduled another cookie for removal, we cannot remove the
4102 * complete header, but we can remove the previous block itself.
4103 */
4104 preserve_hdr = 1;
4105 if (del_from != NULL) {
4106 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4107 val_end += delta;
4108 next += delta;
4109 hdr_end += delta;
4110 prev = del_from;
4111 del_from = NULL;
4112 }
4113 continue;
4114 }
4115
4116 /* if there are spaces around the equal sign, we need to
4117 * strip them otherwise we'll get trouble for cookie captures,
4118 * or even for rewrites. Since this happens extremely rarely,
4119 * it does not hurt performance.
4120 */
4121 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4122 int stripped_before = 0;
4123 int stripped_after = 0;
4124
4125 if (att_end != equal) {
4126 memmove(att_end, equal, hdr_end - equal);
4127 stripped_before = (att_end - equal);
4128 equal += stripped_before;
4129 val_beg += stripped_before;
4130 }
4131
4132 if (val_beg > equal + 1) {
4133 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4134 stripped_after = (equal + 1) - val_beg;
4135 val_beg += stripped_after;
4136 stripped_before += stripped_after;
4137 }
4138
4139 val_end += stripped_before;
4140 next += stripped_before;
4141 hdr_end += stripped_before;
4142 }
4143 /* now everything is as on the diagram above */
4144
4145 /* First, let's see if we want to capture this cookie. We check
4146 * that we don't already have a client side cookie, because we
4147 * can only capture one. Also as an optimisation, we ignore
4148 * cookies shorter than the declared name.
4149 */
4150 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4151 (val_end - att_beg >= sess->fe->capture_namelen) &&
4152 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4153 int log_len = val_end - att_beg;
4154
4155 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4156 ha_alert("HTTP logging : out of memory.\n");
4157 } else {
4158 if (log_len > sess->fe->capture_len)
4159 log_len = sess->fe->capture_len;
4160 memcpy(txn->cli_cookie, att_beg, log_len);
4161 txn->cli_cookie[log_len] = 0;
4162 }
4163 }
4164
4165 /* Persistence cookies in passive, rewrite or insert mode have the
4166 * following form :
4167 *
4168 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4169 *
4170 * For cookies in prefix mode, the form is :
4171 *
4172 * Cookie: NAME=SRV~VALUE
4173 */
4174 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4175 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4176 struct server *srv = s->be->srv;
4177 char *delim;
4178
4179 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4180 * have the server ID between val_beg and delim, and the original cookie between
4181 * delim+1 and val_end. Otherwise, delim==val_end :
4182 *
4183 * hdr_beg
4184 * |
4185 * v
4186 * NAME=SRV; # in all but prefix modes
4187 * NAME=SRV~OPAQUE ; # in prefix mode
4188 * || || | |+-> next
4189 * || || | +--> val_end
4190 * || || +---------> delim
4191 * || |+------------> val_beg
4192 * || +-------------> att_end = equal
4193 * |+-----------------> att_beg
4194 * +------------------> prev
4195 *
4196 */
4197 if (s->be->ck_opts & PR_CK_PFX) {
4198 for (delim = val_beg; delim < val_end; delim++)
4199 if (*delim == COOKIE_DELIM)
4200 break;
4201 }
4202 else {
4203 char *vbar1;
4204 delim = val_end;
4205 /* Now check if the cookie contains a date field, which would
4206 * appear after a vertical bar ('|') just after the server name
4207 * and before the delimiter.
4208 */
4209 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4210 if (vbar1) {
4211 /* OK, so left of the bar is the server's cookie and
4212 * right is the last seen date. It is a base64 encoded
4213 * 30-bit value representing the UNIX date since the
4214 * epoch in 4-second quantities.
4215 */
4216 int val;
4217 delim = vbar1++;
4218 if (val_end - vbar1 >= 5) {
4219 val = b64tos30(vbar1);
4220 if (val > 0)
4221 txn->cookie_last_date = val << 2;
4222 }
4223 /* look for a second vertical bar */
4224 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4225 if (vbar1 && (val_end - vbar1 > 5)) {
4226 val = b64tos30(vbar1 + 1);
4227 if (val > 0)
4228 txn->cookie_first_date = val << 2;
4229 }
4230 }
4231 }
4232
4233 /* if the cookie has an expiration date and the proxy wants to check
4234 * it, then we do that now. We first check if the cookie is too old,
4235 * then only if it has expired. We detect strict overflow because the
4236 * time resolution here is not great (4 seconds). Cookies with dates
4237 * in the future are ignored if their offset is beyond one day. This
4238 * allows an admin to fix timezone issues without expiring everyone
4239 * and at the same time avoids keeping unwanted side effects for too
4240 * long.
4241 */
4242 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4243 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4244 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4245 txn->flags &= ~TX_CK_MASK;
4246 txn->flags |= TX_CK_OLD;
4247 delim = val_beg; // let's pretend we have not found the cookie
4248 txn->cookie_first_date = 0;
4249 txn->cookie_last_date = 0;
4250 }
4251 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4252 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4253 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4254 txn->flags &= ~TX_CK_MASK;
4255 txn->flags |= TX_CK_EXPIRED;
4256 delim = val_beg; // let's pretend we have not found the cookie
4257 txn->cookie_first_date = 0;
4258 txn->cookie_last_date = 0;
4259 }
4260
4261 /* Here, we'll look for the first running server which supports the cookie.
4262 * This allows to share a same cookie between several servers, for example
4263 * to dedicate backup servers to specific servers only.
4264 * However, to prevent clients from sticking to cookie-less backup server
4265 * when they have incidentely learned an empty cookie, we simply ignore
4266 * empty cookies and mark them as invalid.
4267 * The same behaviour is applied when persistence must be ignored.
4268 */
4269 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4270 srv = NULL;
4271
4272 while (srv) {
4273 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4274 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4275 if ((srv->cur_state != SRV_ST_STOPPED) ||
4276 (s->be->options & PR_O_PERSIST) ||
4277 (s->flags & SF_FORCE_PRST)) {
4278 /* we found the server and we can use it */
4279 txn->flags &= ~TX_CK_MASK;
4280 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4281 s->flags |= SF_DIRECT | SF_ASSIGNED;
4282 s->target = &srv->obj_type;
4283 break;
4284 } else {
4285 /* we found a server, but it's down,
4286 * mark it as such and go on in case
4287 * another one is available.
4288 */
4289 txn->flags &= ~TX_CK_MASK;
4290 txn->flags |= TX_CK_DOWN;
4291 }
4292 }
4293 srv = srv->next;
4294 }
4295
4296 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4297 /* no server matched this cookie or we deliberately skipped it */
4298 txn->flags &= ~TX_CK_MASK;
4299 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4300 txn->flags |= TX_CK_UNUSED;
4301 else
4302 txn->flags |= TX_CK_INVALID;
4303 }
4304
4305 /* depending on the cookie mode, we may have to either :
4306 * - delete the complete cookie if we're in insert+indirect mode, so that
4307 * the server never sees it ;
4308 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004309 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004310 * if we're in cookie prefix mode
4311 */
4312 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4313 int delta; /* negative */
4314
4315 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4316 delta = val_beg - (delim + 1);
4317 val_end += delta;
4318 next += delta;
4319 hdr_end += delta;
4320 del_from = NULL;
4321 preserve_hdr = 1; /* we want to keep this cookie */
4322 }
4323 else if (del_from == NULL &&
4324 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4325 del_from = prev;
4326 }
4327 }
4328 else {
4329 /* This is not our cookie, so we must preserve it. But if we already
4330 * scheduled another cookie for removal, we cannot remove the
4331 * complete header, but we can remove the previous block itself.
4332 */
4333 preserve_hdr = 1;
4334
4335 if (del_from != NULL) {
4336 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4337 if (att_beg >= del_from)
4338 att_beg += delta;
4339 if (att_end >= del_from)
4340 att_end += delta;
4341 val_beg += delta;
4342 val_end += delta;
4343 next += delta;
4344 hdr_end += delta;
4345 prev = del_from;
4346 del_from = NULL;
4347 }
4348 }
4349
4350 /* continue with next cookie on this header line */
4351 att_beg = next;
4352 } /* for each cookie */
4353
4354
4355 /* There are no more cookies on this line.
4356 * We may still have one (or several) marked for deletion at the
4357 * end of the line. We must do this now in two ways :
4358 * - if some cookies must be preserved, we only delete from the
4359 * mark to the end of line ;
4360 * - if nothing needs to be preserved, simply delete the whole header
4361 */
4362 if (del_from) {
4363 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4364 }
4365 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004366 if (hdr_beg != hdr_end)
4367 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004368 else
4369 http_remove_header(htx, &ctx);
4370 }
4371 } /* for each "Cookie header */
4372}
4373
4374/*
4375 * Manage server-side cookies. It can impact performance by about 2% so it is
4376 * desirable to call it only when needed. This function is also used when we
4377 * just need to know if there is a cookie (eg: for check-cache).
4378 */
4379static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4380{
4381 struct session *sess = s->sess;
4382 struct http_txn *txn = s->txn;
4383 struct htx *htx;
4384 struct http_hdr_ctx ctx;
4385 struct server *srv;
4386 char *hdr_beg, *hdr_end;
4387 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004388 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004389
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004390 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004391
4392 ctx.blk = NULL;
4393 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004394 int is_first = 1;
4395
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004396 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4397 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4398 break;
4399 is_cookie2 = 1;
4400 }
4401
4402 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4403 * <prev> points to the colon.
4404 */
4405 txn->flags |= TX_SCK_PRESENT;
4406
4407 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4408 * check-cache is enabled) and we are not interested in checking
4409 * them. Warning, the cookie capture is declared in the frontend.
4410 */
4411 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4412 break;
4413
4414 /* OK so now we know we have to process this response cookie.
4415 * The format of the Set-Cookie header is slightly different
4416 * from the format of the Cookie header in that it does not
4417 * support the comma as a cookie delimiter (thus the header
4418 * cannot be folded) because the Expires attribute described in
4419 * the original Netscape's spec may contain an unquoted date
4420 * with a comma inside. We have to live with this because
4421 * many browsers don't support Max-Age and some browsers don't
4422 * support quoted strings. However the Set-Cookie2 header is
4423 * clean.
4424 *
4425 * We have to keep multiple pointers in order to support cookie
4426 * removal at the beginning, middle or end of header without
4427 * corrupting the header (in case of set-cookie2). A special
4428 * pointer, <scav> points to the beginning of the set-cookie-av
4429 * fields after the first semi-colon. The <next> pointer points
4430 * either to the end of line (set-cookie) or next unquoted comma
4431 * (set-cookie2). All of these headers are valid :
4432 *
4433 * hdr_beg hdr_end
4434 * | |
4435 * v |
4436 * NAME1 = VALUE 1 ; Secure; Path="/" |
4437 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4438 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4439 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4440 * | | | | | | | |
4441 * | | | | | | | +-> next
4442 * | | | | | | +------------> scav
4443 * | | | | | +--------------> val_end
4444 * | | | | +--------------------> val_beg
4445 * | | | +----------------------> equal
4446 * | | +------------------------> att_end
4447 * | +----------------------------> att_beg
4448 * +------------------------------> prev
4449 * -------------------------------> hdr_beg
4450 */
4451 hdr_beg = ctx.value.ptr;
4452 hdr_end = hdr_beg + ctx.value.len;
4453 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4454
4455 /* Iterate through all cookies on this line */
4456
4457 /* find att_beg */
4458 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004459 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004460 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004461 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004462
4463 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4464 att_beg++;
4465
4466 /* find att_end : this is the first character after the last non
4467 * space before the equal. It may be equal to hdr_end.
4468 */
4469 equal = att_end = att_beg;
4470
4471 while (equal < hdr_end) {
4472 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4473 break;
4474 if (HTTP_IS_SPHT(*equal++))
4475 continue;
4476 att_end = equal;
4477 }
4478
4479 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4480 * is between <att_beg> and <equal>, both may be identical.
4481 */
4482
4483 /* look for end of cookie if there is an equal sign */
4484 if (equal < hdr_end && *equal == '=') {
4485 /* look for the beginning of the value */
4486 val_beg = equal + 1;
4487 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4488 val_beg++;
4489
4490 /* find the end of the value, respecting quotes */
4491 next = http_find_cookie_value_end(val_beg, hdr_end);
4492
4493 /* make val_end point to the first white space or delimitor after the value */
4494 val_end = next;
4495 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4496 val_end--;
4497 }
4498 else {
4499 /* <equal> points to next comma, semi-colon or EOL */
4500 val_beg = val_end = next = equal;
4501 }
4502
4503 if (next < hdr_end) {
4504 /* Set-Cookie2 supports multiple cookies, and <next> points to
4505 * a colon or semi-colon before the end. So skip all attr-value
4506 * pairs and look for the next comma. For Set-Cookie, since
4507 * commas are permitted in values, skip to the end.
4508 */
4509 if (is_cookie2)
4510 next = http_find_hdr_value_end(next, hdr_end);
4511 else
4512 next = hdr_end;
4513 }
4514
4515 /* Now everything is as on the diagram above */
4516
4517 /* Ignore cookies with no equal sign */
4518 if (equal == val_end)
4519 continue;
4520
4521 /* If there are spaces around the equal sign, we need to
4522 * strip them otherwise we'll get trouble for cookie captures,
4523 * or even for rewrites. Since this happens extremely rarely,
4524 * it does not hurt performance.
4525 */
4526 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4527 int stripped_before = 0;
4528 int stripped_after = 0;
4529
4530 if (att_end != equal) {
4531 memmove(att_end, equal, hdr_end - equal);
4532 stripped_before = (att_end - equal);
4533 equal += stripped_before;
4534 val_beg += stripped_before;
4535 }
4536
4537 if (val_beg > equal + 1) {
4538 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4539 stripped_after = (equal + 1) - val_beg;
4540 val_beg += stripped_after;
4541 stripped_before += stripped_after;
4542 }
4543
4544 val_end += stripped_before;
4545 next += stripped_before;
4546 hdr_end += stripped_before;
4547
Christopher Faulet41dc8432019-06-18 09:49:16 +02004548 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004549 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004550 }
4551
4552 /* First, let's see if we want to capture this cookie. We check
4553 * that we don't already have a server side cookie, because we
4554 * can only capture one. Also as an optimisation, we ignore
4555 * cookies shorter than the declared name.
4556 */
4557 if (sess->fe->capture_name != NULL &&
4558 txn->srv_cookie == NULL &&
4559 (val_end - att_beg >= sess->fe->capture_namelen) &&
4560 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4561 int log_len = val_end - att_beg;
4562 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4563 ha_alert("HTTP logging : out of memory.\n");
4564 }
4565 else {
4566 if (log_len > sess->fe->capture_len)
4567 log_len = sess->fe->capture_len;
4568 memcpy(txn->srv_cookie, att_beg, log_len);
4569 txn->srv_cookie[log_len] = 0;
4570 }
4571 }
4572
4573 srv = objt_server(s->target);
4574 /* now check if we need to process it for persistence */
4575 if (!(s->flags & SF_IGNORE_PRST) &&
4576 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4577 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4578 /* assume passive cookie by default */
4579 txn->flags &= ~TX_SCK_MASK;
4580 txn->flags |= TX_SCK_FOUND;
4581
4582 /* If the cookie is in insert mode on a known server, we'll delete
4583 * this occurrence because we'll insert another one later.
4584 * We'll delete it too if the "indirect" option is set and we're in
4585 * a direct access.
4586 */
4587 if (s->be->ck_opts & PR_CK_PSV) {
4588 /* The "preserve" flag was set, we don't want to touch the
4589 * server's cookie.
4590 */
4591 }
4592 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4593 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4594 /* this cookie must be deleted */
4595 if (prev == hdr_beg && next == hdr_end) {
4596 /* whole header */
4597 http_remove_header(htx, &ctx);
4598 /* note: while both invalid now, <next> and <hdr_end>
4599 * are still equal, so the for() will stop as expected.
4600 */
4601 } else {
4602 /* just remove the value */
4603 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4604 next = prev;
4605 hdr_end += delta;
4606 }
4607 txn->flags &= ~TX_SCK_MASK;
4608 txn->flags |= TX_SCK_DELETED;
4609 /* and go on with next cookie */
4610 }
4611 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4612 /* replace bytes val_beg->val_end with the cookie name associated
4613 * with this server since we know it.
4614 */
4615 int sliding, delta;
4616
4617 ctx.value = ist2(val_beg, val_end - val_beg);
4618 ctx.lws_before = ctx.lws_after = 0;
4619 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4620 delta = srv->cklen - (val_end - val_beg);
4621 sliding = (ctx.value.ptr - val_beg);
4622 hdr_beg += sliding;
4623 val_beg += sliding;
4624 next += sliding + delta;
4625 hdr_end += sliding + delta;
4626
4627 txn->flags &= ~TX_SCK_MASK;
4628 txn->flags |= TX_SCK_REPLACED;
4629 }
4630 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4631 /* insert the cookie name associated with this server
4632 * before existing cookie, and insert a delimiter between them..
4633 */
4634 int sliding, delta;
4635 ctx.value = ist2(val_beg, 0);
4636 ctx.lws_before = ctx.lws_after = 0;
4637 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4638 delta = srv->cklen + 1;
4639 sliding = (ctx.value.ptr - val_beg);
4640 hdr_beg += sliding;
4641 val_beg += sliding;
4642 next += sliding + delta;
4643 hdr_end += sliding + delta;
4644
4645 val_beg[srv->cklen] = COOKIE_DELIM;
4646 txn->flags &= ~TX_SCK_MASK;
4647 txn->flags |= TX_SCK_REPLACED;
4648 }
4649 }
4650 /* that's done for this cookie, check the next one on the same
4651 * line when next != hdr_end (only if is_cookie2).
4652 */
4653 }
4654 }
4655}
4656
Christopher Faulet25a02f62018-10-24 12:00:25 +02004657/*
4658 * Parses the Cache-Control and Pragma request header fields to determine if
4659 * the request may be served from the cache and/or if it is cacheable. Updates
4660 * s->txn->flags.
4661 */
4662void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4663{
4664 struct http_txn *txn = s->txn;
4665 struct htx *htx;
4666 int32_t pos;
4667 int pragma_found, cc_found, i;
4668
4669 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4670 return; /* nothing more to do here */
4671
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004672 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004673 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004674 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004675 struct htx_blk *blk = htx_get_blk(htx, pos);
4676 enum htx_blk_type type = htx_get_blk_type(blk);
4677 struct ist n, v;
4678
4679 if (type == HTX_BLK_EOH)
4680 break;
4681 if (type != HTX_BLK_HDR)
4682 continue;
4683
4684 n = htx_get_blk_name(htx, blk);
4685 v = htx_get_blk_value(htx, blk);
4686
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004687 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004688 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4689 pragma_found = 1;
4690 continue;
4691 }
4692 }
4693
4694 /* Don't use the cache and don't try to store if we found the
4695 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004696 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004697 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4698 txn->flags |= TX_CACHE_IGNORE;
4699 continue;
4700 }
4701
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004702 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004703 continue;
4704
4705 /* OK, right now we know we have a cache-control header */
4706 cc_found = 1;
4707 if (!v.len) /* no info */
4708 continue;
4709
4710 i = 0;
4711 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4712 !isspace((unsigned char)*(v.ptr+i)))
4713 i++;
4714
4715 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4716 * values after max-age, max-stale nor min-fresh, we simply don't
4717 * use the cache when they're specified.
4718 */
4719 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4720 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4721 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4722 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4723 txn->flags |= TX_CACHE_IGNORE;
4724 continue;
4725 }
4726
4727 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4728 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4729 continue;
4730 }
4731 }
4732
4733 /* RFC7234#5.4:
4734 * When the Cache-Control header field is also present and
4735 * understood in a request, Pragma is ignored.
4736 * When the Cache-Control header field is not present in a
4737 * request, caches MUST consider the no-cache request
4738 * pragma-directive as having the same effect as if
4739 * "Cache-Control: no-cache" were present.
4740 */
4741 if (!cc_found && pragma_found)
4742 txn->flags |= TX_CACHE_IGNORE;
4743}
4744
4745/*
4746 * Check if response is cacheable or not. Updates s->txn->flags.
4747 */
4748void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4749{
4750 struct http_txn *txn = s->txn;
4751 struct htx *htx;
4752 int32_t pos;
4753 int i;
4754
4755 if (txn->status < 200) {
4756 /* do not try to cache interim responses! */
4757 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4758 return;
4759 }
4760
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004761 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004762 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004763 struct htx_blk *blk = htx_get_blk(htx, pos);
4764 enum htx_blk_type type = htx_get_blk_type(blk);
4765 struct ist n, v;
4766
4767 if (type == HTX_BLK_EOH)
4768 break;
4769 if (type != HTX_BLK_HDR)
4770 continue;
4771
4772 n = htx_get_blk_name(htx, blk);
4773 v = htx_get_blk_value(htx, blk);
4774
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004775 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004776 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4777 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4778 return;
4779 }
4780 }
4781
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004782 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004783 continue;
4784
4785 /* OK, right now we know we have a cache-control header */
4786 if (!v.len) /* no info */
4787 continue;
4788
4789 i = 0;
4790 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4791 !isspace((unsigned char)*(v.ptr+i)))
4792 i++;
4793
4794 /* we have a complete value between v.ptr and (v.ptr+i) */
4795 if (i < v.len && *(v.ptr + i) == '=') {
4796 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4797 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4798 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4799 continue;
4800 }
4801
4802 /* we have something of the form no-cache="set-cookie" */
4803 if ((v.len >= 21) &&
4804 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4805 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4806 txn->flags &= ~TX_CACHE_COOK;
4807 continue;
4808 }
4809
4810 /* OK, so we know that either p2 points to the end of string or to a comma */
4811 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4812 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4813 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4814 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4815 return;
4816 }
4817
4818 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4819 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4820 continue;
4821 }
4822 }
4823}
4824
Christopher Faulet64159df2018-10-24 21:15:35 +02004825/* send a server's name with an outgoing request over an established connection.
4826 * Note: this function is designed to be called once the request has been
4827 * scheduled for being forwarded. This is the reason why the number of forwarded
4828 * bytes have to be adjusted.
4829 */
4830int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4831{
4832 struct htx *htx;
4833 struct http_hdr_ctx ctx;
4834 struct ist hdr;
4835 uint32_t data;
4836
4837 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004838 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004839 data = htx->data;
4840
4841 ctx.blk = NULL;
4842 while (http_find_header(htx, hdr, &ctx, 1))
4843 http_remove_header(htx, &ctx);
4844 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4845
4846 if (co_data(&s->req)) {
4847 if (data >= htx->data)
4848 c_rew(&s->req, data - htx->data);
4849 else
4850 c_adv(&s->req, htx->data - data);
4851 }
4852 return 0;
4853}
4854
Christopher Faulet377c5a52018-10-24 21:21:30 +02004855/*
4856 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4857 * for the current backend.
4858 *
4859 * It is assumed that the request is either a HEAD, GET, or POST and that the
4860 * uri_auth field is valid.
4861 *
4862 * Returns 1 if stats should be provided, otherwise 0.
4863 */
4864static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4865{
4866 struct uri_auth *uri_auth = backend->uri_auth;
4867 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004868 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004869 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004870
4871 if (!uri_auth)
4872 return 0;
4873
4874 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4875 return 0;
4876
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004877 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004878 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004879 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004880
4881 /* check URI size */
4882 if (uri_auth->uri_len > uri.len)
4883 return 0;
4884
4885 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4886 return 0;
4887
4888 return 1;
4889}
4890
4891/* This function prepares an applet to handle the stats. It can deal with the
4892 * "100-continue" expectation, check that admin rules are met for POST requests,
4893 * and program a response message if something was unexpected. It cannot fail
4894 * and always relies on the stats applet to complete the job. It does not touch
4895 * analysers nor counters, which are left to the caller. It does not touch
4896 * s->target which is supposed to already point to the stats applet. The caller
4897 * is expected to have already assigned an appctx to the stream.
4898 */
4899static int htx_handle_stats(struct stream *s, struct channel *req)
4900{
4901 struct stats_admin_rule *stats_admin_rule;
4902 struct stream_interface *si = &s->si[1];
4903 struct session *sess = s->sess;
4904 struct http_txn *txn = s->txn;
4905 struct http_msg *msg = &txn->req;
4906 struct uri_auth *uri_auth = s->be->uri_auth;
4907 const char *h, *lookup, *end;
4908 struct appctx *appctx;
4909 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004910 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004911
4912 appctx = si_appctx(si);
4913 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4914 appctx->st1 = appctx->st2 = 0;
4915 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4916 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4917 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4918 appctx->ctx.stats.flags |= STAT_CHUNKED;
4919
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004920 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004921 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004922 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4923 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004924
4925 for (h = lookup; h <= end - 3; h++) {
4926 if (memcmp(h, ";up", 3) == 0) {
4927 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4928 break;
4929 }
4930 }
4931
4932 if (uri_auth->refresh) {
4933 for (h = lookup; h <= end - 10; h++) {
4934 if (memcmp(h, ";norefresh", 10) == 0) {
4935 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4936 break;
4937 }
4938 }
4939 }
4940
4941 for (h = lookup; h <= end - 4; h++) {
4942 if (memcmp(h, ";csv", 4) == 0) {
4943 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4944 break;
4945 }
4946 }
4947
4948 for (h = lookup; h <= end - 6; h++) {
4949 if (memcmp(h, ";typed", 6) == 0) {
4950 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4951 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4952 break;
4953 }
4954 }
4955
4956 for (h = lookup; h <= end - 8; h++) {
4957 if (memcmp(h, ";st=", 4) == 0) {
4958 int i;
4959 h += 4;
4960 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4961 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4962 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4963 appctx->ctx.stats.st_code = i;
4964 break;
4965 }
4966 }
4967 break;
4968 }
4969 }
4970
4971 appctx->ctx.stats.scope_str = 0;
4972 appctx->ctx.stats.scope_len = 0;
4973 for (h = lookup; h <= end - 8; h++) {
4974 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4975 int itx = 0;
4976 const char *h2;
4977 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4978 const char *err;
4979
4980 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4981 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004982 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4983 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004984 if (*h == ';' || *h == '&' || *h == ' ')
4985 break;
4986 itx++;
4987 h++;
4988 }
4989
4990 if (itx > STAT_SCOPE_TXT_MAXLEN)
4991 itx = STAT_SCOPE_TXT_MAXLEN;
4992 appctx->ctx.stats.scope_len = itx;
4993
4994 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4995 memcpy(scope_txt, h2, itx);
4996 scope_txt[itx] = '\0';
4997 err = invalid_char(scope_txt);
4998 if (err) {
4999 /* bad char in search text => clear scope */
5000 appctx->ctx.stats.scope_str = 0;
5001 appctx->ctx.stats.scope_len = 0;
5002 }
5003 break;
5004 }
5005 }
5006
5007 /* now check whether we have some admin rules for this request */
5008 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
5009 int ret = 1;
5010
5011 if (stats_admin_rule->cond) {
5012 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
5013 ret = acl_pass(ret);
5014 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
5015 ret = !ret;
5016 }
5017
5018 if (ret) {
5019 /* no rule, or the rule matches */
5020 appctx->ctx.stats.flags |= STAT_ADMIN;
5021 break;
5022 }
5023 }
5024
Christopher Faulet5d45e382019-02-27 15:15:23 +01005025 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
5026 appctx->st0 = STAT_HTTP_HEAD;
5027 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02005028 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02005029 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02005030 if (msg->msg_state < HTTP_MSG_DATA)
5031 req->analysers |= AN_REQ_HTTP_BODY;
5032 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02005033 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005034 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005035 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5036 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5037 appctx->st0 = STAT_HTTP_LAST;
5038 }
5039 }
5040 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005041 /* Unsupported method */
5042 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5043 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5044 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005045 }
5046
5047 s->task->nice = -32; /* small boost for HTTP statistics */
5048 return 1;
5049}
5050
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5052{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005053 struct channel *req = &s->req;
5054 struct channel *res = &s->res;
5055 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005056 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005057 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005058 struct ist path, location;
5059 unsigned int flags;
5060 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005061
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005062 /*
5063 * Create the location
5064 */
5065 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005066
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005067 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005068 /* special prefix "/" means don't change URL */
5069 srv = __objt_server(s->target);
5070 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5071 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5072 return;
5073 }
5074
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005075 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005076 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005077 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005078 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005079 if (!path.ptr)
5080 return;
5081
5082 if (!chunk_memcat(&trash, path.ptr, path.len))
5083 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005084 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005085
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005086 /*
5087 * Create the 302 respone
5088 */
5089 htx = htx_from_buf(&res->buf);
5090 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5091 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5092 ist("HTTP/1.1"), ist("302"), ist("Found"));
5093 if (!sl)
5094 goto fail;
5095 sl->info.res.status = 302;
5096 s->txn->status = 302;
5097
5098 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5099 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5100 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5101 !htx_add_header(htx, ist("Location"), location))
5102 goto fail;
5103
5104 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5105 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005106
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005107 /*
5108 * Send the message
5109 */
5110 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005111 c_adv(res, data);
5112 res->total += data;
5113
5114 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005115 si_shutr(si);
5116 si_shutw(si);
5117 si->err_type = SI_ET_NONE;
5118 si->state = SI_ST_CLO;
5119
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005120 channel_auto_read(req);
5121 channel_abort(req);
5122 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005123 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005124 channel_auto_read(res);
5125 channel_auto_close(res);
5126
5127 if (!(s->flags & SF_ERR_MASK))
5128 s->flags |= SF_ERR_LOCAL;
5129 if (!(s->flags & SF_FINST_MASK))
5130 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005131
5132 /* FIXME: we should increase a counter of redirects per server and per backend. */
5133 srv_inc_sess_ctr(srv);
5134 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005135 return;
5136
5137 fail:
5138 /* If an error occurred, remove the incomplete HTTP response from the
5139 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005140 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005141}
5142
Christopher Fauletf2824e62018-10-01 12:12:37 +02005143/* This function terminates the request because it was completly analyzed or
5144 * because an error was triggered during the body forwarding.
5145 */
5146static void htx_end_request(struct stream *s)
5147{
5148 struct channel *chn = &s->req;
5149 struct http_txn *txn = s->txn;
5150
5151 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5152 now_ms, __FUNCTION__, s,
5153 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5154 s->req.analysers, s->res.analysers);
5155
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005156 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5157 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005158 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005159 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 goto end;
5161 }
5162
5163 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5164 return;
5165
5166 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005167 /* No need to read anymore, the request was completely parsed.
5168 * We can shut the read side unless we want to abort_on_close,
5169 * or we have a POST request. The issue with POST requests is
5170 * that some browsers still send a CRLF after the request, and
5171 * this CRLF must be read so that it does not remain in the kernel
5172 * buffers, otherwise a close could cause an RST on some systems
5173 * (eg: Linux).
5174 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005175 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005176 channel_dont_read(chn);
5177
5178 /* if the server closes the connection, we want to immediately react
5179 * and close the socket to save packets and syscalls.
5180 */
5181 s->si[1].flags |= SI_FL_NOHALF;
5182
5183 /* In any case we've finished parsing the request so we must
5184 * disable Nagle when sending data because 1) we're not going
5185 * to shut this side, and 2) the server is waiting for us to
5186 * send pending data.
5187 */
5188 chn->flags |= CF_NEVER_WAIT;
5189
Christopher Fauletd01ce402019-01-02 17:44:13 +01005190 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5191 /* The server has not finished to respond, so we
5192 * don't want to move in order not to upset it.
5193 */
5194 return;
5195 }
5196
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 /* When we get here, it means that both the request and the
5198 * response have finished receiving. Depending on the connection
5199 * mode, we'll have to wait for the last bytes to leave in either
5200 * direction, and sometimes for a close to be effective.
5201 */
5202 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5203 /* Tunnel mode will not have any analyser so it needs to
5204 * poll for reads.
5205 */
5206 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005207 if (b_data(&chn->buf))
5208 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005209 txn->req.msg_state = HTTP_MSG_TUNNEL;
5210 }
5211 else {
5212 /* we're not expecting any new data to come for this
5213 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005214 *
5215 * However, there is an exception if the response
5216 * length is undefined. In this case, we need to wait
5217 * the close from the server. The response will be
5218 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005219 */
5220 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5221 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005222 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005223
5224 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5225 channel_shutr_now(chn);
5226 channel_shutw_now(chn);
5227 }
5228 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005229 goto check_channel_flags;
5230 }
5231
5232 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5233 http_msg_closing:
5234 /* nothing else to forward, just waiting for the output buffer
5235 * to be empty and for the shutw_now to take effect.
5236 */
5237 if (channel_is_empty(chn)) {
5238 txn->req.msg_state = HTTP_MSG_CLOSED;
5239 goto http_msg_closed;
5240 }
5241 else if (chn->flags & CF_SHUTW) {
5242 txn->req.err_state = txn->req.msg_state;
5243 txn->req.msg_state = HTTP_MSG_ERROR;
5244 goto end;
5245 }
5246 return;
5247 }
5248
5249 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5250 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005251 /* if we don't know whether the server will close, we need to hard close */
5252 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5253 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005254 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005255 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005256 channel_dont_read(chn);
5257 goto end;
5258 }
5259
5260 check_channel_flags:
5261 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5262 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5263 /* if we've just closed an output, let's switch */
5264 txn->req.msg_state = HTTP_MSG_CLOSING;
5265 goto http_msg_closing;
5266 }
5267
5268 end:
5269 chn->analysers &= AN_REQ_FLT_END;
5270 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5271 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5272 channel_auto_close(chn);
5273 channel_auto_read(chn);
5274}
5275
5276
5277/* This function terminates the response because it was completly analyzed or
5278 * because an error was triggered during the body forwarding.
5279 */
5280static void htx_end_response(struct stream *s)
5281{
5282 struct channel *chn = &s->res;
5283 struct http_txn *txn = s->txn;
5284
5285 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5286 now_ms, __FUNCTION__, s,
5287 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5288 s->req.analysers, s->res.analysers);
5289
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005290 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5291 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005292 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005293 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005294 goto end;
5295 }
5296
5297 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5298 return;
5299
5300 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5301 /* In theory, we don't need to read anymore, but we must
5302 * still monitor the server connection for a possible close
5303 * while the request is being uploaded, so we don't disable
5304 * reading.
5305 */
5306 /* channel_dont_read(chn); */
5307
5308 if (txn->req.msg_state < HTTP_MSG_DONE) {
5309 /* The client seems to still be sending data, probably
5310 * because we got an error response during an upload.
5311 * We have the choice of either breaking the connection
5312 * or letting it pass through. Let's do the later.
5313 */
5314 return;
5315 }
5316
5317 /* When we get here, it means that both the request and the
5318 * response have finished receiving. Depending on the connection
5319 * mode, we'll have to wait for the last bytes to leave in either
5320 * direction, and sometimes for a close to be effective.
5321 */
5322 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5323 channel_auto_read(chn);
5324 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005325 if (b_data(&chn->buf))
5326 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005327 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5328 }
5329 else {
5330 /* we're not expecting any new data to come for this
5331 * transaction, so we can close it.
5332 */
5333 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5334 channel_shutr_now(chn);
5335 channel_shutw_now(chn);
5336 }
5337 }
5338 goto check_channel_flags;
5339 }
5340
5341 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5342 http_msg_closing:
5343 /* nothing else to forward, just waiting for the output buffer
5344 * to be empty and for the shutw_now to take effect.
5345 */
5346 if (channel_is_empty(chn)) {
5347 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5348 goto http_msg_closed;
5349 }
5350 else if (chn->flags & CF_SHUTW) {
5351 txn->rsp.err_state = txn->rsp.msg_state;
5352 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005353 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005354 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005355 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005356 goto end;
5357 }
5358 return;
5359 }
5360
5361 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5362 http_msg_closed:
5363 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005364 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005365 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005366 goto end;
5367 }
5368
5369 check_channel_flags:
5370 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5371 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5372 /* if we've just closed an output, let's switch */
5373 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5374 goto http_msg_closing;
5375 }
5376
5377 end:
5378 chn->analysers &= AN_RES_FLT_END;
5379 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5380 chn->analysers |= AN_RES_FLT_XFER_DATA;
5381 channel_auto_close(chn);
5382 channel_auto_read(chn);
5383}
5384
Christopher Faulet0f226952018-10-22 09:29:56 +02005385void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5386 int finst, const struct buffer *msg)
5387{
5388 channel_auto_read(si_oc(si));
5389 channel_abort(si_oc(si));
5390 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005391 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005392 channel_auto_close(si_ic(si));
5393 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005394
5395 /* <msg> is an HTX structure. So we copy it in the response's
5396 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005397 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005398 struct channel *chn = si_ic(si);
5399 struct htx *htx;
5400
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005401 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005402 chn->buf.data = msg->data;
5403 memcpy(chn->buf.area, msg->area, msg->data);
5404 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005405 c_adv(chn, htx->data);
5406 chn->total += htx->data;
5407 }
5408 if (!(s->flags & SF_ERR_MASK))
5409 s->flags |= err;
5410 if (!(s->flags & SF_FINST_MASK))
5411 s->flags |= finst;
5412}
5413
5414void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5415{
5416 channel_auto_read(&s->req);
5417 channel_abort(&s->req);
5418 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005419 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5420 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005421
5422 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005423
5424 /* <msg> is an HTX structure. So we copy it in the response's
5425 * channel */
5426 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005427 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005428 struct channel *chn = &s->res;
5429 struct htx *htx;
5430
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005431 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005432 chn->buf.data = msg->data;
5433 memcpy(chn->buf.area, msg->area, msg->data);
5434 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005435 c_adv(chn, htx->data);
5436 chn->total += htx->data;
5437 }
5438
5439 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5440 channel_auto_read(&s->res);
5441 channel_auto_close(&s->res);
5442 channel_shutr_now(&s->res);
5443}
5444
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005445struct buffer *htx_error_message(struct stream *s)
5446{
5447 const int msgnum = http_get_status_idx(s->txn->status);
5448
5449 if (s->be->errmsg[msgnum].area)
5450 return &s->be->errmsg[msgnum];
5451 else if (strm_fe(s)->errmsg[msgnum].area)
5452 return &strm_fe(s)->errmsg[msgnum];
5453 else
5454 return &htx_err_chunks[msgnum];
5455}
5456
5457
Christopher Faulet4a28a532019-03-01 11:19:40 +01005458/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5459 * on success and -1 on error.
5460 */
5461static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5462{
5463 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5464 * then we must send an HTTP/1.1 100 Continue intermediate response.
5465 */
5466 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5467 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5468 struct ist hdr = { .ptr = "Expect", .len = 6 };
5469 struct http_hdr_ctx ctx;
5470
5471 ctx.blk = NULL;
5472 /* Expect is allowed in 1.1, look for it */
5473 if (http_find_header(htx, hdr, &ctx, 0) &&
5474 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5475 if (htx_reply_100_continue(s) == -1)
5476 return -1;
5477 http_remove_header(htx, &ctx);
5478 }
5479 }
5480 return 0;
5481}
5482
Christopher Faulet23a3c792018-11-28 10:01:23 +01005483/* Send a 100-Continue response to the client. It returns 0 on success and -1
5484 * on error. The response channel is updated accordingly.
5485 */
5486static int htx_reply_100_continue(struct stream *s)
5487{
5488 struct channel *res = &s->res;
5489 struct htx *htx = htx_from_buf(&res->buf);
5490 struct htx_sl *sl;
5491 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5492 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5493 size_t data;
5494
5495 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5496 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5497 if (!sl)
5498 goto fail;
5499 sl->info.res.status = 100;
5500
Christopher Faulet9869f932019-06-26 14:23:54 +02005501 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005502 goto fail;
5503
5504 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005505 c_adv(res, data);
5506 res->total += data;
5507 return 0;
5508
5509 fail:
5510 /* If an error occurred, remove the incomplete HTTP response from the
5511 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005512 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005513 return -1;
5514}
5515
Christopher Faulet12c51e22018-11-28 15:59:42 +01005516
5517/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5518 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5519 * error. The response channel is updated accordingly.
5520 */
5521static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5522{
5523 struct channel *res = &s->res;
5524 struct htx *htx = htx_from_buf(&res->buf);
5525 struct htx_sl *sl;
5526 struct ist code, body;
5527 int status;
5528 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5529 size_t data;
5530
5531 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5532 status = 401;
5533 code = ist("401");
5534 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5535 "You need a valid user and password to access this content.\n"
5536 "</body></html>\n");
5537 }
5538 else {
5539 status = 407;
5540 code = ist("407");
5541 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5542 "You need a valid user and password to access this content.\n"
5543 "</body></html>\n");
5544 }
5545
5546 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5547 ist("HTTP/1.1"), code, ist("Unauthorized"));
5548 if (!sl)
5549 goto fail;
5550 sl->info.res.status = status;
5551 s->txn->status = status;
5552
5553 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5554 goto fail;
5555
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005556 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5557 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005558 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005559 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5560 goto fail;
5561 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5562 goto fail;
5563 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005564 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005565 if (!htx_add_endof(htx, HTX_BLK_EOH))
5566 goto fail;
5567
5568 while (body.len) {
5569 size_t sent = htx_add_data(htx, body);
5570 if (!sent)
5571 goto fail;
5572 body.ptr += sent;
5573 body.len -= sent;
5574 }
5575
5576 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005577 goto fail;
5578
5579 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005580 c_adv(res, data);
5581 res->total += data;
5582
5583 channel_auto_read(&s->req);
5584 channel_abort(&s->req);
5585 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005586 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005587
5588 res->wex = tick_add_ifset(now_ms, res->wto);
5589 channel_auto_read(res);
5590 channel_auto_close(res);
5591 channel_shutr_now(res);
5592 return 0;
5593
5594 fail:
5595 /* If an error occurred, remove the incomplete HTTP response from the
5596 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005597 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005598 return -1;
5599}
5600
Christopher Faulet0f226952018-10-22 09:29:56 +02005601/*
5602 * Capture headers from message <htx> according to header list <cap_hdr>, and
5603 * fill the <cap> pointers appropriately.
5604 */
5605static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5606{
5607 struct cap_hdr *h;
5608 int32_t pos;
5609
Christopher Fauleta3f15502019-05-13 15:27:23 +02005610 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005611 struct htx_blk *blk = htx_get_blk(htx, pos);
5612 enum htx_blk_type type = htx_get_blk_type(blk);
5613 struct ist n, v;
5614
5615 if (type == HTX_BLK_EOH)
5616 break;
5617 if (type != HTX_BLK_HDR)
5618 continue;
5619
5620 n = htx_get_blk_name(htx, blk);
5621
5622 for (h = cap_hdr; h; h = h->next) {
5623 if (h->namelen && (h->namelen == n.len) &&
5624 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5625 if (cap[h->index] == NULL)
5626 cap[h->index] =
5627 pool_alloc(h->pool);
5628
5629 if (cap[h->index] == NULL) {
5630 ha_alert("HTTP capture : out of memory.\n");
5631 break;
5632 }
5633
5634 v = htx_get_blk_value(htx, blk);
5635 if (v.len > h->len)
5636 v.len = h->len;
5637
5638 memcpy(cap[h->index], v.ptr, v.len);
5639 cap[h->index][v.len]=0;
5640 }
5641 }
5642 }
5643}
5644
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005645/* Delete a value in a header between delimiters <from> and <next>. The header
5646 * itself is delimited by <start> and <end> pointers. The number of characters
5647 * displaced is returned, and the pointer to the first delimiter is updated if
5648 * required. The function tries as much as possible to respect the following
5649 * principles :
5650 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5651 * in which case <next> is simply removed
5652 * - set exactly one space character after the new first delimiter, unless there
5653 * are not enough characters in the block being moved to do so.
5654 * - remove unneeded spaces before the previous delimiter and after the new
5655 * one.
5656 *
5657 * It is the caller's responsibility to ensure that :
5658 * - <from> points to a valid delimiter or <start> ;
5659 * - <next> points to a valid delimiter or <end> ;
5660 * - there are non-space chars before <from>.
5661 */
5662static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5663{
5664 char *prev = *from;
5665
5666 if (prev == start) {
5667 /* We're removing the first value. eat the semicolon, if <next>
5668 * is lower than <end> */
5669 if (next < end)
5670 next++;
5671
5672 while (next < end && HTTP_IS_SPHT(*next))
5673 next++;
5674 }
5675 else {
5676 /* Remove useless spaces before the old delimiter. */
5677 while (HTTP_IS_SPHT(*(prev-1)))
5678 prev--;
5679 *from = prev;
5680
5681 /* copy the delimiter and if possible a space if we're
5682 * not at the end of the line.
5683 */
5684 if (next < end) {
5685 *prev++ = *next++;
5686 if (prev + 1 < next)
5687 *prev++ = ' ';
5688 while (next < end && HTTP_IS_SPHT(*next))
5689 next++;
5690 }
5691 }
5692 memmove(prev, next, end - next);
5693 return (prev - next);
5694}
5695
Christopher Faulet0f226952018-10-22 09:29:56 +02005696
5697/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005698 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005699 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005700static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005701{
5702 struct ist dst = ist2(str, 0);
5703
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 goto end;
5706 if (dst.len + 1 > len)
5707 goto end;
5708 dst.ptr[dst.len++] = ' ';
5709
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005710 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005711 goto end;
5712 if (dst.len + 1 > len)
5713 goto end;
5714 dst.ptr[dst.len++] = ' ';
5715
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005716 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005717 end:
5718 return dst.len;
5719}
5720
Christopher Fauletf0523542018-10-24 11:06:58 +02005721/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005722 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005723 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005724static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005725{
5726 struct ist dst = ist2(str, 0);
5727
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005728 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005729 goto end;
5730 if (dst.len + 1 > len)
5731 goto end;
5732 dst.ptr[dst.len++] = ' ';
5733
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005734 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005735 goto end;
5736 if (dst.len + 1 > len)
5737 goto end;
5738 dst.ptr[dst.len++] = ' ';
5739
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005740 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005741 end:
5742 return dst.len;
5743}
5744
5745
Christopher Faulet0f226952018-10-22 09:29:56 +02005746/*
5747 * Print a debug line with a start line.
5748 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005749static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005750{
5751 struct session *sess = strm_sess(s);
5752 int max;
5753
5754 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5755 dir,
5756 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5757 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5758
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005759 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005760 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005761 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005762 trash.area[trash.data++] = ' ';
5763
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005764 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005765 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005766 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005767 trash.area[trash.data++] = ' ';
5768
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005769 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005770 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005771 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005772 trash.area[trash.data++] = '\n';
5773
5774 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5775}
5776
5777/*
5778 * Print a debug line with a header.
5779 */
5780static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5781{
5782 struct session *sess = strm_sess(s);
5783 int max;
5784
5785 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5786 dir,
5787 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5788 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5789
5790 max = n.len;
5791 UBOUND(max, trash.size - trash.data - 3);
5792 chunk_memcat(&trash, n.ptr, max);
5793 trash.area[trash.data++] = ':';
5794 trash.area[trash.data++] = ' ';
5795
5796 max = v.len;
5797 UBOUND(max, trash.size - trash.data - 1);
5798 chunk_memcat(&trash, v.ptr, max);
5799 trash.area[trash.data++] = '\n';
5800
5801 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5802}
5803
5804
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005805__attribute__((constructor))
5806static void __htx_protocol_init(void)
5807{
5808}
5809
5810
5811/*
5812 * Local variables:
5813 * c-indent-level: 8
5814 * c-basic-offset: 8
5815 * End:
5816 */