blob: 35172696b641d304c1fee9be393d7ac9bfc44da2 [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 Faulet03b9d8b2019-03-26 22:02:00 +0100403 /* by default, close the stream at the end of the transaction. */
404 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200405
406 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200407 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 req->analysers |= AN_REQ_HTTP_BODY;
409
410 /*
411 * RFC7234#4:
412 * A cache MUST write through requests with methods
413 * that are unsafe (Section 4.2.1 of [RFC7231]) to
414 * the origin server; i.e., a cache is not allowed
415 * to generate a reply to such a request before
416 * having forwarded the request and having received
417 * a corresponding response.
418 *
419 * RFC7231#4.2.1:
420 * Of the request methods defined by this
421 * specification, the GET, HEAD, OPTIONS, and TRACE
422 * methods are defined to be safe.
423 */
424 if (likely(txn->meth == HTTP_METH_GET ||
425 txn->meth == HTTP_METH_HEAD ||
426 txn->meth == HTTP_METH_OPTIONS ||
427 txn->meth == HTTP_METH_TRACE))
428 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
429
430 /* end of job, return OK */
431 req->analysers &= ~an_bit;
432 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200433
Christopher Faulete0768eb2018-10-03 16:38:02 +0200434 return 1;
435
436 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200437 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200438 txn->req.err_state = txn->req.msg_state;
439 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100440 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100441 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200442 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100443 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200444
445 return_prx_cond:
446 if (!(s->flags & SF_ERR_MASK))
447 s->flags |= SF_ERR_PRXCOND;
448 if (!(s->flags & SF_FINST_MASK))
449 s->flags |= SF_FINST_R;
450
451 req->analysers &= AN_REQ_FLT_END;
452 req->analyse_exp = TICK_ETERNITY;
453 return 0;
454}
455
456
457/* This stream analyser runs all HTTP request processing which is common to
458 * frontends and backends, which means blocking ACLs, filters, connection-close,
459 * reqadd, stats and redirects. This is performed for the designated proxy.
460 * It returns 1 if the processing can continue on next analysers, or zero if it
461 * either needs more data or wants to immediately abort the request (eg: deny,
462 * error, ...).
463 */
464int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
465{
466 struct session *sess = s->sess;
467 struct http_txn *txn = s->txn;
468 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200469 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200470 struct redirect_rule *rule;
471 struct cond_wordlist *wl;
472 enum rule_result verdict;
473 int deny_status = HTTP_ERR_403;
474 struct connection *conn = objt_conn(sess->origin);
475
476 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
477 /* we need more data */
478 goto return_prx_yield;
479 }
480
481 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
482 now_ms, __FUNCTION__,
483 s,
484 req,
485 req->rex, req->wex,
486 req->flags,
487 ci_data(req),
488 req->analysers);
489
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100490 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200491
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200492 /* just in case we have some per-backend tracking. Only called the first
493 * execution of the analyser. */
494 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
495 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200496
497 /* evaluate http-request rules */
498 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200499 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200500
501 switch (verdict) {
502 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
503 goto return_prx_yield;
504
505 case HTTP_RULE_RES_CONT:
506 case HTTP_RULE_RES_STOP: /* nothing to do */
507 break;
508
509 case HTTP_RULE_RES_DENY: /* deny or tarpit */
510 if (txn->flags & TX_CLTARPIT)
511 goto tarpit;
512 goto deny;
513
514 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
515 goto return_prx_cond;
516
517 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
518 goto done;
519
520 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
521 goto return_bad_req;
522 }
523 }
524
525 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
526 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200527 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200528
Christopher Fauletff2759f2018-10-24 11:13:16 +0200529 ctx.blk = NULL;
530 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
531 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200532 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
535
536 /* OK at this stage, we know that the request was accepted according to
537 * the http-request rules, we can check for the stats. Note that the
538 * URI is detected *before* the req* rules in order not to be affected
539 * by a possible reqrep, while they are processed *after* so that a
540 * reqdeny can still block them. This clearly needs to change in 1.6!
541 */
Christopher Faulet8f1aa772019-07-04 11:27:15 +0200542 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200543 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100544 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545 txn->status = 500;
546 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100547 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200548
549 if (!(s->flags & SF_ERR_MASK))
550 s->flags |= SF_ERR_RESOURCE;
551 goto return_prx_cond;
552 }
553
554 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200555 htx_handle_stats(s, req);
556 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200557 /* not all actions implemented: deny, allow, auth */
558
559 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
560 goto deny;
561
562 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
563 goto return_prx_cond;
564 }
565
566 /* evaluate the req* rules except reqadd */
567 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200568 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200569 goto return_bad_req;
570
571 if (txn->flags & TX_CLDENY)
572 goto deny;
573
574 if (txn->flags & TX_CLTARPIT) {
575 deny_status = HTTP_ERR_500;
576 goto tarpit;
577 }
578 }
579
580 /* add request headers from the rule sets in the same order */
581 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200582 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200583 if (wl->cond) {
584 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
585 ret = acl_pass(ret);
586 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
587 ret = !ret;
588 if (!ret)
589 continue;
590 }
591
Christopher Fauletff2759f2018-10-24 11:13:16 +0200592 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
593 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200594 goto return_bad_req;
595 }
596
Christopher Faulet2571bc62019-03-01 11:44:26 +0100597 /* Proceed with the applets now. */
598 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200599 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100600 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100602 if (htx_handle_expect_hdr(s, htx, msg) == -1)
603 goto return_bad_req;
604
Christopher Faulete0768eb2018-10-03 16:38:02 +0200605 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
606 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
607 if (!(s->flags & SF_FINST_MASK))
608 s->flags |= SF_FINST_R;
609
610 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
611 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
612 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
613 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100614
615 req->flags |= CF_SEND_DONTWAIT;
616 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200617 goto done;
618 }
619
620 /* check whether we have some ACLs set to redirect this request */
621 list_for_each_entry(rule, &px->redirect_rules, list) {
622 if (rule->cond) {
623 int ret;
624
625 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
626 ret = acl_pass(ret);
627 if (rule->cond->pol == ACL_COND_UNLESS)
628 ret = !ret;
629 if (!ret)
630 continue;
631 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200632 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200633 goto return_bad_req;
634 goto done;
635 }
636
637 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
638 * If this happens, then the data will not come immediately, so we must
639 * send all what we have without waiting. Note that due to the small gain
640 * in waiting for the body of the request, it's easier to simply put the
641 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
642 * itself once used.
643 */
644 req->flags |= CF_SEND_DONTWAIT;
645
646 done: /* done with this analyser, continue with next ones that the calling
647 * points will have set, if any.
648 */
649 req->analyse_exp = TICK_ETERNITY;
650 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
651 req->analysers &= ~an_bit;
652 return 1;
653
654 tarpit:
655 /* Allow cookie logging
656 */
657 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200658 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200659
660 /* When a connection is tarpitted, we use the tarpit timeout,
661 * which may be the same as the connect timeout if unspecified.
662 * If unset, then set it to zero because we really want it to
663 * eventually expire. We build the tarpit as an analyser.
664 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100665 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200666
667 /* wipe the request out so that we can drop the connection early
668 * if the client closes first.
669 */
670 channel_dont_connect(req);
671
672 txn->status = http_err_codes[deny_status];
673
674 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
675 req->analysers |= AN_REQ_HTTP_TARPIT;
676 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
677 if (!req->analyse_exp)
678 req->analyse_exp = tick_add(now_ms, 0);
679 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100680 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200681 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100682 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200683 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100684 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200685 goto done_without_exp;
686
687 deny: /* this request was blocked (denied) */
688
689 /* Allow cookie logging
690 */
691 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200692 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200693
694 txn->flags |= TX_CLDENY;
695 txn->status = http_err_codes[deny_status];
696 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100697 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100699 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200700 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100701 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100703 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200704 goto return_prx_cond;
705
706 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 txn->req.err_state = txn->req.msg_state;
708 txn->req.msg_state = HTTP_MSG_ERROR;
709 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100710 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711
Olivier Houcharda798bf52019-03-08 18:52:00 +0100712 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200713 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100714 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715
716 return_prx_cond:
717 if (!(s->flags & SF_ERR_MASK))
718 s->flags |= SF_ERR_PRXCOND;
719 if (!(s->flags & SF_FINST_MASK))
720 s->flags |= SF_FINST_R;
721
722 req->analysers &= AN_REQ_FLT_END;
723 req->analyse_exp = TICK_ETERNITY;
724 return 0;
725
726 return_prx_yield:
727 channel_dont_connect(req);
728 return 0;
729}
730
731/* This function performs all the processing enabled for the current request.
732 * It returns 1 if the processing can continue on next analysers, or zero if it
733 * needs more data, encounters an error, or wants to immediately abort the
734 * request. It relies on buffers flags, and updates s->req.analysers.
735 */
736int htx_process_request(struct stream *s, struct channel *req, int an_bit)
737{
738 struct session *sess = s->sess;
739 struct http_txn *txn = s->txn;
740 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200741 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200742 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
743
744 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
745 /* we need more data */
746 channel_dont_connect(req);
747 return 0;
748 }
749
750 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
751 now_ms, __FUNCTION__,
752 s,
753 req,
754 req->rex, req->wex,
755 req->flags,
756 ci_data(req),
757 req->analysers);
758
759 /*
760 * Right now, we know that we have processed the entire headers
761 * and that unwanted requests have been filtered out. We can do
762 * whatever we want with the remaining request. Also, now we
763 * may have separate values for ->fe, ->be.
764 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100765 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200766
767 /*
768 * If HTTP PROXY is set we simply get remote server address parsing
769 * incoming request. Note that this requires that a connection is
770 * allocated on the server side.
771 */
772 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
773 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100774 struct htx_sl *sl;
775 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200776
777 /* Note that for now we don't reuse existing proxy connections */
778 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
779 txn->req.err_state = txn->req.msg_state;
780 txn->req.msg_state = HTTP_MSG_ERROR;
781 txn->status = 500;
782 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100783 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200784
785 if (!(s->flags & SF_ERR_MASK))
786 s->flags |= SF_ERR_RESOURCE;
787 if (!(s->flags & SF_FINST_MASK))
788 s->flags |= SF_FINST_R;
789
790 return 0;
791 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200792 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100793 uri = htx_sl_req_uri(sl);
794 path = http_get_path(uri);
795 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200796 goto return_bad_req;
797
798 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 * uri.ptr and path.ptr (excluded). If it was not found, we need
800 * to replace from all the uri by a single "/".
801 *
802 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100803 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200804 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100806 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau69564b12019-07-18 16:17:15 +0200807 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200808 }
809
810 /*
811 * 7: Now we can work with the cookies.
812 * Note that doing so might move headers in the request, but
813 * the fields will stay coherent and the URI will not move.
814 * This should only be performed in the backend.
815 */
816 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100817 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818
819 /* add unique-id if "header-unique-id" is specified */
820
821 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
822 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
823 goto return_bad_req;
824 s->unique_id[0] = '\0';
825 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
826 }
827
828 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200829 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
830 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
831
832 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200833 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 }
835
836 /*
837 * 9: add X-Forwarded-For if either the frontend or the backend
838 * asks for it.
839 */
840 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200841 struct http_hdr_ctx ctx = { .blk = NULL };
842 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
843 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
844
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200846 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 /* The header is set to be added only if none is present
848 * and we found it, so don't do anything.
849 */
850 }
851 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
852 /* Add an X-Forwarded-For header unless the source IP is
853 * in the 'except' network range.
854 */
855 if ((!sess->fe->except_mask.s_addr ||
856 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
857 != sess->fe->except_net.s_addr) &&
858 (!s->be->except_mask.s_addr ||
859 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
860 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200861 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200862
863 /* Note: we rely on the backend to get the header name to be used for
864 * x-forwarded-for, because the header is really meant for the backends.
865 * However, if the backend did not specify any option, we have to rely
866 * on the frontend's header name.
867 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200868 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
869 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200870 goto return_bad_req;
871 }
872 }
873 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
874 /* FIXME: for the sake of completeness, we should also support
875 * 'except' here, although it is mostly useless in this case.
876 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200877 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200878
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 inet_ntop(AF_INET6,
880 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
881 pn, sizeof(pn));
882
883 /* Note: we rely on the backend to get the header name to be used for
884 * x-forwarded-for, because the header is really meant for the backends.
885 * However, if the backend did not specify any option, we have to rely
886 * on the frontend's header name.
887 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200888 chunk_printf(&trash, "%s", pn);
889 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890 goto return_bad_req;
891 }
892 }
893
894 /*
895 * 10: add X-Original-To if either the frontend or the backend
896 * asks for it.
897 */
898 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
899
900 /* FIXME: don't know if IPv6 can handle that case too. */
901 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
902 /* Add an X-Original-To header unless the destination IP is
903 * in the 'except' network range.
904 */
905 conn_get_to_addr(cli_conn);
906
907 if (cli_conn->addr.to.ss_family == AF_INET &&
908 ((!sess->fe->except_mask_to.s_addr ||
909 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
910 != sess->fe->except_to.s_addr) &&
911 (!s->be->except_mask_to.s_addr ||
912 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
913 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200914 struct ist hdr;
915 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200916
917 /* Note: we rely on the backend to get the header name to be used for
918 * x-original-to, because the header is really meant for the backends.
919 * However, if the backend did not specify any option, we have to rely
920 * on the frontend's header name.
921 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200922 if (s->be->orgto_hdr_len)
923 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
924 else
925 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200926
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200927 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
928 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200929 goto return_bad_req;
930 }
931 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932 }
933
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 /* If we have no server assigned yet and we're balancing on url_param
935 * with a POST request, we may be interested in checking the body for
936 * that parameter. This will be done in another analyser.
937 */
938 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100939 s->txn->meth == HTTP_METH_POST &&
940 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 channel_dont_connect(req);
942 req->analysers |= AN_REQ_HTTP_BODY;
943 }
944
945 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
946 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100947
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 /* We expect some data from the client. Unless we know for sure
949 * we already have a full request, we have to re-enable quick-ack
950 * in case we previously disabled it, otherwise we might cause
951 * the client to delay further data.
952 */
953 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200954 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100955 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200956
957 /*************************************************************
958 * OK, that's finished for the headers. We have done what we *
959 * could. Let's switch to the DATA state. *
960 ************************************************************/
961 req->analyse_exp = TICK_ETERNITY;
962 req->analysers &= ~an_bit;
963
964 s->logs.tv_request = now;
965 /* OK let's go on with the BODY now */
966 return 1;
967
968 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200969 txn->req.err_state = txn->req.msg_state;
970 txn->req.msg_state = HTTP_MSG_ERROR;
971 txn->status = 400;
972 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100973 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200974
Olivier Houcharda798bf52019-03-08 18:52:00 +0100975 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100977 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978
979 if (!(s->flags & SF_ERR_MASK))
980 s->flags |= SF_ERR_PRXCOND;
981 if (!(s->flags & SF_FINST_MASK))
982 s->flags |= SF_FINST_R;
983 return 0;
984}
985
986/* This function is an analyser which processes the HTTP tarpit. It always
987 * returns zero, at the beginning because it prevents any other processing
988 * from occurring, and at the end because it terminates the request.
989 */
990int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
991{
992 struct http_txn *txn = s->txn;
993
994 /* This connection is being tarpitted. The CLIENT side has
995 * already set the connect expiration date to the right
996 * timeout. We just have to check that the client is still
997 * there and that the timeout has not expired.
998 */
999 channel_dont_connect(req);
1000 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1001 !tick_is_expired(req->analyse_exp, now_ms))
1002 return 0;
1003
1004 /* We will set the queue timer to the time spent, just for
1005 * logging purposes. We fake a 500 server error, so that the
1006 * attacker will not suspect his connection has been tarpitted.
1007 * It will not cause trouble to the logs because we can exclude
1008 * the tarpitted connections by filtering on the 'PT' status flags.
1009 */
1010 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1011
1012 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001013 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001066 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1067 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 }
1069
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001070 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1073 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001075 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001076 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 goto http_end;
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1081 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001082 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
1084 if (!(s->flags & SF_ERR_MASK))
1085 s->flags |= SF_ERR_CLITO;
1086 if (!(s->flags & SF_FINST_MASK))
1087 s->flags |= SF_FINST_D;
1088 goto return_err_msg;
1089 }
1090
1091 /* we get here if we need to wait for more data */
1092 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1093 /* Not enough data. We'll re-use the http-request
1094 * timeout here. Ideally, we should set the timeout
1095 * relative to the accept() date. We just set the
1096 * request timeout once at the beginning of the
1097 * request.
1098 */
1099 channel_dont_connect(req);
1100 if (!tick_isset(req->analyse_exp))
1101 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1102 return 0;
1103 }
1104
1105 http_end:
1106 /* The situation will not evolve, so let's give up on the analysis. */
1107 s->logs.tv_request = now; /* update the request timer to reflect full request */
1108 req->analysers &= ~an_bit;
1109 req->analyse_exp = TICK_ETERNITY;
1110 return 1;
1111
1112 return_bad_req: /* let's centralize all bad requests */
1113 txn->req.err_state = txn->req.msg_state;
1114 txn->req.msg_state = HTTP_MSG_ERROR;
1115 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001116 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001117
1118 if (!(s->flags & SF_ERR_MASK))
1119 s->flags |= SF_ERR_PRXCOND;
1120 if (!(s->flags & SF_FINST_MASK))
1121 s->flags |= SF_FINST_R;
1122
1123 return_err_msg:
1124 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128 return 0;
1129}
1130
1131/* This function is an analyser which forwards request body (including chunk
1132 * sizes if any). It is called as soon as we must forward, even if we forward
1133 * zero byte. The only situation where it must not be called is when we're in
1134 * tunnel mode and we want to forward till the close. It's used both to forward
1135 * remaining data and to resync after end of body. It expects the msg_state to
1136 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1137 * read more data, or 1 once we can go on with next request or end the stream.
1138 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1139 * bytes of pending data + the headers if not already done.
1140 */
1141int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1142{
1143 struct session *sess = s->sess;
1144 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001145 struct http_msg *msg = &txn->req;
1146 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001147 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001148 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001149
1150 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1151 now_ms, __FUNCTION__,
1152 s,
1153 req,
1154 req->rex, req->wex,
1155 req->flags,
1156 ci_data(req),
1157 req->analysers);
1158
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001159 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1162 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1163 /* Output closed while we were sending data. We must abort and
1164 * wake the other side up.
1165 */
Olivier Houchard29cac3c2019-07-12 15:48:58 +02001166 /* Don't abort yet if we had L7 retries activated and it
1167 * was a write error, we may recover.
1168 */
1169 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1170 (s->si[1].flags & SI_FL_L7_RETRY))
1171 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001172 msg->err_state = msg->msg_state;
1173 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001174 htx_end_request(s);
1175 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001176 return 1;
1177 }
1178
1179 /* Note that we don't have to send 100-continue back because we don't
1180 * need the data to complete our job, and it's up to the server to
1181 * decide whether to return 100, 417 or anything else in return of
1182 * an "Expect: 100-continue" header.
1183 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001184 if (msg->msg_state == HTTP_MSG_BODY)
1185 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
Christopher Faulete0768eb2018-10-03 16:38:02 +02001187 /* in most states, we should abort in case of early close */
1188 channel_auto_close(req);
1189
1190 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001191 if (req->to_forward == CHN_INFINITE_FORWARD) {
1192 if (req->flags & (CF_SHUTR|CF_EOI)) {
1193 msg->msg_state = HTTP_MSG_DONE;
1194 req->to_forward = 0;
1195 goto done;
1196 }
1197 }
1198 else {
1199 /* We can't process the buffer's contents yet */
1200 req->flags |= CF_WAKE_WRITE;
1201 goto missing_data_or_waiting;
1202 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001203 }
1204
Christopher Faulet9768c262018-10-22 09:34:31 +02001205 if (msg->msg_state >= HTTP_MSG_DONE)
1206 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001207 /* Forward input data. We get it by removing all outgoing data not
1208 * forwarded yet from HTX data size. If there are some data filters, we
1209 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001210 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001211 if (HAS_REQ_DATA_FILTERS(s)) {
1212 ret = flt_http_payload(s, msg, htx->data);
1213 if (ret < 0)
1214 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001215 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001216 }
1217 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001218 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001219 if (msg->flags & HTTP_MSGF_XFER_LEN)
1220 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001221 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001222
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001223 if (txn->meth == HTTP_METH_CONNECT) {
1224 msg->msg_state = HTTP_MSG_TUNNEL;
1225 goto done;
1226 }
1227
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001228
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001230 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1231 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001232 */
1233 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1234 goto missing_data_or_waiting;
1235
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001236 msg->msg_state = HTTP_MSG_ENDING;
1237 if (htx->data != co_data(req))
1238 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001239 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001240 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001241
1242 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243 /* other states, DONE...TUNNEL */
1244 /* we don't want to forward closes on DONE except in tunnel mode. */
1245 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1246 channel_dont_close(req);
1247
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001248 if (HAS_REQ_DATA_FILTERS(s)) {
1249 ret = flt_http_end(s, msg);
1250 if (ret <= 0) {
1251 if (!ret)
1252 goto missing_data_or_waiting;
1253 goto return_bad_req;
1254 }
1255 }
1256
Christopher Fauletf2824e62018-10-01 12:12:37 +02001257 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001259 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001260 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1261 if (req->flags & CF_SHUTW) {
1262 /* request errors are most likely due to the
1263 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001264 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001265 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001266 goto return_bad_req;
1267 }
1268 return 1;
1269 }
1270
1271 /* If "option abortonclose" is set on the backend, we want to monitor
1272 * the client's connection and forward any shutdown notification to the
1273 * server, which will decide whether to close or to go on processing the
1274 * request. We only do that in tunnel mode, and not in other modes since
1275 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001276 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001277 channel_auto_read(req);
1278 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1279 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1280 s->si[1].flags |= SI_FL_NOLINGER;
1281 channel_auto_close(req);
1282 }
1283 else if (s->txn->meth == HTTP_METH_POST) {
1284 /* POST requests may require to read extra CRLF sent by broken
1285 * browsers and which could cause an RST to be sent upon close
1286 * on some systems (eg: Linux). */
1287 channel_auto_read(req);
1288 }
1289 return 0;
1290
1291 missing_data_or_waiting:
1292 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001293 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001294 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001295
1296 waiting:
1297 /* waiting for the last bits to leave the buffer */
1298 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001299 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001300
Christopher Faulet47365272018-10-31 17:40:50 +01001301 if (htx->flags & HTX_FL_PARSING_ERROR)
1302 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001303
Christopher Faulete0768eb2018-10-03 16:38:02 +02001304 /* When TE: chunked is used, we need to get there again to parse remaining
1305 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1306 * And when content-length is used, we never want to let the possible
1307 * shutdown be forwarded to the other side, as the state machine will
1308 * take care of it once the client responds. It's also important to
1309 * prevent TIME_WAITs from accumulating on the backend side, and for
1310 * HTTP/2 where the last frame comes with a shutdown.
1311 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001312 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001313 channel_dont_close(req);
1314
1315 /* We know that more data are expected, but we couldn't send more that
1316 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1317 * system knows it must not set a PUSH on this first part. Interactive
1318 * modes are already handled by the stream sock layer. We must not do
1319 * this in content-length mode because it could present the MSG_MORE
1320 * flag with the last block of forwarded data, which would cause an
1321 * additional delay to be observed by the receiver.
1322 */
1323 if (msg->flags & HTTP_MSGF_TE_CHNK)
1324 req->flags |= CF_EXPECT_MORE;
1325
1326 return 0;
1327
Christopher Faulet93e02d82019-03-08 14:18:50 +01001328 return_cli_abort:
1329 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1330 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1331 if (objt_server(s->target))
1332 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1333 if (!(s->flags & SF_ERR_MASK))
1334 s->flags |= SF_ERR_CLICL;
1335 status = 400;
1336 goto return_error;
1337
1338 return_srv_abort:
1339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1340 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1341 if (objt_server(s->target))
1342 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1343 if (!(s->flags & SF_ERR_MASK))
1344 s->flags |= SF_ERR_SRVCL;
1345 status = 502;
1346 goto return_error;
1347
1348 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001349 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001350 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001351 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001352 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001353 s->flags |= SF_ERR_CLICL;
1354 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001355
Christopher Faulet93e02d82019-03-08 14:18:50 +01001356 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001357 txn->req.err_state = txn->req.msg_state;
1358 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001359 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001361 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001362 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001363 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001364 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 }
1366 req->analysers &= AN_REQ_FLT_END;
1367 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 +01001368 if (!(s->flags & SF_FINST_MASK))
1369 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 return 0;
1371}
1372
Olivier Houcharda254a372019-04-05 15:30:12 +02001373/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1374/* Returns 0 if we can attempt to retry, -1 otherwise */
1375static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1376{
1377 struct channel *req, *res;
1378 int co_data;
1379
1380 si->conn_retries--;
1381 if (si->conn_retries < 0)
1382 return -1;
1383
Willy Tarreau223995e2019-05-04 10:38:31 +02001384 if (objt_server(s->target))
1385 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1386 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1387
Olivier Houcharda254a372019-04-05 15:30:12 +02001388 req = &s->req;
1389 res = &s->res;
1390 /* Remove any write error from the request, and read error from the response */
1391 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1392 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1393 res->analysers = 0;
1394 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard4bd58672019-07-12 16:16:59 +02001395 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001396 si->exp = TICK_ETERNITY;
1397 res->rex = TICK_ETERNITY;
1398 res->to_forward = 0;
1399 res->analyse_exp = TICK_ETERNITY;
1400 res->total = 0;
Olivier Houchard4bd58672019-07-12 16:16:59 +02001401 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001402 si_release_endpoint(&s->si[1]);
1403 b_free(&req->buf);
1404 /* Swap the L7 buffer with the channel buffer */
1405 /* We know we stored the co_data as b_data, so get it there */
1406 co_data = b_data(&si->l7_buffer);
1407 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1408 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1409
1410 co_set_data(req, co_data);
1411 b_reset(&res->buf);
1412 co_set_data(res, 0);
1413 return 0;
1414}
1415
Christopher Faulete0768eb2018-10-03 16:38:02 +02001416/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1417 * processing can continue on next analysers, or zero if it either needs more
1418 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1419 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1420 * when it has nothing left to do, and may remove any analyser when it wants to
1421 * abort.
1422 */
1423int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1424{
Christopher Faulet9768c262018-10-22 09:34:31 +02001425 /*
1426 * We will analyze a complete HTTP response to check the its syntax.
1427 *
1428 * Once the start line and all headers are received, we may perform a
1429 * capture of the error (if any), and we will set a few fields. We also
1430 * logging and finally headers capture.
1431 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001432 struct session *sess = s->sess;
1433 struct http_txn *txn = s->txn;
1434 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001435 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001436 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001437 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001438 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001439 int n;
1440
1441 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1442 now_ms, __FUNCTION__,
1443 s,
1444 rep,
1445 rep->rex, rep->wex,
1446 rep->flags,
1447 ci_data(rep),
1448 rep->analysers);
1449
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001450 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001451
Willy Tarreau4236f032019-03-05 10:43:32 +01001452 /* Parsing errors are caught here */
1453 if (htx->flags & HTX_FL_PARSING_ERROR)
1454 goto return_bad_res;
1455
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456 /*
1457 * Now we quickly check if we have found a full valid response.
1458 * If not so, we check the FD and buffer states before leaving.
1459 * A full response is indicated by the fact that we have seen
1460 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1461 * responses are checked first.
1462 *
1463 * Depending on whether the client is still there or not, we
1464 * may send an error response back or not. Note that normally
1465 * we should only check for HTTP status there, and check I/O
1466 * errors somewhere else.
1467 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001468 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001469 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001470 /* 1: have we encountered a read error ? */
1471 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001472 struct connection *conn = NULL;
1473
Olivier Houchard865d8392019-05-03 22:46:27 +02001474 if (objt_cs(s->si[1].end))
1475 conn = objt_cs(s->si[1].end)->conn;
1476
1477 if (si_b->flags & SI_FL_L7_RETRY &&
1478 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001479 /* If we arrive here, then CF_READ_ERROR was
1480 * set by si_cs_recv() because we matched a
1481 * status, overwise it would have removed
1482 * the SI_FL_L7_RETRY flag, so it's ok not
1483 * to check s->be->retry_type.
1484 */
1485 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1486 return 0;
1487 }
1488
Olivier Houchard6db16992019-05-17 15:40:49 +02001489 if (txn->flags & TX_NOT_FIRST)
1490 goto abort_keep_alive;
1491
Olivier Houcharda798bf52019-03-08 18:52:00 +01001492 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001493 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001494 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001495 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 }
1497
Christopher Faulete0768eb2018-10-03 16:38:02 +02001498 rep->analysers &= AN_RES_FLT_END;
1499 txn->status = 502;
1500
1501 /* Check to see if the server refused the early data.
1502 * If so, just send a 425
1503 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001504 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1505 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001506 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001507 do_l7_retry(s, si_b) == 0)
1508 return 0;
1509 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510 }
1511
1512 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001513 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514
1515 if (!(s->flags & SF_ERR_MASK))
1516 s->flags |= SF_ERR_SRVCL;
1517 if (!(s->flags & SF_FINST_MASK))
1518 s->flags |= SF_FINST_H;
1519 return 0;
1520 }
1521
Christopher Faulet9768c262018-10-22 09:34:31 +02001522 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001524 if ((si_b->flags & SI_FL_L7_RETRY) &&
1525 (s->be->retry_type & PR_RE_TIMEOUT)) {
1526 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1527 return 0;
1528 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001529 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001531 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001532 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001533 }
1534
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 rep->analysers &= AN_RES_FLT_END;
1536 txn->status = 504;
1537 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001538 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539
1540 if (!(s->flags & SF_ERR_MASK))
1541 s->flags |= SF_ERR_SRVTO;
1542 if (!(s->flags & SF_FINST_MASK))
1543 s->flags |= SF_FINST_H;
1544 return 0;
1545 }
1546
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001549 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1550 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001552 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553
1554 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001556 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557
1558 if (!(s->flags & SF_ERR_MASK))
1559 s->flags |= SF_ERR_CLICL;
1560 if (!(s->flags & SF_FINST_MASK))
1561 s->flags |= SF_FINST_H;
1562
1563 /* process_stream() will take care of the error */
1564 return 0;
1565 }
1566
Christopher Faulet9768c262018-10-22 09:34:31 +02001567 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001569 if ((si_b->flags & SI_FL_L7_RETRY) &&
1570 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1571 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1572 return 0;
1573 }
1574
Olivier Houchard6db16992019-05-17 15:40:49 +02001575 if (txn->flags & TX_NOT_FIRST)
1576 goto abort_keep_alive;
1577
Olivier Houcharda798bf52019-03-08 18:52:00 +01001578 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001579 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001580 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001581 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001582 }
1583
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584 rep->analysers &= AN_RES_FLT_END;
1585 txn->status = 502;
1586 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001587 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001588
1589 if (!(s->flags & SF_ERR_MASK))
1590 s->flags |= SF_ERR_SRVCL;
1591 if (!(s->flags & SF_FINST_MASK))
1592 s->flags |= SF_FINST_H;
1593 return 0;
1594 }
1595
Christopher Faulet9768c262018-10-22 09:34:31 +02001596 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001597 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001598 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001599 goto abort_keep_alive;
1600
Olivier Houcharda798bf52019-03-08 18:52:00 +01001601 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603
1604 if (!(s->flags & SF_ERR_MASK))
1605 s->flags |= SF_ERR_CLICL;
1606 if (!(s->flags & SF_FINST_MASK))
1607 s->flags |= SF_FINST_H;
1608
1609 /* process_stream() will take care of the error */
1610 return 0;
1611 }
1612
1613 channel_dont_close(rep);
1614 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1615 return 0;
1616 }
1617
1618 /* More interesting part now : we know that we have a complete
1619 * response which at least looks like HTTP. We have an indicator
1620 * of each header's length, so we can parse them quickly.
1621 */
1622
Christopher Faulet9768c262018-10-22 09:34:31 +02001623 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001624 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001625 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626
Christopher Faulet9768c262018-10-22 09:34:31 +02001627 /* 0: we might have to print this header in debug mode */
1628 if (unlikely((global.mode & MODE_DEBUG) &&
1629 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1630 int32_t pos;
1631
Christopher Faulet03599112018-11-27 11:21:21 +01001632 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001633
Christopher Fauleta3f15502019-05-13 15:27:23 +02001634 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001635 struct htx_blk *blk = htx_get_blk(htx, pos);
1636 enum htx_blk_type type = htx_get_blk_type(blk);
1637
1638 if (type == HTX_BLK_EOH)
1639 break;
1640 if (type != HTX_BLK_HDR)
1641 continue;
1642
1643 htx_debug_hdr("srvhdr", s,
1644 htx_get_blk_name(htx, blk),
1645 htx_get_blk_value(htx, blk));
1646 }
1647 }
1648
Christopher Faulet03599112018-11-27 11:21:21 +01001649 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001650 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001651 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001652 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001653 if (sl->flags & HTX_SL_F_XFER_LEN) {
1654 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001655 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001656 if (sl->flags & HTX_SL_F_BODYLESS)
1657 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001658 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001659
1660 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001661 if (n < 1 || n > 5)
1662 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001663
Christopher Faulete0768eb2018-10-03 16:38:02 +02001664 /* when the client triggers a 4xx from the server, it's most often due
1665 * to a missing object or permission. These events should be tracked
1666 * because if they happen often, it may indicate a brute force or a
1667 * vulnerability scan.
1668 */
1669 if (n == 4)
1670 stream_inc_http_err_ctr(s);
1671
1672 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001673 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001674
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675 /* Adjust server's health based on status code. Note: status codes 501
1676 * and 505 are triggered on demand by client request, so we must not
1677 * count them as server failures.
1678 */
1679 if (objt_server(s->target)) {
1680 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001681 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001682 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001683 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001684 }
1685
1686 /*
1687 * We may be facing a 100-continue response, or any other informational
1688 * 1xx response which is non-final, in which case this is not the right
1689 * response, and we're waiting for the next one. Let's allow this response
1690 * to go to the client and wait for the next one. There's an exception for
1691 * 101 which is used later in the code to switch protocols.
1692 */
1693 if (txn->status < 200 &&
1694 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001695 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001696 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697 msg->msg_state = HTTP_MSG_RPBEFORE;
1698 txn->status = 0;
1699 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001700 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001701 }
1702
1703 /*
1704 * 2: check for cacheability.
1705 */
1706
1707 switch (txn->status) {
1708 case 200:
1709 case 203:
1710 case 204:
1711 case 206:
1712 case 300:
1713 case 301:
1714 case 404:
1715 case 405:
1716 case 410:
1717 case 414:
1718 case 501:
1719 break;
1720 default:
1721 /* RFC7231#6.1:
1722 * Responses with status codes that are defined as
1723 * cacheable by default (e.g., 200, 203, 204, 206,
1724 * 300, 301, 404, 405, 410, 414, and 501 in this
1725 * specification) can be reused by a cache with
1726 * heuristic expiration unless otherwise indicated
1727 * by the method definition or explicit cache
1728 * controls [RFC7234]; all other status codes are
1729 * not cacheable by default.
1730 */
1731 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1732 break;
1733 }
1734
1735 /*
1736 * 3: we may need to capture headers
1737 */
1738 s->logs.logwait &= ~LW_RESP;
1739 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001740 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001741
Christopher Faulet9768c262018-10-22 09:34:31 +02001742 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001743 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1744 txn->status == 101)) {
1745 /* Either we've established an explicit tunnel, or we're
1746 * switching the protocol. In both cases, we're very unlikely
1747 * to understand the next protocols. We have to switch to tunnel
1748 * mode, so that we transfer the request and responses then let
1749 * this protocol pass unmodified. When we later implement specific
1750 * parsers for such protocols, we'll want to check the Upgrade
1751 * header which contains information about that protocol for
1752 * responses with status 101 (eg: see RFC2817 about TLS).
1753 */
1754 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001755 }
1756
Christopher Faulet61608322018-11-23 16:23:45 +01001757 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1758 * 407 (Proxy-Authenticate) responses and set the connection to private
1759 */
1760 srv_conn = cs_conn(objt_cs(s->si[1].end));
1761 if (srv_conn) {
1762 struct ist hdr;
1763 struct http_hdr_ctx ctx;
1764
1765 if (txn->status == 401)
1766 hdr = ist("WWW-Authenticate");
1767 else if (txn->status == 407)
1768 hdr = ist("Proxy-Authenticate");
1769 else
1770 goto end;
1771
1772 ctx.blk = NULL;
1773 while (http_find_header(htx, hdr, &ctx, 0)) {
1774 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001775 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1776 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001777 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001778 }
Christopher Faulet61608322018-11-23 16:23:45 +01001779 }
1780 }
1781
1782 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001783 /* we want to have the response time before we start processing it */
1784 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1785
1786 /* end of job, return OK */
1787 rep->analysers &= ~an_bit;
1788 rep->analyse_exp = TICK_ETERNITY;
1789 channel_auto_close(rep);
1790 return 1;
1791
Christopher Faulet47365272018-10-31 17:40:50 +01001792 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001793 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001794 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001795 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001796 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001797 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001798 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001799 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001800 do_l7_retry(s, si_b) == 0)
1801 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001802 txn->status = 502;
1803 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001804 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001805 rep->analysers &= AN_RES_FLT_END;
1806
1807 if (!(s->flags & SF_ERR_MASK))
1808 s->flags |= SF_ERR_PRXCOND;
1809 if (!(s->flags & SF_FINST_MASK))
1810 s->flags |= SF_FINST_H;
1811 return 0;
1812
Christopher Faulete0768eb2018-10-03 16:38:02 +02001813 abort_keep_alive:
1814 /* A keep-alive request to the server failed on a network error.
1815 * The client is required to retry. We need to close without returning
1816 * any other information so that the client retries.
1817 */
1818 txn->status = 0;
1819 rep->analysers &= AN_RES_FLT_END;
1820 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001821 s->logs.logwait = 0;
1822 s->logs.level = 0;
1823 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001824 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001825 return 0;
1826}
1827
1828/* This function performs all the processing enabled for the current response.
1829 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1830 * and updates s->res.analysers. It might make sense to explode it into several
1831 * other functions. It works like process_request (see indications above).
1832 */
1833int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1834{
1835 struct session *sess = s->sess;
1836 struct http_txn *txn = s->txn;
1837 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001838 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001839 struct proxy *cur_proxy;
1840 struct cond_wordlist *wl;
1841 enum rule_result ret = HTTP_RULE_RES_CONT;
1842
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001843 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1844 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001845
Christopher Faulete0768eb2018-10-03 16:38:02 +02001846 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1847 now_ms, __FUNCTION__,
1848 s,
1849 rep,
1850 rep->rex, rep->wex,
1851 rep->flags,
1852 ci_data(rep),
1853 rep->analysers);
1854
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001855 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001856
1857 /* The stats applet needs to adjust the Connection header but we don't
1858 * apply any filter there.
1859 */
1860 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1861 rep->analysers &= ~an_bit;
1862 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001863 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001864 }
1865
1866 /*
1867 * We will have to evaluate the filters.
1868 * As opposed to version 1.2, now they will be evaluated in the
1869 * filters order and not in the header order. This means that
1870 * each filter has to be validated among all headers.
1871 *
1872 * Filters are tried with ->be first, then with ->fe if it is
1873 * different from ->be.
1874 *
1875 * Maybe we are in resume condiion. In this case I choose the
1876 * "struct proxy" which contains the rule list matching the resume
1877 * pointer. If none of theses "struct proxy" match, I initialise
1878 * the process with the first one.
1879 *
1880 * In fact, I check only correspondance betwwen the current list
1881 * pointer and the ->fe rule list. If it doesn't match, I initialize
1882 * the loop with the ->be.
1883 */
1884 if (s->current_rule_list == &sess->fe->http_res_rules)
1885 cur_proxy = sess->fe;
1886 else
1887 cur_proxy = s->be;
1888 while (1) {
1889 struct proxy *rule_set = cur_proxy;
1890
1891 /* evaluate http-response rules */
1892 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001893 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001894
1895 if (ret == HTTP_RULE_RES_BADREQ)
1896 goto return_srv_prx_502;
1897
1898 if (ret == HTTP_RULE_RES_DONE) {
1899 rep->analysers &= ~an_bit;
1900 rep->analyse_exp = TICK_ETERNITY;
1901 return 1;
1902 }
1903 }
1904
1905 /* we need to be called again. */
1906 if (ret == HTTP_RULE_RES_YIELD) {
1907 channel_dont_close(rep);
1908 return 0;
1909 }
1910
1911 /* try headers filters */
1912 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001913 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1914 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001915 }
1916
1917 /* has the response been denied ? */
1918 if (txn->flags & TX_SVDENY) {
1919 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001920 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001921
Olivier Houcharda798bf52019-03-08 18:52:00 +01001922 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1923 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001924 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001925 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001926 goto return_srv_prx_502;
1927 }
1928
1929 /* add response headers from the rule sets in the same order */
1930 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001931 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001932 if (txn->status < 200 && txn->status != 101)
1933 break;
1934 if (wl->cond) {
1935 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1936 ret = acl_pass(ret);
1937 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1938 ret = !ret;
1939 if (!ret)
1940 continue;
1941 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001942
1943 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1944 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001945 goto return_bad_resp;
1946 }
1947
1948 /* check whether we're already working on the frontend */
1949 if (cur_proxy == sess->fe)
1950 break;
1951 cur_proxy = sess->fe;
1952 }
1953
1954 /* After this point, this anayzer can't return yield, so we can
1955 * remove the bit corresponding to this analyzer from the list.
1956 *
1957 * Note that the intermediate returns and goto found previously
1958 * reset the analyzers.
1959 */
1960 rep->analysers &= ~an_bit;
1961 rep->analyse_exp = TICK_ETERNITY;
1962
1963 /* OK that's all we can do for 1xx responses */
1964 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001965 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966
1967 /*
1968 * Now check for a server cookie.
1969 */
1970 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001971 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001972
1973 /*
1974 * Check for cache-control or pragma headers if required.
1975 */
1976 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
Christopher Faulet75b4cd92019-07-15 22:26:28 +02001977 htx_check_response_for_cacheability(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001978
1979 /*
1980 * Add server cookie in the response if needed
1981 */
1982 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1983 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1984 (!(s->flags & SF_DIRECT) ||
1985 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1986 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1987 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1988 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1989 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1990 !(s->flags & SF_IGNORE_PRST)) {
1991 /* the server is known, it's not the one the client requested, or the
1992 * cookie's last seen date needs to be refreshed. We have to
1993 * insert a set-cookie here, except if we want to insert only on POST
1994 * requests and this one isn't. Note that servers which don't have cookies
1995 * (eg: some backup servers) will return a full cookie removal request.
1996 */
1997 if (!objt_server(s->target)->cookie) {
1998 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001999 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002000 s->be->cookie_name);
2001 }
2002 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002003 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002004
2005 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2006 /* emit last_date, which is mandatory */
2007 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2008 s30tob64((date.tv_sec+3) >> 2,
2009 trash.area + trash.data);
2010 trash.data += 5;
2011
2012 if (s->be->cookie_maxlife) {
2013 /* emit first_date, which is either the original one or
2014 * the current date.
2015 */
2016 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2017 s30tob64(txn->cookie_first_date ?
2018 txn->cookie_first_date >> 2 :
2019 (date.tv_sec+3) >> 2,
2020 trash.area + trash.data);
2021 trash.data += 5;
2022 }
2023 }
2024 chunk_appendf(&trash, "; path=/");
2025 }
2026
2027 if (s->be->cookie_domain)
2028 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2029
2030 if (s->be->ck_opts & PR_CK_HTTPONLY)
2031 chunk_appendf(&trash, "; HttpOnly");
2032
2033 if (s->be->ck_opts & PR_CK_SECURE)
2034 chunk_appendf(&trash, "; Secure");
2035
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002036 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002037 goto return_bad_resp;
2038
2039 txn->flags &= ~TX_SCK_MASK;
2040 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2041 /* the server did not change, only the date was updated */
2042 txn->flags |= TX_SCK_UPDATED;
2043 else
2044 txn->flags |= TX_SCK_INSERTED;
2045
2046 /* Here, we will tell an eventual cache on the client side that we don't
2047 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2048 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2049 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2050 */
2051 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2052
2053 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2054
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002055 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002056 goto return_bad_resp;
2057 }
2058 }
2059
2060 /*
2061 * Check if result will be cacheable with a cookie.
2062 * We'll block the response if security checks have caught
2063 * nasty things such as a cacheable cookie.
2064 */
2065 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2066 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2067 (s->be->options & PR_O_CHK_CACHE)) {
2068 /* we're in presence of a cacheable response containing
2069 * a set-cookie header. We'll block it as requested by
2070 * the 'checkcache' option, and send an alert.
2071 */
2072 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002073 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002074
Olivier Houcharda798bf52019-03-08 18:52:00 +01002075 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2076 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002077 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002078 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002079
2080 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2081 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2082 send_log(s->be, LOG_ALERT,
2083 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2084 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2085 goto return_srv_prx_502;
2086 }
2087
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002088 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002089 /* Always enter in the body analyzer */
2090 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2091 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2092
2093 /* if the user wants to log as soon as possible, without counting
2094 * bytes from the server, then this is the right moment. We have
2095 * to temporarily assign bytes_out to log what we currently have.
2096 */
2097 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2098 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002099 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002100 s->do_log(s);
2101 s->logs.bytes_out = 0;
2102 }
2103 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002104
2105 return_bad_resp:
2106 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002107 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002108 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002109 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002110 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002111
2112 return_srv_prx_502:
2113 rep->analysers &= AN_RES_FLT_END;
2114 txn->status = 502;
2115 s->logs.t_data = -1; /* was not a valid response */
2116 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002117 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002118 if (!(s->flags & SF_ERR_MASK))
2119 s->flags |= SF_ERR_PRXCOND;
2120 if (!(s->flags & SF_FINST_MASK))
2121 s->flags |= SF_FINST_H;
2122 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123}
2124
2125/* This function is an analyser which forwards response body (including chunk
2126 * sizes if any). It is called as soon as we must forward, even if we forward
2127 * zero byte. The only situation where it must not be called is when we're in
2128 * tunnel mode and we want to forward till the close. It's used both to forward
2129 * remaining data and to resync after end of body. It expects the msg_state to
2130 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2131 * read more data, or 1 once we can go on with next request or end the stream.
2132 *
2133 * It is capable of compressing response data both in content-length mode and
2134 * in chunked mode. The state machines follows different flows depending on
2135 * whether content-length and chunked modes are used, since there are no
2136 * trailers in content-length :
2137 *
2138 * chk-mode cl-mode
2139 * ,----- BODY -----.
2140 * / \
2141 * V size > 0 V chk-mode
2142 * .--> SIZE -------------> DATA -------------> CRLF
2143 * | | size == 0 | last byte |
2144 * | v final crlf v inspected |
2145 * | TRAILERS -----------> DONE |
2146 * | |
2147 * `----------------------------------------------'
2148 *
2149 * Compression only happens in the DATA state, and must be flushed in final
2150 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2151 * is performed at once on final states for all bytes parsed, or when leaving
2152 * on missing data.
2153 */
2154int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2155{
2156 struct session *sess = s->sess;
2157 struct http_txn *txn = s->txn;
2158 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002159 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002160 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002161
2162 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2163 now_ms, __FUNCTION__,
2164 s,
2165 res,
2166 res->rex, res->wex,
2167 res->flags,
2168 ci_data(res),
2169 res->analysers);
2170
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002171 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002172
2173 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002174 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002175 /* Output closed while we were sending data. We must abort and
2176 * wake the other side up.
2177 */
2178 msg->err_state = msg->msg_state;
2179 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002180 htx_end_response(s);
2181 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002182 return 1;
2183 }
2184
Christopher Faulet9768c262018-10-22 09:34:31 +02002185 if (msg->msg_state == HTTP_MSG_BODY)
2186 msg->msg_state = HTTP_MSG_DATA;
2187
Christopher Faulete0768eb2018-10-03 16:38:02 +02002188 /* in most states, we should abort in case of early close */
2189 channel_auto_close(res);
2190
Christopher Faulete0768eb2018-10-03 16:38:02 +02002191 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002192 if (res->to_forward == CHN_INFINITE_FORWARD) {
2193 if (res->flags & (CF_SHUTR|CF_EOI)) {
2194 msg->msg_state = HTTP_MSG_DONE;
2195 res->to_forward = 0;
2196 goto done;
2197 }
2198 }
2199 else {
2200 /* We can't process the buffer's contents yet */
2201 res->flags |= CF_WAKE_WRITE;
2202 goto missing_data_or_waiting;
2203 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002204 }
2205
Christopher Faulet9768c262018-10-22 09:34:31 +02002206 if (msg->msg_state >= HTTP_MSG_DONE)
2207 goto done;
2208
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002209 /* Forward input data. We get it by removing all outgoing data not
2210 * forwarded yet from HTX data size. If there are some data filters, we
2211 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002212 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002213 if (HAS_RSP_DATA_FILTERS(s)) {
2214 ret = flt_http_payload(s, msg, htx->data);
2215 if (ret < 0)
2216 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002217 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002218 }
2219 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002220 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002221 if (msg->flags & HTTP_MSGF_XFER_LEN)
2222 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002223 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002224
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002225 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2226 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2227 msg->msg_state = HTTP_MSG_TUNNEL;
2228 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002229 }
2230
Christopher Faulet9768c262018-10-22 09:34:31 +02002231 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002232 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2233 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002234 */
2235 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2236 goto missing_data_or_waiting;
2237
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002238 msg->msg_state = HTTP_MSG_ENDING;
2239 if (htx->data != co_data(res))
2240 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002241 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002242 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002243
2244 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002245 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002246 channel_dont_close(res);
2247
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002248 if (HAS_RSP_DATA_FILTERS(s)) {
2249 ret = flt_http_end(s, msg);
2250 if (ret <= 0) {
2251 if (!ret)
2252 goto missing_data_or_waiting;
2253 goto return_bad_res;
2254 }
2255 }
2256
Christopher Fauletf2824e62018-10-01 12:12:37 +02002257 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002259 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2261 if (res->flags & CF_SHUTW) {
2262 /* response errors are most likely due to the
2263 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002264 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266 goto return_bad_res;
2267 }
2268 return 1;
2269 }
2270 return 0;
2271
2272 missing_data_or_waiting:
2273 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002274 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002275
Christopher Faulet47365272018-10-31 17:40:50 +01002276 if (htx->flags & HTX_FL_PARSING_ERROR)
2277 goto return_bad_res;
2278
Christopher Faulete0768eb2018-10-03 16:38:02 +02002279 /* stop waiting for data if the input is closed before the end. If the
2280 * client side was already closed, it means that the client has aborted,
2281 * so we don't want to count this as a server abort. Otherwise it's a
2282 * server abort.
2283 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002284 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002286 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002287 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002288 if (htx_is_empty(htx))
2289 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 }
2291
Christopher Faulete0768eb2018-10-03 16:38:02 +02002292 /* When TE: chunked is used, we need to get there again to parse
2293 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002294 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2295 * are filters registered on the stream, we don't want to forward a
2296 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002298 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002299 channel_dont_close(res);
2300
2301 /* We know that more data are expected, but we couldn't send more that
2302 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2303 * system knows it must not set a PUSH on this first part. Interactive
2304 * modes are already handled by the stream sock layer. We must not do
2305 * this in content-length mode because it could present the MSG_MORE
2306 * flag with the last block of forwarded data, which would cause an
2307 * additional delay to be observed by the receiver.
2308 */
2309 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2310 res->flags |= CF_EXPECT_MORE;
2311
2312 /* the stream handler will take care of timeouts and errors */
2313 return 0;
2314
Christopher Faulet93e02d82019-03-08 14:18:50 +01002315 return_srv_abort:
2316 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2317 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002318 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002319 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2320 if (!(s->flags & SF_ERR_MASK))
2321 s->flags |= SF_ERR_SRVCL;
2322 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002323
Christopher Faulet93e02d82019-03-08 14:18:50 +01002324 return_cli_abort:
2325 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2326 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002327 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002328 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2329 if (!(s->flags & SF_ERR_MASK))
2330 s->flags |= SF_ERR_CLICL;
2331 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002332
Christopher Faulet93e02d82019-03-08 14:18:50 +01002333 return_bad_res:
2334 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2335 if (objt_server(s->target)) {
2336 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2337 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2338 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002339 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002340 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002341
Christopher Faulet93e02d82019-03-08 14:18:50 +01002342 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002343 txn->rsp.err_state = txn->rsp.msg_state;
2344 txn->rsp.msg_state = HTTP_MSG_ERROR;
2345 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002346 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347 res->analysers &= AN_RES_FLT_END;
2348 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 +02002349 if (!(s->flags & SF_FINST_MASK))
2350 s->flags |= SF_FINST_D;
2351 return 0;
2352}
2353
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002355 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356 * as too large a request to build a valid response.
2357 */
2358int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2359{
Christopher Faulet99daf282018-11-28 22:58:13 +01002360 struct channel *req = &s->req;
2361 struct channel *res = &s->res;
2362 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002363 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002364 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002365 struct ist status, reason, location;
2366 unsigned int flags;
2367 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002368 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369
2370 chunk = alloc_trash_chunk();
2371 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002372 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373
Christopher Faulet99daf282018-11-28 22:58:13 +01002374 /*
2375 * Create the location
2376 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002377 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002378 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002379 case REDIRECT_TYPE_SCHEME: {
2380 struct http_hdr_ctx ctx;
2381 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382
Christopher Faulet99daf282018-11-28 22:58:13 +01002383 host = ist("");
2384 ctx.blk = NULL;
2385 if (http_find_header(htx, ist("Host"), &ctx, 0))
2386 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002387
Christopher Faulet297fbb42019-05-13 14:41:27 +02002388 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 path = http_get_path(htx_sl_req_uri(sl));
2390 /* build message using path */
2391 if (path.ptr) {
2392 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2393 int qs = 0;
2394 while (qs < path.len) {
2395 if (*(path.ptr + qs) == '?') {
2396 path.len = qs;
2397 break;
2398 }
2399 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 }
2402 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002403 else
2404 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405
Christopher Faulet99daf282018-11-28 22:58:13 +01002406 if (rule->rdr_str) { /* this is an old "redirect" rule */
2407 /* add scheme */
2408 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2409 goto fail;
2410 }
2411 else {
2412 /* add scheme with executing log format */
2413 chunk->data += build_logline(s, chunk->area + chunk->data,
2414 chunk->size - chunk->data,
2415 &rule->rdr_fmt);
2416 }
2417 /* add "://" + host + path */
2418 if (!chunk_memcat(chunk, "://", 3) ||
2419 !chunk_memcat(chunk, host.ptr, host.len) ||
2420 !chunk_memcat(chunk, path.ptr, path.len))
2421 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422
Christopher Faulet99daf282018-11-28 22:58:13 +01002423 /* append a slash at the end of the location if needed and missing */
2424 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2425 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2426 if (chunk->data + 1 >= chunk->size)
2427 goto fail;
2428 chunk->area[chunk->data++] = '/';
2429 }
2430 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002431 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 case REDIRECT_TYPE_PREFIX: {
2434 struct ist path;
2435
Christopher Faulet297fbb42019-05-13 14:41:27 +02002436 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 path = http_get_path(htx_sl_req_uri(sl));
2438 /* build message using path */
2439 if (path.ptr) {
2440 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2441 int qs = 0;
2442 while (qs < path.len) {
2443 if (*(path.ptr + qs) == '?') {
2444 path.len = qs;
2445 break;
2446 }
2447 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 }
2450 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002451 else
2452 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453
Christopher Faulet99daf282018-11-28 22:58:13 +01002454 if (rule->rdr_str) { /* this is an old "redirect" rule */
2455 /* add prefix. Note that if prefix == "/", we don't want to
2456 * add anything, otherwise it makes it hard for the user to
2457 * configure a self-redirection.
2458 */
2459 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2460 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2461 goto fail;
2462 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002464 else {
2465 /* add prefix with executing log format */
2466 chunk->data += build_logline(s, chunk->area + chunk->data,
2467 chunk->size - chunk->data,
2468 &rule->rdr_fmt);
2469 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002470
Christopher Faulet99daf282018-11-28 22:58:13 +01002471 /* add path */
2472 if (!chunk_memcat(chunk, path.ptr, path.len))
2473 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002474
Christopher Faulet99daf282018-11-28 22:58:13 +01002475 /* append a slash at the end of the location if needed and missing */
2476 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2477 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2478 if (chunk->data + 1 >= chunk->size)
2479 goto fail;
2480 chunk->area[chunk->data++] = '/';
2481 }
2482 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002483 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002484 case REDIRECT_TYPE_LOCATION:
2485 default:
2486 if (rule->rdr_str) { /* this is an old "redirect" rule */
2487 /* add location */
2488 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2489 goto fail;
2490 }
2491 else {
2492 /* add location with executing log format */
2493 chunk->data += build_logline(s, chunk->area + chunk->data,
2494 chunk->size - chunk->data,
2495 &rule->rdr_fmt);
2496 }
2497 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002498 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 location = ist2(chunk->area, chunk->data);
2500
2501 /*
2502 * Create the 30x response
2503 */
2504 switch (rule->code) {
2505 case 308:
2506 status = ist("308");
2507 reason = ist("Permanent Redirect");
2508 break;
2509 case 307:
2510 status = ist("307");
2511 reason = ist("Temporary Redirect");
2512 break;
2513 case 303:
2514 status = ist("303");
2515 reason = ist("See Other");
2516 break;
2517 case 301:
2518 status = ist("301");
2519 reason = ist("Moved Permanently");
2520 break;
2521 case 302:
2522 default:
2523 status = ist("302");
2524 reason = ist("Found");
2525 break;
2526 }
2527
Christopher Faulet08e66462019-05-23 16:44:59 +02002528 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2529 close = 1;
2530
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 htx = htx_from_buf(&res->buf);
2532 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2533 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2534 if (!sl)
2535 goto fail;
2536 sl->info.res.status = rule->code;
2537 s->txn->status = rule->code;
2538
Christopher Faulet08e66462019-05-23 16:44:59 +02002539 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2540 goto fail;
2541
2542 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002543 !htx_add_header(htx, ist("Location"), location))
2544 goto fail;
2545
2546 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2547 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2548 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002549 }
2550
2551 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2553 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002554 }
2555
Christopher Faulet99daf282018-11-28 22:58:13 +01002556 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2557 goto fail;
2558
Christopher Fauletf2824e62018-10-01 12:12:37 +02002559 /* let's log the request time */
2560 s->logs.tv_request = now;
2561
Christopher Faulet99daf282018-11-28 22:58:13 +01002562 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002563 c_adv(res, data);
2564 res->total += data;
2565
2566 channel_auto_read(req);
2567 channel_abort(req);
2568 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002569 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002570
2571 res->wex = tick_add_ifset(now_ms, res->wto);
2572 channel_auto_read(res);
2573 channel_auto_close(res);
2574 channel_shutr_now(res);
2575
2576 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002577
2578 if (!(s->flags & SF_ERR_MASK))
2579 s->flags |= SF_ERR_LOCAL;
2580 if (!(s->flags & SF_FINST_MASK))
2581 s->flags |= SF_FINST_R;
2582
Christopher Faulet99daf282018-11-28 22:58:13 +01002583 free_trash_chunk(chunk);
2584 return 1;
2585
2586 fail:
2587 /* If an error occurred, remove the incomplete HTTP response from the
2588 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002589 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002590 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002591 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002592}
2593
Christopher Faulet72333522018-10-24 11:25:02 +02002594int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2595 struct ist name, const char *str, struct my_regex *re, int action)
2596{
2597 struct http_hdr_ctx ctx;
2598 struct buffer *output = get_trash_chunk();
2599
2600 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2601 ctx.blk = NULL;
2602 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2603 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2604 continue;
2605
2606 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2607 if (output->data == -1)
2608 return -1;
2609 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2610 return -1;
2611 }
2612 return 0;
2613}
2614
2615static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2616 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2617{
2618 struct buffer *replace;
2619 int ret = -1;
2620
2621 replace = alloc_trash_chunk();
2622 if (!replace)
2623 goto leave;
2624
2625 replace->data = build_logline(s, replace->area, replace->size, fmt);
2626 if (replace->data >= replace->size - 1)
2627 goto leave;
2628
2629 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2630
2631 leave:
2632 free_trash_chunk(replace);
2633 return ret;
2634}
2635
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636
2637/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2638 * on success and -1 on error. The response channel is updated accordingly.
2639 */
2640static int htx_reply_103_early_hints(struct channel *res)
2641{
2642 struct htx *htx = htx_from_buf(&res->buf);
2643 size_t data;
2644
Christopher Faulet1d5ec092019-06-26 14:23:54 +02002645 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646 /* If an error occurred during an Early-hint rule,
2647 * remove the incomplete HTTP 103 response from the
2648 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002649 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 return -1;
2651 }
2652
2653 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 c_adv(res, data);
2655 res->total += data;
2656 return 0;
2657}
2658
Christopher Faulet6eb92892018-11-15 16:39:29 +01002659/*
2660 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2661 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 * If <early_hints> is 0, it is starts a new response by adding the start
2663 * line. If an error occurred -1 is returned. On success 0 is returned. The
2664 * channel is not updated here. It must be done calling the function
2665 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002666 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002667static 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 +01002668{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002669 struct channel *res = &s->res;
2670 struct htx *htx = htx_from_buf(&res->buf);
2671 struct buffer *value = alloc_trash_chunk();
2672
Christopher Faulet6eb92892018-11-15 16:39:29 +01002673 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002674 struct htx_sl *sl;
2675 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2676 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2677
2678 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2679 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2680 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002681 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002682 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002683 }
2684
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002685 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2686 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002687 goto fail;
2688
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002689 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002691
2692 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002693 /* If an error occurred during an Early-hint rule, remove the incomplete
2694 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002695 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002696 free_trash_chunk(value);
2697 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002698}
2699
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002700/* This function executes one of the set-{method,path,query,uri} actions. It
2701 * takes the string from the variable 'replace' with length 'len', then modifies
2702 * the relevant part of the request line accordingly. Then it updates various
2703 * pointers to the next elements which were moved, and the total buffer length.
2704 * It finds the action to be performed in p[2], previously filled by function
2705 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2706 * error, though this can be revisited when this code is finally exploited.
2707 *
2708 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2709 * query string and 3 to replace uri.
2710 *
2711 * In query string case, the mark question '?' must be set at the start of the
2712 * string by the caller, event if the replacement query string is empty.
2713 */
2714int htx_req_replace_stline(int action, const char *replace, int len,
2715 struct proxy *px, struct stream *s)
2716{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002717 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002718
2719 switch (action) {
2720 case 0: // method
2721 if (!http_replace_req_meth(htx, ist2(replace, len)))
2722 return -1;
2723 break;
2724
2725 case 1: // path
2726 if (!http_replace_req_path(htx, ist2(replace, len)))
2727 return -1;
2728 break;
2729
2730 case 2: // query
2731 if (!http_replace_req_query(htx, ist2(replace, len)))
2732 return -1;
2733 break;
2734
2735 case 3: // uri
2736 if (!http_replace_req_uri(htx, ist2(replace, len)))
2737 return -1;
2738 break;
2739
2740 default:
2741 return -1;
2742 }
2743 return 0;
2744}
2745
2746/* This function replace the HTTP status code and the associated message. The
2747 * variable <status> contains the new status code. This function never fails.
2748 */
2749void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2750{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002751 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002752 char *res;
2753
2754 chunk_reset(&trash);
2755 res = ultoa_o(status, trash.area, trash.size);
2756 trash.data = res - trash.area;
2757
2758 /* Do we have a custom reason format string? */
2759 if (reason == NULL)
2760 reason = http_get_reason(status);
2761
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002762 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002763 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2764}
2765
Christopher Faulet3e964192018-10-24 11:39:23 +02002766/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2767 * transaction <txn>. Returns the verdict of the first rule that prevents
2768 * further processing of the request (auth, deny, ...), and defaults to
2769 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2770 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2771 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2772 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2773 * status.
2774 */
2775static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2776 struct stream *s, int *deny_status)
2777{
2778 struct session *sess = strm_sess(s);
2779 struct http_txn *txn = s->txn;
2780 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002781 struct act_rule *rule;
2782 struct http_hdr_ctx ctx;
2783 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002784 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2785 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002786 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002787
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002788 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002789
2790 /* If "the current_rule_list" match the executed rule list, we are in
2791 * resume condition. If a resume is needed it is always in the action
2792 * and never in the ACL or converters. In this case, we initialise the
2793 * current rule, and go to the action execution point.
2794 */
2795 if (s->current_rule) {
2796 rule = s->current_rule;
2797 s->current_rule = NULL;
2798 if (s->current_rule_list == rules)
2799 goto resume_execution;
2800 }
2801 s->current_rule_list = rules;
2802
2803 list_for_each_entry(rule, rules, list) {
2804 /* check optional condition */
2805 if (rule->cond) {
2806 int ret;
2807
2808 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2809 ret = acl_pass(ret);
2810
2811 if (rule->cond->pol == ACL_COND_UNLESS)
2812 ret = !ret;
2813
2814 if (!ret) /* condition not matched */
2815 continue;
2816 }
2817
2818 act_flags |= ACT_FLAG_FIRST;
2819 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002820 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2821 early_hints = 0;
2822 if (htx_reply_103_early_hints(&s->res) == -1) {
2823 rule_ret = HTTP_RULE_RES_BADREQ;
2824 goto end;
2825 }
2826 }
2827
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 switch (rule->action) {
2829 case ACT_ACTION_ALLOW:
2830 rule_ret = HTTP_RULE_RES_STOP;
2831 goto end;
2832
2833 case ACT_ACTION_DENY:
2834 if (deny_status)
2835 *deny_status = rule->deny_status;
2836 rule_ret = HTTP_RULE_RES_DENY;
2837 goto end;
2838
2839 case ACT_HTTP_REQ_TARPIT:
2840 txn->flags |= TX_CLTARPIT;
2841 if (deny_status)
2842 *deny_status = rule->deny_status;
2843 rule_ret = HTTP_RULE_RES_DENY;
2844 goto end;
2845
2846 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002847 /* Auth might be performed on regular http-req rules as well as on stats */
2848 auth_realm = rule->arg.auth.realm;
2849 if (!auth_realm) {
2850 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2851 auth_realm = STATS_DEFAULT_REALM;
2852 else
2853 auth_realm = px->id;
2854 }
2855 /* send 401/407 depending on whether we use a proxy or not. We still
2856 * count one error, because normal browsing won't significantly
2857 * increase the counter but brute force attempts will.
2858 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002859 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002860 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2861 rule_ret = HTTP_RULE_RES_BADREQ;
2862 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002863 goto end;
2864
2865 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002866 rule_ret = HTTP_RULE_RES_DONE;
2867 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2868 rule_ret = HTTP_RULE_RES_BADREQ;
2869 goto end;
2870
2871 case ACT_HTTP_SET_NICE:
2872 s->task->nice = rule->arg.nice;
2873 break;
2874
2875 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002876 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002877 break;
2878
2879 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002880 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002881 break;
2882
2883 case ACT_HTTP_SET_LOGL:
2884 s->logs.level = rule->arg.loglevel;
2885 break;
2886
2887 case ACT_HTTP_REPLACE_HDR:
2888 case ACT_HTTP_REPLACE_VAL:
2889 if (htx_transform_header(s, &s->req, htx,
2890 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2891 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002892 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002893 rule_ret = HTTP_RULE_RES_BADREQ;
2894 goto end;
2895 }
2896 break;
2897
2898 case ACT_HTTP_DEL_HDR:
2899 /* remove all occurrences of the header */
2900 ctx.blk = NULL;
2901 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2902 http_remove_header(htx, &ctx);
2903 break;
2904
2905 case ACT_HTTP_SET_HDR:
2906 case ACT_HTTP_ADD_HDR: {
2907 /* The scope of the trash buffer must be limited to this function. The
2908 * build_logline() function can execute a lot of other function which
2909 * can use the trash buffer. So for limiting the scope of this global
2910 * buffer, we build first the header value using build_logline, and
2911 * after we store the header name.
2912 */
2913 struct buffer *replace;
2914 struct ist n, v;
2915
2916 replace = alloc_trash_chunk();
2917 if (!replace) {
2918 rule_ret = HTTP_RULE_RES_BADREQ;
2919 goto end;
2920 }
2921
2922 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2923 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2924 v = ist2(replace->area, replace->data);
2925
2926 if (rule->action == ACT_HTTP_SET_HDR) {
2927 /* remove all occurrences of the header */
2928 ctx.blk = NULL;
2929 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2930 http_remove_header(htx, &ctx);
2931 }
2932
2933 if (!http_add_header(htx, n, v)) {
2934 static unsigned char rate_limit = 0;
2935
2936 if ((rate_limit++ & 255) == 0) {
2937 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);
2938 }
2939
Olivier Houcharda798bf52019-03-08 18:52:00 +01002940 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002941 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002942 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002943 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002944 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002945 }
2946 free_trash_chunk(replace);
2947 break;
2948 }
2949
2950 case ACT_HTTP_DEL_ACL:
2951 case ACT_HTTP_DEL_MAP: {
2952 struct pat_ref *ref;
2953 struct buffer *key;
2954
2955 /* collect reference */
2956 ref = pat_ref_lookup(rule->arg.map.ref);
2957 if (!ref)
2958 continue;
2959
2960 /* allocate key */
2961 key = alloc_trash_chunk();
2962 if (!key) {
2963 rule_ret = HTTP_RULE_RES_BADREQ;
2964 goto end;
2965 }
2966
2967 /* collect key */
2968 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2969 key->area[key->data] = '\0';
2970
2971 /* perform update */
2972 /* returned code: 1=ok, 0=ko */
2973 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2974 pat_ref_delete(ref, key->area);
2975 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2976
2977 free_trash_chunk(key);
2978 break;
2979 }
2980
2981 case ACT_HTTP_ADD_ACL: {
2982 struct pat_ref *ref;
2983 struct buffer *key;
2984
2985 /* collect reference */
2986 ref = pat_ref_lookup(rule->arg.map.ref);
2987 if (!ref)
2988 continue;
2989
2990 /* allocate key */
2991 key = alloc_trash_chunk();
2992 if (!key) {
2993 rule_ret = HTTP_RULE_RES_BADREQ;
2994 goto end;
2995 }
2996
2997 /* collect key */
2998 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2999 key->area[key->data] = '\0';
3000
3001 /* perform update */
3002 /* add entry only if it does not already exist */
3003 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3004 if (pat_ref_find_elt(ref, key->area) == NULL)
3005 pat_ref_add(ref, key->area, NULL, NULL);
3006 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3007
3008 free_trash_chunk(key);
3009 break;
3010 }
3011
3012 case ACT_HTTP_SET_MAP: {
3013 struct pat_ref *ref;
3014 struct buffer *key, *value;
3015
3016 /* collect reference */
3017 ref = pat_ref_lookup(rule->arg.map.ref);
3018 if (!ref)
3019 continue;
3020
3021 /* allocate key */
3022 key = alloc_trash_chunk();
3023 if (!key) {
3024 rule_ret = HTTP_RULE_RES_BADREQ;
3025 goto end;
3026 }
3027
3028 /* allocate value */
3029 value = alloc_trash_chunk();
3030 if (!value) {
3031 free_trash_chunk(key);
3032 rule_ret = HTTP_RULE_RES_BADREQ;
3033 goto end;
3034 }
3035
3036 /* collect key */
3037 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3038 key->area[key->data] = '\0';
3039
3040 /* collect value */
3041 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3042 value->area[value->data] = '\0';
3043
3044 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003045 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003046 if (pat_ref_find_elt(ref, key->area) != NULL)
3047 /* update entry if it exists */
3048 pat_ref_set(ref, key->area, value->area, NULL);
3049 else
3050 /* insert a new entry */
3051 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003052 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003053 free_trash_chunk(key);
3054 free_trash_chunk(value);
3055 break;
3056 }
3057
3058 case ACT_HTTP_EARLY_HINT:
3059 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3060 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003061 early_hints = htx_add_early_hint_header(s, early_hints,
3062 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003063 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003064 if (early_hints == -1) {
3065 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003066 goto end;
3067 }
3068 break;
3069
3070 case ACT_CUSTOM:
3071 if ((s->req.flags & CF_READ_ERROR) ||
3072 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003073 (px->options & PR_O_ABRT_CLOSE)))
3074 act_flags |= ACT_FLAG_FINAL;
3075
3076 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3077 case ACT_RET_ERR:
3078 case ACT_RET_CONT:
3079 break;
3080 case ACT_RET_STOP:
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003081 rule_ret = HTTP_RULE_RES_STOP;
3082 goto end;
3083 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003084 rule_ret = HTTP_RULE_RES_DONE;
3085 goto end;
3086 case ACT_RET_YIELD:
3087 s->current_rule = rule;
3088 rule_ret = HTTP_RULE_RES_YIELD;
3089 goto end;
3090 }
3091 break;
3092
3093 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3094 /* Note: only the first valid tracking parameter of each
3095 * applies.
3096 */
3097
3098 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3099 struct stktable *t;
3100 struct stksess *ts;
3101 struct stktable_key *key;
3102 void *ptr1, *ptr2;
3103
3104 t = rule->arg.trk_ctr.table.t;
3105 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3106 rule->arg.trk_ctr.expr, NULL);
3107
3108 if (key && (ts = stktable_get_entry(t, key))) {
3109 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3110
3111 /* let's count a new HTTP request as it's the first time we do it */
3112 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3113 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3114 if (ptr1 || ptr2) {
3115 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3116
3117 if (ptr1)
3118 stktable_data_cast(ptr1, http_req_cnt)++;
3119
3120 if (ptr2)
3121 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3122 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3123
3124 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3125
3126 /* If data was modified, we need to touch to re-schedule sync */
3127 stktable_touch_local(t, ts, 0);
3128 }
3129
3130 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3131 if (sess->fe != s->be)
3132 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3133 }
3134 }
3135 break;
3136
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003137 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003138 default:
3139 break;
3140 }
3141 }
3142
3143 end:
3144 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003145 if (htx_reply_103_early_hints(&s->res) == -1)
3146 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003147 }
3148
3149 /* we reached the end of the rules, nothing to report */
3150 return rule_ret;
3151}
3152
3153/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3154 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3155 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3156 * is returned, the process can continue the evaluation of next rule list. If
3157 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3158 * is returned, it means the operation could not be processed and a server error
3159 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3160 * deny rule. If *YIELD is returned, the caller must call again the function
3161 * with the same context.
3162 */
3163static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3164 struct stream *s)
3165{
3166 struct session *sess = strm_sess(s);
3167 struct http_txn *txn = s->txn;
3168 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003169 struct act_rule *rule;
3170 struct http_hdr_ctx ctx;
3171 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3172 int act_flags = 0;
3173
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003174 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003175
3176 /* If "the current_rule_list" match the executed rule list, we are in
3177 * resume condition. If a resume is needed it is always in the action
3178 * and never in the ACL or converters. In this case, we initialise the
3179 * current rule, and go to the action execution point.
3180 */
3181 if (s->current_rule) {
3182 rule = s->current_rule;
3183 s->current_rule = NULL;
3184 if (s->current_rule_list == rules)
3185 goto resume_execution;
3186 }
3187 s->current_rule_list = rules;
3188
3189 list_for_each_entry(rule, rules, list) {
3190 /* check optional condition */
3191 if (rule->cond) {
3192 int ret;
3193
3194 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3195 ret = acl_pass(ret);
3196
3197 if (rule->cond->pol == ACL_COND_UNLESS)
3198 ret = !ret;
3199
3200 if (!ret) /* condition not matched */
3201 continue;
3202 }
3203
3204 act_flags |= ACT_FLAG_FIRST;
3205resume_execution:
3206 switch (rule->action) {
3207 case ACT_ACTION_ALLOW:
3208 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3209 goto end;
3210
3211 case ACT_ACTION_DENY:
3212 txn->flags |= TX_SVDENY;
3213 rule_ret = HTTP_RULE_RES_STOP;
3214 goto end;
3215
3216 case ACT_HTTP_SET_NICE:
3217 s->task->nice = rule->arg.nice;
3218 break;
3219
3220 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003221 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003222 break;
3223
3224 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003225 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003226 break;
3227
3228 case ACT_HTTP_SET_LOGL:
3229 s->logs.level = rule->arg.loglevel;
3230 break;
3231
3232 case ACT_HTTP_REPLACE_HDR:
3233 case ACT_HTTP_REPLACE_VAL:
3234 if (htx_transform_header(s, &s->res, htx,
3235 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3236 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003237 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003238 rule_ret = HTTP_RULE_RES_BADREQ;
3239 goto end;
3240 }
3241 break;
3242
3243 case ACT_HTTP_DEL_HDR:
3244 /* remove all occurrences of the header */
3245 ctx.blk = NULL;
3246 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3247 http_remove_header(htx, &ctx);
3248 break;
3249
3250 case ACT_HTTP_SET_HDR:
3251 case ACT_HTTP_ADD_HDR: {
3252 struct buffer *replace;
3253 struct ist n, v;
3254
3255 replace = alloc_trash_chunk();
3256 if (!replace) {
3257 rule_ret = HTTP_RULE_RES_BADREQ;
3258 goto end;
3259 }
3260
3261 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3262 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3263 v = ist2(replace->area, replace->data);
3264
3265 if (rule->action == ACT_HTTP_SET_HDR) {
3266 /* remove all occurrences of the header */
3267 ctx.blk = NULL;
3268 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3269 http_remove_header(htx, &ctx);
3270 }
3271
3272 if (!http_add_header(htx, n, v)) {
3273 static unsigned char rate_limit = 0;
3274
3275 if ((rate_limit++ & 255) == 0) {
3276 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);
3277 }
3278
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003283 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003284 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003285 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003286 }
3287 free_trash_chunk(replace);
3288 break;
3289 }
3290
3291 case ACT_HTTP_DEL_ACL:
3292 case ACT_HTTP_DEL_MAP: {
3293 struct pat_ref *ref;
3294 struct buffer *key;
3295
3296 /* collect reference */
3297 ref = pat_ref_lookup(rule->arg.map.ref);
3298 if (!ref)
3299 continue;
3300
3301 /* allocate key */
3302 key = alloc_trash_chunk();
3303 if (!key) {
3304 rule_ret = HTTP_RULE_RES_BADREQ;
3305 goto end;
3306 }
3307
3308 /* collect key */
3309 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3310 key->area[key->data] = '\0';
3311
3312 /* perform update */
3313 /* returned code: 1=ok, 0=ko */
3314 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3315 pat_ref_delete(ref, key->area);
3316 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3317
3318 free_trash_chunk(key);
3319 break;
3320 }
3321
3322 case ACT_HTTP_ADD_ACL: {
3323 struct pat_ref *ref;
3324 struct buffer *key;
3325
3326 /* collect reference */
3327 ref = pat_ref_lookup(rule->arg.map.ref);
3328 if (!ref)
3329 continue;
3330
3331 /* allocate key */
3332 key = alloc_trash_chunk();
3333 if (!key) {
3334 rule_ret = HTTP_RULE_RES_BADREQ;
3335 goto end;
3336 }
3337
3338 /* collect key */
3339 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3340 key->area[key->data] = '\0';
3341
3342 /* perform update */
3343 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003344 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003345 if (pat_ref_find_elt(ref, key->area) == NULL)
3346 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003347 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003348 free_trash_chunk(key);
3349 break;
3350 }
3351
3352 case ACT_HTTP_SET_MAP: {
3353 struct pat_ref *ref;
3354 struct buffer *key, *value;
3355
3356 /* collect reference */
3357 ref = pat_ref_lookup(rule->arg.map.ref);
3358 if (!ref)
3359 continue;
3360
3361 /* allocate key */
3362 key = alloc_trash_chunk();
3363 if (!key) {
3364 rule_ret = HTTP_RULE_RES_BADREQ;
3365 goto end;
3366 }
3367
3368 /* allocate value */
3369 value = alloc_trash_chunk();
3370 if (!value) {
3371 free_trash_chunk(key);
3372 rule_ret = HTTP_RULE_RES_BADREQ;
3373 goto end;
3374 }
3375
3376 /* collect key */
3377 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3378 key->area[key->data] = '\0';
3379
3380 /* collect value */
3381 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3382 value->area[value->data] = '\0';
3383
3384 /* perform update */
3385 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3386 if (pat_ref_find_elt(ref, key->area) != NULL)
3387 /* update entry if it exists */
3388 pat_ref_set(ref, key->area, value->area, NULL);
3389 else
3390 /* insert a new entry */
3391 pat_ref_add(ref, key->area, value->area, NULL);
3392 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3393 free_trash_chunk(key);
3394 free_trash_chunk(value);
3395 break;
3396 }
3397
3398 case ACT_HTTP_REDIR:
3399 rule_ret = HTTP_RULE_RES_DONE;
Christopher Faulet00618aa2019-07-15 12:05:35 +02003400 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
Christopher Faulet3e964192018-10-24 11:39:23 +02003401 rule_ret = HTTP_RULE_RES_BADREQ;
3402 goto end;
3403
3404 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3405 /* Note: only the first valid tracking parameter of each
3406 * applies.
3407 */
3408 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3409 struct stktable *t;
3410 struct stksess *ts;
3411 struct stktable_key *key;
3412 void *ptr;
3413
3414 t = rule->arg.trk_ctr.table.t;
3415 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3416 rule->arg.trk_ctr.expr, NULL);
3417
3418 if (key && (ts = stktable_get_entry(t, key))) {
3419 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3420
3421 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3422
3423 /* let's count a new HTTP request as it's the first time we do it */
3424 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3425 if (ptr)
3426 stktable_data_cast(ptr, http_req_cnt)++;
3427
3428 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3429 if (ptr)
3430 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3431 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3432
3433 /* When the client triggers a 4xx from the server, it's most often due
3434 * to a missing object or permission. These events should be tracked
3435 * because if they happen often, it may indicate a brute force or a
3436 * vulnerability scan. Normally this is done when receiving the response
3437 * but here we're tracking after this ought to have been done so we have
3438 * to do it on purpose.
3439 */
3440 if ((unsigned)(txn->status - 400) < 100) {
3441 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3442 if (ptr)
3443 stktable_data_cast(ptr, http_err_cnt)++;
3444
3445 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3446 if (ptr)
3447 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3448 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3449 }
3450
3451 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3452
3453 /* If data was modified, we need to touch to re-schedule sync */
3454 stktable_touch_local(t, ts, 0);
3455
3456 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3457 if (sess->fe != s->be)
3458 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3459 }
3460 }
3461 break;
3462
3463 case ACT_CUSTOM:
3464 if ((s->req.flags & CF_READ_ERROR) ||
3465 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003466 (px->options & PR_O_ABRT_CLOSE)))
3467 act_flags |= ACT_FLAG_FINAL;
3468
3469 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3470 case ACT_RET_ERR:
3471 case ACT_RET_CONT:
3472 break;
3473 case ACT_RET_STOP:
3474 rule_ret = HTTP_RULE_RES_STOP;
3475 goto end;
Christopher Faulet8f1aa772019-07-04 11:27:15 +02003476 case ACT_RET_DONE:
3477 rule_ret = HTTP_RULE_RES_DONE;
3478 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003479 case ACT_RET_YIELD:
3480 s->current_rule = rule;
3481 rule_ret = HTTP_RULE_RES_YIELD;
3482 goto end;
3483 }
3484 break;
3485
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003486 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003487 default:
3488 break;
3489 }
3490 }
3491
3492 end:
3493 /* we reached the end of the rules, nothing to report */
3494 return rule_ret;
3495}
3496
Christopher Faulet33640082018-10-24 11:53:01 +02003497/* Iterate the same filter through all request headers.
3498 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3499 * Since it can manage the switch to another backend, it updates the per-proxy
3500 * DENY stats.
3501 */
3502static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3503{
3504 struct http_txn *txn = s->txn;
3505 struct htx *htx;
3506 struct buffer *hdr = get_trash_chunk();
3507 int32_t pos;
3508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003509 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003510
Christopher Fauleta3f15502019-05-13 15:27:23 +02003511 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003512 struct htx_blk *blk = htx_get_blk(htx, pos);
3513 enum htx_blk_type type;
3514 struct ist n, v;
3515
3516 next_hdr:
3517 type = htx_get_blk_type(blk);
3518 if (type == HTX_BLK_EOH)
3519 break;
3520 if (type != HTX_BLK_HDR)
3521 continue;
3522
3523 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3524 return 1;
3525 else if (unlikely(txn->flags & TX_CLALLOW) &&
3526 (exp->action == ACT_ALLOW ||
3527 exp->action == ACT_DENY ||
3528 exp->action == ACT_TARPIT))
3529 return 0;
3530
3531 n = htx_get_blk_name(htx, blk);
3532 v = htx_get_blk_value(htx, blk);
3533
Christopher Faulet02e771a2019-02-26 15:36:05 +01003534 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003535 hdr->area[hdr->data++] = ':';
3536 hdr->area[hdr->data++] = ' ';
3537 chunk_memcat(hdr, v.ptr, v.len);
3538
3539 /* Now we have one header in <hdr> */
3540
3541 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3542 struct http_hdr_ctx ctx;
3543 int len;
3544
3545 switch (exp->action) {
3546 case ACT_ALLOW:
3547 txn->flags |= TX_CLALLOW;
3548 goto end;
3549
3550 case ACT_DENY:
3551 txn->flags |= TX_CLDENY;
3552 goto end;
3553
3554 case ACT_TARPIT:
3555 txn->flags |= TX_CLTARPIT;
3556 goto end;
3557
3558 case ACT_REPLACE:
3559 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3560 if (len < 0)
3561 return -1;
3562
3563 http_parse_header(ist2(trash.area, len), &n, &v);
3564 ctx.blk = blk;
3565 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003566 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003567 if (!http_replace_header(htx, &ctx, n, v))
3568 return -1;
3569 if (!ctx.blk)
3570 goto end;
3571 pos = htx_get_blk_pos(htx, blk);
3572 break;
3573
3574 case ACT_REMOVE:
3575 ctx.blk = blk;
3576 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003577 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003578 if (!http_remove_header(htx, &ctx))
3579 return -1;
3580 if (!ctx.blk)
3581 goto end;
3582 pos = htx_get_blk_pos(htx, blk);
3583 goto next_hdr;
3584
3585 }
3586 }
3587 }
3588 end:
3589 return 0;
3590}
3591
3592/* Apply the filter to the request line.
3593 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3594 * or -1 if a replacement resulted in an invalid request line.
3595 * Since it can manage the switch to another backend, it updates the per-proxy
3596 * DENY stats.
3597 */
3598static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3599{
3600 struct http_txn *txn = s->txn;
3601 struct htx *htx;
3602 struct buffer *reqline = get_trash_chunk();
3603 int done;
3604
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003605 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003606
3607 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3608 return 1;
3609 else if (unlikely(txn->flags & TX_CLALLOW) &&
3610 (exp->action == ACT_ALLOW ||
3611 exp->action == ACT_DENY ||
3612 exp->action == ACT_TARPIT))
3613 return 0;
3614 else if (exp->action == ACT_REMOVE)
3615 return 0;
3616
3617 done = 0;
3618
Christopher Faulet297fbb42019-05-13 14:41:27 +02003619 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003620
3621 /* Now we have the request line between cur_ptr and cur_end */
3622 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003623 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003624 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003625 int len;
3626
3627 switch (exp->action) {
3628 case ACT_ALLOW:
3629 txn->flags |= TX_CLALLOW;
3630 done = 1;
3631 break;
3632
3633 case ACT_DENY:
3634 txn->flags |= TX_CLDENY;
3635 done = 1;
3636 break;
3637
3638 case ACT_TARPIT:
3639 txn->flags |= TX_CLTARPIT;
3640 done = 1;
3641 break;
3642
3643 case ACT_REPLACE:
3644 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3645 if (len < 0)
3646 return -1;
3647
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003648 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3649 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3650 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003651 return -1;
3652 done = 1;
3653 break;
3654 }
3655 }
3656 return done;
3657}
3658
3659/*
3660 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3661 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3662 * unparsable request. Since it can manage the switch to another backend, it
3663 * updates the per-proxy DENY stats.
3664 */
3665static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3666{
3667 struct session *sess = s->sess;
3668 struct http_txn *txn = s->txn;
3669 struct hdr_exp *exp;
3670
3671 for (exp = px->req_exp; exp; exp = exp->next) {
3672 int ret;
3673
3674 /*
3675 * The interleaving of transformations and verdicts
3676 * makes it difficult to decide to continue or stop
3677 * the evaluation.
3678 */
3679
3680 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3681 break;
3682
3683 if ((txn->flags & TX_CLALLOW) &&
3684 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3685 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3686 continue;
3687
3688 /* if this filter had a condition, evaluate it now and skip to
3689 * next filter if the condition does not match.
3690 */
3691 if (exp->cond) {
3692 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3693 ret = acl_pass(ret);
3694 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3695 ret = !ret;
3696
3697 if (!ret)
3698 continue;
3699 }
3700
3701 /* Apply the filter to the request line. */
3702 ret = htx_apply_filter_to_req_line(s, req, exp);
3703 if (unlikely(ret < 0))
3704 return -1;
3705
3706 if (likely(ret == 0)) {
3707 /* The filter did not match the request, it can be
3708 * iterated through all headers.
3709 */
3710 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3711 return -1;
3712 }
3713 }
3714 return 0;
3715}
3716
3717/* Iterate the same filter through all response headers contained in <res>.
3718 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3719 */
3720static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3721{
3722 struct http_txn *txn = s->txn;
3723 struct htx *htx;
3724 struct buffer *hdr = get_trash_chunk();
3725 int32_t pos;
3726
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003727 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003728
Christopher Fauleta3f15502019-05-13 15:27:23 +02003729 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003730 struct htx_blk *blk = htx_get_blk(htx, pos);
3731 enum htx_blk_type type;
3732 struct ist n, v;
3733
3734 next_hdr:
3735 type = htx_get_blk_type(blk);
3736 if (type == HTX_BLK_EOH)
3737 break;
3738 if (type != HTX_BLK_HDR)
3739 continue;
3740
3741 if (unlikely(txn->flags & TX_SVDENY))
3742 return 1;
3743 else if (unlikely(txn->flags & TX_SVALLOW) &&
3744 (exp->action == ACT_ALLOW ||
3745 exp->action == ACT_DENY))
3746 return 0;
3747
3748 n = htx_get_blk_name(htx, blk);
3749 v = htx_get_blk_value(htx, blk);
3750
Christopher Faulet02e771a2019-02-26 15:36:05 +01003751 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003752 hdr->area[hdr->data++] = ':';
3753 hdr->area[hdr->data++] = ' ';
3754 chunk_memcat(hdr, v.ptr, v.len);
3755
3756 /* Now we have one header in <hdr> */
3757
3758 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3759 struct http_hdr_ctx ctx;
3760 int len;
3761
3762 switch (exp->action) {
3763 case ACT_ALLOW:
3764 txn->flags |= TX_SVALLOW;
3765 goto end;
3766 break;
3767
3768 case ACT_DENY:
3769 txn->flags |= TX_SVDENY;
3770 goto end;
3771 break;
3772
3773 case ACT_REPLACE:
3774 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3775 if (len < 0)
3776 return -1;
3777
3778 http_parse_header(ist2(trash.area, len), &n, &v);
3779 ctx.blk = blk;
3780 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003781 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003782 if (!http_replace_header(htx, &ctx, n, v))
3783 return -1;
3784 if (!ctx.blk)
3785 goto end;
3786 pos = htx_get_blk_pos(htx, blk);
3787 break;
3788
3789 case ACT_REMOVE:
3790 ctx.blk = blk;
3791 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003792 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003793 if (!http_remove_header(htx, &ctx))
3794 return -1;
3795 if (!ctx.blk)
3796 goto end;
3797 pos = htx_get_blk_pos(htx, blk);
3798 goto next_hdr;
3799 }
3800 }
3801
3802 }
3803 end:
3804 return 0;
3805}
3806
3807/* Apply the filter to the status line in the response buffer <res>.
3808 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3809 * or -1 if a replacement resulted in an invalid status line.
3810 */
3811static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3812{
3813 struct http_txn *txn = s->txn;
3814 struct htx *htx;
3815 struct buffer *resline = get_trash_chunk();
3816 int done;
3817
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003818 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003819
3820 if (unlikely(txn->flags & TX_SVDENY))
3821 return 1;
3822 else if (unlikely(txn->flags & TX_SVALLOW) &&
3823 (exp->action == ACT_ALLOW ||
3824 exp->action == ACT_DENY))
3825 return 0;
3826 else if (exp->action == ACT_REMOVE)
3827 return 0;
3828
3829 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003830 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003831
3832 /* Now we have the status line between cur_ptr and cur_end */
3833 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003834 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003835 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003836 int len;
3837
3838 switch (exp->action) {
3839 case ACT_ALLOW:
3840 txn->flags |= TX_SVALLOW;
3841 done = 1;
3842 break;
3843
3844 case ACT_DENY:
3845 txn->flags |= TX_SVDENY;
3846 done = 1;
3847 break;
3848
3849 case ACT_REPLACE:
3850 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3851 if (len < 0)
3852 return -1;
3853
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003854 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3855 sl->info.res.status = strl2ui(code.ptr, code.len);
3856 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003857 return -1;
3858
3859 done = 1;
3860 return 1;
3861 }
3862 }
3863 return done;
3864}
3865
3866/*
3867 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3868 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3869 * unparsable response.
3870 */
3871static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3872{
3873 struct session *sess = s->sess;
3874 struct http_txn *txn = s->txn;
3875 struct hdr_exp *exp;
3876
3877 for (exp = px->rsp_exp; exp; exp = exp->next) {
3878 int ret;
3879
3880 /*
3881 * The interleaving of transformations and verdicts
3882 * makes it difficult to decide to continue or stop
3883 * the evaluation.
3884 */
3885
3886 if (txn->flags & TX_SVDENY)
3887 break;
3888
3889 if ((txn->flags & TX_SVALLOW) &&
3890 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3891 exp->action == ACT_PASS)) {
3892 exp = exp->next;
3893 continue;
3894 }
3895
3896 /* if this filter had a condition, evaluate it now and skip to
3897 * next filter if the condition does not match.
3898 */
3899 if (exp->cond) {
3900 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3901 ret = acl_pass(ret);
3902 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3903 ret = !ret;
3904 if (!ret)
3905 continue;
3906 }
3907
3908 /* Apply the filter to the status line. */
3909 ret = htx_apply_filter_to_sts_line(s, res, exp);
3910 if (unlikely(ret < 0))
3911 return -1;
3912
3913 if (likely(ret == 0)) {
3914 /* The filter did not match the response, it can be
3915 * iterated through all headers.
3916 */
3917 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3918 return -1;
3919 }
3920 }
3921 return 0;
3922}
3923
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003924/*
3925 * Manage client-side cookie. It can impact performance by about 2% so it is
3926 * desirable to call it only when needed. This code is quite complex because
3927 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3928 * highly recommended not to touch this part without a good reason !
3929 */
3930static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3931{
3932 struct session *sess = s->sess;
3933 struct http_txn *txn = s->txn;
3934 struct htx *htx;
3935 struct http_hdr_ctx ctx;
3936 char *hdr_beg, *hdr_end, *del_from;
3937 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3938 int preserve_hdr;
3939
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003940 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003941 ctx.blk = NULL;
3942 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3943 del_from = NULL; /* nothing to be deleted */
3944 preserve_hdr = 0; /* assume we may kill the whole header */
3945
3946 /* Now look for cookies. Conforming to RFC2109, we have to support
3947 * attributes whose name begin with a '$', and associate them with
3948 * the right cookie, if we want to delete this cookie.
3949 * So there are 3 cases for each cookie read :
3950 * 1) it's a special attribute, beginning with a '$' : ignore it.
3951 * 2) it's a server id cookie that we *MAY* want to delete : save
3952 * some pointers on it (last semi-colon, beginning of cookie...)
3953 * 3) it's an application cookie : we *MAY* have to delete a previous
3954 * "special" cookie.
3955 * At the end of loop, if a "special" cookie remains, we may have to
3956 * remove it. If no application cookie persists in the header, we
3957 * *MUST* delete it.
3958 *
3959 * Note: RFC2965 is unclear about the processing of spaces around
3960 * the equal sign in the ATTR=VALUE form. A careful inspection of
3961 * the RFC explicitly allows spaces before it, and not within the
3962 * tokens (attrs or values). An inspection of RFC2109 allows that
3963 * too but section 10.1.3 lets one think that spaces may be allowed
3964 * after the equal sign too, resulting in some (rare) buggy
3965 * implementations trying to do that. So let's do what servers do.
3966 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3967 * allowed quoted strings in values, with any possible character
3968 * after a backslash, including control chars and delimitors, which
3969 * causes parsing to become ambiguous. Browsers also allow spaces
3970 * within values even without quotes.
3971 *
3972 * We have to keep multiple pointers in order to support cookie
3973 * removal at the beginning, middle or end of header without
3974 * corrupting the header. All of these headers are valid :
3975 *
3976 * hdr_beg hdr_end
3977 * | |
3978 * v |
3979 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3980 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3981 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3982 * | | | | | | |
3983 * | | | | | | |
3984 * | | | | | | +--> next
3985 * | | | | | +----> val_end
3986 * | | | | +-----------> val_beg
3987 * | | | +--------------> equal
3988 * | | +----------------> att_end
3989 * | +---------------------> att_beg
3990 * +--------------------------> prev
3991 *
3992 */
3993 hdr_beg = ctx.value.ptr;
3994 hdr_end = hdr_beg + ctx.value.len;
3995 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3996 /* Iterate through all cookies on this line */
3997
3998 /* find att_beg */
3999 att_beg = prev;
4000 if (prev > hdr_beg)
4001 att_beg++;
4002
4003 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4004 att_beg++;
4005
4006 /* find att_end : this is the first character after the last non
4007 * space before the equal. It may be equal to hdr_end.
4008 */
4009 equal = att_end = att_beg;
4010 while (equal < hdr_end) {
4011 if (*equal == '=' || *equal == ',' || *equal == ';')
4012 break;
4013 if (HTTP_IS_SPHT(*equal++))
4014 continue;
4015 att_end = equal;
4016 }
4017
4018 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4019 * is between <att_beg> and <equal>, both may be identical.
4020 */
4021 /* look for end of cookie if there is an equal sign */
4022 if (equal < hdr_end && *equal == '=') {
4023 /* look for the beginning of the value */
4024 val_beg = equal + 1;
4025 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4026 val_beg++;
4027
4028 /* find the end of the value, respecting quotes */
4029 next = http_find_cookie_value_end(val_beg, hdr_end);
4030
4031 /* make val_end point to the first white space or delimitor after the value */
4032 val_end = next;
4033 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4034 val_end--;
4035 }
4036 else
4037 val_beg = val_end = next = equal;
4038
4039 /* We have nothing to do with attributes beginning with
4040 * '$'. However, they will automatically be removed if a
4041 * header before them is removed, since they're supposed
4042 * to be linked together.
4043 */
4044 if (*att_beg == '$')
4045 continue;
4046
4047 /* Ignore cookies with no equal sign */
4048 if (equal == next) {
4049 /* This is not our cookie, so we must preserve it. But if we already
4050 * scheduled another cookie for removal, we cannot remove the
4051 * complete header, but we can remove the previous block itself.
4052 */
4053 preserve_hdr = 1;
4054 if (del_from != NULL) {
4055 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4056 val_end += delta;
4057 next += delta;
4058 hdr_end += delta;
4059 prev = del_from;
4060 del_from = NULL;
4061 }
4062 continue;
4063 }
4064
4065 /* if there are spaces around the equal sign, we need to
4066 * strip them otherwise we'll get trouble for cookie captures,
4067 * or even for rewrites. Since this happens extremely rarely,
4068 * it does not hurt performance.
4069 */
4070 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4071 int stripped_before = 0;
4072 int stripped_after = 0;
4073
4074 if (att_end != equal) {
4075 memmove(att_end, equal, hdr_end - equal);
4076 stripped_before = (att_end - equal);
4077 equal += stripped_before;
4078 val_beg += stripped_before;
4079 }
4080
4081 if (val_beg > equal + 1) {
4082 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4083 stripped_after = (equal + 1) - val_beg;
4084 val_beg += stripped_after;
4085 stripped_before += stripped_after;
4086 }
4087
4088 val_end += stripped_before;
4089 next += stripped_before;
4090 hdr_end += stripped_before;
4091 }
4092 /* now everything is as on the diagram above */
4093
4094 /* First, let's see if we want to capture this cookie. We check
4095 * that we don't already have a client side cookie, because we
4096 * can only capture one. Also as an optimisation, we ignore
4097 * cookies shorter than the declared name.
4098 */
4099 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4100 (val_end - att_beg >= sess->fe->capture_namelen) &&
4101 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4102 int log_len = val_end - att_beg;
4103
4104 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4105 ha_alert("HTTP logging : out of memory.\n");
4106 } else {
4107 if (log_len > sess->fe->capture_len)
4108 log_len = sess->fe->capture_len;
4109 memcpy(txn->cli_cookie, att_beg, log_len);
4110 txn->cli_cookie[log_len] = 0;
4111 }
4112 }
4113
4114 /* Persistence cookies in passive, rewrite or insert mode have the
4115 * following form :
4116 *
4117 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4118 *
4119 * For cookies in prefix mode, the form is :
4120 *
4121 * Cookie: NAME=SRV~VALUE
4122 */
4123 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4124 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4125 struct server *srv = s->be->srv;
4126 char *delim;
4127
4128 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4129 * have the server ID between val_beg and delim, and the original cookie between
4130 * delim+1 and val_end. Otherwise, delim==val_end :
4131 *
4132 * hdr_beg
4133 * |
4134 * v
4135 * NAME=SRV; # in all but prefix modes
4136 * NAME=SRV~OPAQUE ; # in prefix mode
4137 * || || | |+-> next
4138 * || || | +--> val_end
4139 * || || +---------> delim
4140 * || |+------------> val_beg
4141 * || +-------------> att_end = equal
4142 * |+-----------------> att_beg
4143 * +------------------> prev
4144 *
4145 */
4146 if (s->be->ck_opts & PR_CK_PFX) {
4147 for (delim = val_beg; delim < val_end; delim++)
4148 if (*delim == COOKIE_DELIM)
4149 break;
4150 }
4151 else {
4152 char *vbar1;
4153 delim = val_end;
4154 /* Now check if the cookie contains a date field, which would
4155 * appear after a vertical bar ('|') just after the server name
4156 * and before the delimiter.
4157 */
4158 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4159 if (vbar1) {
4160 /* OK, so left of the bar is the server's cookie and
4161 * right is the last seen date. It is a base64 encoded
4162 * 30-bit value representing the UNIX date since the
4163 * epoch in 4-second quantities.
4164 */
4165 int val;
4166 delim = vbar1++;
4167 if (val_end - vbar1 >= 5) {
4168 val = b64tos30(vbar1);
4169 if (val > 0)
4170 txn->cookie_last_date = val << 2;
4171 }
4172 /* look for a second vertical bar */
4173 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4174 if (vbar1 && (val_end - vbar1 > 5)) {
4175 val = b64tos30(vbar1 + 1);
4176 if (val > 0)
4177 txn->cookie_first_date = val << 2;
4178 }
4179 }
4180 }
4181
4182 /* if the cookie has an expiration date and the proxy wants to check
4183 * it, then we do that now. We first check if the cookie is too old,
4184 * then only if it has expired. We detect strict overflow because the
4185 * time resolution here is not great (4 seconds). Cookies with dates
4186 * in the future are ignored if their offset is beyond one day. This
4187 * allows an admin to fix timezone issues without expiring everyone
4188 * and at the same time avoids keeping unwanted side effects for too
4189 * long.
4190 */
4191 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4192 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4193 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4194 txn->flags &= ~TX_CK_MASK;
4195 txn->flags |= TX_CK_OLD;
4196 delim = val_beg; // let's pretend we have not found the cookie
4197 txn->cookie_first_date = 0;
4198 txn->cookie_last_date = 0;
4199 }
4200 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4201 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4202 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4203 txn->flags &= ~TX_CK_MASK;
4204 txn->flags |= TX_CK_EXPIRED;
4205 delim = val_beg; // let's pretend we have not found the cookie
4206 txn->cookie_first_date = 0;
4207 txn->cookie_last_date = 0;
4208 }
4209
4210 /* Here, we'll look for the first running server which supports the cookie.
4211 * This allows to share a same cookie between several servers, for example
4212 * to dedicate backup servers to specific servers only.
4213 * However, to prevent clients from sticking to cookie-less backup server
4214 * when they have incidentely learned an empty cookie, we simply ignore
4215 * empty cookies and mark them as invalid.
4216 * The same behaviour is applied when persistence must be ignored.
4217 */
4218 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4219 srv = NULL;
4220
4221 while (srv) {
4222 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4223 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4224 if ((srv->cur_state != SRV_ST_STOPPED) ||
4225 (s->be->options & PR_O_PERSIST) ||
4226 (s->flags & SF_FORCE_PRST)) {
4227 /* we found the server and we can use it */
4228 txn->flags &= ~TX_CK_MASK;
4229 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4230 s->flags |= SF_DIRECT | SF_ASSIGNED;
4231 s->target = &srv->obj_type;
4232 break;
4233 } else {
4234 /* we found a server, but it's down,
4235 * mark it as such and go on in case
4236 * another one is available.
4237 */
4238 txn->flags &= ~TX_CK_MASK;
4239 txn->flags |= TX_CK_DOWN;
4240 }
4241 }
4242 srv = srv->next;
4243 }
4244
4245 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4246 /* no server matched this cookie or we deliberately skipped it */
4247 txn->flags &= ~TX_CK_MASK;
4248 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4249 txn->flags |= TX_CK_UNUSED;
4250 else
4251 txn->flags |= TX_CK_INVALID;
4252 }
4253
4254 /* depending on the cookie mode, we may have to either :
4255 * - delete the complete cookie if we're in insert+indirect mode, so that
4256 * the server never sees it ;
4257 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004258 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004259 * if we're in cookie prefix mode
4260 */
4261 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4262 int delta; /* negative */
4263
4264 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4265 delta = val_beg - (delim + 1);
4266 val_end += delta;
4267 next += delta;
4268 hdr_end += delta;
4269 del_from = NULL;
4270 preserve_hdr = 1; /* we want to keep this cookie */
4271 }
4272 else if (del_from == NULL &&
4273 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4274 del_from = prev;
4275 }
4276 }
4277 else {
4278 /* This is not our cookie, so we must preserve it. But if we already
4279 * scheduled another cookie for removal, we cannot remove the
4280 * complete header, but we can remove the previous block itself.
4281 */
4282 preserve_hdr = 1;
4283
4284 if (del_from != NULL) {
4285 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4286 if (att_beg >= del_from)
4287 att_beg += delta;
4288 if (att_end >= del_from)
4289 att_end += delta;
4290 val_beg += delta;
4291 val_end += delta;
4292 next += delta;
4293 hdr_end += delta;
4294 prev = del_from;
4295 del_from = NULL;
4296 }
4297 }
4298
4299 /* continue with next cookie on this header line */
4300 att_beg = next;
4301 } /* for each cookie */
4302
4303
4304 /* There are no more cookies on this line.
4305 * We may still have one (or several) marked for deletion at the
4306 * end of the line. We must do this now in two ways :
4307 * - if some cookies must be preserved, we only delete from the
4308 * mark to the end of line ;
4309 * - if nothing needs to be preserved, simply delete the whole header
4310 */
4311 if (del_from) {
4312 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4313 }
4314 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004315 if (hdr_beg != hdr_end)
4316 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004317 else
4318 http_remove_header(htx, &ctx);
4319 }
4320 } /* for each "Cookie header */
4321}
4322
4323/*
4324 * Manage server-side cookies. It can impact performance by about 2% so it is
4325 * desirable to call it only when needed. This function is also used when we
4326 * just need to know if there is a cookie (eg: for check-cache).
4327 */
4328static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4329{
4330 struct session *sess = s->sess;
4331 struct http_txn *txn = s->txn;
4332 struct htx *htx;
4333 struct http_hdr_ctx ctx;
4334 struct server *srv;
4335 char *hdr_beg, *hdr_end;
4336 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004337 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004338
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004339 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004340
4341 ctx.blk = NULL;
4342 while (1) {
4343 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4344 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4345 break;
4346 is_cookie2 = 1;
4347 }
4348
4349 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4350 * <prev> points to the colon.
4351 */
4352 txn->flags |= TX_SCK_PRESENT;
4353
4354 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4355 * check-cache is enabled) and we are not interested in checking
4356 * them. Warning, the cookie capture is declared in the frontend.
4357 */
4358 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4359 break;
4360
4361 /* OK so now we know we have to process this response cookie.
4362 * The format of the Set-Cookie header is slightly different
4363 * from the format of the Cookie header in that it does not
4364 * support the comma as a cookie delimiter (thus the header
4365 * cannot be folded) because the Expires attribute described in
4366 * the original Netscape's spec may contain an unquoted date
4367 * with a comma inside. We have to live with this because
4368 * many browsers don't support Max-Age and some browsers don't
4369 * support quoted strings. However the Set-Cookie2 header is
4370 * clean.
4371 *
4372 * We have to keep multiple pointers in order to support cookie
4373 * removal at the beginning, middle or end of header without
4374 * corrupting the header (in case of set-cookie2). A special
4375 * pointer, <scav> points to the beginning of the set-cookie-av
4376 * fields after the first semi-colon. The <next> pointer points
4377 * either to the end of line (set-cookie) or next unquoted comma
4378 * (set-cookie2). All of these headers are valid :
4379 *
4380 * hdr_beg hdr_end
4381 * | |
4382 * v |
4383 * NAME1 = VALUE 1 ; Secure; Path="/" |
4384 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4385 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4386 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4387 * | | | | | | | |
4388 * | | | | | | | +-> next
4389 * | | | | | | +------------> scav
4390 * | | | | | +--------------> val_end
4391 * | | | | +--------------------> val_beg
4392 * | | | +----------------------> equal
4393 * | | +------------------------> att_end
4394 * | +----------------------------> att_beg
4395 * +------------------------------> prev
4396 * -------------------------------> hdr_beg
4397 */
4398 hdr_beg = ctx.value.ptr;
4399 hdr_end = hdr_beg + ctx.value.len;
4400 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4401
4402 /* Iterate through all cookies on this line */
4403
4404 /* find att_beg */
4405 att_beg = prev;
4406 if (prev > hdr_beg)
4407 att_beg++;
4408
4409 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4410 att_beg++;
4411
4412 /* find att_end : this is the first character after the last non
4413 * space before the equal. It may be equal to hdr_end.
4414 */
4415 equal = att_end = att_beg;
4416
4417 while (equal < hdr_end) {
4418 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4419 break;
4420 if (HTTP_IS_SPHT(*equal++))
4421 continue;
4422 att_end = equal;
4423 }
4424
4425 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4426 * is between <att_beg> and <equal>, both may be identical.
4427 */
4428
4429 /* look for end of cookie if there is an equal sign */
4430 if (equal < hdr_end && *equal == '=') {
4431 /* look for the beginning of the value */
4432 val_beg = equal + 1;
4433 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4434 val_beg++;
4435
4436 /* find the end of the value, respecting quotes */
4437 next = http_find_cookie_value_end(val_beg, hdr_end);
4438
4439 /* make val_end point to the first white space or delimitor after the value */
4440 val_end = next;
4441 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4442 val_end--;
4443 }
4444 else {
4445 /* <equal> points to next comma, semi-colon or EOL */
4446 val_beg = val_end = next = equal;
4447 }
4448
4449 if (next < hdr_end) {
4450 /* Set-Cookie2 supports multiple cookies, and <next> points to
4451 * a colon or semi-colon before the end. So skip all attr-value
4452 * pairs and look for the next comma. For Set-Cookie, since
4453 * commas are permitted in values, skip to the end.
4454 */
4455 if (is_cookie2)
4456 next = http_find_hdr_value_end(next, hdr_end);
4457 else
4458 next = hdr_end;
4459 }
4460
4461 /* Now everything is as on the diagram above */
4462
4463 /* Ignore cookies with no equal sign */
4464 if (equal == val_end)
4465 continue;
4466
4467 /* If there are spaces around the equal sign, we need to
4468 * strip them otherwise we'll get trouble for cookie captures,
4469 * or even for rewrites. Since this happens extremely rarely,
4470 * it does not hurt performance.
4471 */
4472 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4473 int stripped_before = 0;
4474 int stripped_after = 0;
4475
4476 if (att_end != equal) {
4477 memmove(att_end, equal, hdr_end - equal);
4478 stripped_before = (att_end - equal);
4479 equal += stripped_before;
4480 val_beg += stripped_before;
4481 }
4482
4483 if (val_beg > equal + 1) {
4484 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4485 stripped_after = (equal + 1) - val_beg;
4486 val_beg += stripped_after;
4487 stripped_before += stripped_after;
4488 }
4489
4490 val_end += stripped_before;
4491 next += stripped_before;
4492 hdr_end += stripped_before;
4493
Christopher Faulet3e2638e2019-06-18 09:49:16 +02004494 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004495 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004496 }
4497
4498 /* First, let's see if we want to capture this cookie. We check
4499 * that we don't already have a server side cookie, because we
4500 * can only capture one. Also as an optimisation, we ignore
4501 * cookies shorter than the declared name.
4502 */
4503 if (sess->fe->capture_name != NULL &&
4504 txn->srv_cookie == NULL &&
4505 (val_end - att_beg >= sess->fe->capture_namelen) &&
4506 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4507 int log_len = val_end - att_beg;
4508 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4509 ha_alert("HTTP logging : out of memory.\n");
4510 }
4511 else {
4512 if (log_len > sess->fe->capture_len)
4513 log_len = sess->fe->capture_len;
4514 memcpy(txn->srv_cookie, att_beg, log_len);
4515 txn->srv_cookie[log_len] = 0;
4516 }
4517 }
4518
4519 srv = objt_server(s->target);
4520 /* now check if we need to process it for persistence */
4521 if (!(s->flags & SF_IGNORE_PRST) &&
4522 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4523 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4524 /* assume passive cookie by default */
4525 txn->flags &= ~TX_SCK_MASK;
4526 txn->flags |= TX_SCK_FOUND;
4527
4528 /* If the cookie is in insert mode on a known server, we'll delete
4529 * this occurrence because we'll insert another one later.
4530 * We'll delete it too if the "indirect" option is set and we're in
4531 * a direct access.
4532 */
4533 if (s->be->ck_opts & PR_CK_PSV) {
4534 /* The "preserve" flag was set, we don't want to touch the
4535 * server's cookie.
4536 */
4537 }
4538 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4539 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4540 /* this cookie must be deleted */
4541 if (prev == hdr_beg && next == hdr_end) {
4542 /* whole header */
4543 http_remove_header(htx, &ctx);
4544 /* note: while both invalid now, <next> and <hdr_end>
4545 * are still equal, so the for() will stop as expected.
4546 */
4547 } else {
4548 /* just remove the value */
4549 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4550 next = prev;
4551 hdr_end += delta;
4552 }
4553 txn->flags &= ~TX_SCK_MASK;
4554 txn->flags |= TX_SCK_DELETED;
4555 /* and go on with next cookie */
4556 }
4557 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4558 /* replace bytes val_beg->val_end with the cookie name associated
4559 * with this server since we know it.
4560 */
4561 int sliding, delta;
4562
4563 ctx.value = ist2(val_beg, val_end - val_beg);
4564 ctx.lws_before = ctx.lws_after = 0;
4565 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4566 delta = srv->cklen - (val_end - val_beg);
4567 sliding = (ctx.value.ptr - val_beg);
4568 hdr_beg += sliding;
4569 val_beg += sliding;
4570 next += sliding + delta;
4571 hdr_end += sliding + delta;
4572
4573 txn->flags &= ~TX_SCK_MASK;
4574 txn->flags |= TX_SCK_REPLACED;
4575 }
4576 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4577 /* insert the cookie name associated with this server
4578 * before existing cookie, and insert a delimiter between them..
4579 */
4580 int sliding, delta;
4581 ctx.value = ist2(val_beg, 0);
4582 ctx.lws_before = ctx.lws_after = 0;
4583 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4584 delta = srv->cklen + 1;
4585 sliding = (ctx.value.ptr - val_beg);
4586 hdr_beg += sliding;
4587 val_beg += sliding;
4588 next += sliding + delta;
4589 hdr_end += sliding + delta;
4590
4591 val_beg[srv->cklen] = COOKIE_DELIM;
4592 txn->flags &= ~TX_SCK_MASK;
4593 txn->flags |= TX_SCK_REPLACED;
4594 }
4595 }
4596 /* that's done for this cookie, check the next one on the same
4597 * line when next != hdr_end (only if is_cookie2).
4598 */
4599 }
4600 }
4601}
4602
Christopher Faulet25a02f62018-10-24 12:00:25 +02004603/*
4604 * Parses the Cache-Control and Pragma request header fields to determine if
4605 * the request may be served from the cache and/or if it is cacheable. Updates
4606 * s->txn->flags.
4607 */
4608void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4609{
4610 struct http_txn *txn = s->txn;
4611 struct htx *htx;
4612 int32_t pos;
4613 int pragma_found, cc_found, i;
4614
4615 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4616 return; /* nothing more to do here */
4617
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004618 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004619 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004620 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004621 struct htx_blk *blk = htx_get_blk(htx, pos);
4622 enum htx_blk_type type = htx_get_blk_type(blk);
4623 struct ist n, v;
4624
4625 if (type == HTX_BLK_EOH)
4626 break;
4627 if (type != HTX_BLK_HDR)
4628 continue;
4629
4630 n = htx_get_blk_name(htx, blk);
4631 v = htx_get_blk_value(htx, blk);
4632
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004633 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004634 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4635 pragma_found = 1;
4636 continue;
4637 }
4638 }
4639
4640 /* Don't use the cache and don't try to store if we found the
4641 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004642 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004643 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4644 txn->flags |= TX_CACHE_IGNORE;
4645 continue;
4646 }
4647
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004648 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004649 continue;
4650
4651 /* OK, right now we know we have a cache-control header */
4652 cc_found = 1;
4653 if (!v.len) /* no info */
4654 continue;
4655
4656 i = 0;
4657 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4658 !isspace((unsigned char)*(v.ptr+i)))
4659 i++;
4660
4661 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4662 * values after max-age, max-stale nor min-fresh, we simply don't
4663 * use the cache when they're specified.
4664 */
4665 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4666 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4667 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4668 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4669 txn->flags |= TX_CACHE_IGNORE;
4670 continue;
4671 }
4672
4673 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4674 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4675 continue;
4676 }
4677 }
4678
4679 /* RFC7234#5.4:
4680 * When the Cache-Control header field is also present and
4681 * understood in a request, Pragma is ignored.
4682 * When the Cache-Control header field is not present in a
4683 * request, caches MUST consider the no-cache request
4684 * pragma-directive as having the same effect as if
4685 * "Cache-Control: no-cache" were present.
4686 */
4687 if (!cc_found && pragma_found)
4688 txn->flags |= TX_CACHE_IGNORE;
4689}
4690
4691/*
4692 * Check if response is cacheable or not. Updates s->txn->flags.
4693 */
4694void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4695{
4696 struct http_txn *txn = s->txn;
4697 struct htx *htx;
4698 int32_t pos;
4699 int i;
4700
4701 if (txn->status < 200) {
4702 /* do not try to cache interim responses! */
4703 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4704 return;
4705 }
4706
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004707 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004708 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004709 struct htx_blk *blk = htx_get_blk(htx, pos);
4710 enum htx_blk_type type = htx_get_blk_type(blk);
4711 struct ist n, v;
4712
4713 if (type == HTX_BLK_EOH)
4714 break;
4715 if (type != HTX_BLK_HDR)
4716 continue;
4717
4718 n = htx_get_blk_name(htx, blk);
4719 v = htx_get_blk_value(htx, blk);
4720
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004721 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004722 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 return;
4725 }
4726 }
4727
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004728 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004729 continue;
4730
4731 /* OK, right now we know we have a cache-control header */
4732 if (!v.len) /* no info */
4733 continue;
4734
4735 i = 0;
4736 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4737 !isspace((unsigned char)*(v.ptr+i)))
4738 i++;
4739
4740 /* we have a complete value between v.ptr and (v.ptr+i) */
4741 if (i < v.len && *(v.ptr + i) == '=') {
4742 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4743 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4744 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4745 continue;
4746 }
4747
4748 /* we have something of the form no-cache="set-cookie" */
4749 if ((v.len >= 21) &&
4750 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4751 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4752 txn->flags &= ~TX_CACHE_COOK;
4753 continue;
4754 }
4755
4756 /* OK, so we know that either p2 points to the end of string or to a comma */
4757 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4758 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4759 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4760 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4761 return;
4762 }
4763
4764 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4765 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4766 continue;
4767 }
4768 }
4769}
4770
Christopher Faulet64159df2018-10-24 21:15:35 +02004771/* send a server's name with an outgoing request over an established connection.
4772 * Note: this function is designed to be called once the request has been
4773 * scheduled for being forwarded. This is the reason why the number of forwarded
4774 * bytes have to be adjusted.
4775 */
4776int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4777{
4778 struct htx *htx;
4779 struct http_hdr_ctx ctx;
4780 struct ist hdr;
4781 uint32_t data;
4782
4783 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004784 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004785 data = htx->data;
4786
4787 ctx.blk = NULL;
4788 while (http_find_header(htx, hdr, &ctx, 1))
4789 http_remove_header(htx, &ctx);
4790 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4791
4792 if (co_data(&s->req)) {
4793 if (data >= htx->data)
4794 c_rew(&s->req, data - htx->data);
4795 else
4796 c_adv(&s->req, htx->data - data);
4797 }
4798 return 0;
4799}
4800
Christopher Faulet377c5a52018-10-24 21:21:30 +02004801/*
4802 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4803 * for the current backend.
4804 *
4805 * It is assumed that the request is either a HEAD, GET, or POST and that the
4806 * uri_auth field is valid.
4807 *
4808 * Returns 1 if stats should be provided, otherwise 0.
4809 */
4810static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4811{
4812 struct uri_auth *uri_auth = backend->uri_auth;
4813 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004814 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004815 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004816
4817 if (!uri_auth)
4818 return 0;
4819
4820 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4821 return 0;
4822
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004823 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004824 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004825 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004826
4827 /* check URI size */
4828 if (uri_auth->uri_len > uri.len)
4829 return 0;
4830
4831 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4832 return 0;
4833
4834 return 1;
4835}
4836
4837/* This function prepares an applet to handle the stats. It can deal with the
4838 * "100-continue" expectation, check that admin rules are met for POST requests,
4839 * and program a response message if something was unexpected. It cannot fail
4840 * and always relies on the stats applet to complete the job. It does not touch
4841 * analysers nor counters, which are left to the caller. It does not touch
4842 * s->target which is supposed to already point to the stats applet. The caller
4843 * is expected to have already assigned an appctx to the stream.
4844 */
4845static int htx_handle_stats(struct stream *s, struct channel *req)
4846{
4847 struct stats_admin_rule *stats_admin_rule;
4848 struct stream_interface *si = &s->si[1];
4849 struct session *sess = s->sess;
4850 struct http_txn *txn = s->txn;
4851 struct http_msg *msg = &txn->req;
4852 struct uri_auth *uri_auth = s->be->uri_auth;
4853 const char *h, *lookup, *end;
4854 struct appctx *appctx;
4855 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004856 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004857
4858 appctx = si_appctx(si);
4859 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4860 appctx->st1 = appctx->st2 = 0;
4861 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4862 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4863 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4864 appctx->ctx.stats.flags |= STAT_CHUNKED;
4865
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004866 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004867 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004868 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4869 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004870
4871 for (h = lookup; h <= end - 3; h++) {
4872 if (memcmp(h, ";up", 3) == 0) {
4873 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4874 break;
4875 }
4876 }
4877
4878 if (uri_auth->refresh) {
4879 for (h = lookup; h <= end - 10; h++) {
4880 if (memcmp(h, ";norefresh", 10) == 0) {
4881 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4882 break;
4883 }
4884 }
4885 }
4886
4887 for (h = lookup; h <= end - 4; h++) {
4888 if (memcmp(h, ";csv", 4) == 0) {
4889 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4890 break;
4891 }
4892 }
4893
4894 for (h = lookup; h <= end - 6; h++) {
4895 if (memcmp(h, ";typed", 6) == 0) {
4896 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4897 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4898 break;
4899 }
4900 }
4901
4902 for (h = lookup; h <= end - 8; h++) {
4903 if (memcmp(h, ";st=", 4) == 0) {
4904 int i;
4905 h += 4;
4906 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4907 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4908 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4909 appctx->ctx.stats.st_code = i;
4910 break;
4911 }
4912 }
4913 break;
4914 }
4915 }
4916
4917 appctx->ctx.stats.scope_str = 0;
4918 appctx->ctx.stats.scope_len = 0;
4919 for (h = lookup; h <= end - 8; h++) {
4920 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4921 int itx = 0;
4922 const char *h2;
4923 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4924 const char *err;
4925
4926 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4927 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004928 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4929 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004930 if (*h == ';' || *h == '&' || *h == ' ')
4931 break;
4932 itx++;
4933 h++;
4934 }
4935
4936 if (itx > STAT_SCOPE_TXT_MAXLEN)
4937 itx = STAT_SCOPE_TXT_MAXLEN;
4938 appctx->ctx.stats.scope_len = itx;
4939
4940 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4941 memcpy(scope_txt, h2, itx);
4942 scope_txt[itx] = '\0';
4943 err = invalid_char(scope_txt);
4944 if (err) {
4945 /* bad char in search text => clear scope */
4946 appctx->ctx.stats.scope_str = 0;
4947 appctx->ctx.stats.scope_len = 0;
4948 }
4949 break;
4950 }
4951 }
4952
4953 /* now check whether we have some admin rules for this request */
4954 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4955 int ret = 1;
4956
4957 if (stats_admin_rule->cond) {
4958 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4959 ret = acl_pass(ret);
4960 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4961 ret = !ret;
4962 }
4963
4964 if (ret) {
4965 /* no rule, or the rule matches */
4966 appctx->ctx.stats.flags |= STAT_ADMIN;
4967 break;
4968 }
4969 }
4970
Christopher Faulet5d45e382019-02-27 15:15:23 +01004971 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4972 appctx->st0 = STAT_HTTP_HEAD;
4973 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004974 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004975 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004976 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004977 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004978 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4979 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4980 appctx->st0 = STAT_HTTP_LAST;
4981 }
4982 }
4983 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004984 /* Unsupported method */
4985 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4986 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4987 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004988 }
4989
4990 s->task->nice = -32; /* small boost for HTTP statistics */
4991 return 1;
4992}
4993
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004994void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4995{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004996 struct channel *req = &s->req;
4997 struct channel *res = &s->res;
4998 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004999 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005000 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 struct ist path, location;
5002 unsigned int flags;
5003 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005004
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005005 /*
5006 * Create the location
5007 */
5008 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005009
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005010 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011 /* special prefix "/" means don't change URL */
5012 srv = __objt_server(s->target);
5013 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5014 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5015 return;
5016 }
5017
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005018 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005019 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005020 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005021 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022 if (!path.ptr)
5023 return;
5024
5025 if (!chunk_memcat(&trash, path.ptr, path.len))
5026 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005027 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 /*
5030 * Create the 302 respone
5031 */
5032 htx = htx_from_buf(&res->buf);
5033 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5034 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5035 ist("HTTP/1.1"), ist("302"), ist("Found"));
5036 if (!sl)
5037 goto fail;
5038 sl->info.res.status = 302;
5039 s->txn->status = 302;
5040
5041 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5042 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5043 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5044 !htx_add_header(htx, ist("Location"), location))
5045 goto fail;
5046
5047 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5048 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005049
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 /*
5051 * Send the message
5052 */
5053 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005054 c_adv(res, data);
5055 res->total += data;
5056
5057 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005058 si_shutr(si);
5059 si_shutw(si);
5060 si->err_type = SI_ET_NONE;
5061 si->state = SI_ST_CLO;
5062
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005063 channel_auto_read(req);
5064 channel_abort(req);
5065 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005066 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005067 channel_auto_read(res);
5068 channel_auto_close(res);
5069
5070 if (!(s->flags & SF_ERR_MASK))
5071 s->flags |= SF_ERR_LOCAL;
5072 if (!(s->flags & SF_FINST_MASK))
5073 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005074
5075 /* FIXME: we should increase a counter of redirects per server and per backend. */
5076 srv_inc_sess_ctr(srv);
5077 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005078 return;
5079
5080 fail:
5081 /* If an error occurred, remove the incomplete HTTP response from the
5082 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005083 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005084}
5085
Christopher Fauletf2824e62018-10-01 12:12:37 +02005086/* This function terminates the request because it was completly analyzed or
5087 * because an error was triggered during the body forwarding.
5088 */
5089static void htx_end_request(struct stream *s)
5090{
5091 struct channel *chn = &s->req;
5092 struct http_txn *txn = s->txn;
5093
5094 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5095 now_ms, __FUNCTION__, s,
5096 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5097 s->req.analysers, s->res.analysers);
5098
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005099 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5100 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005101 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005102 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 goto end;
5104 }
5105
5106 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5107 return;
5108
5109 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005110 /* No need to read anymore, the request was completely parsed.
5111 * We can shut the read side unless we want to abort_on_close,
5112 * or we have a POST request. The issue with POST requests is
5113 * that some browsers still send a CRLF after the request, and
5114 * this CRLF must be read so that it does not remain in the kernel
5115 * buffers, otherwise a close could cause an RST on some systems
5116 * (eg: Linux).
5117 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005118 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005119 channel_dont_read(chn);
5120
5121 /* if the server closes the connection, we want to immediately react
5122 * and close the socket to save packets and syscalls.
5123 */
5124 s->si[1].flags |= SI_FL_NOHALF;
5125
5126 /* In any case we've finished parsing the request so we must
5127 * disable Nagle when sending data because 1) we're not going
5128 * to shut this side, and 2) the server is waiting for us to
5129 * send pending data.
5130 */
5131 chn->flags |= CF_NEVER_WAIT;
5132
Christopher Fauletd01ce402019-01-02 17:44:13 +01005133 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5134 /* The server has not finished to respond, so we
5135 * don't want to move in order not to upset it.
5136 */
5137 return;
5138 }
5139
Christopher Fauletf2824e62018-10-01 12:12:37 +02005140 /* When we get here, it means that both the request and the
5141 * response have finished receiving. Depending on the connection
5142 * mode, we'll have to wait for the last bytes to leave in either
5143 * direction, and sometimes for a close to be effective.
5144 */
5145 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5146 /* Tunnel mode will not have any analyser so it needs to
5147 * poll for reads.
5148 */
5149 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005150 if (b_data(&chn->buf))
5151 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005152 txn->req.msg_state = HTTP_MSG_TUNNEL;
5153 }
5154 else {
5155 /* we're not expecting any new data to come for this
5156 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005157 *
5158 * However, there is an exception if the response
5159 * length is undefined. In this case, we need to wait
5160 * the close from the server. The response will be
5161 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162 */
5163 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5164 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005165 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005166
5167 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5168 channel_shutr_now(chn);
5169 channel_shutw_now(chn);
5170 }
5171 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172 goto check_channel_flags;
5173 }
5174
5175 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5176 http_msg_closing:
5177 /* nothing else to forward, just waiting for the output buffer
5178 * to be empty and for the shutw_now to take effect.
5179 */
5180 if (channel_is_empty(chn)) {
5181 txn->req.msg_state = HTTP_MSG_CLOSED;
5182 goto http_msg_closed;
5183 }
5184 else if (chn->flags & CF_SHUTW) {
5185 txn->req.err_state = txn->req.msg_state;
5186 txn->req.msg_state = HTTP_MSG_ERROR;
5187 goto end;
5188 }
5189 return;
5190 }
5191
5192 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5193 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005194 /* if we don't know whether the server will close, we need to hard close */
5195 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5196 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005198 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005199 channel_dont_read(chn);
5200 goto end;
5201 }
5202
5203 check_channel_flags:
5204 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5205 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5206 /* if we've just closed an output, let's switch */
5207 txn->req.msg_state = HTTP_MSG_CLOSING;
5208 goto http_msg_closing;
5209 }
5210
5211 end:
5212 chn->analysers &= AN_REQ_FLT_END;
5213 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5214 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5215 channel_auto_close(chn);
5216 channel_auto_read(chn);
5217}
5218
5219
5220/* This function terminates the response because it was completly analyzed or
5221 * because an error was triggered during the body forwarding.
5222 */
5223static void htx_end_response(struct stream *s)
5224{
5225 struct channel *chn = &s->res;
5226 struct http_txn *txn = s->txn;
5227
5228 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5229 now_ms, __FUNCTION__, s,
5230 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5231 s->req.analysers, s->res.analysers);
5232
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005233 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5234 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005235 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005237 goto end;
5238 }
5239
5240 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5241 return;
5242
5243 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5244 /* In theory, we don't need to read anymore, but we must
5245 * still monitor the server connection for a possible close
5246 * while the request is being uploaded, so we don't disable
5247 * reading.
5248 */
5249 /* channel_dont_read(chn); */
5250
5251 if (txn->req.msg_state < HTTP_MSG_DONE) {
5252 /* The client seems to still be sending data, probably
5253 * because we got an error response during an upload.
5254 * We have the choice of either breaking the connection
5255 * or letting it pass through. Let's do the later.
5256 */
5257 return;
5258 }
5259
5260 /* When we get here, it means that both the request and the
5261 * response have finished receiving. Depending on the connection
5262 * mode, we'll have to wait for the last bytes to leave in either
5263 * direction, and sometimes for a close to be effective.
5264 */
5265 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5266 channel_auto_read(chn);
5267 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005268 if (b_data(&chn->buf))
5269 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005270 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5271 }
5272 else {
5273 /* we're not expecting any new data to come for this
5274 * transaction, so we can close it.
5275 */
5276 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5277 channel_shutr_now(chn);
5278 channel_shutw_now(chn);
5279 }
5280 }
5281 goto check_channel_flags;
5282 }
5283
5284 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5285 http_msg_closing:
5286 /* nothing else to forward, just waiting for the output buffer
5287 * to be empty and for the shutw_now to take effect.
5288 */
5289 if (channel_is_empty(chn)) {
5290 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5291 goto http_msg_closed;
5292 }
5293 else if (chn->flags & CF_SHUTW) {
5294 txn->rsp.err_state = txn->rsp.msg_state;
5295 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005296 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005297 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005298 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 goto end;
5300 }
5301 return;
5302 }
5303
5304 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5305 http_msg_closed:
5306 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005307 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005308 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005309 goto end;
5310 }
5311
5312 check_channel_flags:
5313 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5314 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5315 /* if we've just closed an output, let's switch */
5316 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5317 goto http_msg_closing;
5318 }
5319
5320 end:
5321 chn->analysers &= AN_RES_FLT_END;
5322 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5323 chn->analysers |= AN_RES_FLT_XFER_DATA;
5324 channel_auto_close(chn);
5325 channel_auto_read(chn);
5326}
5327
Christopher Faulet0f226952018-10-22 09:29:56 +02005328void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5329 int finst, const struct buffer *msg)
5330{
5331 channel_auto_read(si_oc(si));
5332 channel_abort(si_oc(si));
5333 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005334 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005335 channel_auto_close(si_ic(si));
5336 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005337
5338 /* <msg> is an HTX structure. So we copy it in the response's
5339 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005340 if (msg) {
5341 struct channel *chn = si_ic(si);
5342 struct htx *htx;
5343
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005344 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005345 chn->buf.data = msg->data;
5346 memcpy(chn->buf.area, msg->area, msg->data);
5347 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005348 c_adv(chn, htx->data);
5349 chn->total += htx->data;
5350 }
5351 if (!(s->flags & SF_ERR_MASK))
5352 s->flags |= err;
5353 if (!(s->flags & SF_FINST_MASK))
5354 s->flags |= finst;
5355}
5356
5357void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5358{
5359 channel_auto_read(&s->req);
5360 channel_abort(&s->req);
5361 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005362 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5363 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005364
5365 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005366
5367 /* <msg> is an HTX structure. So we copy it in the response's
5368 * channel */
5369 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005370 if (msg) {
5371 struct channel *chn = &s->res;
5372 struct htx *htx;
5373
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005374 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005375 chn->buf.data = msg->data;
5376 memcpy(chn->buf.area, msg->area, msg->data);
5377 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005378 c_adv(chn, htx->data);
5379 chn->total += htx->data;
5380 }
5381
5382 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5383 channel_auto_read(&s->res);
5384 channel_auto_close(&s->res);
5385 channel_shutr_now(&s->res);
5386}
5387
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005388struct buffer *htx_error_message(struct stream *s)
5389{
5390 const int msgnum = http_get_status_idx(s->txn->status);
5391
5392 if (s->be->errmsg[msgnum].area)
5393 return &s->be->errmsg[msgnum];
5394 else if (strm_fe(s)->errmsg[msgnum].area)
5395 return &strm_fe(s)->errmsg[msgnum];
5396 else
5397 return &htx_err_chunks[msgnum];
5398}
5399
Christopher Faulet304cc402019-07-15 15:46:28 +02005400/* Return the error message corresponding to si->err_type. It is assumed
5401 * that the server side is closed. Note that err_type is actually a
5402 * bitmask, where almost only aborts may be cumulated with other
5403 * values. We consider that aborted operations are more important
5404 * than timeouts or errors due to the fact that nobody else in the
5405 * logs might explain incomplete retries. All others should avoid
5406 * being cumulated. It should normally not be possible to have multiple
5407 * aborts at once, but just in case, the first one in sequence is reported.
5408 * Note that connection errors appearing on the second request of a keep-alive
5409 * connection are not reported since this allows the client to retry.
5410 */
5411void htx_return_srv_error(struct stream *s, struct stream_interface *si)
5412{
5413 int err_type = si->err_type;
5414
5415 /* set s->txn->status for http_error_message(s) */
5416 s->txn->status = 503;
5417
5418 if (err_type & SI_ET_QUEUE_ABRT)
5419 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
5420 htx_error_message(s));
5421 else if (err_type & SI_ET_CONN_ABRT)
5422 htx_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
5423 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5424 htx_error_message(s));
5425 else if (err_type & SI_ET_QUEUE_TO)
5426 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
5427 htx_error_message(s));
5428 else if (err_type & SI_ET_QUEUE_ERR)
5429 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
5430 htx_error_message(s));
5431 else if (err_type & SI_ET_CONN_TO)
5432 htx_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
5433 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5434 htx_error_message(s));
5435 else if (err_type & SI_ET_CONN_ERR)
5436 htx_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
5437 (s->flags & SF_SRV_REUSED) ? NULL :
5438 htx_error_message(s));
5439 else if (err_type & SI_ET_CONN_RES)
5440 htx_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
5441 (s->txn->flags & TX_NOT_FIRST) ? NULL :
5442 htx_error_message(s));
5443 else { /* SI_ET_CONN_OTHER and others */
5444 s->txn->status = 500;
5445 htx_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
5446 htx_error_message(s));
5447 }
5448}
5449
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005450
Christopher Faulet4a28a532019-03-01 11:19:40 +01005451/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5452 * on success and -1 on error.
5453 */
5454static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5455{
5456 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5457 * then we must send an HTTP/1.1 100 Continue intermediate response.
5458 */
5459 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5460 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5461 struct ist hdr = { .ptr = "Expect", .len = 6 };
5462 struct http_hdr_ctx ctx;
5463
5464 ctx.blk = NULL;
5465 /* Expect is allowed in 1.1, look for it */
5466 if (http_find_header(htx, hdr, &ctx, 0) &&
5467 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5468 if (htx_reply_100_continue(s) == -1)
5469 return -1;
5470 http_remove_header(htx, &ctx);
5471 }
5472 }
5473 return 0;
5474}
5475
Christopher Faulet23a3c792018-11-28 10:01:23 +01005476/* Send a 100-Continue response to the client. It returns 0 on success and -1
5477 * on error. The response channel is updated accordingly.
5478 */
5479static int htx_reply_100_continue(struct stream *s)
5480{
5481 struct channel *res = &s->res;
5482 struct htx *htx = htx_from_buf(&res->buf);
5483 struct htx_sl *sl;
5484 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5485 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5486 size_t data;
5487
5488 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5489 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5490 if (!sl)
5491 goto fail;
5492 sl->info.res.status = 100;
5493
Christopher Faulet1d5ec092019-06-26 14:23:54 +02005494 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005495 goto fail;
5496
5497 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005498 c_adv(res, data);
5499 res->total += data;
5500 return 0;
5501
5502 fail:
5503 /* If an error occurred, remove the incomplete HTTP response from the
5504 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005505 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005506 return -1;
5507}
5508
Christopher Faulet12c51e22018-11-28 15:59:42 +01005509
5510/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5511 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5512 * error. The response channel is updated accordingly.
5513 */
5514static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5515{
5516 struct channel *res = &s->res;
5517 struct htx *htx = htx_from_buf(&res->buf);
5518 struct htx_sl *sl;
5519 struct ist code, body;
5520 int status;
5521 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5522 size_t data;
5523
5524 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5525 status = 401;
5526 code = ist("401");
5527 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5528 "You need a valid user and password to access this content.\n"
5529 "</body></html>\n");
5530 }
5531 else {
5532 status = 407;
5533 code = ist("407");
5534 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5535 "You need a valid user and password to access this content.\n"
5536 "</body></html>\n");
5537 }
5538
5539 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5540 ist("HTTP/1.1"), code, ist("Unauthorized"));
5541 if (!sl)
5542 goto fail;
5543 sl->info.res.status = status;
5544 s->txn->status = status;
5545
5546 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5547 goto fail;
5548
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005549 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5550 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005551 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005552 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5553 goto fail;
5554 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5555 goto fail;
5556 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005557 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005558 if (!htx_add_endof(htx, HTX_BLK_EOH))
5559 goto fail;
5560
5561 while (body.len) {
5562 size_t sent = htx_add_data(htx, body);
5563 if (!sent)
5564 goto fail;
5565 body.ptr += sent;
5566 body.len -= sent;
5567 }
5568
5569 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005570 goto fail;
5571
5572 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005573 c_adv(res, data);
5574 res->total += data;
5575
5576 channel_auto_read(&s->req);
5577 channel_abort(&s->req);
5578 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005579 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005580
5581 res->wex = tick_add_ifset(now_ms, res->wto);
5582 channel_auto_read(res);
5583 channel_auto_close(res);
5584 channel_shutr_now(res);
5585 return 0;
5586
5587 fail:
5588 /* If an error occurred, remove the incomplete HTTP response from the
5589 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005590 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005591 return -1;
5592}
5593
Christopher Faulet0f226952018-10-22 09:29:56 +02005594/*
5595 * Capture headers from message <htx> according to header list <cap_hdr>, and
5596 * fill the <cap> pointers appropriately.
5597 */
5598static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5599{
5600 struct cap_hdr *h;
5601 int32_t pos;
5602
Christopher Fauleta3f15502019-05-13 15:27:23 +02005603 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005604 struct htx_blk *blk = htx_get_blk(htx, pos);
5605 enum htx_blk_type type = htx_get_blk_type(blk);
5606 struct ist n, v;
5607
5608 if (type == HTX_BLK_EOH)
5609 break;
5610 if (type != HTX_BLK_HDR)
5611 continue;
5612
5613 n = htx_get_blk_name(htx, blk);
5614
5615 for (h = cap_hdr; h; h = h->next) {
5616 if (h->namelen && (h->namelen == n.len) &&
5617 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5618 if (cap[h->index] == NULL)
5619 cap[h->index] =
5620 pool_alloc(h->pool);
5621
5622 if (cap[h->index] == NULL) {
5623 ha_alert("HTTP capture : out of memory.\n");
5624 break;
5625 }
5626
5627 v = htx_get_blk_value(htx, blk);
5628 if (v.len > h->len)
5629 v.len = h->len;
5630
5631 memcpy(cap[h->index], v.ptr, v.len);
5632 cap[h->index][v.len]=0;
5633 }
5634 }
5635 }
5636}
5637
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005638/* Delete a value in a header between delimiters <from> and <next>. The header
5639 * itself is delimited by <start> and <end> pointers. The number of characters
5640 * displaced is returned, and the pointer to the first delimiter is updated if
5641 * required. The function tries as much as possible to respect the following
5642 * principles :
5643 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5644 * in which case <next> is simply removed
5645 * - set exactly one space character after the new first delimiter, unless there
5646 * are not enough characters in the block being moved to do so.
5647 * - remove unneeded spaces before the previous delimiter and after the new
5648 * one.
5649 *
5650 * It is the caller's responsibility to ensure that :
5651 * - <from> points to a valid delimiter or <start> ;
5652 * - <next> points to a valid delimiter or <end> ;
5653 * - there are non-space chars before <from>.
5654 */
5655static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5656{
5657 char *prev = *from;
5658
5659 if (prev == start) {
5660 /* We're removing the first value. eat the semicolon, if <next>
5661 * is lower than <end> */
5662 if (next < end)
5663 next++;
5664
5665 while (next < end && HTTP_IS_SPHT(*next))
5666 next++;
5667 }
5668 else {
5669 /* Remove useless spaces before the old delimiter. */
5670 while (HTTP_IS_SPHT(*(prev-1)))
5671 prev--;
5672 *from = prev;
5673
5674 /* copy the delimiter and if possible a space if we're
5675 * not at the end of the line.
5676 */
5677 if (next < end) {
5678 *prev++ = *next++;
5679 if (prev + 1 < next)
5680 *prev++ = ' ';
5681 while (next < end && HTTP_IS_SPHT(*next))
5682 next++;
5683 }
5684 }
5685 memmove(prev, next, end - next);
5686 return (prev - next);
5687}
5688
Christopher Faulet0f226952018-10-22 09:29:56 +02005689
5690/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005691 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005692 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005693static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005694{
5695 struct ist dst = ist2(str, 0);
5696
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005697 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005698 goto end;
5699 if (dst.len + 1 > len)
5700 goto end;
5701 dst.ptr[dst.len++] = ' ';
5702
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005703 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005704 goto end;
5705 if (dst.len + 1 > len)
5706 goto end;
5707 dst.ptr[dst.len++] = ' ';
5708
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005709 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 end:
5711 return dst.len;
5712}
5713
Christopher Fauletf0523542018-10-24 11:06:58 +02005714/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005715 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005716 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005717static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005718{
5719 struct ist dst = ist2(str, 0);
5720
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005721 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005722 goto end;
5723 if (dst.len + 1 > len)
5724 goto end;
5725 dst.ptr[dst.len++] = ' ';
5726
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005727 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005728 goto end;
5729 if (dst.len + 1 > len)
5730 goto end;
5731 dst.ptr[dst.len++] = ' ';
5732
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005733 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005734 end:
5735 return dst.len;
5736}
5737
5738
Christopher Faulet0f226952018-10-22 09:29:56 +02005739/*
5740 * Print a debug line with a start line.
5741 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005742static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005743{
5744 struct session *sess = strm_sess(s);
5745 int max;
5746
5747 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5748 dir,
5749 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5750 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5751
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005752 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005753 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005754 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005755 trash.area[trash.data++] = ' ';
5756
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005757 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005758 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005759 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005760 trash.area[trash.data++] = ' ';
5761
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005762 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005763 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005764 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005765 trash.area[trash.data++] = '\n';
5766
5767 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5768}
5769
5770/*
5771 * Print a debug line with a header.
5772 */
5773static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5774{
5775 struct session *sess = strm_sess(s);
5776 int max;
5777
5778 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5779 dir,
5780 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5781 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5782
5783 max = n.len;
5784 UBOUND(max, trash.size - trash.data - 3);
5785 chunk_memcat(&trash, n.ptr, max);
5786 trash.area[trash.data++] = ':';
5787 trash.area[trash.data++] = ' ';
5788
5789 max = v.len;
5790 UBOUND(max, trash.size - trash.data - 1);
5791 chunk_memcat(&trash, v.ptr, max);
5792 trash.area[trash.data++] = '\n';
5793
5794 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5795}
5796
5797
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005798__attribute__((constructor))
5799static void __htx_protocol_init(void)
5800{
5801}
5802
5803
5804/*
5805 * Local variables:
5806 * c-indent-level: 8
5807 * c-basic-offset: 8
5808 * End:
5809 */