blob: 88be56e52f5394c4ec2f1a89355131ba980169f7 [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>
Christopher Faulet0f226952018-10-22 09:29:56 +020027#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020028#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020029#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020030#include <proto/proto_http.h>
31#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020032#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020033#include <proto/stream.h>
34#include <proto/stream_interface.h>
35#include <proto/stats.h>
36
Christopher Faulet377c5a52018-10-24 21:21:30 +020037extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020038
39static void htx_end_request(struct stream *s);
40static void htx_end_response(struct stream *s);
41
Christopher Faulet0f226952018-10-22 09:29:56 +020042static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020043static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010044static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
45static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
46static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020047static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
48
Christopher Faulet3e964192018-10-24 11:39:23 +020049static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
50static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
51
Christopher Faulet33640082018-10-24 11:53:01 +020052static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
53static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
54
Christopher Fauletfcda7c62018-10-24 11:56:22 +020055static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
56static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
57
Christopher Faulet377c5a52018-10-24 21:21:30 +020058static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
59static int htx_handle_stats(struct stream *s, struct channel *req);
60
Christopher Faulet4a28a532019-03-01 11:19:40 +010061static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010062static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010063static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010064
Christopher Faulete0768eb2018-10-03 16:38:02 +020065/* This stream analyser waits for a complete HTTP request. It returns 1 if the
66 * processing can continue on next analysers, or zero if it either needs more
67 * data or wants to immediately abort the request (eg: timeout, error, ...). It
68 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
69 * when it has nothing left to do, and may remove any analyser when it wants to
70 * abort.
71 */
72int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
73{
Christopher Faulet9768c262018-10-22 09:34:31 +020074
Christopher Faulete0768eb2018-10-03 16:38:02 +020075 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020076 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020077 *
Christopher Faulet9768c262018-10-22 09:34:31 +020078 * Once the start line and all headers are received, we may perform a
79 * capture of the error (if any), and we will set a few fields. We also
80 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020081 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 struct session *sess = s->sess;
83 struct http_txn *txn = s->txn;
84 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020085 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010086 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020087
88 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
89 now_ms, __FUNCTION__,
90 s,
91 req,
92 req->rex, req->wex,
93 req->flags,
94 ci_data(req),
95 req->analysers);
96
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010097 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020098
Willy Tarreau4236f032019-03-05 10:43:32 +010099 /* Parsing errors are caught here */
100 if (htx->flags & HTX_FL_PARSING_ERROR) {
101 stream_inc_http_req_ctr(s);
102 stream_inc_http_err_ctr(s);
103 proxy_inc_fe_req_ctr(sess->fe);
104 goto return_bad_req;
105 }
106
Christopher Faulete0768eb2018-10-03 16:38:02 +0200107 /* we're speaking HTTP here, so let's speak HTTP to the client */
Christopher Faulet304cc402019-07-15 15:46:28 +0200108 s->srv_error = htx_return_srv_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200109
110 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100111 if (c_data(req) && s->logs.t_idle == -1) {
112 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
113
114 s->logs.t_idle = ((csinfo)
115 ? csinfo->t_idle
116 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
117 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200118
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119 /*
120 * Now we quickly check if we have found a full valid request.
121 * If not so, we check the FD and buffer states before leaving.
122 * A full request is indicated by the fact that we have seen
123 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
124 * requests are checked first. When waiting for a second request
125 * on a keep-alive stream, if we encounter and error, close, t/o,
126 * we note the error in the stream flags but don't set any state.
127 * Since the error will be noted there, it will not be counted by
128 * process_stream() as a frontend error.
129 * Last, we may increase some tracked counters' http request errors on
130 * the cases that are deliberately the client's fault. For instance,
131 * a timeout or connection reset is not counted as an error. However
132 * a bad request is.
133 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200134 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200135 if (htx->flags & HTX_FL_UPGRADE)
136 goto failed_keep_alive;
137
Christopher Faulet9768c262018-10-22 09:34:31 +0200138 /* 1: have we encountered a read error ? */
139 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200140 if (!(s->flags & SF_ERR_MASK))
141 s->flags |= SF_ERR_CLICL;
142
143 if (txn->flags & TX_WAIT_NEXT_RQ)
144 goto failed_keep_alive;
145
146 if (sess->fe->options & PR_O_IGNORE_PRB)
147 goto failed_keep_alive;
148
Christopher Faulet9768c262018-10-22 09:34:31 +0200149 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 stream_inc_http_req_ctr(s);
151 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100152 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200153 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100154 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200155
Christopher Faulet9768c262018-10-22 09:34:31 +0200156 txn->status = 400;
157 msg->err_state = msg->msg_state;
158 msg->msg_state = HTTP_MSG_ERROR;
159 htx_reply_and_close(s, txn->status, NULL);
160 req->analysers &= AN_REQ_FLT_END;
161
Christopher Faulete0768eb2018-10-03 16:38:02 +0200162 if (!(s->flags & SF_FINST_MASK))
163 s->flags |= SF_FINST_R;
164 return 0;
165 }
166
Christopher Faulet9768c262018-10-22 09:34:31 +0200167 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
169 if (!(s->flags & SF_ERR_MASK))
170 s->flags |= SF_ERR_CLITO;
171
172 if (txn->flags & TX_WAIT_NEXT_RQ)
173 goto failed_keep_alive;
174
175 if (sess->fe->options & PR_O_IGNORE_PRB)
176 goto failed_keep_alive;
177
Christopher Faulet9768c262018-10-22 09:34:31 +0200178 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200179 stream_inc_http_req_ctr(s);
180 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100181 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200182 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100183 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200184
Christopher Faulet9768c262018-10-22 09:34:31 +0200185 txn->status = 408;
186 msg->err_state = msg->msg_state;
187 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100188 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200189 req->analysers &= AN_REQ_FLT_END;
190
Christopher Faulete0768eb2018-10-03 16:38:02 +0200191 if (!(s->flags & SF_FINST_MASK))
192 s->flags |= SF_FINST_R;
193 return 0;
194 }
195
Christopher Faulet9768c262018-10-22 09:34:31 +0200196 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197 else if (req->flags & CF_SHUTR) {
198 if (!(s->flags & SF_ERR_MASK))
199 s->flags |= SF_ERR_CLICL;
200
201 if (txn->flags & TX_WAIT_NEXT_RQ)
202 goto failed_keep_alive;
203
204 if (sess->fe->options & PR_O_IGNORE_PRB)
205 goto failed_keep_alive;
206
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 stream_inc_http_err_ctr(s);
208 stream_inc_http_req_ctr(s);
209 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100210 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200211 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100212 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200213
Christopher Faulet9768c262018-10-22 09:34:31 +0200214 txn->status = 400;
215 msg->err_state = msg->msg_state;
216 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100217 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200218 req->analysers &= AN_REQ_FLT_END;
219
Christopher Faulete0768eb2018-10-03 16:38:02 +0200220 if (!(s->flags & SF_FINST_MASK))
221 s->flags |= SF_FINST_R;
222 return 0;
223 }
224
225 channel_dont_connect(req);
226 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
227 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100228
Christopher Faulet9768c262018-10-22 09:34:31 +0200229 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
231 /* We need more data, we have to re-enable quick-ack in case we
232 * previously disabled it, otherwise we might cause the client
233 * to delay next data.
234 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100235 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200236 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100237
Christopher Faulet47365272018-10-31 17:40:50 +0100238 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200239 /* If the client starts to talk, let's fall back to
240 * request timeout processing.
241 */
242 txn->flags &= ~TX_WAIT_NEXT_RQ;
243 req->analyse_exp = TICK_ETERNITY;
244 }
245
246 /* just set the request timeout once at the beginning of the request */
247 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
250 else
251 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
252 }
253
254 /* we're not ready yet */
255 return 0;
256
257 failed_keep_alive:
258 /* Here we process low-level errors for keep-alive requests. In
259 * short, if the request is not the first one and it experiences
260 * a timeout, read error or shutdown, we just silently close so
261 * that the client can try again.
262 */
263 txn->status = 0;
264 msg->msg_state = HTTP_MSG_RQBEFORE;
265 req->analysers &= AN_REQ_FLT_END;
266 s->logs.logwait = 0;
267 s->logs.level = 0;
268 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200269 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200270 return 0;
271 }
272
Christopher Faulet9768c262018-10-22 09:34:31 +0200273 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200274 stream_inc_http_req_ctr(s);
275 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
276
Christopher Faulet9768c262018-10-22 09:34:31 +0200277 /* kill the pending keep-alive timeout */
278 txn->flags &= ~TX_WAIT_NEXT_RQ;
279 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280
Christopher Faulet29f17582019-05-23 11:03:26 +0200281 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200282 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100283
Christopher Faulet9768c262018-10-22 09:34:31 +0200284 /* 0: we might have to print this header in debug mode */
285 if (unlikely((global.mode & MODE_DEBUG) &&
286 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
287 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200288
Christopher Faulet03599112018-11-27 11:21:21 +0100289 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200290
Christopher Fauleta3f15502019-05-13 15:27:23 +0200291 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200292 struct htx_blk *blk = htx_get_blk(htx, pos);
293 enum htx_blk_type type = htx_get_blk_type(blk);
294
295 if (type == HTX_BLK_EOH)
296 break;
297 if (type != HTX_BLK_HDR)
298 continue;
299
300 htx_debug_hdr("clihdr", s,
301 htx_get_blk_name(htx, blk),
302 htx_get_blk_value(htx, blk));
303 }
304 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200305
306 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100307 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200308 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100309 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100310 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200311 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100312 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100313 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100314 if (sl->flags & HTX_SL_F_BODYLESS)
315 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200316
317 /* we can make use of server redirect on GET and HEAD */
318 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
319 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100320 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200321 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 goto return_bad_req;
323 }
324
325 /*
326 * 2: check if the URI matches the monitor_uri.
327 * We have to do this for every request which gets in, because
328 * the monitor-uri is defined by the frontend.
329 */
330 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100331 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200332 /*
333 * We have found the monitor URI
334 */
335 struct acl_cond *cond;
336
337 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100338 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200339
340 /* Check if we want to fail this monitor request or not */
341 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
342 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
343
344 ret = acl_pass(ret);
345 if (cond->pol == ACL_COND_UNLESS)
346 ret = !ret;
347
348 if (ret) {
349 /* we fail this request, let's return 503 service unavail */
350 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100351 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200352 if (!(s->flags & SF_ERR_MASK))
353 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
354 goto return_prx_cond;
355 }
356 }
357
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800358 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200359 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365
366 /*
367 * 3: Maybe we have to copy the original REQURI for the logs ?
368 * Note: we cannot log anymore if the request has been
369 * classified as invalid.
370 */
371 if (unlikely(s->logs.logwait & LW_REQ)) {
372 /* we have a complete HTTP request that we must log */
373 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200374 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200375
Christopher Faulet9768c262018-10-22 09:34:31 +0200376 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
377 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200378
379 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
380 s->do_log(s);
381 } else {
382 ha_alert("HTTP logging : out of memory.\n");
383 }
384 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386 /* if the frontend has "option http-use-proxy-header", we'll check if
387 * we have what looks like a proxied connection instead of a connection,
388 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
389 * Note that this is *not* RFC-compliant, however browsers and proxies
390 * happen to do that despite being non-standard :-(
391 * We consider that a request not beginning with either '/' or '*' is
392 * a proxied connection, which covers both "scheme://location" and
393 * CONNECT ip:port.
394 */
395 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100396 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200397 txn->flags |= TX_USE_PX_CONN;
398
Christopher Faulete0768eb2018-10-03 16:38:02 +0200399 /* 5: we may need to capture headers */
400 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200401 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200402
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200404 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200405 req->analysers |= AN_REQ_HTTP_BODY;
406
407 /*
408 * RFC7234#4:
409 * A cache MUST write through requests with methods
410 * that are unsafe (Section 4.2.1 of [RFC7231]) to
411 * the origin server; i.e., a cache is not allowed
412 * to generate a reply to such a request before
413 * having forwarded the request and having received
414 * a corresponding response.
415 *
416 * RFC7231#4.2.1:
417 * Of the request methods defined by this
418 * specification, the GET, HEAD, OPTIONS, and TRACE
419 * methods are defined to be safe.
420 */
421 if (likely(txn->meth == HTTP_METH_GET ||
422 txn->meth == HTTP_METH_HEAD ||
423 txn->meth == HTTP_METH_OPTIONS ||
424 txn->meth == HTTP_METH_TRACE))
425 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
426
427 /* end of job, return OK */
428 req->analysers &= ~an_bit;
429 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200430
Christopher Faulete0768eb2018-10-03 16:38:02 +0200431 return 1;
432
433 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200434 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 txn->req.err_state = txn->req.msg_state;
436 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100437 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100438 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100440 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200441
442 return_prx_cond:
443 if (!(s->flags & SF_ERR_MASK))
444 s->flags |= SF_ERR_PRXCOND;
445 if (!(s->flags & SF_FINST_MASK))
446 s->flags |= SF_FINST_R;
447
448 req->analysers &= AN_REQ_FLT_END;
449 req->analyse_exp = TICK_ETERNITY;
450 return 0;
451}
452
453
454/* This stream analyser runs all HTTP request processing which is common to
455 * frontends and backends, which means blocking ACLs, filters, connection-close,
456 * reqadd, stats and redirects. This is performed for the designated proxy.
457 * It returns 1 if the processing can continue on next analysers, or zero if it
458 * either needs more data or wants to immediately abort the request (eg: deny,
459 * error, ...).
460 */
461int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
462{
463 struct session *sess = s->sess;
464 struct http_txn *txn = s->txn;
465 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200466 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200467 struct redirect_rule *rule;
468 struct cond_wordlist *wl;
469 enum rule_result verdict;
470 int deny_status = HTTP_ERR_403;
471 struct connection *conn = objt_conn(sess->origin);
472
473 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
474 /* we need more data */
475 goto return_prx_yield;
476 }
477
478 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
479 now_ms, __FUNCTION__,
480 s,
481 req,
482 req->rex, req->wex,
483 req->flags,
484 ci_data(req),
485 req->analysers);
486
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100487 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200489 /* just in case we have some per-backend tracking. Only called the first
490 * execution of the analyser. */
491 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
492 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200493
494 /* evaluate http-request rules */
495 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200496 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 switch (verdict) {
499 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
500 goto return_prx_yield;
501
502 case HTTP_RULE_RES_CONT:
503 case HTTP_RULE_RES_STOP: /* nothing to do */
504 break;
505
506 case HTTP_RULE_RES_DENY: /* deny or tarpit */
507 if (txn->flags & TX_CLTARPIT)
508 goto tarpit;
509 goto deny;
510
511 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
512 goto return_prx_cond;
513
514 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
515 goto done;
516
517 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
518 goto return_bad_req;
519 }
520 }
521
522 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
523 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200524 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200525
Christopher Fauletff2759f2018-10-24 11:13:16 +0200526 ctx.blk = NULL;
527 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
528 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200530 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200531 }
532
533 /* OK at this stage, we know that the request was accepted according to
534 * the http-request rules, we can check for the stats. Note that the
535 * URI is detected *before* the req* rules in order not to be affected
536 * by a possible reqrep, while they are processed *after* so that a
537 * reqdeny can still block them. This clearly needs to change in 1.6!
538 */
Christopher Faulet8f1aa772019-07-04 11:27:15 +0200539 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100541 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 txn->status = 500;
543 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100544 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
546 if (!(s->flags & SF_ERR_MASK))
547 s->flags |= SF_ERR_RESOURCE;
548 goto return_prx_cond;
549 }
550
551 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200552 htx_handle_stats(s, req);
553 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200554 /* not all actions implemented: deny, allow, auth */
555
556 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
557 goto deny;
558
559 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
560 goto return_prx_cond;
561 }
562
563 /* evaluate the req* rules except reqadd */
564 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200565 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200566 goto return_bad_req;
567
568 if (txn->flags & TX_CLDENY)
569 goto deny;
570
571 if (txn->flags & TX_CLTARPIT) {
572 deny_status = HTTP_ERR_500;
573 goto tarpit;
574 }
575 }
576
577 /* add request headers from the rule sets in the same order */
578 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200579 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200580 if (wl->cond) {
581 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
582 ret = acl_pass(ret);
583 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
584 ret = !ret;
585 if (!ret)
586 continue;
587 }
588
Christopher Fauletff2759f2018-10-24 11:13:16 +0200589 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
590 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200591 goto return_bad_req;
592 }
593
Christopher Faulet2571bc62019-03-01 11:44:26 +0100594 /* Proceed with the applets now. */
595 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200596 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100597 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200598
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100599 if (htx_handle_expect_hdr(s, htx, msg) == -1)
600 goto return_bad_req;
601
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
603 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
604 if (!(s->flags & SF_FINST_MASK))
605 s->flags |= SF_FINST_R;
606
607 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
608 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
609 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
610 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100611
612 req->flags |= CF_SEND_DONTWAIT;
613 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200614 goto done;
615 }
616
617 /* check whether we have some ACLs set to redirect this request */
618 list_for_each_entry(rule, &px->redirect_rules, list) {
619 if (rule->cond) {
620 int ret;
621
622 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
623 ret = acl_pass(ret);
624 if (rule->cond->pol == ACL_COND_UNLESS)
625 ret = !ret;
626 if (!ret)
627 continue;
628 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200629 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200630 goto return_bad_req;
631 goto done;
632 }
633
634 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
635 * If this happens, then the data will not come immediately, so we must
636 * send all what we have without waiting. Note that due to the small gain
637 * in waiting for the body of the request, it's easier to simply put the
638 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
639 * itself once used.
640 */
641 req->flags |= CF_SEND_DONTWAIT;
642
643 done: /* done with this analyser, continue with next ones that the calling
644 * points will have set, if any.
645 */
646 req->analyse_exp = TICK_ETERNITY;
647 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
648 req->analysers &= ~an_bit;
649 return 1;
650
651 tarpit:
652 /* Allow cookie logging
653 */
654 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200655 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200656
657 /* When a connection is tarpitted, we use the tarpit timeout,
658 * which may be the same as the connect timeout if unspecified.
659 * If unset, then set it to zero because we really want it to
660 * eventually expire. We build the tarpit as an analyser.
661 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100662 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200663
664 /* wipe the request out so that we can drop the connection early
665 * if the client closes first.
666 */
667 channel_dont_connect(req);
668
669 txn->status = http_err_codes[deny_status];
670
671 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
672 req->analysers |= AN_REQ_HTTP_TARPIT;
673 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
674 if (!req->analyse_exp)
675 req->analyse_exp = tick_add(now_ms, 0);
676 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100677 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200678 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100679 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200680 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 goto done_without_exp;
683
684 deny: /* this request was blocked (denied) */
685
686 /* Allow cookie logging
687 */
688 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200689 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200690
691 txn->flags |= TX_CLDENY;
692 txn->status = http_err_codes[deny_status];
693 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100694 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200695 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100696 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200697 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100698 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 goto return_prx_cond;
702
703 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200704 txn->req.err_state = txn->req.msg_state;
705 txn->req.msg_state = HTTP_MSG_ERROR;
706 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100707 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708
Olivier Houcharda798bf52019-03-08 18:52:00 +0100709 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100711 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
713 return_prx_cond:
714 if (!(s->flags & SF_ERR_MASK))
715 s->flags |= SF_ERR_PRXCOND;
716 if (!(s->flags & SF_FINST_MASK))
717 s->flags |= SF_FINST_R;
718
719 req->analysers &= AN_REQ_FLT_END;
720 req->analyse_exp = TICK_ETERNITY;
721 return 0;
722
723 return_prx_yield:
724 channel_dont_connect(req);
725 return 0;
726}
727
728/* This function performs all the processing enabled for the current request.
729 * It returns 1 if the processing can continue on next analysers, or zero if it
730 * needs more data, encounters an error, or wants to immediately abort the
731 * request. It relies on buffers flags, and updates s->req.analysers.
732 */
733int htx_process_request(struct stream *s, struct channel *req, int an_bit)
734{
735 struct session *sess = s->sess;
736 struct http_txn *txn = s->txn;
737 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200738 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200739 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
740
741 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
742 /* we need more data */
743 channel_dont_connect(req);
744 return 0;
745 }
746
747 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
748 now_ms, __FUNCTION__,
749 s,
750 req,
751 req->rex, req->wex,
752 req->flags,
753 ci_data(req),
754 req->analysers);
755
756 /*
757 * Right now, we know that we have processed the entire headers
758 * and that unwanted requests have been filtered out. We can do
759 * whatever we want with the remaining request. Also, now we
760 * may have separate values for ->fe, ->be.
761 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100762 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200763
764 /*
765 * If HTTP PROXY is set we simply get remote server address parsing
766 * incoming request. Note that this requires that a connection is
767 * allocated on the server side.
768 */
769 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
770 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100771 struct htx_sl *sl;
772 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200773
774 /* Note that for now we don't reuse existing proxy connections */
775 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
776 txn->req.err_state = txn->req.msg_state;
777 txn->req.msg_state = HTTP_MSG_ERROR;
778 txn->status = 500;
779 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100780 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200781
782 if (!(s->flags & SF_ERR_MASK))
783 s->flags |= SF_ERR_RESOURCE;
784 if (!(s->flags & SF_FINST_MASK))
785 s->flags |= SF_FINST_R;
786
787 return 0;
788 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200789 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100790 uri = htx_sl_req_uri(sl);
791 path = http_get_path(uri);
792 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793 goto return_bad_req;
794
795 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200796 * uri.ptr and path.ptr (excluded). If it was not found, we need
797 * to replace from all the uri by a single "/".
798 *
799 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100800 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200801 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200802 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100803 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau69564b12019-07-18 16:17:15 +0200804 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 }
806
807 /*
808 * 7: Now we can work with the cookies.
809 * Note that doing so might move headers in the request, but
810 * the fields will stay coherent and the URI will not move.
811 * This should only be performed in the backend.
812 */
813 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100814 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200815
816 /* add unique-id if "header-unique-id" is specified */
817
818 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
819 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
820 goto return_bad_req;
821 s->unique_id[0] = '\0';
822 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
823 }
824
825 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200826 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
827 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
828
829 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200830 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200831 }
832
833 /*
834 * 9: add X-Forwarded-For if either the frontend or the backend
835 * asks for it.
836 */
837 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200838 struct http_hdr_ctx ctx = { .blk = NULL };
839 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
840 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
841
Christopher Faulete0768eb2018-10-03 16:38:02 +0200842 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200843 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200844 /* The header is set to be added only if none is present
845 * and we found it, so don't do anything.
846 */
847 }
848 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
849 /* Add an X-Forwarded-For header unless the source IP is
850 * in the 'except' network range.
851 */
852 if ((!sess->fe->except_mask.s_addr ||
853 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
854 != sess->fe->except_net.s_addr) &&
855 (!s->be->except_mask.s_addr ||
856 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
857 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200858 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200859
860 /* Note: we rely on the backend to get the header name to be used for
861 * x-forwarded-for, because the header is really meant for the backends.
862 * However, if the backend did not specify any option, we have to rely
863 * on the frontend's header name.
864 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200865 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
866 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200867 goto return_bad_req;
868 }
869 }
870 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
871 /* FIXME: for the sake of completeness, we should also support
872 * 'except' here, although it is mostly useless in this case.
873 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200874 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200875
Christopher Faulete0768eb2018-10-03 16:38:02 +0200876 inet_ntop(AF_INET6,
877 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
878 pn, sizeof(pn));
879
880 /* Note: we rely on the backend to get the header name to be used for
881 * x-forwarded-for, because the header is really meant for the backends.
882 * However, if the backend did not specify any option, we have to rely
883 * on the frontend's header name.
884 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200885 chunk_printf(&trash, "%s", pn);
886 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200887 goto return_bad_req;
888 }
889 }
890
891 /*
892 * 10: add X-Original-To if either the frontend or the backend
893 * asks for it.
894 */
895 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
896
897 /* FIXME: don't know if IPv6 can handle that case too. */
898 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
899 /* Add an X-Original-To header unless the destination IP is
900 * in the 'except' network range.
901 */
902 conn_get_to_addr(cli_conn);
903
904 if (cli_conn->addr.to.ss_family == AF_INET &&
905 ((!sess->fe->except_mask_to.s_addr ||
906 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
907 != sess->fe->except_to.s_addr) &&
908 (!s->be->except_mask_to.s_addr ||
909 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
910 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200911 struct ist hdr;
912 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200913
914 /* Note: we rely on the backend to get the header name to be used for
915 * x-original-to, because the header is really meant for the backends.
916 * However, if the backend did not specify any option, we have to rely
917 * on the frontend's header name.
918 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200919 if (s->be->orgto_hdr_len)
920 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
921 else
922 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200923
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200924 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
925 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200926 goto return_bad_req;
927 }
928 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200929 }
930
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 /* If we have no server assigned yet and we're balancing on url_param
932 * with a POST request, we may be interested in checking the body for
933 * that parameter. This will be done in another analyser.
934 */
935 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100936 s->txn->meth == HTTP_METH_POST &&
937 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938 channel_dont_connect(req);
939 req->analysers |= AN_REQ_HTTP_BODY;
940 }
941
942 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
943 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100944
Christopher Faulete0768eb2018-10-03 16:38:02 +0200945 /* We expect some data from the client. Unless we know for sure
946 * we already have a full request, we have to re-enable quick-ack
947 * in case we previously disabled it, otherwise we might cause
948 * the client to delay further data.
949 */
950 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200951 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100952 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200953
954 /*************************************************************
955 * OK, that's finished for the headers. We have done what we *
956 * could. Let's switch to the DATA state. *
957 ************************************************************/
958 req->analyse_exp = TICK_ETERNITY;
959 req->analysers &= ~an_bit;
960
961 s->logs.tv_request = now;
962 /* OK let's go on with the BODY now */
963 return 1;
964
965 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200966 txn->req.err_state = txn->req.msg_state;
967 txn->req.msg_state = HTTP_MSG_ERROR;
968 txn->status = 400;
969 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100970 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200971
Olivier Houcharda798bf52019-03-08 18:52:00 +0100972 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200973 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100974 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
976 if (!(s->flags & SF_ERR_MASK))
977 s->flags |= SF_ERR_PRXCOND;
978 if (!(s->flags & SF_FINST_MASK))
979 s->flags |= SF_FINST_R;
980 return 0;
981}
982
983/* This function is an analyser which processes the HTTP tarpit. It always
984 * returns zero, at the beginning because it prevents any other processing
985 * from occurring, and at the end because it terminates the request.
986 */
987int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
988{
989 struct http_txn *txn = s->txn;
990
991 /* This connection is being tarpitted. The CLIENT side has
992 * already set the connect expiration date to the right
993 * timeout. We just have to check that the client is still
994 * there and that the timeout has not expired.
995 */
996 channel_dont_connect(req);
997 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
998 !tick_is_expired(req->analyse_exp, now_ms))
999 return 0;
1000
1001 /* We will set the queue timer to the time spent, just for
1002 * logging purposes. We fake a 500 server error, so that the
1003 * attacker will not suspect his connection has been tarpitted.
1004 * It will not cause trouble to the logs because we can exclude
1005 * the tarpitted connections by filtering on the 'PT' status flags.
1006 */
1007 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1008
1009 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001010 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001011
1012 req->analysers &= AN_REQ_FLT_END;
1013 req->analyse_exp = TICK_ETERNITY;
1014
1015 if (!(s->flags & SF_ERR_MASK))
1016 s->flags |= SF_ERR_PRXCOND;
1017 if (!(s->flags & SF_FINST_MASK))
1018 s->flags |= SF_FINST_T;
1019 return 0;
1020}
1021
1022/* This function is an analyser which waits for the HTTP request body. It waits
1023 * for either the buffer to be full, or the full advertised contents to have
1024 * reached the buffer. It must only be called after the standard HTTP request
1025 * processing has occurred, because it expects the request to be parsed and will
1026 * look for the Expect header. It may send a 100-Continue interim response. It
1027 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1028 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1029 * needs to read more data, or 1 once it has completed its analysis.
1030 */
1031int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1032{
1033 struct session *sess = s->sess;
1034 struct http_txn *txn = s->txn;
1035 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001036 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001037
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001038
1039 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1040 now_ms, __FUNCTION__,
1041 s,
1042 req,
1043 req->rex, req->wex,
1044 req->flags,
1045 ci_data(req),
1046 req->analysers);
1047
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001048 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001049
Willy Tarreau4236f032019-03-05 10:43:32 +01001050 if (htx->flags & HTX_FL_PARSING_ERROR)
1051 goto return_bad_req;
1052
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053 if (msg->msg_state < HTTP_MSG_BODY)
1054 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001055
Christopher Faulete0768eb2018-10-03 16:38:02 +02001056 /* We have to parse the HTTP request body to find any required data.
1057 * "balance url_param check_post" should have been the only way to get
1058 * into this. We were brought here after HTTP header analysis, so all
1059 * related structures are ready.
1060 */
1061
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001062 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001063 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1064 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001065 }
1066
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001067 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1070 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001072 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001073 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 goto http_end;
1075
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001076 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1078 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001079 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080
1081 if (!(s->flags & SF_ERR_MASK))
1082 s->flags |= SF_ERR_CLITO;
1083 if (!(s->flags & SF_FINST_MASK))
1084 s->flags |= SF_FINST_D;
1085 goto return_err_msg;
1086 }
1087
1088 /* we get here if we need to wait for more data */
1089 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1090 /* Not enough data. We'll re-use the http-request
1091 * timeout here. Ideally, we should set the timeout
1092 * relative to the accept() date. We just set the
1093 * request timeout once at the beginning of the
1094 * request.
1095 */
1096 channel_dont_connect(req);
1097 if (!tick_isset(req->analyse_exp))
1098 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1099 return 0;
1100 }
1101
1102 http_end:
1103 /* The situation will not evolve, so let's give up on the analysis. */
1104 s->logs.tv_request = now; /* update the request timer to reflect full request */
1105 req->analysers &= ~an_bit;
1106 req->analyse_exp = TICK_ETERNITY;
1107 return 1;
1108
1109 return_bad_req: /* let's centralize all bad requests */
1110 txn->req.err_state = txn->req.msg_state;
1111 txn->req.msg_state = HTTP_MSG_ERROR;
1112 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001113 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001114
1115 if (!(s->flags & SF_ERR_MASK))
1116 s->flags |= SF_ERR_PRXCOND;
1117 if (!(s->flags & SF_FINST_MASK))
1118 s->flags |= SF_FINST_R;
1119
1120 return_err_msg:
1121 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001122 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001123 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001124 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001125 return 0;
1126}
1127
1128/* This function is an analyser which forwards request body (including chunk
1129 * sizes if any). It is called as soon as we must forward, even if we forward
1130 * zero byte. The only situation where it must not be called is when we're in
1131 * tunnel mode and we want to forward till the close. It's used both to forward
1132 * remaining data and to resync after end of body. It expects the msg_state to
1133 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1134 * read more data, or 1 once we can go on with next request or end the stream.
1135 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1136 * bytes of pending data + the headers if not already done.
1137 */
1138int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1139{
1140 struct session *sess = s->sess;
1141 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001142 struct http_msg *msg = &txn->req;
1143 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001144 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001145 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001146
1147 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1148 now_ms, __FUNCTION__,
1149 s,
1150 req,
1151 req->rex, req->wex,
1152 req->flags,
1153 ci_data(req),
1154 req->analysers);
1155
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001156 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001157
1158 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1159 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1160 /* Output closed while we were sending data. We must abort and
1161 * wake the other side up.
1162 */
Olivier Houchard29cac3c2019-07-12 15:48:58 +02001163 /* Don't abort yet if we had L7 retries activated and it
1164 * was a write error, we may recover.
1165 */
1166 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1167 (s->si[1].flags & SI_FL_L7_RETRY))
1168 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001169 msg->err_state = msg->msg_state;
1170 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001171 htx_end_request(s);
1172 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001173 return 1;
1174 }
1175
1176 /* Note that we don't have to send 100-continue back because we don't
1177 * need the data to complete our job, and it's up to the server to
1178 * decide whether to return 100, 417 or anything else in return of
1179 * an "Expect: 100-continue" header.
1180 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001181 if (msg->msg_state == HTTP_MSG_BODY)
1182 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001183
Christopher Faulete0768eb2018-10-03 16:38:02 +02001184 /* in most states, we should abort in case of early close */
1185 channel_auto_close(req);
1186
1187 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001188 if (req->to_forward == CHN_INFINITE_FORWARD) {
1189 if (req->flags & (CF_SHUTR|CF_EOI)) {
1190 msg->msg_state = HTTP_MSG_DONE;
1191 req->to_forward = 0;
1192 goto done;
1193 }
1194 }
1195 else {
1196 /* We can't process the buffer's contents yet */
1197 req->flags |= CF_WAKE_WRITE;
1198 goto missing_data_or_waiting;
1199 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001200 }
1201
Christopher Faulet9768c262018-10-22 09:34:31 +02001202 if (msg->msg_state >= HTTP_MSG_DONE)
1203 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001204 /* Forward input data. We get it by removing all outgoing data not
1205 * forwarded yet from HTX data size. If there are some data filters, we
1206 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001207 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001208 if (HAS_REQ_DATA_FILTERS(s)) {
1209 ret = flt_http_payload(s, msg, htx->data);
1210 if (ret < 0)
1211 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001212 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001213 }
1214 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001215 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001216 if (msg->flags & HTTP_MSGF_XFER_LEN)
1217 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001218 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001219
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001220 if (txn->meth == HTTP_METH_CONNECT) {
1221 msg->msg_state = HTTP_MSG_TUNNEL;
1222 goto done;
1223 }
1224
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001225
Christopher Faulet9768c262018-10-22 09:34:31 +02001226 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001227 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1228 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 */
1230 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1231 goto missing_data_or_waiting;
1232
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001233 msg->msg_state = HTTP_MSG_ENDING;
1234 if (htx->data != co_data(req))
1235 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001236 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001237 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001238
1239 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001240 /* other states, DONE...TUNNEL */
1241 /* we don't want to forward closes on DONE except in tunnel mode. */
Christopher Fauletc41547b2019-07-16 14:32:23 +02001242 if (!(txn->flags & TX_CON_WANT_TUN))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243 channel_dont_close(req);
1244
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001245 if (HAS_REQ_DATA_FILTERS(s)) {
1246 ret = flt_http_end(s, msg);
1247 if (ret <= 0) {
1248 if (!ret)
1249 goto missing_data_or_waiting;
1250 goto return_bad_req;
1251 }
1252 }
1253
Christopher Fauletf2824e62018-10-01 12:12:37 +02001254 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001255 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001256 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001257 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1258 if (req->flags & CF_SHUTW) {
1259 /* request errors are most likely due to the
1260 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001261 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001262 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001263 goto return_bad_req;
1264 }
1265 return 1;
1266 }
1267
1268 /* If "option abortonclose" is set on the backend, we want to monitor
1269 * the client's connection and forward any shutdown notification to the
1270 * server, which will decide whether to close or to go on processing the
1271 * request. We only do that in tunnel mode, and not in other modes since
1272 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001273 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 channel_auto_read(req);
Christopher Fauletc41547b2019-07-16 14:32:23 +02001275 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) && !(txn->flags & TX_CON_WANT_TUN))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 s->si[1].flags |= SI_FL_NOLINGER;
1277 channel_auto_close(req);
1278 }
1279 else if (s->txn->meth == HTTP_METH_POST) {
1280 /* POST requests may require to read extra CRLF sent by broken
1281 * browsers and which could cause an RST to be sent upon close
1282 * on some systems (eg: Linux). */
1283 channel_auto_read(req);
1284 }
1285 return 0;
1286
1287 missing_data_or_waiting:
1288 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001289 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001290 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001291
1292 waiting:
1293 /* waiting for the last bits to leave the buffer */
1294 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001295 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001296
Christopher Faulet47365272018-10-31 17:40:50 +01001297 if (htx->flags & HTX_FL_PARSING_ERROR)
1298 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001299
Christopher Faulete0768eb2018-10-03 16:38:02 +02001300 /* When TE: chunked is used, we need to get there again to parse remaining
1301 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1302 * And when content-length is used, we never want to let the possible
1303 * shutdown be forwarded to the other side, as the state machine will
1304 * take care of it once the client responds. It's also important to
1305 * prevent TIME_WAITs from accumulating on the backend side, and for
1306 * HTTP/2 where the last frame comes with a shutdown.
1307 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001308 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001309 channel_dont_close(req);
1310
1311 /* We know that more data are expected, but we couldn't send more that
1312 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1313 * system knows it must not set a PUSH on this first part. Interactive
1314 * modes are already handled by the stream sock layer. We must not do
1315 * this in content-length mode because it could present the MSG_MORE
1316 * flag with the last block of forwarded data, which would cause an
1317 * additional delay to be observed by the receiver.
1318 */
1319 if (msg->flags & HTTP_MSGF_TE_CHNK)
1320 req->flags |= CF_EXPECT_MORE;
1321
1322 return 0;
1323
Christopher Faulet93e02d82019-03-08 14:18:50 +01001324 return_cli_abort:
1325 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1326 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1327 if (objt_server(s->target))
1328 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1329 if (!(s->flags & SF_ERR_MASK))
1330 s->flags |= SF_ERR_CLICL;
1331 status = 400;
1332 goto return_error;
1333
1334 return_srv_abort:
1335 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1336 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1337 if (objt_server(s->target))
1338 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1339 if (!(s->flags & SF_ERR_MASK))
1340 s->flags |= SF_ERR_SRVCL;
1341 status = 502;
1342 goto return_error;
1343
1344 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001345 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001346 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001347 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001348 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001349 s->flags |= SF_ERR_CLICL;
1350 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001351
Christopher Faulet93e02d82019-03-08 14:18:50 +01001352 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001353 txn->req.err_state = txn->req.msg_state;
1354 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001355 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001356 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001357 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001359 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361 }
1362 req->analysers &= AN_REQ_FLT_END;
1363 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 +01001364 if (!(s->flags & SF_FINST_MASK))
1365 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 return 0;
1367}
1368
Olivier Houcharda254a372019-04-05 15:30:12 +02001369/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1370/* Returns 0 if we can attempt to retry, -1 otherwise */
1371static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1372{
1373 struct channel *req, *res;
1374 int co_data;
1375
1376 si->conn_retries--;
1377 if (si->conn_retries < 0)
1378 return -1;
1379
Willy Tarreau223995e2019-05-04 10:38:31 +02001380 if (objt_server(s->target))
1381 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1382 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1383
Olivier Houcharda254a372019-04-05 15:30:12 +02001384 req = &s->req;
1385 res = &s->res;
1386 /* Remove any write error from the request, and read error from the response */
1387 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1388 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1389 res->analysers = 0;
1390 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard4bd58672019-07-12 16:16:59 +02001391 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001392 si->exp = TICK_ETERNITY;
1393 res->rex = TICK_ETERNITY;
1394 res->to_forward = 0;
1395 res->analyse_exp = TICK_ETERNITY;
1396 res->total = 0;
Olivier Houchard4bd58672019-07-12 16:16:59 +02001397 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001398 si_release_endpoint(&s->si[1]);
1399 b_free(&req->buf);
1400 /* Swap the L7 buffer with the channel buffer */
1401 /* We know we stored the co_data as b_data, so get it there */
1402 co_data = b_data(&si->l7_buffer);
1403 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1404 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1405
1406 co_set_data(req, co_data);
1407 b_reset(&res->buf);
1408 co_set_data(res, 0);
1409 return 0;
1410}
1411
Christopher Faulete0768eb2018-10-03 16:38:02 +02001412/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1413 * processing can continue on next analysers, or zero if it either needs more
1414 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1415 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1416 * when it has nothing left to do, and may remove any analyser when it wants to
1417 * abort.
1418 */
1419int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1420{
Christopher Faulet9768c262018-10-22 09:34:31 +02001421 /*
1422 * We will analyze a complete HTTP response to check the its syntax.
1423 *
1424 * Once the start line and all headers are received, we may perform a
1425 * capture of the error (if any), and we will set a few fields. We also
1426 * logging and finally headers capture.
1427 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428 struct session *sess = s->sess;
1429 struct http_txn *txn = s->txn;
1430 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001431 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001432 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001433 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001434 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001435 int n;
1436
1437 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1438 now_ms, __FUNCTION__,
1439 s,
1440 rep,
1441 rep->rex, rep->wex,
1442 rep->flags,
1443 ci_data(rep),
1444 rep->analysers);
1445
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001446 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001447
Willy Tarreau4236f032019-03-05 10:43:32 +01001448 /* Parsing errors are caught here */
1449 if (htx->flags & HTX_FL_PARSING_ERROR)
1450 goto return_bad_res;
1451
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452 /*
1453 * Now we quickly check if we have found a full valid response.
1454 * If not so, we check the FD and buffer states before leaving.
1455 * A full response is indicated by the fact that we have seen
1456 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1457 * responses are checked first.
1458 *
1459 * Depending on whether the client is still there or not, we
1460 * may send an error response back or not. Note that normally
1461 * we should only check for HTTP status there, and check I/O
1462 * errors somewhere else.
1463 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001464 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001465 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001466 /* 1: have we encountered a read error ? */
1467 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001468 struct connection *conn = NULL;
1469
Olivier Houchard865d8392019-05-03 22:46:27 +02001470 if (objt_cs(s->si[1].end))
1471 conn = objt_cs(s->si[1].end)->conn;
1472
1473 if (si_b->flags & SI_FL_L7_RETRY &&
1474 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001475 /* If we arrive here, then CF_READ_ERROR was
1476 * set by si_cs_recv() because we matched a
1477 * status, overwise it would have removed
1478 * the SI_FL_L7_RETRY flag, so it's ok not
1479 * to check s->be->retry_type.
1480 */
1481 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1482 return 0;
1483 }
1484
Olivier Houchard6db16992019-05-17 15:40:49 +02001485 if (txn->flags & TX_NOT_FIRST)
1486 goto abort_keep_alive;
1487
Olivier Houcharda798bf52019-03-08 18:52:00 +01001488 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001489 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001490 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001491 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001492 }
1493
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494 rep->analysers &= AN_RES_FLT_END;
1495 txn->status = 502;
1496
1497 /* Check to see if the server refused the early data.
1498 * If so, just send a 425
1499 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001500 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1501 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001502 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001503 do_l7_retry(s, si_b) == 0)
1504 return 0;
1505 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 }
1507
1508 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001509 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510
1511 if (!(s->flags & SF_ERR_MASK))
1512 s->flags |= SF_ERR_SRVCL;
1513 if (!(s->flags & SF_FINST_MASK))
1514 s->flags |= SF_FINST_H;
1515 return 0;
1516 }
1517
Christopher Faulet9768c262018-10-22 09:34:31 +02001518 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001520 if ((si_b->flags & SI_FL_L7_RETRY) &&
1521 (s->be->retry_type & PR_RE_TIMEOUT)) {
1522 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1523 return 0;
1524 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001525 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001527 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001528 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 }
1530
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 rep->analysers &= AN_RES_FLT_END;
1532 txn->status = 504;
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_SRVTO;
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 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001545 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1546 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001548 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549
1550 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001552 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553
1554 if (!(s->flags & SF_ERR_MASK))
1555 s->flags |= SF_ERR_CLICL;
1556 if (!(s->flags & SF_FINST_MASK))
1557 s->flags |= SF_FINST_H;
1558
1559 /* process_stream() will take care of the error */
1560 return 0;
1561 }
1562
Christopher Faulet9768c262018-10-22 09:34:31 +02001563 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001565 if ((si_b->flags & SI_FL_L7_RETRY) &&
1566 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1567 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1568 return 0;
1569 }
1570
Olivier Houchard6db16992019-05-17 15:40:49 +02001571 if (txn->flags & TX_NOT_FIRST)
1572 goto abort_keep_alive;
1573
Olivier Houcharda798bf52019-03-08 18:52:00 +01001574 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001575 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001576 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001577 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578 }
1579
Christopher Faulete0768eb2018-10-03 16:38:02 +02001580 rep->analysers &= AN_RES_FLT_END;
1581 txn->status = 502;
1582 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001583 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584
1585 if (!(s->flags & SF_ERR_MASK))
1586 s->flags |= SF_ERR_SRVCL;
1587 if (!(s->flags & SF_FINST_MASK))
1588 s->flags |= SF_FINST_H;
1589 return 0;
1590 }
1591
Christopher Faulet9768c262018-10-22 09:34:31 +02001592 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001594 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001595 goto abort_keep_alive;
1596
Olivier Houcharda798bf52019-03-08 18:52:00 +01001597 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001598 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001599
1600 if (!(s->flags & SF_ERR_MASK))
1601 s->flags |= SF_ERR_CLICL;
1602 if (!(s->flags & SF_FINST_MASK))
1603 s->flags |= SF_FINST_H;
1604
1605 /* process_stream() will take care of the error */
1606 return 0;
1607 }
1608
1609 channel_dont_close(rep);
1610 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1611 return 0;
1612 }
1613
1614 /* More interesting part now : we know that we have a complete
1615 * response which at least looks like HTTP. We have an indicator
1616 * of each header's length, so we can parse them quickly.
1617 */
1618
Christopher Faulet9768c262018-10-22 09:34:31 +02001619 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001620 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001621 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001622
Christopher Faulet9768c262018-10-22 09:34:31 +02001623 /* 0: we might have to print this header in debug mode */
1624 if (unlikely((global.mode & MODE_DEBUG) &&
1625 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1626 int32_t pos;
1627
Christopher Faulet03599112018-11-27 11:21:21 +01001628 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001629
Christopher Fauleta3f15502019-05-13 15:27:23 +02001630 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001631 struct htx_blk *blk = htx_get_blk(htx, pos);
1632 enum htx_blk_type type = htx_get_blk_type(blk);
1633
1634 if (type == HTX_BLK_EOH)
1635 break;
1636 if (type != HTX_BLK_HDR)
1637 continue;
1638
1639 htx_debug_hdr("srvhdr", s,
1640 htx_get_blk_name(htx, blk),
1641 htx_get_blk_value(htx, blk));
1642 }
1643 }
1644
Christopher Faulet03599112018-11-27 11:21:21 +01001645 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001646 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001647 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001648 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001649 if (sl->flags & HTX_SL_F_XFER_LEN) {
1650 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001651 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001652 if (sl->flags & HTX_SL_F_BODYLESS)
1653 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001654 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001655
1656 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001657 if (n < 1 || n > 5)
1658 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001659
Christopher Faulete0768eb2018-10-03 16:38:02 +02001660 /* when the client triggers a 4xx from the server, it's most often due
1661 * to a missing object or permission. These events should be tracked
1662 * because if they happen often, it may indicate a brute force or a
1663 * vulnerability scan.
1664 */
1665 if (n == 4)
1666 stream_inc_http_err_ctr(s);
1667
1668 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001669 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001670
Christopher Faulete0768eb2018-10-03 16:38:02 +02001671 /* Adjust server's health based on status code. Note: status codes 501
1672 * and 505 are triggered on demand by client request, so we must not
1673 * count them as server failures.
1674 */
1675 if (objt_server(s->target)) {
1676 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001677 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001678 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001679 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001680 }
1681
1682 /*
1683 * We may be facing a 100-continue response, or any other informational
1684 * 1xx response which is non-final, in which case this is not the right
1685 * response, and we're waiting for the next one. Let's allow this response
1686 * to go to the client and wait for the next one. There's an exception for
1687 * 101 which is used later in the code to switch protocols.
1688 */
1689 if (txn->status < 200 &&
1690 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001691 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001692 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001693 msg->msg_state = HTTP_MSG_RPBEFORE;
1694 txn->status = 0;
1695 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001696 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697 }
1698
1699 /*
1700 * 2: check for cacheability.
1701 */
1702
1703 switch (txn->status) {
1704 case 200:
1705 case 203:
1706 case 204:
1707 case 206:
1708 case 300:
1709 case 301:
1710 case 404:
1711 case 405:
1712 case 410:
1713 case 414:
1714 case 501:
1715 break;
1716 default:
1717 /* RFC7231#6.1:
1718 * Responses with status codes that are defined as
1719 * cacheable by default (e.g., 200, 203, 204, 206,
1720 * 300, 301, 404, 405, 410, 414, and 501 in this
1721 * specification) can be reused by a cache with
1722 * heuristic expiration unless otherwise indicated
1723 * by the method definition or explicit cache
1724 * controls [RFC7234]; all other status codes are
1725 * not cacheable by default.
1726 */
1727 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1728 break;
1729 }
1730
1731 /*
1732 * 3: we may need to capture headers
1733 */
1734 s->logs.logwait &= ~LW_RESP;
1735 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001736 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001737
Christopher Faulet9768c262018-10-22 09:34:31 +02001738 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001739 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1740 txn->status == 101)) {
1741 /* Either we've established an explicit tunnel, or we're
1742 * switching the protocol. In both cases, we're very unlikely
1743 * to understand the next protocols. We have to switch to tunnel
1744 * mode, so that we transfer the request and responses then let
1745 * this protocol pass unmodified. When we later implement specific
1746 * parsers for such protocols, we'll want to check the Upgrade
1747 * header which contains information about that protocol for
1748 * responses with status 101 (eg: see RFC2817 about TLS).
1749 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02001750 txn->flags |= TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001751 }
1752
Christopher Faulet61608322018-11-23 16:23:45 +01001753 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1754 * 407 (Proxy-Authenticate) responses and set the connection to private
1755 */
1756 srv_conn = cs_conn(objt_cs(s->si[1].end));
1757 if (srv_conn) {
1758 struct ist hdr;
1759 struct http_hdr_ctx ctx;
1760
1761 if (txn->status == 401)
1762 hdr = ist("WWW-Authenticate");
1763 else if (txn->status == 407)
1764 hdr = ist("Proxy-Authenticate");
1765 else
1766 goto end;
1767
1768 ctx.blk = NULL;
1769 while (http_find_header(htx, hdr, &ctx, 0)) {
1770 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001771 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1772 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001773 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001774 }
Christopher Faulet61608322018-11-23 16:23:45 +01001775 }
1776 }
1777
1778 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 /* we want to have the response time before we start processing it */
1780 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1781
1782 /* end of job, return OK */
1783 rep->analysers &= ~an_bit;
1784 rep->analyse_exp = TICK_ETERNITY;
1785 channel_auto_close(rep);
1786 return 1;
1787
Christopher Faulet47365272018-10-31 17:40:50 +01001788 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001789 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001790 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001791 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001792 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001793 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001794 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001795 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001796 do_l7_retry(s, si_b) == 0)
1797 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001798 txn->status = 502;
1799 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001800 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001801 rep->analysers &= AN_RES_FLT_END;
1802
1803 if (!(s->flags & SF_ERR_MASK))
1804 s->flags |= SF_ERR_PRXCOND;
1805 if (!(s->flags & SF_FINST_MASK))
1806 s->flags |= SF_FINST_H;
1807 return 0;
1808
Christopher Faulete0768eb2018-10-03 16:38:02 +02001809 abort_keep_alive:
1810 /* A keep-alive request to the server failed on a network error.
1811 * The client is required to retry. We need to close without returning
1812 * any other information so that the client retries.
1813 */
1814 txn->status = 0;
1815 rep->analysers &= AN_RES_FLT_END;
1816 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001817 s->logs.logwait = 0;
1818 s->logs.level = 0;
1819 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001820 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001821 return 0;
1822}
1823
1824/* This function performs all the processing enabled for the current response.
1825 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1826 * and updates s->res.analysers. It might make sense to explode it into several
1827 * other functions. It works like process_request (see indications above).
1828 */
1829int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1830{
1831 struct session *sess = s->sess;
1832 struct http_txn *txn = s->txn;
1833 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001834 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001835 struct proxy *cur_proxy;
1836 struct cond_wordlist *wl;
1837 enum rule_result ret = HTTP_RULE_RES_CONT;
1838
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001839 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1840 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001841
Christopher Faulete0768eb2018-10-03 16:38:02 +02001842 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1843 now_ms, __FUNCTION__,
1844 s,
1845 rep,
1846 rep->rex, rep->wex,
1847 rep->flags,
1848 ci_data(rep),
1849 rep->analysers);
1850
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001851 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001852
1853 /* The stats applet needs to adjust the Connection header but we don't
1854 * apply any filter there.
1855 */
1856 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1857 rep->analysers &= ~an_bit;
1858 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001859 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001860 }
1861
1862 /*
1863 * We will have to evaluate the filters.
1864 * As opposed to version 1.2, now they will be evaluated in the
1865 * filters order and not in the header order. This means that
1866 * each filter has to be validated among all headers.
1867 *
1868 * Filters are tried with ->be first, then with ->fe if it is
1869 * different from ->be.
1870 *
1871 * Maybe we are in resume condiion. In this case I choose the
1872 * "struct proxy" which contains the rule list matching the resume
1873 * pointer. If none of theses "struct proxy" match, I initialise
1874 * the process with the first one.
1875 *
1876 * In fact, I check only correspondance betwwen the current list
1877 * pointer and the ->fe rule list. If it doesn't match, I initialize
1878 * the loop with the ->be.
1879 */
1880 if (s->current_rule_list == &sess->fe->http_res_rules)
1881 cur_proxy = sess->fe;
1882 else
1883 cur_proxy = s->be;
1884 while (1) {
1885 struct proxy *rule_set = cur_proxy;
1886
1887 /* evaluate http-response rules */
1888 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001889 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890
1891 if (ret == HTTP_RULE_RES_BADREQ)
1892 goto return_srv_prx_502;
1893
1894 if (ret == HTTP_RULE_RES_DONE) {
1895 rep->analysers &= ~an_bit;
1896 rep->analyse_exp = TICK_ETERNITY;
1897 return 1;
1898 }
1899 }
1900
1901 /* we need to be called again. */
1902 if (ret == HTTP_RULE_RES_YIELD) {
1903 channel_dont_close(rep);
1904 return 0;
1905 }
1906
1907 /* try headers filters */
1908 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001909 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1910 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001911 }
1912
1913 /* has the response been denied ? */
1914 if (txn->flags & TX_SVDENY) {
1915 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001916 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001917
Olivier Houcharda798bf52019-03-08 18:52:00 +01001918 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1919 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001920 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001921 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001922 goto return_srv_prx_502;
1923 }
1924
1925 /* add response headers from the rule sets in the same order */
1926 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001927 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001928 if (txn->status < 200 && txn->status != 101)
1929 break;
1930 if (wl->cond) {
1931 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1932 ret = acl_pass(ret);
1933 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1934 ret = !ret;
1935 if (!ret)
1936 continue;
1937 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001938
1939 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1940 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001941 goto return_bad_resp;
1942 }
1943
1944 /* check whether we're already working on the frontend */
1945 if (cur_proxy == sess->fe)
1946 break;
1947 cur_proxy = sess->fe;
1948 }
1949
1950 /* After this point, this anayzer can't return yield, so we can
1951 * remove the bit corresponding to this analyzer from the list.
1952 *
1953 * Note that the intermediate returns and goto found previously
1954 * reset the analyzers.
1955 */
1956 rep->analysers &= ~an_bit;
1957 rep->analyse_exp = TICK_ETERNITY;
1958
1959 /* OK that's all we can do for 1xx responses */
1960 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001961 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001962
1963 /*
1964 * Now check for a server cookie.
1965 */
1966 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001967 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968
1969 /*
1970 * Check for cache-control or pragma headers if required.
1971 */
1972 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
Christopher Faulet75b4cd92019-07-15 22:26:28 +02001973 htx_check_response_for_cacheability(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001974
1975 /*
1976 * Add server cookie in the response if needed
1977 */
1978 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1979 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1980 (!(s->flags & SF_DIRECT) ||
1981 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1982 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1983 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1984 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1985 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1986 !(s->flags & SF_IGNORE_PRST)) {
1987 /* the server is known, it's not the one the client requested, or the
1988 * cookie's last seen date needs to be refreshed. We have to
1989 * insert a set-cookie here, except if we want to insert only on POST
1990 * requests and this one isn't. Note that servers which don't have cookies
1991 * (eg: some backup servers) will return a full cookie removal request.
1992 */
1993 if (!objt_server(s->target)->cookie) {
1994 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001995 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001996 s->be->cookie_name);
1997 }
1998 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001999 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002000
2001 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2002 /* emit last_date, which is mandatory */
2003 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2004 s30tob64((date.tv_sec+3) >> 2,
2005 trash.area + trash.data);
2006 trash.data += 5;
2007
2008 if (s->be->cookie_maxlife) {
2009 /* emit first_date, which is either the original one or
2010 * the current date.
2011 */
2012 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2013 s30tob64(txn->cookie_first_date ?
2014 txn->cookie_first_date >> 2 :
2015 (date.tv_sec+3) >> 2,
2016 trash.area + trash.data);
2017 trash.data += 5;
2018 }
2019 }
2020 chunk_appendf(&trash, "; path=/");
2021 }
2022
2023 if (s->be->cookie_domain)
2024 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2025
2026 if (s->be->ck_opts & PR_CK_HTTPONLY)
2027 chunk_appendf(&trash, "; HttpOnly");
2028
2029 if (s->be->ck_opts & PR_CK_SECURE)
2030 chunk_appendf(&trash, "; Secure");
2031
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002032 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002033 goto return_bad_resp;
2034
2035 txn->flags &= ~TX_SCK_MASK;
2036 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2037 /* the server did not change, only the date was updated */
2038 txn->flags |= TX_SCK_UPDATED;
2039 else
2040 txn->flags |= TX_SCK_INSERTED;
2041
2042 /* Here, we will tell an eventual cache on the client side that we don't
2043 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2044 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2045 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2046 */
2047 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2048
2049 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2050
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002051 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002052 goto return_bad_resp;
2053 }
2054 }
2055
2056 /*
2057 * Check if result will be cacheable with a cookie.
2058 * We'll block the response if security checks have caught
2059 * nasty things such as a cacheable cookie.
2060 */
2061 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2062 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2063 (s->be->options & PR_O_CHK_CACHE)) {
2064 /* we're in presence of a cacheable response containing
2065 * a set-cookie header. We'll block it as requested by
2066 * the 'checkcache' option, and send an alert.
2067 */
2068 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002069 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002070
Olivier Houcharda798bf52019-03-08 18:52:00 +01002071 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2072 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002073 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002074 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002075
2076 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2077 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2078 send_log(s->be, LOG_ALERT,
2079 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2080 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2081 goto return_srv_prx_502;
2082 }
2083
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002084 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002085 /* Always enter in the body analyzer */
2086 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2087 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2088
2089 /* if the user wants to log as soon as possible, without counting
2090 * bytes from the server, then this is the right moment. We have
2091 * to temporarily assign bytes_out to log what we currently have.
2092 */
2093 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2094 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002095 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002096 s->do_log(s);
2097 s->logs.bytes_out = 0;
2098 }
2099 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002100
2101 return_bad_resp:
2102 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002103 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002104 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002105 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002106 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002107
2108 return_srv_prx_502:
2109 rep->analysers &= AN_RES_FLT_END;
2110 txn->status = 502;
2111 s->logs.t_data = -1; /* was not a valid response */
2112 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002113 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002114 if (!(s->flags & SF_ERR_MASK))
2115 s->flags |= SF_ERR_PRXCOND;
2116 if (!(s->flags & SF_FINST_MASK))
2117 s->flags |= SF_FINST_H;
2118 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002119}
2120
2121/* This function is an analyser which forwards response body (including chunk
2122 * sizes if any). It is called as soon as we must forward, even if we forward
2123 * zero byte. The only situation where it must not be called is when we're in
2124 * tunnel mode and we want to forward till the close. It's used both to forward
2125 * remaining data and to resync after end of body. It expects the msg_state to
2126 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2127 * read more data, or 1 once we can go on with next request or end the stream.
2128 *
2129 * It is capable of compressing response data both in content-length mode and
2130 * in chunked mode. The state machines follows different flows depending on
2131 * whether content-length and chunked modes are used, since there are no
2132 * trailers in content-length :
2133 *
2134 * chk-mode cl-mode
2135 * ,----- BODY -----.
2136 * / \
2137 * V size > 0 V chk-mode
2138 * .--> SIZE -------------> DATA -------------> CRLF
2139 * | | size == 0 | last byte |
2140 * | v final crlf v inspected |
2141 * | TRAILERS -----------> DONE |
2142 * | |
2143 * `----------------------------------------------'
2144 *
2145 * Compression only happens in the DATA state, and must be flushed in final
2146 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2147 * is performed at once on final states for all bytes parsed, or when leaving
2148 * on missing data.
2149 */
2150int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2151{
2152 struct session *sess = s->sess;
2153 struct http_txn *txn = s->txn;
2154 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002155 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002156 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002157
2158 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2159 now_ms, __FUNCTION__,
2160 s,
2161 res,
2162 res->rex, res->wex,
2163 res->flags,
2164 ci_data(res),
2165 res->analysers);
2166
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002167 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002168
2169 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002170 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002171 /* Output closed while we were sending data. We must abort and
2172 * wake the other side up.
2173 */
2174 msg->err_state = msg->msg_state;
2175 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002176 htx_end_response(s);
2177 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002178 return 1;
2179 }
2180
Christopher Faulet9768c262018-10-22 09:34:31 +02002181 if (msg->msg_state == HTTP_MSG_BODY)
2182 msg->msg_state = HTTP_MSG_DATA;
2183
Christopher Faulete0768eb2018-10-03 16:38:02 +02002184 /* in most states, we should abort in case of early close */
2185 channel_auto_close(res);
2186
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002188 if (res->to_forward == CHN_INFINITE_FORWARD) {
2189 if (res->flags & (CF_SHUTR|CF_EOI)) {
2190 msg->msg_state = HTTP_MSG_DONE;
2191 res->to_forward = 0;
2192 goto done;
2193 }
2194 }
2195 else {
2196 /* We can't process the buffer's contents yet */
2197 res->flags |= CF_WAKE_WRITE;
2198 goto missing_data_or_waiting;
2199 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 }
2201
Christopher Faulet9768c262018-10-22 09:34:31 +02002202 if (msg->msg_state >= HTTP_MSG_DONE)
2203 goto done;
2204
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002205 /* Forward input data. We get it by removing all outgoing data not
2206 * forwarded yet from HTX data size. If there are some data filters, we
2207 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002208 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002209 if (HAS_RSP_DATA_FILTERS(s)) {
2210 ret = flt_http_payload(s, msg, htx->data);
2211 if (ret < 0)
2212 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002213 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 }
2215 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002216 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002217 if (msg->flags & HTTP_MSGF_XFER_LEN)
2218 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002219 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002220
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002221 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2222 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2223 msg->msg_state = HTTP_MSG_TUNNEL;
2224 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002225 }
2226
Christopher Faulet9768c262018-10-22 09:34:31 +02002227 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002228 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2229 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002230 */
2231 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2232 goto missing_data_or_waiting;
2233
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002234 msg->msg_state = HTTP_MSG_ENDING;
2235 if (htx->data != co_data(res))
2236 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002237 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002238 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002239
2240 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002242 channel_dont_close(res);
2243
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002244 if (HAS_RSP_DATA_FILTERS(s)) {
2245 ret = flt_http_end(s, msg);
2246 if (ret <= 0) {
2247 if (!ret)
2248 goto missing_data_or_waiting;
2249 goto return_bad_res;
2250 }
2251 }
2252
Christopher Fauletf2824e62018-10-01 12:12:37 +02002253 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002254 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002255 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002256 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2257 if (res->flags & CF_SHUTW) {
2258 /* response errors are most likely due to the
2259 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002260 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002262 goto return_bad_res;
2263 }
2264 return 1;
2265 }
2266 return 0;
2267
2268 missing_data_or_waiting:
2269 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002270 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002271
Christopher Faulet47365272018-10-31 17:40:50 +01002272 if (htx->flags & HTX_FL_PARSING_ERROR)
2273 goto return_bad_res;
2274
Christopher Faulete0768eb2018-10-03 16:38:02 +02002275 /* stop waiting for data if the input is closed before the end. If the
2276 * client side was already closed, it means that the client has aborted,
2277 * so we don't want to count this as a server abort. Otherwise it's a
2278 * server abort.
2279 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002280 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002281 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002282 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002284 if (htx_is_empty(htx))
2285 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 }
2287
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 /* When TE: chunked is used, we need to get there again to parse
2289 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002290 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2291 * are filters registered on the stream, we don't want to forward a
2292 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002294 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295 channel_dont_close(res);
2296
2297 /* We know that more data are expected, but we couldn't send more that
2298 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2299 * system knows it must not set a PUSH on this first part. Interactive
2300 * modes are already handled by the stream sock layer. We must not do
2301 * this in content-length mode because it could present the MSG_MORE
2302 * flag with the last block of forwarded data, which would cause an
2303 * additional delay to be observed by the receiver.
2304 */
2305 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2306 res->flags |= CF_EXPECT_MORE;
2307
2308 /* the stream handler will take care of timeouts and errors */
2309 return 0;
2310
Christopher Faulet93e02d82019-03-08 14:18:50 +01002311 return_srv_abort:
2312 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2313 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002314 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002315 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2316 if (!(s->flags & SF_ERR_MASK))
2317 s->flags |= SF_ERR_SRVCL;
2318 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002319
Christopher Faulet93e02d82019-03-08 14:18:50 +01002320 return_cli_abort:
2321 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2322 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002323 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002324 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2325 if (!(s->flags & SF_ERR_MASK))
2326 s->flags |= SF_ERR_CLICL;
2327 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 return_bad_res:
2330 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2331 if (objt_server(s->target)) {
2332 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2333 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2334 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002336 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002337
Christopher Faulet93e02d82019-03-08 14:18:50 +01002338 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002339 txn->rsp.err_state = txn->rsp.msg_state;
2340 txn->rsp.msg_state = HTTP_MSG_ERROR;
2341 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002342 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343 res->analysers &= AN_RES_FLT_END;
2344 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 +02002345 if (!(s->flags & SF_FINST_MASK))
2346 s->flags |= SF_FINST_D;
2347 return 0;
2348}
2349
Christopher Fauletf2824e62018-10-01 12:12:37 +02002350/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002352 * as too large a request to build a valid response.
2353 */
2354int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2355{
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 struct channel *req = &s->req;
2357 struct channel *res = &s->res;
2358 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002359 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002360 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 struct ist status, reason, location;
2362 unsigned int flags;
2363 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002364 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002365
2366 chunk = alloc_trash_chunk();
2367 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002368 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 /*
2371 * Create the location
2372 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002373 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 case REDIRECT_TYPE_SCHEME: {
2376 struct http_hdr_ctx ctx;
2377 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002378
Christopher Faulet99daf282018-11-28 22:58:13 +01002379 host = ist("");
2380 ctx.blk = NULL;
2381 if (http_find_header(htx, ist("Host"), &ctx, 0))
2382 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
Christopher Faulet297fbb42019-05-13 14:41:27 +02002384 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 path = http_get_path(htx_sl_req_uri(sl));
2386 /* build message using path */
2387 if (path.ptr) {
2388 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2389 int qs = 0;
2390 while (qs < path.len) {
2391 if (*(path.ptr + qs) == '?') {
2392 path.len = qs;
2393 break;
2394 }
2395 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002396 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397 }
2398 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002399 else
2400 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401
Christopher Faulet99daf282018-11-28 22:58:13 +01002402 if (rule->rdr_str) { /* this is an old "redirect" rule */
2403 /* add scheme */
2404 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2405 goto fail;
2406 }
2407 else {
2408 /* add scheme with executing log format */
2409 chunk->data += build_logline(s, chunk->area + chunk->data,
2410 chunk->size - chunk->data,
2411 &rule->rdr_fmt);
2412 }
2413 /* add "://" + host + path */
2414 if (!chunk_memcat(chunk, "://", 3) ||
2415 !chunk_memcat(chunk, host.ptr, host.len) ||
2416 !chunk_memcat(chunk, path.ptr, path.len))
2417 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002418
Christopher Faulet99daf282018-11-28 22:58:13 +01002419 /* append a slash at the end of the location if needed and missing */
2420 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2421 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2422 if (chunk->data + 1 >= chunk->size)
2423 goto fail;
2424 chunk->area[chunk->data++] = '/';
2425 }
2426 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428
Christopher Faulet99daf282018-11-28 22:58:13 +01002429 case REDIRECT_TYPE_PREFIX: {
2430 struct ist path;
2431
Christopher Faulet297fbb42019-05-13 14:41:27 +02002432 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 path = http_get_path(htx_sl_req_uri(sl));
2434 /* build message using path */
2435 if (path.ptr) {
2436 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2437 int qs = 0;
2438 while (qs < path.len) {
2439 if (*(path.ptr + qs) == '?') {
2440 path.len = qs;
2441 break;
2442 }
2443 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002445 }
2446 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002447 else
2448 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 if (rule->rdr_str) { /* this is an old "redirect" rule */
2451 /* add prefix. Note that if prefix == "/", we don't want to
2452 * add anything, otherwise it makes it hard for the user to
2453 * configure a self-redirection.
2454 */
2455 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2456 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2457 goto fail;
2458 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002460 else {
2461 /* add prefix with executing log format */
2462 chunk->data += build_logline(s, chunk->area + chunk->data,
2463 chunk->size - chunk->data,
2464 &rule->rdr_fmt);
2465 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466
Christopher Faulet99daf282018-11-28 22:58:13 +01002467 /* add path */
2468 if (!chunk_memcat(chunk, path.ptr, path.len))
2469 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002470
Christopher Faulet99daf282018-11-28 22:58:13 +01002471 /* append a slash at the end of the location if needed and missing */
2472 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2473 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2474 if (chunk->data + 1 >= chunk->size)
2475 goto fail;
2476 chunk->area[chunk->data++] = '/';
2477 }
2478 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002479 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002480 case REDIRECT_TYPE_LOCATION:
2481 default:
2482 if (rule->rdr_str) { /* this is an old "redirect" rule */
2483 /* add location */
2484 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2485 goto fail;
2486 }
2487 else {
2488 /* add location with executing log format */
2489 chunk->data += build_logline(s, chunk->area + chunk->data,
2490 chunk->size - chunk->data,
2491 &rule->rdr_fmt);
2492 }
2493 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002494 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002495 location = ist2(chunk->area, chunk->data);
2496
2497 /*
2498 * Create the 30x response
2499 */
2500 switch (rule->code) {
2501 case 308:
2502 status = ist("308");
2503 reason = ist("Permanent Redirect");
2504 break;
2505 case 307:
2506 status = ist("307");
2507 reason = ist("Temporary Redirect");
2508 break;
2509 case 303:
2510 status = ist("303");
2511 reason = ist("See Other");
2512 break;
2513 case 301:
2514 status = ist("301");
2515 reason = ist("Moved Permanently");
2516 break;
2517 case 302:
2518 default:
2519 status = ist("302");
2520 reason = ist("Found");
2521 break;
2522 }
2523
Christopher Faulet08e66462019-05-23 16:44:59 +02002524 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2525 close = 1;
2526
Christopher Faulet99daf282018-11-28 22:58:13 +01002527 htx = htx_from_buf(&res->buf);
2528 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2529 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2530 if (!sl)
2531 goto fail;
2532 sl->info.res.status = rule->code;
2533 s->txn->status = rule->code;
2534
Christopher Faulet08e66462019-05-23 16:44:59 +02002535 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2536 goto fail;
2537
2538 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 !htx_add_header(htx, ist("Location"), location))
2540 goto fail;
2541
2542 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2543 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2544 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002545 }
2546
2547 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002548 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2549 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002550 }
2551
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2553 goto fail;
2554
Christopher Fauletf2824e62018-10-01 12:12:37 +02002555 /* let's log the request time */
2556 s->logs.tv_request = now;
2557
Christopher Faulet99daf282018-11-28 22:58:13 +01002558 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002559 c_adv(res, data);
2560 res->total += data;
2561
2562 channel_auto_read(req);
2563 channel_abort(req);
2564 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002565 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002566
2567 res->wex = tick_add_ifset(now_ms, res->wto);
2568 channel_auto_read(res);
2569 channel_auto_close(res);
2570 channel_shutr_now(res);
2571
2572 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002573
2574 if (!(s->flags & SF_ERR_MASK))
2575 s->flags |= SF_ERR_LOCAL;
2576 if (!(s->flags & SF_FINST_MASK))
2577 s->flags |= SF_FINST_R;
2578
Christopher Faulet99daf282018-11-28 22:58:13 +01002579 free_trash_chunk(chunk);
2580 return 1;
2581
2582 fail:
2583 /* If an error occurred, remove the incomplete HTTP response from the
2584 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002585 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002586 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002587 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002588}
2589
Christopher Faulet72333522018-10-24 11:25:02 +02002590int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2591 struct ist name, const char *str, struct my_regex *re, int action)
2592{
2593 struct http_hdr_ctx ctx;
2594 struct buffer *output = get_trash_chunk();
2595
2596 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2597 ctx.blk = NULL;
2598 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2599 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2600 continue;
2601
2602 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2603 if (output->data == -1)
2604 return -1;
2605 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2606 return -1;
2607 }
2608 return 0;
2609}
2610
2611static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2612 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2613{
2614 struct buffer *replace;
2615 int ret = -1;
2616
2617 replace = alloc_trash_chunk();
2618 if (!replace)
2619 goto leave;
2620
2621 replace->data = build_logline(s, replace->area, replace->size, fmt);
2622 if (replace->data >= replace->size - 1)
2623 goto leave;
2624
2625 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2626
2627 leave:
2628 free_trash_chunk(replace);
2629 return ret;
2630}
2631
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002632
2633/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2634 * on success and -1 on error. The response channel is updated accordingly.
2635 */
2636static int htx_reply_103_early_hints(struct channel *res)
2637{
2638 struct htx *htx = htx_from_buf(&res->buf);
2639 size_t data;
2640
Christopher Faulet1d5ec092019-06-26 14:23:54 +02002641 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 /* If an error occurred during an Early-hint rule,
2643 * remove the incomplete HTTP 103 response from the
2644 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002645 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646 return -1;
2647 }
2648
2649 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 c_adv(res, data);
2651 res->total += data;
2652 return 0;
2653}
2654
Christopher Faulet6eb92892018-11-15 16:39:29 +01002655/*
2656 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2657 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 * If <early_hints> is 0, it is starts a new response by adding the start
2659 * line. If an error occurred -1 is returned. On success 0 is returned. The
2660 * channel is not updated here. It must be done calling the function
2661 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002662 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002663static 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 +01002664{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 struct channel *res = &s->res;
2666 struct htx *htx = htx_from_buf(&res->buf);
2667 struct buffer *value = alloc_trash_chunk();
2668
Christopher Faulet6eb92892018-11-15 16:39:29 +01002669 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 struct htx_sl *sl;
2671 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2672 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2673
2674 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2675 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2676 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002677 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002678 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002679 }
2680
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002681 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2682 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002683 goto fail;
2684
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002685 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002686 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002687
2688 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002689 /* If an error occurred during an Early-hint rule, remove the incomplete
2690 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002691 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002692 free_trash_chunk(value);
2693 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002694}
2695
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002696/* This function executes one of the set-{method,path,query,uri} actions. It
2697 * takes the string from the variable 'replace' with length 'len', then modifies
2698 * the relevant part of the request line accordingly. Then it updates various
2699 * pointers to the next elements which were moved, and the total buffer length.
2700 * It finds the action to be performed in p[2], previously filled by function
2701 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2702 * error, though this can be revisited when this code is finally exploited.
2703 *
2704 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2705 * query string and 3 to replace uri.
2706 *
2707 * In query string case, the mark question '?' must be set at the start of the
2708 * string by the caller, event if the replacement query string is empty.
2709 */
2710int htx_req_replace_stline(int action, const char *replace, int len,
2711 struct proxy *px, struct stream *s)
2712{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002713 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002714
2715 switch (action) {
2716 case 0: // method
2717 if (!http_replace_req_meth(htx, ist2(replace, len)))
2718 return -1;
2719 break;
2720
2721 case 1: // path
2722 if (!http_replace_req_path(htx, ist2(replace, len)))
2723 return -1;
2724 break;
2725
2726 case 2: // query
2727 if (!http_replace_req_query(htx, ist2(replace, len)))
2728 return -1;
2729 break;
2730
2731 case 3: // uri
2732 if (!http_replace_req_uri(htx, ist2(replace, len)))
2733 return -1;
2734 break;
2735
2736 default:
2737 return -1;
2738 }
2739 return 0;
2740}
2741
2742/* This function replace the HTTP status code and the associated message. The
2743 * variable <status> contains the new status code. This function never fails.
2744 */
2745void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2746{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002747 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002748 char *res;
2749
2750 chunk_reset(&trash);
2751 res = ultoa_o(status, trash.area, trash.size);
2752 trash.data = res - trash.area;
2753
2754 /* Do we have a custom reason format string? */
2755 if (reason == NULL)
2756 reason = http_get_reason(status);
2757
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002758 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002759 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2760}
2761
Christopher Faulet3e964192018-10-24 11:39:23 +02002762/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2763 * transaction <txn>. Returns the verdict of the first rule that prevents
2764 * further processing of the request (auth, deny, ...), and defaults to
2765 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2766 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2767 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2768 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2769 * status.
2770 */
2771static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2772 struct stream *s, int *deny_status)
2773{
2774 struct session *sess = strm_sess(s);
2775 struct http_txn *txn = s->txn;
2776 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002777 struct act_rule *rule;
2778 struct http_hdr_ctx ctx;
2779 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002780 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2781 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002782 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002783
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002784 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002785
2786 /* If "the current_rule_list" match the executed rule list, we are in
2787 * resume condition. If a resume is needed it is always in the action
2788 * and never in the ACL or converters. In this case, we initialise the
2789 * current rule, and go to the action execution point.
2790 */
2791 if (s->current_rule) {
2792 rule = s->current_rule;
2793 s->current_rule = NULL;
2794 if (s->current_rule_list == rules)
2795 goto resume_execution;
2796 }
2797 s->current_rule_list = rules;
2798
2799 list_for_each_entry(rule, rules, list) {
2800 /* check optional condition */
2801 if (rule->cond) {
2802 int ret;
2803
2804 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2805 ret = acl_pass(ret);
2806
2807 if (rule->cond->pol == ACL_COND_UNLESS)
2808 ret = !ret;
2809
2810 if (!ret) /* condition not matched */
2811 continue;
2812 }
2813
2814 act_flags |= ACT_FLAG_FIRST;
2815 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002816 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2817 early_hints = 0;
2818 if (htx_reply_103_early_hints(&s->res) == -1) {
2819 rule_ret = HTTP_RULE_RES_BADREQ;
2820 goto end;
2821 }
2822 }
2823
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 switch (rule->action) {
2825 case ACT_ACTION_ALLOW:
2826 rule_ret = HTTP_RULE_RES_STOP;
2827 goto end;
2828
2829 case ACT_ACTION_DENY:
2830 if (deny_status)
2831 *deny_status = rule->deny_status;
2832 rule_ret = HTTP_RULE_RES_DENY;
2833 goto end;
2834
2835 case ACT_HTTP_REQ_TARPIT:
2836 txn->flags |= TX_CLTARPIT;
2837 if (deny_status)
2838 *deny_status = rule->deny_status;
2839 rule_ret = HTTP_RULE_RES_DENY;
2840 goto end;
2841
2842 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002843 /* Auth might be performed on regular http-req rules as well as on stats */
2844 auth_realm = rule->arg.auth.realm;
2845 if (!auth_realm) {
2846 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2847 auth_realm = STATS_DEFAULT_REALM;
2848 else
2849 auth_realm = px->id;
2850 }
2851 /* send 401/407 depending on whether we use a proxy or not. We still
2852 * count one error, because normal browsing won't significantly
2853 * increase the counter but brute force attempts will.
2854 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002855 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002856 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2857 rule_ret = HTTP_RULE_RES_BADREQ;
2858 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002859 goto end;
2860
2861 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 rule_ret = HTTP_RULE_RES_DONE;
2863 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2864 rule_ret = HTTP_RULE_RES_BADREQ;
2865 goto end;
2866
2867 case ACT_HTTP_SET_NICE:
2868 s->task->nice = rule->arg.nice;
2869 break;
2870
2871 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002872 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002873 break;
2874
2875 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002876 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002877 break;
2878
2879 case ACT_HTTP_SET_LOGL:
2880 s->logs.level = rule->arg.loglevel;
2881 break;
2882
2883 case ACT_HTTP_REPLACE_HDR:
2884 case ACT_HTTP_REPLACE_VAL:
2885 if (htx_transform_header(s, &s->req, htx,
2886 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2887 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002888 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002889 rule_ret = HTTP_RULE_RES_BADREQ;
2890 goto end;
2891 }
2892 break;
2893
2894 case ACT_HTTP_DEL_HDR:
2895 /* remove all occurrences of the header */
2896 ctx.blk = NULL;
2897 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2898 http_remove_header(htx, &ctx);
2899 break;
2900
2901 case ACT_HTTP_SET_HDR:
2902 case ACT_HTTP_ADD_HDR: {
2903 /* The scope of the trash buffer must be limited to this function. The
2904 * build_logline() function can execute a lot of other function which
2905 * can use the trash buffer. So for limiting the scope of this global
2906 * buffer, we build first the header value using build_logline, and
2907 * after we store the header name.
2908 */
2909 struct buffer *replace;
2910 struct ist n, v;
2911
2912 replace = alloc_trash_chunk();
2913 if (!replace) {
2914 rule_ret = HTTP_RULE_RES_BADREQ;
2915 goto end;
2916 }
2917
2918 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2919 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2920 v = ist2(replace->area, replace->data);
2921
2922 if (rule->action == ACT_HTTP_SET_HDR) {
2923 /* remove all occurrences of the header */
2924 ctx.blk = NULL;
2925 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2926 http_remove_header(htx, &ctx);
2927 }
2928
2929 if (!http_add_header(htx, n, v)) {
2930 static unsigned char rate_limit = 0;
2931
2932 if ((rate_limit++ & 255) == 0) {
2933 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);
2934 }
2935
Olivier Houcharda798bf52019-03-08 18:52:00 +01002936 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002937 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002938 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002939 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002940 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002941 }
2942 free_trash_chunk(replace);
2943 break;
2944 }
2945
2946 case ACT_HTTP_DEL_ACL:
2947 case ACT_HTTP_DEL_MAP: {
2948 struct pat_ref *ref;
2949 struct buffer *key;
2950
2951 /* collect reference */
2952 ref = pat_ref_lookup(rule->arg.map.ref);
2953 if (!ref)
2954 continue;
2955
2956 /* allocate key */
2957 key = alloc_trash_chunk();
2958 if (!key) {
2959 rule_ret = HTTP_RULE_RES_BADREQ;
2960 goto end;
2961 }
2962
2963 /* collect key */
2964 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2965 key->area[key->data] = '\0';
2966
2967 /* perform update */
2968 /* returned code: 1=ok, 0=ko */
2969 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2970 pat_ref_delete(ref, key->area);
2971 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2972
2973 free_trash_chunk(key);
2974 break;
2975 }
2976
2977 case ACT_HTTP_ADD_ACL: {
2978 struct pat_ref *ref;
2979 struct buffer *key;
2980
2981 /* collect reference */
2982 ref = pat_ref_lookup(rule->arg.map.ref);
2983 if (!ref)
2984 continue;
2985
2986 /* allocate key */
2987 key = alloc_trash_chunk();
2988 if (!key) {
2989 rule_ret = HTTP_RULE_RES_BADREQ;
2990 goto end;
2991 }
2992
2993 /* collect key */
2994 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2995 key->area[key->data] = '\0';
2996
2997 /* perform update */
2998 /* add entry only if it does not already exist */
2999 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3000 if (pat_ref_find_elt(ref, key->area) == NULL)
3001 pat_ref_add(ref, key->area, NULL, NULL);
3002 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3003
3004 free_trash_chunk(key);
3005 break;
3006 }
3007
3008 case ACT_HTTP_SET_MAP: {
3009 struct pat_ref *ref;
3010 struct buffer *key, *value;
3011
3012 /* collect reference */
3013 ref = pat_ref_lookup(rule->arg.map.ref);
3014 if (!ref)
3015 continue;
3016
3017 /* allocate key */
3018 key = alloc_trash_chunk();
3019 if (!key) {
3020 rule_ret = HTTP_RULE_RES_BADREQ;
3021 goto end;
3022 }
3023
3024 /* allocate value */
3025 value = alloc_trash_chunk();
3026 if (!value) {
3027 free_trash_chunk(key);
3028 rule_ret = HTTP_RULE_RES_BADREQ;
3029 goto end;
3030 }
3031
3032 /* collect key */
3033 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3034 key->area[key->data] = '\0';
3035
3036 /* collect value */
3037 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3038 value->area[value->data] = '\0';
3039
3040 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003041 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003042 if (pat_ref_find_elt(ref, key->area) != NULL)
3043 /* update entry if it exists */
3044 pat_ref_set(ref, key->area, value->area, NULL);
3045 else
3046 /* insert a new entry */
3047 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003048 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003049 free_trash_chunk(key);
3050 free_trash_chunk(value);
3051 break;
3052 }
3053
3054 case ACT_HTTP_EARLY_HINT:
3055 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3056 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003057 early_hints = htx_add_early_hint_header(s, early_hints,
3058 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003059 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003060 if (early_hints == -1) {
3061 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003062 goto end;
3063 }
3064 break;
3065
3066 case ACT_CUSTOM:
3067 if ((s->req.flags & CF_READ_ERROR) ||
3068 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003069 (px->options & PR_O_ABRT_CLOSE)))
3070 act_flags |= ACT_FLAG_FINAL;
3071
3072 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3073 case ACT_RET_ERR:
3074 case ACT_RET_CONT:
3075 break;
3076 case ACT_RET_STOP:
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003077 rule_ret = HTTP_RULE_RES_STOP;
3078 goto end;
3079 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003080 rule_ret = HTTP_RULE_RES_DONE;
3081 goto end;
3082 case ACT_RET_YIELD:
3083 s->current_rule = rule;
3084 rule_ret = HTTP_RULE_RES_YIELD;
3085 goto end;
3086 }
3087 break;
3088
3089 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3090 /* Note: only the first valid tracking parameter of each
3091 * applies.
3092 */
3093
3094 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3095 struct stktable *t;
3096 struct stksess *ts;
3097 struct stktable_key *key;
3098 void *ptr1, *ptr2;
3099
3100 t = rule->arg.trk_ctr.table.t;
3101 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3102 rule->arg.trk_ctr.expr, NULL);
3103
3104 if (key && (ts = stktable_get_entry(t, key))) {
3105 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3106
3107 /* let's count a new HTTP request as it's the first time we do it */
3108 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3109 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3110 if (ptr1 || ptr2) {
3111 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3112
3113 if (ptr1)
3114 stktable_data_cast(ptr1, http_req_cnt)++;
3115
3116 if (ptr2)
3117 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3118 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3119
3120 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3121
3122 /* If data was modified, we need to touch to re-schedule sync */
3123 stktable_touch_local(t, ts, 0);
3124 }
3125
3126 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3127 if (sess->fe != s->be)
3128 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3129 }
3130 }
3131 break;
3132
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003133 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003134 default:
3135 break;
3136 }
3137 }
3138
3139 end:
3140 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003141 if (htx_reply_103_early_hints(&s->res) == -1)
3142 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003143 }
3144
3145 /* we reached the end of the rules, nothing to report */
3146 return rule_ret;
3147}
3148
3149/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3150 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3151 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3152 * is returned, the process can continue the evaluation of next rule list. If
3153 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3154 * is returned, it means the operation could not be processed and a server error
3155 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3156 * deny rule. If *YIELD is returned, the caller must call again the function
3157 * with the same context.
3158 */
3159static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3160 struct stream *s)
3161{
3162 struct session *sess = strm_sess(s);
3163 struct http_txn *txn = s->txn;
3164 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003165 struct act_rule *rule;
3166 struct http_hdr_ctx ctx;
3167 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3168 int act_flags = 0;
3169
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003170 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003171
3172 /* If "the current_rule_list" match the executed rule list, we are in
3173 * resume condition. If a resume is needed it is always in the action
3174 * and never in the ACL or converters. In this case, we initialise the
3175 * current rule, and go to the action execution point.
3176 */
3177 if (s->current_rule) {
3178 rule = s->current_rule;
3179 s->current_rule = NULL;
3180 if (s->current_rule_list == rules)
3181 goto resume_execution;
3182 }
3183 s->current_rule_list = rules;
3184
3185 list_for_each_entry(rule, rules, list) {
3186 /* check optional condition */
3187 if (rule->cond) {
3188 int ret;
3189
3190 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3191 ret = acl_pass(ret);
3192
3193 if (rule->cond->pol == ACL_COND_UNLESS)
3194 ret = !ret;
3195
3196 if (!ret) /* condition not matched */
3197 continue;
3198 }
3199
3200 act_flags |= ACT_FLAG_FIRST;
3201resume_execution:
3202 switch (rule->action) {
3203 case ACT_ACTION_ALLOW:
3204 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3205 goto end;
3206
3207 case ACT_ACTION_DENY:
3208 txn->flags |= TX_SVDENY;
3209 rule_ret = HTTP_RULE_RES_STOP;
3210 goto end;
3211
3212 case ACT_HTTP_SET_NICE:
3213 s->task->nice = rule->arg.nice;
3214 break;
3215
3216 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003217 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003218 break;
3219
3220 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003221 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 break;
3223
3224 case ACT_HTTP_SET_LOGL:
3225 s->logs.level = rule->arg.loglevel;
3226 break;
3227
3228 case ACT_HTTP_REPLACE_HDR:
3229 case ACT_HTTP_REPLACE_VAL:
3230 if (htx_transform_header(s, &s->res, htx,
3231 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3232 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003233 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003234 rule_ret = HTTP_RULE_RES_BADREQ;
3235 goto end;
3236 }
3237 break;
3238
3239 case ACT_HTTP_DEL_HDR:
3240 /* remove all occurrences of the header */
3241 ctx.blk = NULL;
3242 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3243 http_remove_header(htx, &ctx);
3244 break;
3245
3246 case ACT_HTTP_SET_HDR:
3247 case ACT_HTTP_ADD_HDR: {
3248 struct buffer *replace;
3249 struct ist n, v;
3250
3251 replace = alloc_trash_chunk();
3252 if (!replace) {
3253 rule_ret = HTTP_RULE_RES_BADREQ;
3254 goto end;
3255 }
3256
3257 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3258 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3259 v = ist2(replace->area, replace->data);
3260
3261 if (rule->action == ACT_HTTP_SET_HDR) {
3262 /* remove all occurrences of the header */
3263 ctx.blk = NULL;
3264 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3265 http_remove_header(htx, &ctx);
3266 }
3267
3268 if (!http_add_header(htx, n, v)) {
3269 static unsigned char rate_limit = 0;
3270
3271 if ((rate_limit++ & 255) == 0) {
3272 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);
3273 }
3274
Olivier Houcharda798bf52019-03-08 18:52:00 +01003275 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003276 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003277 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003278 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 }
3283 free_trash_chunk(replace);
3284 break;
3285 }
3286
3287 case ACT_HTTP_DEL_ACL:
3288 case ACT_HTTP_DEL_MAP: {
3289 struct pat_ref *ref;
3290 struct buffer *key;
3291
3292 /* collect reference */
3293 ref = pat_ref_lookup(rule->arg.map.ref);
3294 if (!ref)
3295 continue;
3296
3297 /* allocate key */
3298 key = alloc_trash_chunk();
3299 if (!key) {
3300 rule_ret = HTTP_RULE_RES_BADREQ;
3301 goto end;
3302 }
3303
3304 /* collect key */
3305 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3306 key->area[key->data] = '\0';
3307
3308 /* perform update */
3309 /* returned code: 1=ok, 0=ko */
3310 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3311 pat_ref_delete(ref, key->area);
3312 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3313
3314 free_trash_chunk(key);
3315 break;
3316 }
3317
3318 case ACT_HTTP_ADD_ACL: {
3319 struct pat_ref *ref;
3320 struct buffer *key;
3321
3322 /* collect reference */
3323 ref = pat_ref_lookup(rule->arg.map.ref);
3324 if (!ref)
3325 continue;
3326
3327 /* allocate key */
3328 key = alloc_trash_chunk();
3329 if (!key) {
3330 rule_ret = HTTP_RULE_RES_BADREQ;
3331 goto end;
3332 }
3333
3334 /* collect key */
3335 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3336 key->area[key->data] = '\0';
3337
3338 /* perform update */
3339 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003340 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003341 if (pat_ref_find_elt(ref, key->area) == NULL)
3342 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003343 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003344 free_trash_chunk(key);
3345 break;
3346 }
3347
3348 case ACT_HTTP_SET_MAP: {
3349 struct pat_ref *ref;
3350 struct buffer *key, *value;
3351
3352 /* collect reference */
3353 ref = pat_ref_lookup(rule->arg.map.ref);
3354 if (!ref)
3355 continue;
3356
3357 /* allocate key */
3358 key = alloc_trash_chunk();
3359 if (!key) {
3360 rule_ret = HTTP_RULE_RES_BADREQ;
3361 goto end;
3362 }
3363
3364 /* allocate value */
3365 value = alloc_trash_chunk();
3366 if (!value) {
3367 free_trash_chunk(key);
3368 rule_ret = HTTP_RULE_RES_BADREQ;
3369 goto end;
3370 }
3371
3372 /* collect key */
3373 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3374 key->area[key->data] = '\0';
3375
3376 /* collect value */
3377 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3378 value->area[value->data] = '\0';
3379
3380 /* perform update */
3381 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3382 if (pat_ref_find_elt(ref, key->area) != NULL)
3383 /* update entry if it exists */
3384 pat_ref_set(ref, key->area, value->area, NULL);
3385 else
3386 /* insert a new entry */
3387 pat_ref_add(ref, key->area, value->area, NULL);
3388 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3389 free_trash_chunk(key);
3390 free_trash_chunk(value);
3391 break;
3392 }
3393
3394 case ACT_HTTP_REDIR:
3395 rule_ret = HTTP_RULE_RES_DONE;
Christopher Faulet00618aa2019-07-15 12:05:35 +02003396 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02003397 rule_ret = HTTP_RULE_RES_BADREQ;
3398 goto end;
3399
3400 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3401 /* Note: only the first valid tracking parameter of each
3402 * applies.
3403 */
3404 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3405 struct stktable *t;
3406 struct stksess *ts;
3407 struct stktable_key *key;
3408 void *ptr;
3409
3410 t = rule->arg.trk_ctr.table.t;
3411 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3412 rule->arg.trk_ctr.expr, NULL);
3413
3414 if (key && (ts = stktable_get_entry(t, key))) {
3415 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3416
3417 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3418
3419 /* let's count a new HTTP request as it's the first time we do it */
3420 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3421 if (ptr)
3422 stktable_data_cast(ptr, http_req_cnt)++;
3423
3424 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3425 if (ptr)
3426 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3427 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3428
3429 /* When the client triggers a 4xx from the server, it's most often due
3430 * to a missing object or permission. These events should be tracked
3431 * because if they happen often, it may indicate a brute force or a
3432 * vulnerability scan. Normally this is done when receiving the response
3433 * but here we're tracking after this ought to have been done so we have
3434 * to do it on purpose.
3435 */
3436 if ((unsigned)(txn->status - 400) < 100) {
3437 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3438 if (ptr)
3439 stktable_data_cast(ptr, http_err_cnt)++;
3440
3441 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3442 if (ptr)
3443 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3444 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3445 }
3446
3447 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3448
3449 /* If data was modified, we need to touch to re-schedule sync */
3450 stktable_touch_local(t, ts, 0);
3451
3452 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3453 if (sess->fe != s->be)
3454 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3455 }
3456 }
3457 break;
3458
3459 case ACT_CUSTOM:
3460 if ((s->req.flags & CF_READ_ERROR) ||
3461 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003462 (px->options & PR_O_ABRT_CLOSE)))
3463 act_flags |= ACT_FLAG_FINAL;
3464
3465 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3466 case ACT_RET_ERR:
3467 case ACT_RET_CONT:
3468 break;
3469 case ACT_RET_STOP:
3470 rule_ret = HTTP_RULE_RES_STOP;
3471 goto end;
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003472 case ACT_RET_DONE:
3473 rule_ret = HTTP_RULE_RES_DONE;
3474 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003475 case ACT_RET_YIELD:
3476 s->current_rule = rule;
3477 rule_ret = HTTP_RULE_RES_YIELD;
3478 goto end;
3479 }
3480 break;
3481
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003482 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003483 default:
3484 break;
3485 }
3486 }
3487
3488 end:
3489 /* we reached the end of the rules, nothing to report */
3490 return rule_ret;
3491}
3492
Christopher Faulet33640082018-10-24 11:53:01 +02003493/* Iterate the same filter through all request headers.
3494 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3495 * Since it can manage the switch to another backend, it updates the per-proxy
3496 * DENY stats.
3497 */
3498static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3499{
3500 struct http_txn *txn = s->txn;
3501 struct htx *htx;
3502 struct buffer *hdr = get_trash_chunk();
3503 int32_t pos;
3504
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003505 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003506
Christopher Fauleta3f15502019-05-13 15:27:23 +02003507 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003508 struct htx_blk *blk = htx_get_blk(htx, pos);
3509 enum htx_blk_type type;
3510 struct ist n, v;
3511
3512 next_hdr:
3513 type = htx_get_blk_type(blk);
3514 if (type == HTX_BLK_EOH)
3515 break;
3516 if (type != HTX_BLK_HDR)
3517 continue;
3518
3519 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3520 return 1;
3521 else if (unlikely(txn->flags & TX_CLALLOW) &&
3522 (exp->action == ACT_ALLOW ||
3523 exp->action == ACT_DENY ||
3524 exp->action == ACT_TARPIT))
3525 return 0;
3526
3527 n = htx_get_blk_name(htx, blk);
3528 v = htx_get_blk_value(htx, blk);
3529
Christopher Faulet02e771a2019-02-26 15:36:05 +01003530 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003531 hdr->area[hdr->data++] = ':';
3532 hdr->area[hdr->data++] = ' ';
3533 chunk_memcat(hdr, v.ptr, v.len);
3534
3535 /* Now we have one header in <hdr> */
3536
3537 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3538 struct http_hdr_ctx ctx;
3539 int len;
3540
3541 switch (exp->action) {
3542 case ACT_ALLOW:
3543 txn->flags |= TX_CLALLOW;
3544 goto end;
3545
3546 case ACT_DENY:
3547 txn->flags |= TX_CLDENY;
3548 goto end;
3549
3550 case ACT_TARPIT:
3551 txn->flags |= TX_CLTARPIT;
3552 goto end;
3553
3554 case ACT_REPLACE:
3555 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3556 if (len < 0)
3557 return -1;
3558
3559 http_parse_header(ist2(trash.area, len), &n, &v);
3560 ctx.blk = blk;
3561 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003562 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003563 if (!http_replace_header(htx, &ctx, n, v))
3564 return -1;
3565 if (!ctx.blk)
3566 goto end;
3567 pos = htx_get_blk_pos(htx, blk);
3568 break;
3569
3570 case ACT_REMOVE:
3571 ctx.blk = blk;
3572 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003573 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003574 if (!http_remove_header(htx, &ctx))
3575 return -1;
3576 if (!ctx.blk)
3577 goto end;
3578 pos = htx_get_blk_pos(htx, blk);
3579 goto next_hdr;
3580
3581 }
3582 }
3583 }
3584 end:
3585 return 0;
3586}
3587
3588/* Apply the filter to the request line.
3589 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3590 * or -1 if a replacement resulted in an invalid request line.
3591 * Since it can manage the switch to another backend, it updates the per-proxy
3592 * DENY stats.
3593 */
3594static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3595{
3596 struct http_txn *txn = s->txn;
3597 struct htx *htx;
3598 struct buffer *reqline = get_trash_chunk();
3599 int done;
3600
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003601 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003602
3603 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3604 return 1;
3605 else if (unlikely(txn->flags & TX_CLALLOW) &&
3606 (exp->action == ACT_ALLOW ||
3607 exp->action == ACT_DENY ||
3608 exp->action == ACT_TARPIT))
3609 return 0;
3610 else if (exp->action == ACT_REMOVE)
3611 return 0;
3612
3613 done = 0;
3614
Christopher Faulet297fbb42019-05-13 14:41:27 +02003615 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003616
3617 /* Now we have the request line between cur_ptr and cur_end */
3618 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003619 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003620 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003621 int len;
3622
3623 switch (exp->action) {
3624 case ACT_ALLOW:
3625 txn->flags |= TX_CLALLOW;
3626 done = 1;
3627 break;
3628
3629 case ACT_DENY:
3630 txn->flags |= TX_CLDENY;
3631 done = 1;
3632 break;
3633
3634 case ACT_TARPIT:
3635 txn->flags |= TX_CLTARPIT;
3636 done = 1;
3637 break;
3638
3639 case ACT_REPLACE:
3640 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3641 if (len < 0)
3642 return -1;
3643
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003644 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3645 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3646 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003647 return -1;
3648 done = 1;
3649 break;
3650 }
3651 }
3652 return done;
3653}
3654
3655/*
3656 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3657 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3658 * unparsable request. Since it can manage the switch to another backend, it
3659 * updates the per-proxy DENY stats.
3660 */
3661static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3662{
3663 struct session *sess = s->sess;
3664 struct http_txn *txn = s->txn;
3665 struct hdr_exp *exp;
3666
3667 for (exp = px->req_exp; exp; exp = exp->next) {
3668 int ret;
3669
3670 /*
3671 * The interleaving of transformations and verdicts
3672 * makes it difficult to decide to continue or stop
3673 * the evaluation.
3674 */
3675
3676 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3677 break;
3678
3679 if ((txn->flags & TX_CLALLOW) &&
3680 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3681 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3682 continue;
3683
3684 /* if this filter had a condition, evaluate it now and skip to
3685 * next filter if the condition does not match.
3686 */
3687 if (exp->cond) {
3688 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3689 ret = acl_pass(ret);
3690 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3691 ret = !ret;
3692
3693 if (!ret)
3694 continue;
3695 }
3696
3697 /* Apply the filter to the request line. */
3698 ret = htx_apply_filter_to_req_line(s, req, exp);
3699 if (unlikely(ret < 0))
3700 return -1;
3701
3702 if (likely(ret == 0)) {
3703 /* The filter did not match the request, it can be
3704 * iterated through all headers.
3705 */
3706 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3707 return -1;
3708 }
3709 }
3710 return 0;
3711}
3712
3713/* Iterate the same filter through all response headers contained in <res>.
3714 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3715 */
3716static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3717{
3718 struct http_txn *txn = s->txn;
3719 struct htx *htx;
3720 struct buffer *hdr = get_trash_chunk();
3721 int32_t pos;
3722
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003723 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003724
Christopher Fauleta3f15502019-05-13 15:27:23 +02003725 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003726 struct htx_blk *blk = htx_get_blk(htx, pos);
3727 enum htx_blk_type type;
3728 struct ist n, v;
3729
3730 next_hdr:
3731 type = htx_get_blk_type(blk);
3732 if (type == HTX_BLK_EOH)
3733 break;
3734 if (type != HTX_BLK_HDR)
3735 continue;
3736
3737 if (unlikely(txn->flags & TX_SVDENY))
3738 return 1;
3739 else if (unlikely(txn->flags & TX_SVALLOW) &&
3740 (exp->action == ACT_ALLOW ||
3741 exp->action == ACT_DENY))
3742 return 0;
3743
3744 n = htx_get_blk_name(htx, blk);
3745 v = htx_get_blk_value(htx, blk);
3746
Christopher Faulet02e771a2019-02-26 15:36:05 +01003747 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003748 hdr->area[hdr->data++] = ':';
3749 hdr->area[hdr->data++] = ' ';
3750 chunk_memcat(hdr, v.ptr, v.len);
3751
3752 /* Now we have one header in <hdr> */
3753
3754 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3755 struct http_hdr_ctx ctx;
3756 int len;
3757
3758 switch (exp->action) {
3759 case ACT_ALLOW:
3760 txn->flags |= TX_SVALLOW;
3761 goto end;
3762 break;
3763
3764 case ACT_DENY:
3765 txn->flags |= TX_SVDENY;
3766 goto end;
3767 break;
3768
3769 case ACT_REPLACE:
3770 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3771 if (len < 0)
3772 return -1;
3773
3774 http_parse_header(ist2(trash.area, len), &n, &v);
3775 ctx.blk = blk;
3776 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003777 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003778 if (!http_replace_header(htx, &ctx, n, v))
3779 return -1;
3780 if (!ctx.blk)
3781 goto end;
3782 pos = htx_get_blk_pos(htx, blk);
3783 break;
3784
3785 case ACT_REMOVE:
3786 ctx.blk = blk;
3787 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003788 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003789 if (!http_remove_header(htx, &ctx))
3790 return -1;
3791 if (!ctx.blk)
3792 goto end;
3793 pos = htx_get_blk_pos(htx, blk);
3794 goto next_hdr;
3795 }
3796 }
3797
3798 }
3799 end:
3800 return 0;
3801}
3802
3803/* Apply the filter to the status line in the response buffer <res>.
3804 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3805 * or -1 if a replacement resulted in an invalid status line.
3806 */
3807static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3808{
3809 struct http_txn *txn = s->txn;
3810 struct htx *htx;
3811 struct buffer *resline = get_trash_chunk();
3812 int done;
3813
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003814 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003815
3816 if (unlikely(txn->flags & TX_SVDENY))
3817 return 1;
3818 else if (unlikely(txn->flags & TX_SVALLOW) &&
3819 (exp->action == ACT_ALLOW ||
3820 exp->action == ACT_DENY))
3821 return 0;
3822 else if (exp->action == ACT_REMOVE)
3823 return 0;
3824
3825 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003826 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003827
3828 /* Now we have the status line between cur_ptr and cur_end */
3829 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003830 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003831 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003832 int len;
3833
3834 switch (exp->action) {
3835 case ACT_ALLOW:
3836 txn->flags |= TX_SVALLOW;
3837 done = 1;
3838 break;
3839
3840 case ACT_DENY:
3841 txn->flags |= TX_SVDENY;
3842 done = 1;
3843 break;
3844
3845 case ACT_REPLACE:
3846 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3847 if (len < 0)
3848 return -1;
3849
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003850 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3851 sl->info.res.status = strl2ui(code.ptr, code.len);
3852 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003853 return -1;
3854
3855 done = 1;
3856 return 1;
3857 }
3858 }
3859 return done;
3860}
3861
3862/*
3863 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3864 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3865 * unparsable response.
3866 */
3867static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3868{
3869 struct session *sess = s->sess;
3870 struct http_txn *txn = s->txn;
3871 struct hdr_exp *exp;
3872
3873 for (exp = px->rsp_exp; exp; exp = exp->next) {
3874 int ret;
3875
3876 /*
3877 * The interleaving of transformations and verdicts
3878 * makes it difficult to decide to continue or stop
3879 * the evaluation.
3880 */
3881
3882 if (txn->flags & TX_SVDENY)
3883 break;
3884
3885 if ((txn->flags & TX_SVALLOW) &&
3886 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3887 exp->action == ACT_PASS)) {
3888 exp = exp->next;
3889 continue;
3890 }
3891
3892 /* if this filter had a condition, evaluate it now and skip to
3893 * next filter if the condition does not match.
3894 */
3895 if (exp->cond) {
3896 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3897 ret = acl_pass(ret);
3898 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3899 ret = !ret;
3900 if (!ret)
3901 continue;
3902 }
3903
3904 /* Apply the filter to the status line. */
3905 ret = htx_apply_filter_to_sts_line(s, res, exp);
3906 if (unlikely(ret < 0))
3907 return -1;
3908
3909 if (likely(ret == 0)) {
3910 /* The filter did not match the response, it can be
3911 * iterated through all headers.
3912 */
3913 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3914 return -1;
3915 }
3916 }
3917 return 0;
3918}
3919
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003920/*
3921 * Manage client-side cookie. It can impact performance by about 2% so it is
3922 * desirable to call it only when needed. This code is quite complex because
3923 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3924 * highly recommended not to touch this part without a good reason !
3925 */
3926static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3927{
3928 struct session *sess = s->sess;
3929 struct http_txn *txn = s->txn;
3930 struct htx *htx;
3931 struct http_hdr_ctx ctx;
3932 char *hdr_beg, *hdr_end, *del_from;
3933 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3934 int preserve_hdr;
3935
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003936 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003937 ctx.blk = NULL;
3938 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3939 del_from = NULL; /* nothing to be deleted */
3940 preserve_hdr = 0; /* assume we may kill the whole header */
3941
3942 /* Now look for cookies. Conforming to RFC2109, we have to support
3943 * attributes whose name begin with a '$', and associate them with
3944 * the right cookie, if we want to delete this cookie.
3945 * So there are 3 cases for each cookie read :
3946 * 1) it's a special attribute, beginning with a '$' : ignore it.
3947 * 2) it's a server id cookie that we *MAY* want to delete : save
3948 * some pointers on it (last semi-colon, beginning of cookie...)
3949 * 3) it's an application cookie : we *MAY* have to delete a previous
3950 * "special" cookie.
3951 * At the end of loop, if a "special" cookie remains, we may have to
3952 * remove it. If no application cookie persists in the header, we
3953 * *MUST* delete it.
3954 *
3955 * Note: RFC2965 is unclear about the processing of spaces around
3956 * the equal sign in the ATTR=VALUE form. A careful inspection of
3957 * the RFC explicitly allows spaces before it, and not within the
3958 * tokens (attrs or values). An inspection of RFC2109 allows that
3959 * too but section 10.1.3 lets one think that spaces may be allowed
3960 * after the equal sign too, resulting in some (rare) buggy
3961 * implementations trying to do that. So let's do what servers do.
3962 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3963 * allowed quoted strings in values, with any possible character
3964 * after a backslash, including control chars and delimitors, which
3965 * causes parsing to become ambiguous. Browsers also allow spaces
3966 * within values even without quotes.
3967 *
3968 * We have to keep multiple pointers in order to support cookie
3969 * removal at the beginning, middle or end of header without
3970 * corrupting the header. All of these headers are valid :
3971 *
3972 * hdr_beg hdr_end
3973 * | |
3974 * v |
3975 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3976 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3977 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3978 * | | | | | | |
3979 * | | | | | | |
3980 * | | | | | | +--> next
3981 * | | | | | +----> val_end
3982 * | | | | +-----------> val_beg
3983 * | | | +--------------> equal
3984 * | | +----------------> att_end
3985 * | +---------------------> att_beg
3986 * +--------------------------> prev
3987 *
3988 */
3989 hdr_beg = ctx.value.ptr;
3990 hdr_end = hdr_beg + ctx.value.len;
3991 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3992 /* Iterate through all cookies on this line */
3993
3994 /* find att_beg */
3995 att_beg = prev;
3996 if (prev > hdr_beg)
3997 att_beg++;
3998
3999 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4000 att_beg++;
4001
4002 /* find att_end : this is the first character after the last non
4003 * space before the equal. It may be equal to hdr_end.
4004 */
4005 equal = att_end = att_beg;
4006 while (equal < hdr_end) {
4007 if (*equal == '=' || *equal == ',' || *equal == ';')
4008 break;
4009 if (HTTP_IS_SPHT(*equal++))
4010 continue;
4011 att_end = equal;
4012 }
4013
4014 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4015 * is between <att_beg> and <equal>, both may be identical.
4016 */
4017 /* look for end of cookie if there is an equal sign */
4018 if (equal < hdr_end && *equal == '=') {
4019 /* look for the beginning of the value */
4020 val_beg = equal + 1;
4021 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4022 val_beg++;
4023
4024 /* find the end of the value, respecting quotes */
4025 next = http_find_cookie_value_end(val_beg, hdr_end);
4026
4027 /* make val_end point to the first white space or delimitor after the value */
4028 val_end = next;
4029 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4030 val_end--;
4031 }
4032 else
4033 val_beg = val_end = next = equal;
4034
4035 /* We have nothing to do with attributes beginning with
4036 * '$'. However, they will automatically be removed if a
4037 * header before them is removed, since they're supposed
4038 * to be linked together.
4039 */
4040 if (*att_beg == '$')
4041 continue;
4042
4043 /* Ignore cookies with no equal sign */
4044 if (equal == next) {
4045 /* This is not our cookie, so we must preserve it. But if we already
4046 * scheduled another cookie for removal, we cannot remove the
4047 * complete header, but we can remove the previous block itself.
4048 */
4049 preserve_hdr = 1;
4050 if (del_from != NULL) {
4051 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4052 val_end += delta;
4053 next += delta;
4054 hdr_end += delta;
4055 prev = del_from;
4056 del_from = NULL;
4057 }
4058 continue;
4059 }
4060
4061 /* if there are spaces around the equal sign, we need to
4062 * strip them otherwise we'll get trouble for cookie captures,
4063 * or even for rewrites. Since this happens extremely rarely,
4064 * it does not hurt performance.
4065 */
4066 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4067 int stripped_before = 0;
4068 int stripped_after = 0;
4069
4070 if (att_end != equal) {
4071 memmove(att_end, equal, hdr_end - equal);
4072 stripped_before = (att_end - equal);
4073 equal += stripped_before;
4074 val_beg += stripped_before;
4075 }
4076
4077 if (val_beg > equal + 1) {
4078 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4079 stripped_after = (equal + 1) - val_beg;
4080 val_beg += stripped_after;
4081 stripped_before += stripped_after;
4082 }
4083
4084 val_end += stripped_before;
4085 next += stripped_before;
4086 hdr_end += stripped_before;
4087 }
4088 /* now everything is as on the diagram above */
4089
4090 /* First, let's see if we want to capture this cookie. We check
4091 * that we don't already have a client side cookie, because we
4092 * can only capture one. Also as an optimisation, we ignore
4093 * cookies shorter than the declared name.
4094 */
4095 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4096 (val_end - att_beg >= sess->fe->capture_namelen) &&
4097 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4098 int log_len = val_end - att_beg;
4099
4100 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4101 ha_alert("HTTP logging : out of memory.\n");
4102 } else {
4103 if (log_len > sess->fe->capture_len)
4104 log_len = sess->fe->capture_len;
4105 memcpy(txn->cli_cookie, att_beg, log_len);
4106 txn->cli_cookie[log_len] = 0;
4107 }
4108 }
4109
4110 /* Persistence cookies in passive, rewrite or insert mode have the
4111 * following form :
4112 *
4113 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4114 *
4115 * For cookies in prefix mode, the form is :
4116 *
4117 * Cookie: NAME=SRV~VALUE
4118 */
4119 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4120 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4121 struct server *srv = s->be->srv;
4122 char *delim;
4123
4124 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4125 * have the server ID between val_beg and delim, and the original cookie between
4126 * delim+1 and val_end. Otherwise, delim==val_end :
4127 *
4128 * hdr_beg
4129 * |
4130 * v
4131 * NAME=SRV; # in all but prefix modes
4132 * NAME=SRV~OPAQUE ; # in prefix mode
4133 * || || | |+-> next
4134 * || || | +--> val_end
4135 * || || +---------> delim
4136 * || |+------------> val_beg
4137 * || +-------------> att_end = equal
4138 * |+-----------------> att_beg
4139 * +------------------> prev
4140 *
4141 */
4142 if (s->be->ck_opts & PR_CK_PFX) {
4143 for (delim = val_beg; delim < val_end; delim++)
4144 if (*delim == COOKIE_DELIM)
4145 break;
4146 }
4147 else {
4148 char *vbar1;
4149 delim = val_end;
4150 /* Now check if the cookie contains a date field, which would
4151 * appear after a vertical bar ('|') just after the server name
4152 * and before the delimiter.
4153 */
4154 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4155 if (vbar1) {
4156 /* OK, so left of the bar is the server's cookie and
4157 * right is the last seen date. It is a base64 encoded
4158 * 30-bit value representing the UNIX date since the
4159 * epoch in 4-second quantities.
4160 */
4161 int val;
4162 delim = vbar1++;
4163 if (val_end - vbar1 >= 5) {
4164 val = b64tos30(vbar1);
4165 if (val > 0)
4166 txn->cookie_last_date = val << 2;
4167 }
4168 /* look for a second vertical bar */
4169 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4170 if (vbar1 && (val_end - vbar1 > 5)) {
4171 val = b64tos30(vbar1 + 1);
4172 if (val > 0)
4173 txn->cookie_first_date = val << 2;
4174 }
4175 }
4176 }
4177
4178 /* if the cookie has an expiration date and the proxy wants to check
4179 * it, then we do that now. We first check if the cookie is too old,
4180 * then only if it has expired. We detect strict overflow because the
4181 * time resolution here is not great (4 seconds). Cookies with dates
4182 * in the future are ignored if their offset is beyond one day. This
4183 * allows an admin to fix timezone issues without expiring everyone
4184 * and at the same time avoids keeping unwanted side effects for too
4185 * long.
4186 */
4187 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4188 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4189 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4190 txn->flags &= ~TX_CK_MASK;
4191 txn->flags |= TX_CK_OLD;
4192 delim = val_beg; // let's pretend we have not found the cookie
4193 txn->cookie_first_date = 0;
4194 txn->cookie_last_date = 0;
4195 }
4196 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4197 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4198 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4199 txn->flags &= ~TX_CK_MASK;
4200 txn->flags |= TX_CK_EXPIRED;
4201 delim = val_beg; // let's pretend we have not found the cookie
4202 txn->cookie_first_date = 0;
4203 txn->cookie_last_date = 0;
4204 }
4205
4206 /* Here, we'll look for the first running server which supports the cookie.
4207 * This allows to share a same cookie between several servers, for example
4208 * to dedicate backup servers to specific servers only.
4209 * However, to prevent clients from sticking to cookie-less backup server
4210 * when they have incidentely learned an empty cookie, we simply ignore
4211 * empty cookies and mark them as invalid.
4212 * The same behaviour is applied when persistence must be ignored.
4213 */
4214 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4215 srv = NULL;
4216
4217 while (srv) {
4218 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4219 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4220 if ((srv->cur_state != SRV_ST_STOPPED) ||
4221 (s->be->options & PR_O_PERSIST) ||
4222 (s->flags & SF_FORCE_PRST)) {
4223 /* we found the server and we can use it */
4224 txn->flags &= ~TX_CK_MASK;
4225 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4226 s->flags |= SF_DIRECT | SF_ASSIGNED;
4227 s->target = &srv->obj_type;
4228 break;
4229 } else {
4230 /* we found a server, but it's down,
4231 * mark it as such and go on in case
4232 * another one is available.
4233 */
4234 txn->flags &= ~TX_CK_MASK;
4235 txn->flags |= TX_CK_DOWN;
4236 }
4237 }
4238 srv = srv->next;
4239 }
4240
4241 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4242 /* no server matched this cookie or we deliberately skipped it */
4243 txn->flags &= ~TX_CK_MASK;
4244 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4245 txn->flags |= TX_CK_UNUSED;
4246 else
4247 txn->flags |= TX_CK_INVALID;
4248 }
4249
4250 /* depending on the cookie mode, we may have to either :
4251 * - delete the complete cookie if we're in insert+indirect mode, so that
4252 * the server never sees it ;
4253 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004254 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004255 * if we're in cookie prefix mode
4256 */
4257 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4258 int delta; /* negative */
4259
4260 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4261 delta = val_beg - (delim + 1);
4262 val_end += delta;
4263 next += delta;
4264 hdr_end += delta;
4265 del_from = NULL;
4266 preserve_hdr = 1; /* we want to keep this cookie */
4267 }
4268 else if (del_from == NULL &&
4269 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4270 del_from = prev;
4271 }
4272 }
4273 else {
4274 /* This is not our cookie, so we must preserve it. But if we already
4275 * scheduled another cookie for removal, we cannot remove the
4276 * complete header, but we can remove the previous block itself.
4277 */
4278 preserve_hdr = 1;
4279
4280 if (del_from != NULL) {
4281 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4282 if (att_beg >= del_from)
4283 att_beg += delta;
4284 if (att_end >= del_from)
4285 att_end += delta;
4286 val_beg += delta;
4287 val_end += delta;
4288 next += delta;
4289 hdr_end += delta;
4290 prev = del_from;
4291 del_from = NULL;
4292 }
4293 }
4294
4295 /* continue with next cookie on this header line */
4296 att_beg = next;
4297 } /* for each cookie */
4298
4299
4300 /* There are no more cookies on this line.
4301 * We may still have one (or several) marked for deletion at the
4302 * end of the line. We must do this now in two ways :
4303 * - if some cookies must be preserved, we only delete from the
4304 * mark to the end of line ;
4305 * - if nothing needs to be preserved, simply delete the whole header
4306 */
4307 if (del_from) {
4308 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4309 }
4310 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004311 if (hdr_beg != hdr_end)
4312 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004313 else
4314 http_remove_header(htx, &ctx);
4315 }
4316 } /* for each "Cookie header */
4317}
4318
4319/*
4320 * Manage server-side cookies. It can impact performance by about 2% so it is
4321 * desirable to call it only when needed. This function is also used when we
4322 * just need to know if there is a cookie (eg: for check-cache).
4323 */
4324static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4325{
4326 struct session *sess = s->sess;
4327 struct http_txn *txn = s->txn;
4328 struct htx *htx;
4329 struct http_hdr_ctx ctx;
4330 struct server *srv;
4331 char *hdr_beg, *hdr_end;
4332 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004333 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004334
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004335 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004336
4337 ctx.blk = NULL;
4338 while (1) {
4339 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4340 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4341 break;
4342 is_cookie2 = 1;
4343 }
4344
4345 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4346 * <prev> points to the colon.
4347 */
4348 txn->flags |= TX_SCK_PRESENT;
4349
4350 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4351 * check-cache is enabled) and we are not interested in checking
4352 * them. Warning, the cookie capture is declared in the frontend.
4353 */
4354 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4355 break;
4356
4357 /* OK so now we know we have to process this response cookie.
4358 * The format of the Set-Cookie header is slightly different
4359 * from the format of the Cookie header in that it does not
4360 * support the comma as a cookie delimiter (thus the header
4361 * cannot be folded) because the Expires attribute described in
4362 * the original Netscape's spec may contain an unquoted date
4363 * with a comma inside. We have to live with this because
4364 * many browsers don't support Max-Age and some browsers don't
4365 * support quoted strings. However the Set-Cookie2 header is
4366 * clean.
4367 *
4368 * We have to keep multiple pointers in order to support cookie
4369 * removal at the beginning, middle or end of header without
4370 * corrupting the header (in case of set-cookie2). A special
4371 * pointer, <scav> points to the beginning of the set-cookie-av
4372 * fields after the first semi-colon. The <next> pointer points
4373 * either to the end of line (set-cookie) or next unquoted comma
4374 * (set-cookie2). All of these headers are valid :
4375 *
4376 * hdr_beg hdr_end
4377 * | |
4378 * v |
4379 * NAME1 = VALUE 1 ; Secure; Path="/" |
4380 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4381 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4382 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4383 * | | | | | | | |
4384 * | | | | | | | +-> next
4385 * | | | | | | +------------> scav
4386 * | | | | | +--------------> val_end
4387 * | | | | +--------------------> val_beg
4388 * | | | +----------------------> equal
4389 * | | +------------------------> att_end
4390 * | +----------------------------> att_beg
4391 * +------------------------------> prev
4392 * -------------------------------> hdr_beg
4393 */
4394 hdr_beg = ctx.value.ptr;
4395 hdr_end = hdr_beg + ctx.value.len;
4396 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4397
4398 /* Iterate through all cookies on this line */
4399
4400 /* find att_beg */
4401 att_beg = prev;
4402 if (prev > hdr_beg)
4403 att_beg++;
4404
4405 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4406 att_beg++;
4407
4408 /* find att_end : this is the first character after the last non
4409 * space before the equal. It may be equal to hdr_end.
4410 */
4411 equal = att_end = att_beg;
4412
4413 while (equal < hdr_end) {
4414 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4415 break;
4416 if (HTTP_IS_SPHT(*equal++))
4417 continue;
4418 att_end = equal;
4419 }
4420
4421 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4422 * is between <att_beg> and <equal>, both may be identical.
4423 */
4424
4425 /* look for end of cookie if there is an equal sign */
4426 if (equal < hdr_end && *equal == '=') {
4427 /* look for the beginning of the value */
4428 val_beg = equal + 1;
4429 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4430 val_beg++;
4431
4432 /* find the end of the value, respecting quotes */
4433 next = http_find_cookie_value_end(val_beg, hdr_end);
4434
4435 /* make val_end point to the first white space or delimitor after the value */
4436 val_end = next;
4437 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4438 val_end--;
4439 }
4440 else {
4441 /* <equal> points to next comma, semi-colon or EOL */
4442 val_beg = val_end = next = equal;
4443 }
4444
4445 if (next < hdr_end) {
4446 /* Set-Cookie2 supports multiple cookies, and <next> points to
4447 * a colon or semi-colon before the end. So skip all attr-value
4448 * pairs and look for the next comma. For Set-Cookie, since
4449 * commas are permitted in values, skip to the end.
4450 */
4451 if (is_cookie2)
4452 next = http_find_hdr_value_end(next, hdr_end);
4453 else
4454 next = hdr_end;
4455 }
4456
4457 /* Now everything is as on the diagram above */
4458
4459 /* Ignore cookies with no equal sign */
4460 if (equal == val_end)
4461 continue;
4462
4463 /* If there are spaces around the equal sign, we need to
4464 * strip them otherwise we'll get trouble for cookie captures,
4465 * or even for rewrites. Since this happens extremely rarely,
4466 * it does not hurt performance.
4467 */
4468 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4469 int stripped_before = 0;
4470 int stripped_after = 0;
4471
4472 if (att_end != equal) {
4473 memmove(att_end, equal, hdr_end - equal);
4474 stripped_before = (att_end - equal);
4475 equal += stripped_before;
4476 val_beg += stripped_before;
4477 }
4478
4479 if (val_beg > equal + 1) {
4480 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4481 stripped_after = (equal + 1) - val_beg;
4482 val_beg += stripped_after;
4483 stripped_before += stripped_after;
4484 }
4485
4486 val_end += stripped_before;
4487 next += stripped_before;
4488 hdr_end += stripped_before;
4489
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004490 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004491 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004492 }
4493
4494 /* First, let's see if we want to capture this cookie. We check
4495 * that we don't already have a server side cookie, because we
4496 * can only capture one. Also as an optimisation, we ignore
4497 * cookies shorter than the declared name.
4498 */
4499 if (sess->fe->capture_name != NULL &&
4500 txn->srv_cookie == NULL &&
4501 (val_end - att_beg >= sess->fe->capture_namelen) &&
4502 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4503 int log_len = val_end - att_beg;
4504 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4505 ha_alert("HTTP logging : out of memory.\n");
4506 }
4507 else {
4508 if (log_len > sess->fe->capture_len)
4509 log_len = sess->fe->capture_len;
4510 memcpy(txn->srv_cookie, att_beg, log_len);
4511 txn->srv_cookie[log_len] = 0;
4512 }
4513 }
4514
4515 srv = objt_server(s->target);
4516 /* now check if we need to process it for persistence */
4517 if (!(s->flags & SF_IGNORE_PRST) &&
4518 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4519 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4520 /* assume passive cookie by default */
4521 txn->flags &= ~TX_SCK_MASK;
4522 txn->flags |= TX_SCK_FOUND;
4523
4524 /* If the cookie is in insert mode on a known server, we'll delete
4525 * this occurrence because we'll insert another one later.
4526 * We'll delete it too if the "indirect" option is set and we're in
4527 * a direct access.
4528 */
4529 if (s->be->ck_opts & PR_CK_PSV) {
4530 /* The "preserve" flag was set, we don't want to touch the
4531 * server's cookie.
4532 */
4533 }
4534 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4535 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4536 /* this cookie must be deleted */
4537 if (prev == hdr_beg && next == hdr_end) {
4538 /* whole header */
4539 http_remove_header(htx, &ctx);
4540 /* note: while both invalid now, <next> and <hdr_end>
4541 * are still equal, so the for() will stop as expected.
4542 */
4543 } else {
4544 /* just remove the value */
4545 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4546 next = prev;
4547 hdr_end += delta;
4548 }
4549 txn->flags &= ~TX_SCK_MASK;
4550 txn->flags |= TX_SCK_DELETED;
4551 /* and go on with next cookie */
4552 }
4553 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4554 /* replace bytes val_beg->val_end with the cookie name associated
4555 * with this server since we know it.
4556 */
4557 int sliding, delta;
4558
4559 ctx.value = ist2(val_beg, val_end - val_beg);
4560 ctx.lws_before = ctx.lws_after = 0;
4561 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4562 delta = srv->cklen - (val_end - val_beg);
4563 sliding = (ctx.value.ptr - val_beg);
4564 hdr_beg += sliding;
4565 val_beg += sliding;
4566 next += sliding + delta;
4567 hdr_end += sliding + delta;
4568
4569 txn->flags &= ~TX_SCK_MASK;
4570 txn->flags |= TX_SCK_REPLACED;
4571 }
4572 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4573 /* insert the cookie name associated with this server
4574 * before existing cookie, and insert a delimiter between them..
4575 */
4576 int sliding, delta;
4577 ctx.value = ist2(val_beg, 0);
4578 ctx.lws_before = ctx.lws_after = 0;
4579 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4580 delta = srv->cklen + 1;
4581 sliding = (ctx.value.ptr - val_beg);
4582 hdr_beg += sliding;
4583 val_beg += sliding;
4584 next += sliding + delta;
4585 hdr_end += sliding + delta;
4586
4587 val_beg[srv->cklen] = COOKIE_DELIM;
4588 txn->flags &= ~TX_SCK_MASK;
4589 txn->flags |= TX_SCK_REPLACED;
4590 }
4591 }
4592 /* that's done for this cookie, check the next one on the same
4593 * line when next != hdr_end (only if is_cookie2).
4594 */
4595 }
4596 }
4597}
4598
Christopher Faulet25a02f62018-10-24 12:00:25 +02004599/*
4600 * Parses the Cache-Control and Pragma request header fields to determine if
4601 * the request may be served from the cache and/or if it is cacheable. Updates
4602 * s->txn->flags.
4603 */
4604void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4605{
4606 struct http_txn *txn = s->txn;
4607 struct htx *htx;
4608 int32_t pos;
4609 int pragma_found, cc_found, i;
4610
4611 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4612 return; /* nothing more to do here */
4613
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004614 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004615 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004616 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004617 struct htx_blk *blk = htx_get_blk(htx, pos);
4618 enum htx_blk_type type = htx_get_blk_type(blk);
4619 struct ist n, v;
4620
4621 if (type == HTX_BLK_EOH)
4622 break;
4623 if (type != HTX_BLK_HDR)
4624 continue;
4625
4626 n = htx_get_blk_name(htx, blk);
4627 v = htx_get_blk_value(htx, blk);
4628
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004629 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004630 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4631 pragma_found = 1;
4632 continue;
4633 }
4634 }
4635
4636 /* Don't use the cache and don't try to store if we found the
4637 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004638 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004639 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4640 txn->flags |= TX_CACHE_IGNORE;
4641 continue;
4642 }
4643
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 continue;
4646
4647 /* OK, right now we know we have a cache-control header */
4648 cc_found = 1;
4649 if (!v.len) /* no info */
4650 continue;
4651
4652 i = 0;
4653 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4654 !isspace((unsigned char)*(v.ptr+i)))
4655 i++;
4656
4657 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4658 * values after max-age, max-stale nor min-fresh, we simply don't
4659 * use the cache when they're specified.
4660 */
4661 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4662 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4663 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4664 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4665 txn->flags |= TX_CACHE_IGNORE;
4666 continue;
4667 }
4668
4669 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4670 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4671 continue;
4672 }
4673 }
4674
4675 /* RFC7234#5.4:
4676 * When the Cache-Control header field is also present and
4677 * understood in a request, Pragma is ignored.
4678 * When the Cache-Control header field is not present in a
4679 * request, caches MUST consider the no-cache request
4680 * pragma-directive as having the same effect as if
4681 * "Cache-Control: no-cache" were present.
4682 */
4683 if (!cc_found && pragma_found)
4684 txn->flags |= TX_CACHE_IGNORE;
4685}
4686
4687/*
4688 * Check if response is cacheable or not. Updates s->txn->flags.
4689 */
4690void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4691{
4692 struct http_txn *txn = s->txn;
4693 struct htx *htx;
4694 int32_t pos;
4695 int i;
4696
4697 if (txn->status < 200) {
4698 /* do not try to cache interim responses! */
4699 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4700 return;
4701 }
4702
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004703 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004704 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004705 struct htx_blk *blk = htx_get_blk(htx, pos);
4706 enum htx_blk_type type = htx_get_blk_type(blk);
4707 struct ist n, v;
4708
4709 if (type == HTX_BLK_EOH)
4710 break;
4711 if (type != HTX_BLK_HDR)
4712 continue;
4713
4714 n = htx_get_blk_name(htx, blk);
4715 v = htx_get_blk_value(htx, blk);
4716
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004717 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004718 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4719 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4720 return;
4721 }
4722 }
4723
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004724 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004725 continue;
4726
4727 /* OK, right now we know we have a cache-control header */
4728 if (!v.len) /* no info */
4729 continue;
4730
4731 i = 0;
4732 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4733 !isspace((unsigned char)*(v.ptr+i)))
4734 i++;
4735
4736 /* we have a complete value between v.ptr and (v.ptr+i) */
4737 if (i < v.len && *(v.ptr + i) == '=') {
4738 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4739 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4740 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4741 continue;
4742 }
4743
4744 /* we have something of the form no-cache="set-cookie" */
4745 if ((v.len >= 21) &&
4746 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4747 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4748 txn->flags &= ~TX_CACHE_COOK;
4749 continue;
4750 }
4751
4752 /* OK, so we know that either p2 points to the end of string or to a comma */
4753 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4754 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4755 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4756 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4757 return;
4758 }
4759
4760 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4761 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4762 continue;
4763 }
4764 }
4765}
4766
Christopher Faulet64159df2018-10-24 21:15:35 +02004767/* send a server's name with an outgoing request over an established connection.
4768 * Note: this function is designed to be called once the request has been
4769 * scheduled for being forwarded. This is the reason why the number of forwarded
4770 * bytes have to be adjusted.
4771 */
4772int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4773{
4774 struct htx *htx;
4775 struct http_hdr_ctx ctx;
4776 struct ist hdr;
4777 uint32_t data;
4778
4779 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004780 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004781 data = htx->data;
4782
4783 ctx.blk = NULL;
4784 while (http_find_header(htx, hdr, &ctx, 1))
4785 http_remove_header(htx, &ctx);
4786 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4787
4788 if (co_data(&s->req)) {
4789 if (data >= htx->data)
4790 c_rew(&s->req, data - htx->data);
4791 else
4792 c_adv(&s->req, htx->data - data);
4793 }
4794 return 0;
4795}
4796
Christopher Faulet377c5a52018-10-24 21:21:30 +02004797/*
4798 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4799 * for the current backend.
4800 *
4801 * It is assumed that the request is either a HEAD, GET, or POST and that the
4802 * uri_auth field is valid.
4803 *
4804 * Returns 1 if stats should be provided, otherwise 0.
4805 */
4806static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4807{
4808 struct uri_auth *uri_auth = backend->uri_auth;
4809 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004810 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004811 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812
4813 if (!uri_auth)
4814 return 0;
4815
4816 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4817 return 0;
4818
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004819 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004820 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004821 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004822
4823 /* check URI size */
4824 if (uri_auth->uri_len > uri.len)
4825 return 0;
4826
4827 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4828 return 0;
4829
4830 return 1;
4831}
4832
4833/* This function prepares an applet to handle the stats. It can deal with the
4834 * "100-continue" expectation, check that admin rules are met for POST requests,
4835 * and program a response message if something was unexpected. It cannot fail
4836 * and always relies on the stats applet to complete the job. It does not touch
4837 * analysers nor counters, which are left to the caller. It does not touch
4838 * s->target which is supposed to already point to the stats applet. The caller
4839 * is expected to have already assigned an appctx to the stream.
4840 */
4841static int htx_handle_stats(struct stream *s, struct channel *req)
4842{
4843 struct stats_admin_rule *stats_admin_rule;
4844 struct stream_interface *si = &s->si[1];
4845 struct session *sess = s->sess;
4846 struct http_txn *txn = s->txn;
4847 struct http_msg *msg = &txn->req;
4848 struct uri_auth *uri_auth = s->be->uri_auth;
4849 const char *h, *lookup, *end;
4850 struct appctx *appctx;
4851 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004852 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004853
4854 appctx = si_appctx(si);
4855 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4856 appctx->st1 = appctx->st2 = 0;
4857 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4858 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4859 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4860 appctx->ctx.stats.flags |= STAT_CHUNKED;
4861
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004862 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004863 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004864 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4865 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004866
4867 for (h = lookup; h <= end - 3; h++) {
4868 if (memcmp(h, ";up", 3) == 0) {
4869 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4870 break;
4871 }
4872 }
4873
4874 if (uri_auth->refresh) {
4875 for (h = lookup; h <= end - 10; h++) {
4876 if (memcmp(h, ";norefresh", 10) == 0) {
4877 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4878 break;
4879 }
4880 }
4881 }
4882
4883 for (h = lookup; h <= end - 4; h++) {
4884 if (memcmp(h, ";csv", 4) == 0) {
4885 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4886 break;
4887 }
4888 }
4889
4890 for (h = lookup; h <= end - 6; h++) {
4891 if (memcmp(h, ";typed", 6) == 0) {
4892 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4893 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4894 break;
4895 }
4896 }
4897
4898 for (h = lookup; h <= end - 8; h++) {
4899 if (memcmp(h, ";st=", 4) == 0) {
4900 int i;
4901 h += 4;
4902 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4903 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4904 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4905 appctx->ctx.stats.st_code = i;
4906 break;
4907 }
4908 }
4909 break;
4910 }
4911 }
4912
4913 appctx->ctx.stats.scope_str = 0;
4914 appctx->ctx.stats.scope_len = 0;
4915 for (h = lookup; h <= end - 8; h++) {
4916 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4917 int itx = 0;
4918 const char *h2;
4919 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4920 const char *err;
4921
4922 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4923 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004924 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4925 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004926 if (*h == ';' || *h == '&' || *h == ' ')
4927 break;
4928 itx++;
4929 h++;
4930 }
4931
4932 if (itx > STAT_SCOPE_TXT_MAXLEN)
4933 itx = STAT_SCOPE_TXT_MAXLEN;
4934 appctx->ctx.stats.scope_len = itx;
4935
4936 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4937 memcpy(scope_txt, h2, itx);
4938 scope_txt[itx] = '\0';
4939 err = invalid_char(scope_txt);
4940 if (err) {
4941 /* bad char in search text => clear scope */
4942 appctx->ctx.stats.scope_str = 0;
4943 appctx->ctx.stats.scope_len = 0;
4944 }
4945 break;
4946 }
4947 }
4948
4949 /* now check whether we have some admin rules for this request */
4950 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4951 int ret = 1;
4952
4953 if (stats_admin_rule->cond) {
4954 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4955 ret = acl_pass(ret);
4956 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4957 ret = !ret;
4958 }
4959
4960 if (ret) {
4961 /* no rule, or the rule matches */
4962 appctx->ctx.stats.flags |= STAT_ADMIN;
4963 break;
4964 }
4965 }
4966
Christopher Faulet5d45e382019-02-27 15:15:23 +01004967 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4968 appctx->st0 = STAT_HTTP_HEAD;
4969 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004970 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004971 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004972 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004973 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004974 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4975 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4976 appctx->st0 = STAT_HTTP_LAST;
4977 }
4978 }
4979 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004980 /* Unsupported method */
4981 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4982 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4983 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004984 }
4985
4986 s->task->nice = -32; /* small boost for HTTP statistics */
4987 return 1;
4988}
4989
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4991{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004992 struct channel *req = &s->req;
4993 struct channel *res = &s->res;
4994 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004996 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 struct ist path, location;
4998 unsigned int flags;
4999 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005000
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 /*
5002 * Create the location
5003 */
5004 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005006 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007 /* special prefix "/" means don't change URL */
5008 srv = __objt_server(s->target);
5009 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5010 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5011 return;
5012 }
5013
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005014 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005015 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005016 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005017 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005018 if (!path.ptr)
5019 return;
5020
5021 if (!chunk_memcat(&trash, path.ptr, path.len))
5022 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005023 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 /*
5026 * Create the 302 respone
5027 */
5028 htx = htx_from_buf(&res->buf);
5029 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5030 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5031 ist("HTTP/1.1"), ist("302"), ist("Found"));
5032 if (!sl)
5033 goto fail;
5034 sl->info.res.status = 302;
5035 s->txn->status = 302;
5036
5037 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5038 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5039 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5040 !htx_add_header(htx, ist("Location"), location))
5041 goto fail;
5042
5043 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5044 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005046 /*
5047 * Send the message
5048 */
5049 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 c_adv(res, data);
5051 res->total += data;
5052
5053 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005054 si_shutr(si);
5055 si_shutw(si);
5056 si->err_type = SI_ET_NONE;
5057 si->state = SI_ST_CLO;
5058
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005059 channel_auto_read(req);
5060 channel_abort(req);
5061 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005062 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 channel_auto_read(res);
5064 channel_auto_close(res);
5065
5066 if (!(s->flags & SF_ERR_MASK))
5067 s->flags |= SF_ERR_LOCAL;
5068 if (!(s->flags & SF_FINST_MASK))
5069 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005070
5071 /* FIXME: we should increase a counter of redirects per server and per backend. */
5072 srv_inc_sess_ctr(srv);
5073 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005074 return;
5075
5076 fail:
5077 /* If an error occurred, remove the incomplete HTTP response from the
5078 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005079 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005080}
5081
Christopher Fauletf2824e62018-10-01 12:12:37 +02005082/* This function terminates the request because it was completly analyzed or
5083 * because an error was triggered during the body forwarding.
5084 */
5085static void htx_end_request(struct stream *s)
5086{
5087 struct channel *chn = &s->req;
5088 struct http_txn *txn = s->txn;
5089
5090 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5091 now_ms, __FUNCTION__, s,
5092 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5093 s->req.analysers, s->res.analysers);
5094
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005095 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5096 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005097 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005098 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 goto end;
5100 }
5101
5102 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5103 return;
5104
5105 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005106 /* No need to read anymore, the request was completely parsed.
5107 * We can shut the read side unless we want to abort_on_close,
5108 * or we have a POST request. The issue with POST requests is
5109 * that some browsers still send a CRLF after the request, and
5110 * this CRLF must be read so that it does not remain in the kernel
5111 * buffers, otherwise a close could cause an RST on some systems
5112 * (eg: Linux).
5113 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005114 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 channel_dont_read(chn);
5116
5117 /* if the server closes the connection, we want to immediately react
5118 * and close the socket to save packets and syscalls.
5119 */
5120 s->si[1].flags |= SI_FL_NOHALF;
5121
5122 /* In any case we've finished parsing the request so we must
5123 * disable Nagle when sending data because 1) we're not going
5124 * to shut this side, and 2) the server is waiting for us to
5125 * send pending data.
5126 */
5127 chn->flags |= CF_NEVER_WAIT;
5128
Christopher Fauletd01ce402019-01-02 17:44:13 +01005129 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5130 /* The server has not finished to respond, so we
5131 * don't want to move in order not to upset it.
5132 */
5133 return;
5134 }
5135
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136 /* When we get here, it means that both the request and the
5137 * response have finished receiving. Depending on the connection
5138 * mode, we'll have to wait for the last bytes to leave in either
5139 * direction, and sometimes for a close to be effective.
5140 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02005141 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005142 /* Tunnel mode will not have any analyser so it needs to
5143 * poll for reads.
5144 */
5145 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005146 if (b_data(&chn->buf))
5147 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005148 txn->req.msg_state = HTTP_MSG_TUNNEL;
5149 }
5150 else {
5151 /* we're not expecting any new data to come for this
5152 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005153 *
5154 * However, there is an exception if the response
5155 * length is undefined. In this case, we need to wait
5156 * the close from the server. The response will be
5157 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005158 */
5159 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5160 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005161 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162
5163 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5164 channel_shutr_now(chn);
5165 channel_shutw_now(chn);
5166 }
5167 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168 goto check_channel_flags;
5169 }
5170
5171 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5172 http_msg_closing:
5173 /* nothing else to forward, just waiting for the output buffer
5174 * to be empty and for the shutw_now to take effect.
5175 */
5176 if (channel_is_empty(chn)) {
5177 txn->req.msg_state = HTTP_MSG_CLOSED;
5178 goto http_msg_closed;
5179 }
5180 else if (chn->flags & CF_SHUTW) {
5181 txn->req.err_state = txn->req.msg_state;
5182 txn->req.msg_state = HTTP_MSG_ERROR;
5183 goto end;
5184 }
5185 return;
5186 }
5187
5188 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5189 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005190 /* if we don't know whether the server will close, we need to hard close */
5191 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5192 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005193 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005194 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 channel_dont_read(chn);
5196 goto end;
5197 }
5198
5199 check_channel_flags:
5200 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5201 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5202 /* if we've just closed an output, let's switch */
5203 txn->req.msg_state = HTTP_MSG_CLOSING;
5204 goto http_msg_closing;
5205 }
5206
5207 end:
5208 chn->analysers &= AN_REQ_FLT_END;
5209 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5210 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5211 channel_auto_close(chn);
5212 channel_auto_read(chn);
5213}
5214
5215
5216/* This function terminates the response because it was completly analyzed or
5217 * because an error was triggered during the body forwarding.
5218 */
5219static void htx_end_response(struct stream *s)
5220{
5221 struct channel *chn = &s->res;
5222 struct http_txn *txn = s->txn;
5223
5224 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5225 now_ms, __FUNCTION__, s,
5226 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5227 s->req.analysers, s->res.analysers);
5228
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005229 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5230 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005231 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005232 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 goto end;
5234 }
5235
5236 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5237 return;
5238
5239 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5240 /* In theory, we don't need to read anymore, but we must
5241 * still monitor the server connection for a possible close
5242 * while the request is being uploaded, so we don't disable
5243 * reading.
5244 */
5245 /* channel_dont_read(chn); */
5246
5247 if (txn->req.msg_state < HTTP_MSG_DONE) {
5248 /* The client seems to still be sending data, probably
5249 * because we got an error response during an upload.
5250 * We have the choice of either breaking the connection
5251 * or letting it pass through. Let's do the later.
5252 */
5253 return;
5254 }
5255
5256 /* When we get here, it means that both the request and the
5257 * response have finished receiving. Depending on the connection
5258 * mode, we'll have to wait for the last bytes to leave in either
5259 * direction, and sometimes for a close to be effective.
5260 */
Christopher Fauletc41547b2019-07-16 14:32:23 +02005261 if (txn->flags & TX_CON_WANT_TUN) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005262 channel_auto_read(chn);
5263 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005264 if (b_data(&chn->buf))
5265 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005266 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5267 }
5268 else {
5269 /* we're not expecting any new data to come for this
5270 * transaction, so we can close it.
5271 */
5272 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5273 channel_shutr_now(chn);
5274 channel_shutw_now(chn);
5275 }
5276 }
5277 goto check_channel_flags;
5278 }
5279
5280 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5281 http_msg_closing:
5282 /* nothing else to forward, just waiting for the output buffer
5283 * to be empty and for the shutw_now to take effect.
5284 */
5285 if (channel_is_empty(chn)) {
5286 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5287 goto http_msg_closed;
5288 }
5289 else if (chn->flags & CF_SHUTW) {
5290 txn->rsp.err_state = txn->rsp.msg_state;
5291 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005292 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005293 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005294 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005295 goto end;
5296 }
5297 return;
5298 }
5299
5300 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5301 http_msg_closed:
5302 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005303 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005304 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005305 goto end;
5306 }
5307
5308 check_channel_flags:
5309 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5310 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5311 /* if we've just closed an output, let's switch */
5312 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5313 goto http_msg_closing;
5314 }
5315
5316 end:
5317 chn->analysers &= AN_RES_FLT_END;
5318 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5319 chn->analysers |= AN_RES_FLT_XFER_DATA;
5320 channel_auto_close(chn);
5321 channel_auto_read(chn);
5322}
5323
Christopher Faulet0f226952018-10-22 09:29:56 +02005324void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5325 int finst, const struct buffer *msg)
5326{
5327 channel_auto_read(si_oc(si));
5328 channel_abort(si_oc(si));
5329 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005330 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005331 channel_auto_close(si_ic(si));
5332 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005333
5334 /* <msg> is an HTX structure. So we copy it in the response's
5335 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005336 if (msg) {
5337 struct channel *chn = si_ic(si);
5338 struct htx *htx;
5339
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005340 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005341 chn->buf.data = msg->data;
5342 memcpy(chn->buf.area, msg->area, msg->data);
5343 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005344 c_adv(chn, htx->data);
5345 chn->total += htx->data;
5346 }
5347 if (!(s->flags & SF_ERR_MASK))
5348 s->flags |= err;
5349 if (!(s->flags & SF_FINST_MASK))
5350 s->flags |= finst;
5351}
5352
5353void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5354{
5355 channel_auto_read(&s->req);
5356 channel_abort(&s->req);
5357 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005358 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5359 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005360
5361 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005362
5363 /* <msg> is an HTX structure. So we copy it in the response's
5364 * channel */
5365 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005366 if (msg) {
5367 struct channel *chn = &s->res;
5368 struct htx *htx;
5369
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005370 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005371 chn->buf.data = msg->data;
5372 memcpy(chn->buf.area, msg->area, msg->data);
5373 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005374 c_adv(chn, htx->data);
5375 chn->total += htx->data;
5376 }
5377
5378 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5379 channel_auto_read(&s->res);
5380 channel_auto_close(&s->res);
5381 channel_shutr_now(&s->res);
5382}
5383
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005384struct buffer *htx_error_message(struct stream *s)
5385{
5386 const int msgnum = http_get_status_idx(s->txn->status);
5387
5388 if (s->be->errmsg[msgnum].area)
5389 return &s->be->errmsg[msgnum];
5390 else if (strm_fe(s)->errmsg[msgnum].area)
5391 return &strm_fe(s)->errmsg[msgnum];
5392 else
5393 return &htx_err_chunks[msgnum];
5394}
5395
Christopher Faulet304cc402019-07-15 15:46:28 +02005396/* Return the error message corresponding to si->err_type. It is assumed
5397 * that the server side is closed. Note that err_type is actually a
5398 * bitmask, where almost only aborts may be cumulated with other
5399 * values. We consider that aborted operations are more important
5400 * than timeouts or errors due to the fact that nobody else in the
5401 * logs might explain incomplete retries. All others should avoid
5402 * being cumulated. It should normally not be possible to have multiple
5403 * aborts at once, but just in case, the first one in sequence is reported.
5404 * Note that connection errors appearing on the second request of a keep-alive
5405 * connection are not reported since this allows the client to retry.
5406 */
5407void htx_return_srv_error(struct stream *s, struct stream_interface *si)
5408{
5409 int err_type = si->err_type;
5410
5411 /* set s->txn->status for http_error_message(s) */
5412 s->txn->status = 503;
5413
5414 if (err_type & SI_ET_QUEUE_ABRT)
5415 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
5416 htx_error_message(s));
5417 else if (err_type & SI_ET_CONN_ABRT)
5418 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
5419 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5420 htx_error_message(s));
5421 else if (err_type & SI_ET_QUEUE_TO)
5422 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
5423 htx_error_message(s));
5424 else if (err_type & SI_ET_QUEUE_ERR)
5425 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
5426 htx_error_message(s));
5427 else if (err_type & SI_ET_CONN_TO)
5428 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
5429 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5430 htx_error_message(s));
5431 else if (err_type & SI_ET_CONN_ERR)
5432 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
5433 (s->flags & SF_SRV_REUSED) ? NULL :
5434 htx_error_message(s));
5435 else if (err_type & SI_ET_CONN_RES)
5436 htx_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
5437 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5438 htx_error_message(s));
5439 else { /* SI_ET_CONN_OTHER and others */
5440 s->txn->status = 500;
5441 htx_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
5442 htx_error_message(s));
5443 }
5444}
5445
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005446
Christopher Faulet4a28a532019-03-01 11:19:40 +01005447/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5448 * on success and -1 on error.
5449 */
5450static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5451{
5452 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5453 * then we must send an HTTP/1.1 100 Continue intermediate response.
5454 */
5455 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5456 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5457 struct ist hdr = { .ptr = "Expect", .len = 6 };
5458 struct http_hdr_ctx ctx;
5459
5460 ctx.blk = NULL;
5461 /* Expect is allowed in 1.1, look for it */
5462 if (http_find_header(htx, hdr, &ctx, 0) &&
5463 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5464 if (htx_reply_100_continue(s) == -1)
5465 return -1;
5466 http_remove_header(htx, &ctx);
5467 }
5468 }
5469 return 0;
5470}
5471
Christopher Faulet23a3c792018-11-28 10:01:23 +01005472/* Send a 100-Continue response to the client. It returns 0 on success and -1
5473 * on error. The response channel is updated accordingly.
5474 */
5475static int htx_reply_100_continue(struct stream *s)
5476{
5477 struct channel *res = &s->res;
5478 struct htx *htx = htx_from_buf(&res->buf);
5479 struct htx_sl *sl;
5480 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5481 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5482 size_t data;
5483
5484 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5485 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5486 if (!sl)
5487 goto fail;
5488 sl->info.res.status = 100;
5489
Christopher Faulet1d5ec092019-06-26 14:23:54 +02005490 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005491 goto fail;
5492
5493 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005494 c_adv(res, data);
5495 res->total += data;
5496 return 0;
5497
5498 fail:
5499 /* If an error occurred, remove the incomplete HTTP response from the
5500 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005501 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005502 return -1;
5503}
5504
Christopher Faulet12c51e22018-11-28 15:59:42 +01005505
5506/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5507 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5508 * error. The response channel is updated accordingly.
5509 */
5510static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5511{
5512 struct channel *res = &s->res;
5513 struct htx *htx = htx_from_buf(&res->buf);
5514 struct htx_sl *sl;
5515 struct ist code, body;
5516 int status;
5517 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5518 size_t data;
5519
5520 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5521 status = 401;
5522 code = ist("401");
5523 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5524 "You need a valid user and password to access this content.\n"
5525 "</body></html>\n");
5526 }
5527 else {
5528 status = 407;
5529 code = ist("407");
5530 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5531 "You need a valid user and password to access this content.\n"
5532 "</body></html>\n");
5533 }
5534
5535 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5536 ist("HTTP/1.1"), code, ist("Unauthorized"));
5537 if (!sl)
5538 goto fail;
5539 sl->info.res.status = status;
5540 s->txn->status = status;
5541
5542 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5543 goto fail;
5544
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005545 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5546 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005547 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005548 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5549 goto fail;
5550 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5551 goto fail;
5552 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005553 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005554 if (!htx_add_endof(htx, HTX_BLK_EOH))
5555 goto fail;
5556
5557 while (body.len) {
5558 size_t sent = htx_add_data(htx, body);
5559 if (!sent)
5560 goto fail;
5561 body.ptr += sent;
5562 body.len -= sent;
5563 }
5564
5565 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005566 goto fail;
5567
5568 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005569 c_adv(res, data);
5570 res->total += data;
5571
5572 channel_auto_read(&s->req);
5573 channel_abort(&s->req);
5574 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005575 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005576
5577 res->wex = tick_add_ifset(now_ms, res->wto);
5578 channel_auto_read(res);
5579 channel_auto_close(res);
5580 channel_shutr_now(res);
5581 return 0;
5582
5583 fail:
5584 /* If an error occurred, remove the incomplete HTTP response from the
5585 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005586 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005587 return -1;
5588}
5589
Christopher Faulet0f226952018-10-22 09:29:56 +02005590/*
5591 * Capture headers from message <htx> according to header list <cap_hdr>, and
5592 * fill the <cap> pointers appropriately.
5593 */
5594static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5595{
5596 struct cap_hdr *h;
5597 int32_t pos;
5598
Christopher Fauleta3f15502019-05-13 15:27:23 +02005599 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005600 struct htx_blk *blk = htx_get_blk(htx, pos);
5601 enum htx_blk_type type = htx_get_blk_type(blk);
5602 struct ist n, v;
5603
5604 if (type == HTX_BLK_EOH)
5605 break;
5606 if (type != HTX_BLK_HDR)
5607 continue;
5608
5609 n = htx_get_blk_name(htx, blk);
5610
5611 for (h = cap_hdr; h; h = h->next) {
5612 if (h->namelen && (h->namelen == n.len) &&
5613 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5614 if (cap[h->index] == NULL)
5615 cap[h->index] =
5616 pool_alloc(h->pool);
5617
5618 if (cap[h->index] == NULL) {
5619 ha_alert("HTTP capture : out of memory.\n");
5620 break;
5621 }
5622
5623 v = htx_get_blk_value(htx, blk);
5624 if (v.len > h->len)
5625 v.len = h->len;
5626
5627 memcpy(cap[h->index], v.ptr, v.len);
5628 cap[h->index][v.len]=0;
5629 }
5630 }
5631 }
5632}
5633
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005634/* Delete a value in a header between delimiters <from> and <next>. The header
5635 * itself is delimited by <start> and <end> pointers. The number of characters
5636 * displaced is returned, and the pointer to the first delimiter is updated if
5637 * required. The function tries as much as possible to respect the following
5638 * principles :
5639 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5640 * in which case <next> is simply removed
5641 * - set exactly one space character after the new first delimiter, unless there
5642 * are not enough characters in the block being moved to do so.
5643 * - remove unneeded spaces before the previous delimiter and after the new
5644 * one.
5645 *
5646 * It is the caller's responsibility to ensure that :
5647 * - <from> points to a valid delimiter or <start> ;
5648 * - <next> points to a valid delimiter or <end> ;
5649 * - there are non-space chars before <from>.
5650 */
5651static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5652{
5653 char *prev = *from;
5654
5655 if (prev == start) {
5656 /* We're removing the first value. eat the semicolon, if <next>
5657 * is lower than <end> */
5658 if (next < end)
5659 next++;
5660
5661 while (next < end && HTTP_IS_SPHT(*next))
5662 next++;
5663 }
5664 else {
5665 /* Remove useless spaces before the old delimiter. */
5666 while (HTTP_IS_SPHT(*(prev-1)))
5667 prev--;
5668 *from = prev;
5669
5670 /* copy the delimiter and if possible a space if we're
5671 * not at the end of the line.
5672 */
5673 if (next < end) {
5674 *prev++ = *next++;
5675 if (prev + 1 < next)
5676 *prev++ = ' ';
5677 while (next < end && HTTP_IS_SPHT(*next))
5678 next++;
5679 }
5680 }
5681 memmove(prev, next, end - next);
5682 return (prev - next);
5683}
5684
Christopher Faulet0f226952018-10-22 09:29:56 +02005685
5686/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005687 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005688 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005689static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005690{
5691 struct ist dst = ist2(str, 0);
5692
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005693 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005694 goto end;
5695 if (dst.len + 1 > len)
5696 goto end;
5697 dst.ptr[dst.len++] = ' ';
5698
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 goto end;
5701 if (dst.len + 1 > len)
5702 goto end;
5703 dst.ptr[dst.len++] = ' ';
5704
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005705 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005706 end:
5707 return dst.len;
5708}
5709
Christopher Fauletf0523542018-10-24 11:06:58 +02005710/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005711 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005712 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005713static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005714{
5715 struct ist dst = ist2(str, 0);
5716
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005717 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005718 goto end;
5719 if (dst.len + 1 > len)
5720 goto end;
5721 dst.ptr[dst.len++] = ' ';
5722
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005723 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005724 goto end;
5725 if (dst.len + 1 > len)
5726 goto end;
5727 dst.ptr[dst.len++] = ' ';
5728
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005729 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005730 end:
5731 return dst.len;
5732}
5733
5734
Christopher Faulet0f226952018-10-22 09:29:56 +02005735/*
5736 * Print a debug line with a start line.
5737 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005738static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005739{
5740 struct session *sess = strm_sess(s);
5741 int max;
5742
5743 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5744 dir,
5745 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5746 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5747
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005748 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005749 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005750 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005751 trash.area[trash.data++] = ' ';
5752
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005753 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005754 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005755 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005756 trash.area[trash.data++] = ' ';
5757
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005758 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005759 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005760 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005761 trash.area[trash.data++] = '\n';
5762
5763 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5764}
5765
5766/*
5767 * Print a debug line with a header.
5768 */
5769static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5770{
5771 struct session *sess = strm_sess(s);
5772 int max;
5773
5774 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5775 dir,
5776 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5777 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5778
5779 max = n.len;
5780 UBOUND(max, trash.size - trash.data - 3);
5781 chunk_memcat(&trash, n.ptr, max);
5782 trash.area[trash.data++] = ':';
5783 trash.area[trash.data++] = ' ';
5784
5785 max = v.len;
5786 UBOUND(max, trash.size - trash.data - 1);
5787 chunk_memcat(&trash, v.ptr, max);
5788 trash.area[trash.data++] = '\n';
5789
5790 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5791}
5792
5793
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005794__attribute__((constructor))
5795static void __htx_protocol_init(void)
5796{
5797}
5798
5799
5800/*
5801 * Local variables:
5802 * c-indent-level: 8
5803 * c-basic-offset: 8
5804 * End:
5805 */