blob: 857e820e5886f9b7578af0b3dd596d47e8b84924 [file] [log] [blame]
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02001/*
2 * HTTP protocol analyzer
3 *
4 * Copyright (C) 2018 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Christopher Faulete0768eb2018-10-03 16:38:02 +020013#include <common/base64.h>
14#include <common/config.h>
15#include <common/debug.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
Christopher Faulet0f226952018-10-22 09:29:56 +020019#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020020
21#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020022#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020023#include <proto/channel.h>
24#include <proto/checks.h>
25#include <proto/connection.h>
26#include <proto/filters.h>
27#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020028#include <proto/http_htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020029#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020030#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020031#include <proto/proto_http.h>
32#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020033#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020034#include <proto/stream.h>
35#include <proto/stream_interface.h>
36#include <proto/stats.h>
37
Christopher Faulet377c5a52018-10-24 21:21:30 +020038extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020039
40static void htx_end_request(struct stream *s);
41static void htx_end_response(struct stream *s);
42
Christopher Faulet0f226952018-10-22 09:29:56 +020043static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020044static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010045static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
46static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
47static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
49
Christopher Faulet3e964192018-10-24 11:39:23 +020050static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
51static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
52
Christopher Faulet33640082018-10-24 11:53:01 +020053static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
54static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
55
Christopher Fauletfcda7c62018-10-24 11:56:22 +020056static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
57static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
58
Christopher Faulet377c5a52018-10-24 21:21:30 +020059static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
60static int htx_handle_stats(struct stream *s, struct channel *req);
61
Christopher Faulet4a28a532019-03-01 11:19:40 +010062static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg);
Christopher Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet29f17582019-05-23 11:03:26 +0200135 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet0ef372a2019-04-08 10:57:20 +0200136 if (htx->flags & HTX_FL_UPGRADE)
137 goto failed_keep_alive;
138
Christopher Faulet9768c262018-10-22 09:34:31 +0200139 /* 1: have we encountered a read error ? */
140 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200141 if (!(s->flags & SF_ERR_MASK))
142 s->flags |= SF_ERR_CLICL;
143
144 if (txn->flags & TX_WAIT_NEXT_RQ)
145 goto failed_keep_alive;
146
147 if (sess->fe->options & PR_O_IGNORE_PRB)
148 goto failed_keep_alive;
149
Christopher Faulet9768c262018-10-22 09:34:31 +0200150 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200151 stream_inc_http_req_ctr(s);
152 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100153 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100155 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200156
Christopher Faulet9768c262018-10-22 09:34:31 +0200157 txn->status = 400;
158 msg->err_state = msg->msg_state;
159 msg->msg_state = HTTP_MSG_ERROR;
160 htx_reply_and_close(s, txn->status, NULL);
161 req->analysers &= AN_REQ_FLT_END;
162
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (!(s->flags & SF_FINST_MASK))
164 s->flags |= SF_FINST_R;
165 return 0;
166 }
167
Christopher Faulet9768c262018-10-22 09:34:31 +0200168 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200169 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
170 if (!(s->flags & SF_ERR_MASK))
171 s->flags |= SF_ERR_CLITO;
172
173 if (txn->flags & TX_WAIT_NEXT_RQ)
174 goto failed_keep_alive;
175
176 if (sess->fe->options & PR_O_IGNORE_PRB)
177 goto failed_keep_alive;
178
Christopher Faulet9768c262018-10-22 09:34:31 +0200179 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200180 stream_inc_http_req_ctr(s);
181 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100182 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100184 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200185
Christopher Faulet9768c262018-10-22 09:34:31 +0200186 txn->status = 408;
187 msg->err_state = msg->msg_state;
188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100189 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200190 req->analysers &= AN_REQ_FLT_END;
191
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (!(s->flags & SF_FINST_MASK))
193 s->flags |= SF_FINST_R;
194 return 0;
195 }
196
Christopher Faulet9768c262018-10-22 09:34:31 +0200197 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200198 else if (req->flags & CF_SHUTR) {
199 if (!(s->flags & SF_ERR_MASK))
200 s->flags |= SF_ERR_CLICL;
201
202 if (txn->flags & TX_WAIT_NEXT_RQ)
203 goto failed_keep_alive;
204
205 if (sess->fe->options & PR_O_IGNORE_PRB)
206 goto failed_keep_alive;
207
Christopher Faulete0768eb2018-10-03 16:38:02 +0200208 stream_inc_http_err_ctr(s);
209 stream_inc_http_req_ctr(s);
210 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100211 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100213 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200214
Christopher Faulet9768c262018-10-22 09:34:31 +0200215 txn->status = 400;
216 msg->err_state = msg->msg_state;
217 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100218 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200219 req->analysers &= AN_REQ_FLT_END;
220
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (!(s->flags & SF_FINST_MASK))
222 s->flags |= SF_FINST_R;
223 return 0;
224 }
225
226 channel_dont_connect(req);
227 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
228 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100229
Christopher Faulet9768c262018-10-22 09:34:31 +0200230 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
232 /* We need more data, we have to re-enable quick-ack in case we
233 * previously disabled it, otherwise we might cause the client
234 * to delay next data.
235 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100236 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200237 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet47365272018-10-31 17:40:50 +0100239 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 /* If the client starts to talk, let's fall back to
241 * request timeout processing.
242 */
243 txn->flags &= ~TX_WAIT_NEXT_RQ;
244 req->analyse_exp = TICK_ETERNITY;
245 }
246
247 /* just set the request timeout once at the beginning of the request */
248 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100249 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200250 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
251 else
252 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
253 }
254
255 /* we're not ready yet */
256 return 0;
257
258 failed_keep_alive:
259 /* Here we process low-level errors for keep-alive requests. In
260 * short, if the request is not the first one and it experiences
261 * a timeout, read error or shutdown, we just silently close so
262 * that the client can try again.
263 */
264 txn->status = 0;
265 msg->msg_state = HTTP_MSG_RQBEFORE;
266 req->analysers &= AN_REQ_FLT_END;
267 s->logs.logwait = 0;
268 s->logs.level = 0;
269 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200270 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200271 return 0;
272 }
273
Christopher Faulet9768c262018-10-22 09:34:31 +0200274 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200275 stream_inc_http_req_ctr(s);
276 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 /* kill the pending keep-alive timeout */
279 txn->flags &= ~TX_WAIT_NEXT_RQ;
280 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200281
Christopher Faulet29f17582019-05-23 11:03:26 +0200282 BUG_ON(htx_get_first_type(htx) != HTX_BLK_REQ_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +0200283 sl = http_get_stline(htx);
Christopher Faulet03599112018-11-27 11:21:21 +0100284
Christopher Faulet9768c262018-10-22 09:34:31 +0200285 /* 0: we might have to print this header in debug mode */
286 if (unlikely((global.mode & MODE_DEBUG) &&
287 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
288 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200289
Christopher Faulet03599112018-11-27 11:21:21 +0100290 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200291
Christopher Fauleta3f15502019-05-13 15:27:23 +0200292 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 struct htx_blk *blk = htx_get_blk(htx, pos);
294 enum htx_blk_type type = htx_get_blk_type(blk);
295
296 if (type == HTX_BLK_EOH)
297 break;
298 if (type != HTX_BLK_HDR)
299 continue;
300
301 htx_debug_hdr("clihdr", s,
302 htx_get_blk_name(htx, blk),
303 htx_get_blk_value(htx, blk));
304 }
305 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306
307 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100308 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200309 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100310 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200312 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100313 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100314 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100315 if (sl->flags & HTX_SL_F_BODYLESS)
316 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317
318 /* we can make use of server redirect on GET and HEAD */
319 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
320 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100321 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200322 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 goto return_bad_req;
324 }
325
326 /*
327 * 2: check if the URI matches the monitor_uri.
328 * We have to do this for every request which gets in, because
329 * the monitor-uri is defined by the frontend.
330 */
331 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100332 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200333 /*
334 * We have found the monitor URI
335 */
336 struct acl_cond *cond;
337
338 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100339 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200340
341 /* Check if we want to fail this monitor request or not */
342 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
343 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
344
345 ret = acl_pass(ret);
346 if (cond->pol == ACL_COND_UNLESS)
347 ret = !ret;
348
349 if (ret) {
350 /* we fail this request, let's return 503 service unavail */
351 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100352 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200353 if (!(s->flags & SF_ERR_MASK))
354 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
355 goto return_prx_cond;
356 }
357 }
358
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800359 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100361 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200362 if (!(s->flags & SF_ERR_MASK))
363 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
364 goto return_prx_cond;
365 }
366
367 /*
368 * 3: Maybe we have to copy the original REQURI for the logs ?
369 * Note: we cannot log anymore if the request has been
370 * classified as invalid.
371 */
372 if (unlikely(s->logs.logwait & LW_REQ)) {
373 /* we have a complete HTTP request that we must log */
374 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulet9768c262018-10-22 09:34:31 +0200377 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
378 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200379
380 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
381 s->do_log(s);
382 } else {
383 ha_alert("HTTP logging : out of memory.\n");
384 }
385 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200386
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387 /* if the frontend has "option http-use-proxy-header", we'll check if
388 * we have what looks like a proxied connection instead of a connection,
389 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
390 * Note that this is *not* RFC-compliant, however browsers and proxies
391 * happen to do that despite being non-standard :-(
392 * We consider that a request not beginning with either '/' or '*' is
393 * a proxied connection, which covers both "scheme://location" and
394 * CONNECT ip:port.
395 */
396 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100397 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 txn->flags |= TX_USE_PX_CONN;
399
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400 /* 5: we may need to capture headers */
401 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200402 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200403
Christopher Faulet03b9d8b2019-03-26 22:02:00 +0100404 /* by default, close the stream at the end of the transaction. */
405 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100441 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100442 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100444 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100491 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200492
Christopher Faulet1907ccc2019-04-29 13:12:02 +0200493 /* just in case we have some per-backend tracking. Only called the first
494 * execution of the analyser. */
495 if (!s->current_rule || s->current_rule_list != &px->http_req_rules)
496 stream_inc_be_http_req_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200497
498 /* evaluate http-request rules */
499 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501
502 switch (verdict) {
503 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
504 goto return_prx_yield;
505
506 case HTTP_RULE_RES_CONT:
507 case HTTP_RULE_RES_STOP: /* nothing to do */
508 break;
509
510 case HTTP_RULE_RES_DENY: /* deny or tarpit */
511 if (txn->flags & TX_CLTARPIT)
512 goto tarpit;
513 goto deny;
514
515 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
516 goto return_prx_cond;
517
518 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
519 goto done;
520
521 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
522 goto return_bad_req;
523 }
524 }
525
526 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
527 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200529
Christopher Fauletff2759f2018-10-24 11:13:16 +0200530 ctx.blk = NULL;
531 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
532 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535 }
536
537 /* OK at this stage, we know that the request was accepted according to
538 * the http-request rules, we can check for the stats. Note that the
539 * URI is detected *before* the req* rules in order not to be affected
540 * by a possible reqrep, while they are processed *after* so that a
541 * reqdeny can still block them. This clearly needs to change in 1.6!
542 */
Christopher Faulet4629d082019-07-04 11:27:15 +0200543 if (!s->target && htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100545 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200546 txn->status = 500;
547 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100548 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549
550 if (!(s->flags & SF_ERR_MASK))
551 s->flags |= SF_ERR_RESOURCE;
552 goto return_prx_cond;
553 }
554
555 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200556 htx_handle_stats(s, req);
557 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558 /* not all actions implemented: deny, allow, auth */
559
560 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
561 goto deny;
562
563 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
564 goto return_prx_cond;
565 }
566
567 /* evaluate the req* rules except reqadd */
568 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200569 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200570 goto return_bad_req;
571
572 if (txn->flags & TX_CLDENY)
573 goto deny;
574
575 if (txn->flags & TX_CLTARPIT) {
576 deny_status = HTTP_ERR_500;
577 goto tarpit;
578 }
579 }
580
581 /* add request headers from the rule sets in the same order */
582 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200583 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200584 if (wl->cond) {
585 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
586 ret = acl_pass(ret);
587 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
588 ret = !ret;
589 if (!ret)
590 continue;
591 }
592
Christopher Fauletff2759f2018-10-24 11:13:16 +0200593 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
594 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 goto return_bad_req;
596 }
597
Christopher Faulet2571bc62019-03-01 11:44:26 +0100598 /* Proceed with the applets now. */
599 if (unlikely(objt_applet(s->target))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100601 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200602
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100603 if (htx_handle_expect_hdr(s, htx, msg) == -1)
604 goto return_bad_req;
605
Christopher Faulete0768eb2018-10-03 16:38:02 +0200606 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
607 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
608 if (!(s->flags & SF_FINST_MASK))
609 s->flags |= SF_FINST_R;
610
611 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
612 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
613 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
614 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Christopher Fauletbcf242a2019-03-01 11:36:26 +0100615
616 req->flags |= CF_SEND_DONTWAIT;
617 s->flags |= SF_ASSIGNED;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100666 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100681 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200682 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100683 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100685 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100698 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100700 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100702 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200703 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100704 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100711 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
Olivier Houcharda798bf52019-03-08 18:52:00 +0100713 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100715 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100766 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100775 struct htx_sl *sl;
776 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100784 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Faulet297fbb42019-05-13 14:41:27 +0200793 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100794 uri = htx_sl_req_uri(sl);
795 path = http_get_path(uri);
796 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797 goto return_bad_req;
798
799 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 * uri.ptr and path.ptr (excluded). If it was not found, we need
801 * to replace from all the uri by a single "/".
802 *
803 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100804 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200806 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100807 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Willy Tarreau3284dd22019-07-18 16:17:15 +0200808 conn->target = &s->be->obj_type;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 }
810
811 /*
812 * 7: Now we can work with the cookies.
813 * Note that doing so might move headers in the request, but
814 * the fields will stay coherent and the URI will not move.
815 * This should only be performed in the backend.
816 */
817 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100818 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200819
820 /* add unique-id if "header-unique-id" is specified */
821
822 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
823 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
824 goto return_bad_req;
825 s->unique_id[0] = '\0';
826 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
827 }
828
829 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200830 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
831 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
832
833 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 }
836
837 /*
838 * 9: add X-Forwarded-For if either the frontend or the backend
839 * asks for it.
840 */
841 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200842 struct http_hdr_ctx ctx = { .blk = NULL };
843 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
844 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
845
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200847 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200848 /* The header is set to be added only if none is present
849 * and we found it, so don't do anything.
850 */
851 }
852 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
853 /* Add an X-Forwarded-For header unless the source IP is
854 * in the 'except' network range.
855 */
856 if ((!sess->fe->except_mask.s_addr ||
857 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
858 != sess->fe->except_net.s_addr) &&
859 (!s->be->except_mask.s_addr ||
860 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
861 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200862 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200863
864 /* Note: we rely on the backend to get the header name to be used for
865 * x-forwarded-for, because the header is really meant for the backends.
866 * However, if the backend did not specify any option, we have to rely
867 * on the frontend's header name.
868 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
870 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200871 goto return_bad_req;
872 }
873 }
874 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
875 /* FIXME: for the sake of completeness, we should also support
876 * 'except' here, although it is mostly useless in this case.
877 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200879
Christopher Faulete0768eb2018-10-03 16:38:02 +0200880 inet_ntop(AF_INET6,
881 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
882 pn, sizeof(pn));
883
884 /* Note: we rely on the backend to get the header name to be used for
885 * x-forwarded-for, because the header is really meant for the backends.
886 * However, if the backend did not specify any option, we have to rely
887 * on the frontend's header name.
888 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200889 chunk_printf(&trash, "%s", pn);
890 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 goto return_bad_req;
892 }
893 }
894
895 /*
896 * 10: add X-Original-To if either the frontend or the backend
897 * asks for it.
898 */
899 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
900
901 /* FIXME: don't know if IPv6 can handle that case too. */
902 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
903 /* Add an X-Original-To header unless the destination IP is
904 * in the 'except' network range.
905 */
906 conn_get_to_addr(cli_conn);
907
908 if (cli_conn->addr.to.ss_family == AF_INET &&
909 ((!sess->fe->except_mask_to.s_addr ||
910 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
911 != sess->fe->except_to.s_addr) &&
912 (!s->be->except_mask_to.s_addr ||
913 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
914 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200915 struct ist hdr;
916 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200917
918 /* Note: we rely on the backend to get the header name to be used for
919 * x-original-to, because the header is really meant for the backends.
920 * However, if the backend did not specify any option, we have to rely
921 * on the frontend's header name.
922 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200923 if (s->be->orgto_hdr_len)
924 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
925 else
926 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200927
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200928 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
929 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200930 goto return_bad_req;
931 }
932 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200933 }
934
Christopher Faulete0768eb2018-10-03 16:38:02 +0200935 /* If we have no server assigned yet and we're balancing on url_param
936 * with a POST request, we may be interested in checking the body for
937 * that parameter. This will be done in another analyser.
938 */
939 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100940 s->txn->meth == HTTP_METH_POST &&
941 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100948
Christopher Faulete0768eb2018-10-03 16:38:02 +0200949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200955 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957
958 /*************************************************************
959 * OK, that's finished for the headers. We have done what we *
960 * could. Let's switch to the DATA state. *
961 ************************************************************/
962 req->analyse_exp = TICK_ETERNITY;
963 req->analysers &= ~an_bit;
964
965 s->logs.tv_request = now;
966 /* OK let's go on with the BODY now */
967 return 1;
968
969 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200970 txn->req.err_state = txn->req.msg_state;
971 txn->req.msg_state = HTTP_MSG_ERROR;
972 txn->status = 400;
973 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100974 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
Olivier Houcharda798bf52019-03-08 18:52:00 +0100976 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100978 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_R;
984 return 0;
985}
986
987/* This function is an analyser which processes the HTTP tarpit. It always
988 * returns zero, at the beginning because it prevents any other processing
989 * from occurring, and at the end because it terminates the request.
990 */
991int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
992{
993 struct http_txn *txn = s->txn;
994
995 /* This connection is being tarpitted. The CLIENT side has
996 * already set the connect expiration date to the right
997 * timeout. We just have to check that the client is still
998 * there and that the timeout has not expired.
999 */
1000 channel_dont_connect(req);
1001 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1002 !tick_is_expired(req->analyse_exp, now_ms))
1003 return 0;
1004
1005 /* We will set the queue timer to the time spent, just for
1006 * logging purposes. We fake a 500 server error, so that the
1007 * attacker will not suspect his connection has been tarpitted.
1008 * It will not cause trouble to the logs because we can exclude
1009 * the tarpitted connections by filtering on the 'PT' status flags.
1010 */
1011 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1012
1013 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001014 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001015
1016 req->analysers &= AN_REQ_FLT_END;
1017 req->analyse_exp = TICK_ETERNITY;
1018
1019 if (!(s->flags & SF_ERR_MASK))
1020 s->flags |= SF_ERR_PRXCOND;
1021 if (!(s->flags & SF_FINST_MASK))
1022 s->flags |= SF_FINST_T;
1023 return 0;
1024}
1025
1026/* This function is an analyser which waits for the HTTP request body. It waits
1027 * for either the buffer to be full, or the full advertised contents to have
1028 * reached the buffer. It must only be called after the standard HTTP request
1029 * processing has occurred, because it expects the request to be parsed and will
1030 * look for the Expect header. It may send a 100-Continue interim response. It
1031 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1032 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1033 * needs to read more data, or 1 once it has completed its analysis.
1034 */
1035int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1036{
1037 struct session *sess = s->sess;
1038 struct http_txn *txn = s->txn;
1039 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001040 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001041
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001042
1043 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1044 now_ms, __FUNCTION__,
1045 s,
1046 req,
1047 req->rex, req->wex,
1048 req->flags,
1049 ci_data(req),
1050 req->analysers);
1051
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001052 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053
Willy Tarreau4236f032019-03-05 10:43:32 +01001054 if (htx->flags & HTX_FL_PARSING_ERROR)
1055 goto return_bad_req;
1056
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057 if (msg->msg_state < HTTP_MSG_BODY)
1058 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001059
Christopher Faulete0768eb2018-10-03 16:38:02 +02001060 /* We have to parse the HTTP request body to find any required data.
1061 * "balance url_param check_post" should have been the only way to get
1062 * into this. We were brought here after HTTP header analysis, so all
1063 * related structures are ready.
1064 */
1065
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001066 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001067 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1068 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001069 }
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001073 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1074 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001075 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001076 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001077 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001078 goto http_end;
1079
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001080 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001081 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1082 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001083 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
1085 if (!(s->flags & SF_ERR_MASK))
1086 s->flags |= SF_ERR_CLITO;
1087 if (!(s->flags & SF_FINST_MASK))
1088 s->flags |= SF_FINST_D;
1089 goto return_err_msg;
1090 }
1091
1092 /* we get here if we need to wait for more data */
1093 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1094 /* Not enough data. We'll re-use the http-request
1095 * timeout here. Ideally, we should set the timeout
1096 * relative to the accept() date. We just set the
1097 * request timeout once at the beginning of the
1098 * request.
1099 */
1100 channel_dont_connect(req);
1101 if (!tick_isset(req->analyse_exp))
1102 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1103 return 0;
1104 }
1105
1106 http_end:
1107 /* The situation will not evolve, so let's give up on the analysis. */
1108 s->logs.tv_request = now; /* update the request timer to reflect full request */
1109 req->analysers &= ~an_bit;
1110 req->analyse_exp = TICK_ETERNITY;
1111 return 1;
1112
1113 return_bad_req: /* let's centralize all bad requests */
1114 txn->req.err_state = txn->req.msg_state;
1115 txn->req.msg_state = HTTP_MSG_ERROR;
1116 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001117 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001118
1119 if (!(s->flags & SF_ERR_MASK))
1120 s->flags |= SF_ERR_PRXCOND;
1121 if (!(s->flags & SF_FINST_MASK))
1122 s->flags |= SF_FINST_R;
1123
1124 return_err_msg:
1125 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001126 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001127 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001128 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001129 return 0;
1130}
1131
1132/* This function is an analyser which forwards request body (including chunk
1133 * sizes if any). It is called as soon as we must forward, even if we forward
1134 * zero byte. The only situation where it must not be called is when we're in
1135 * tunnel mode and we want to forward till the close. It's used both to forward
1136 * remaining data and to resync after end of body. It expects the msg_state to
1137 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1138 * read more data, or 1 once we can go on with next request or end the stream.
1139 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1140 * bytes of pending data + the headers if not already done.
1141 */
1142int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1143{
1144 struct session *sess = s->sess;
1145 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001146 struct http_msg *msg = &txn->req;
1147 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001148 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001149 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001150
1151 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1152 now_ms, __FUNCTION__,
1153 s,
1154 req,
1155 req->rex, req->wex,
1156 req->flags,
1157 ci_data(req),
1158 req->analysers);
1159
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001160 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001161
1162 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1163 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1164 /* Output closed while we were sending data. We must abort and
1165 * wake the other side up.
1166 */
Olivier Houcharde8b04b12019-07-12 15:48:58 +02001167 /* Don't abort yet if we had L7 retries activated and it
1168 * was a write error, we may recover.
1169 */
1170 if (!(req->flags & (CF_READ_ERROR | CF_READ_TIMEOUT)) &&
1171 (s->si[1].flags & SI_FL_L7_RETRY))
1172 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001173 msg->err_state = msg->msg_state;
1174 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001175 htx_end_request(s);
1176 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001177 return 1;
1178 }
1179
1180 /* Note that we don't have to send 100-continue back because we don't
1181 * need the data to complete our job, and it's up to the server to
1182 * decide whether to return 100, 417 or anything else in return of
1183 * an "Expect: 100-continue" header.
1184 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001185 if (msg->msg_state == HTTP_MSG_BODY)
1186 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001187
1188 /* Some post-connect processing might want us to refrain from starting to
1189 * forward data. Currently, the only reason for this is "balance url_param"
1190 * whichs need to parse/process the request after we've enabled forwarding.
1191 */
1192 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1193 if (!(s->res.flags & CF_READ_ATTACHED)) {
1194 channel_auto_connect(req);
1195 req->flags |= CF_WAKE_CONNECT;
1196 channel_dont_close(req); /* don't fail on early shutr */
1197 goto waiting;
1198 }
1199 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1200 }
1201
1202 /* in most states, we should abort in case of early close */
1203 channel_auto_close(req);
1204
1205 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001206 if (req->to_forward == CHN_INFINITE_FORWARD) {
1207 if (req->flags & (CF_SHUTR|CF_EOI)) {
1208 msg->msg_state = HTTP_MSG_DONE;
1209 req->to_forward = 0;
1210 goto done;
1211 }
1212 }
1213 else {
1214 /* We can't process the buffer's contents yet */
1215 req->flags |= CF_WAKE_WRITE;
1216 goto missing_data_or_waiting;
1217 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001218 }
1219
Christopher Faulet9768c262018-10-22 09:34:31 +02001220 if (msg->msg_state >= HTTP_MSG_DONE)
1221 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001222 /* Forward input data. We get it by removing all outgoing data not
1223 * forwarded yet from HTX data size. If there are some data filters, we
1224 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001225 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001226 if (HAS_REQ_DATA_FILTERS(s)) {
1227 ret = flt_http_payload(s, msg, htx->data);
1228 if (ret < 0)
1229 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001230 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001231 }
1232 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001233 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001234 if (msg->flags & HTTP_MSGF_XFER_LEN)
1235 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001236 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001237
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001238 if (txn->meth == HTTP_METH_CONNECT) {
1239 msg->msg_state = HTTP_MSG_TUNNEL;
1240 goto done;
1241 }
1242
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001243
Christopher Faulet9768c262018-10-22 09:34:31 +02001244 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001245 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1246 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001247 */
1248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1249 goto missing_data_or_waiting;
1250
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001251 msg->msg_state = HTTP_MSG_ENDING;
1252 if (htx->data != co_data(req))
1253 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001254 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001255 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001256
1257 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258 /* other states, DONE...TUNNEL */
1259 /* we don't want to forward closes on DONE except in tunnel mode. */
1260 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1261 channel_dont_close(req);
1262
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001263 if (HAS_REQ_DATA_FILTERS(s)) {
1264 ret = flt_http_end(s, msg);
1265 if (ret <= 0) {
1266 if (!ret)
1267 goto missing_data_or_waiting;
1268 goto return_bad_req;
1269 }
1270 }
1271
Christopher Fauletf2824e62018-10-01 12:12:37 +02001272 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001273 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001274 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001275 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1276 if (req->flags & CF_SHUTW) {
1277 /* request errors are most likely due to the
1278 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001279 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001281 goto return_bad_req;
1282 }
1283 return 1;
1284 }
1285
1286 /* If "option abortonclose" is set on the backend, we want to monitor
1287 * the client's connection and forward any shutdown notification to the
1288 * server, which will decide whether to close or to go on processing the
1289 * request. We only do that in tunnel mode, and not in other modes since
1290 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001291 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001292 channel_auto_read(req);
1293 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1294 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1295 s->si[1].flags |= SI_FL_NOLINGER;
1296 channel_auto_close(req);
1297 }
1298 else if (s->txn->meth == HTTP_METH_POST) {
1299 /* POST requests may require to read extra CRLF sent by broken
1300 * browsers and which could cause an RST to be sent upon close
1301 * on some systems (eg: Linux). */
1302 channel_auto_read(req);
1303 }
1304 return 0;
1305
1306 missing_data_or_waiting:
1307 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001308 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001309 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001310
1311 waiting:
1312 /* waiting for the last bits to leave the buffer */
1313 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001314 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001315
Christopher Faulet47365272018-10-31 17:40:50 +01001316 if (htx->flags & HTX_FL_PARSING_ERROR)
1317 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001318
Christopher Faulete0768eb2018-10-03 16:38:02 +02001319 /* When TE: chunked is used, we need to get there again to parse remaining
1320 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1321 * And when content-length is used, we never want to let the possible
1322 * shutdown be forwarded to the other side, as the state machine will
1323 * take care of it once the client responds. It's also important to
1324 * prevent TIME_WAITs from accumulating on the backend side, and for
1325 * HTTP/2 where the last frame comes with a shutdown.
1326 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001327 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001328 channel_dont_close(req);
1329
1330 /* We know that more data are expected, but we couldn't send more that
1331 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1332 * system knows it must not set a PUSH on this first part. Interactive
1333 * modes are already handled by the stream sock layer. We must not do
1334 * this in content-length mode because it could present the MSG_MORE
1335 * flag with the last block of forwarded data, which would cause an
1336 * additional delay to be observed by the receiver.
1337 */
1338 if (msg->flags & HTTP_MSGF_TE_CHNK)
1339 req->flags |= CF_EXPECT_MORE;
1340
1341 return 0;
1342
Christopher Faulet93e02d82019-03-08 14:18:50 +01001343 return_cli_abort:
1344 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1345 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1346 if (objt_server(s->target))
1347 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1348 if (!(s->flags & SF_ERR_MASK))
1349 s->flags |= SF_ERR_CLICL;
1350 status = 400;
1351 goto return_error;
1352
1353 return_srv_abort:
1354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1355 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1356 if (objt_server(s->target))
1357 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1358 if (!(s->flags & SF_ERR_MASK))
1359 s->flags |= SF_ERR_SRVCL;
1360 status = 502;
1361 goto return_error;
1362
1363 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001364 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001366 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001368 s->flags |= SF_ERR_CLICL;
1369 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370
Christopher Faulet93e02d82019-03-08 14:18:50 +01001371 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 txn->req.err_state = txn->req.msg_state;
1373 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001374 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001376 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001378 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001379 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001380 }
1381 req->analysers &= AN_REQ_FLT_END;
1382 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 +01001383 if (!(s->flags & SF_FINST_MASK))
1384 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001385 return 0;
1386}
1387
Olivier Houcharda254a372019-04-05 15:30:12 +02001388/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1389/* Returns 0 if we can attempt to retry, -1 otherwise */
1390static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1391{
1392 struct channel *req, *res;
1393 int co_data;
1394
1395 si->conn_retries--;
1396 if (si->conn_retries < 0)
1397 return -1;
1398
Willy Tarreau223995e2019-05-04 10:38:31 +02001399 if (objt_server(s->target))
1400 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1401 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1402
Olivier Houcharda254a372019-04-05 15:30:12 +02001403 req = &s->req;
1404 res = &s->res;
1405 /* Remove any write error from the request, and read error from the response */
1406 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1407 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1408 res->analysers = 0;
1409 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
Olivier Houchard530249c2019-07-12 16:16:59 +02001410 stream_choose_redispatch(s);
Olivier Houcharda254a372019-04-05 15:30:12 +02001411 si->exp = TICK_ETERNITY;
1412 res->rex = TICK_ETERNITY;
1413 res->to_forward = 0;
1414 res->analyse_exp = TICK_ETERNITY;
1415 res->total = 0;
Olivier Houchard530249c2019-07-12 16:16:59 +02001416 s->flags &= ~(SF_ERR_SRVTO | SF_ERR_SRVCL);
Olivier Houcharda254a372019-04-05 15:30:12 +02001417 si_release_endpoint(&s->si[1]);
1418 b_free(&req->buf);
1419 /* Swap the L7 buffer with the channel buffer */
1420 /* We know we stored the co_data as b_data, so get it there */
1421 co_data = b_data(&si->l7_buffer);
1422 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1423 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1424
1425 co_set_data(req, co_data);
1426 b_reset(&res->buf);
1427 co_set_data(res, 0);
1428 return 0;
1429}
1430
Christopher Faulete0768eb2018-10-03 16:38:02 +02001431/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1432 * processing can continue on next analysers, or zero if it either needs more
1433 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1434 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1435 * when it has nothing left to do, and may remove any analyser when it wants to
1436 * abort.
1437 */
1438int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1439{
Christopher Faulet9768c262018-10-22 09:34:31 +02001440 /*
1441 * We will analyze a complete HTTP response to check the its syntax.
1442 *
1443 * Once the start line and all headers are received, we may perform a
1444 * capture of the error (if any), and we will set a few fields. We also
1445 * logging and finally headers capture.
1446 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001447 struct session *sess = s->sess;
1448 struct http_txn *txn = s->txn;
1449 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001450 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001451 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001452 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001453 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454 int n;
1455
1456 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1457 now_ms, __FUNCTION__,
1458 s,
1459 rep,
1460 rep->rex, rep->wex,
1461 rep->flags,
1462 ci_data(rep),
1463 rep->analysers);
1464
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001465 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001466
Willy Tarreau4236f032019-03-05 10:43:32 +01001467 /* Parsing errors are caught here */
1468 if (htx->flags & HTX_FL_PARSING_ERROR)
1469 goto return_bad_res;
1470
Christopher Faulete0768eb2018-10-03 16:38:02 +02001471 /*
1472 * Now we quickly check if we have found a full valid response.
1473 * If not so, we check the FD and buffer states before leaving.
1474 * A full response is indicated by the fact that we have seen
1475 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1476 * responses are checked first.
1477 *
1478 * Depending on whether the client is still there or not, we
1479 * may send an error response back or not. Note that normally
1480 * we should only check for HTTP status there, and check I/O
1481 * errors somewhere else.
1482 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001483 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001484 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001485 /* 1: have we encountered a read error ? */
1486 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001487 struct connection *conn = NULL;
1488
Olivier Houchard865d8392019-05-03 22:46:27 +02001489 if (objt_cs(s->si[1].end))
1490 conn = objt_cs(s->si[1].end)->conn;
1491
1492 if (si_b->flags & SI_FL_L7_RETRY &&
1493 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001494 /* If we arrive here, then CF_READ_ERROR was
1495 * set by si_cs_recv() because we matched a
1496 * status, overwise it would have removed
1497 * the SI_FL_L7_RETRY flag, so it's ok not
1498 * to check s->be->retry_type.
1499 */
1500 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1501 return 0;
1502 }
1503
Olivier Houchard6db16992019-05-17 15:40:49 +02001504 if (txn->flags & TX_NOT_FIRST)
1505 goto abort_keep_alive;
1506
Olivier Houcharda798bf52019-03-08 18:52:00 +01001507 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001509 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001510 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511 }
1512
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513 rep->analysers &= AN_RES_FLT_END;
1514 txn->status = 502;
1515
1516 /* Check to see if the server refused the early data.
1517 * If so, just send a 425
1518 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001519 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1520 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001521 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001522 do_l7_retry(s, si_b) == 0)
1523 return 0;
1524 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 }
1526
1527 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001528 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529
1530 if (!(s->flags & SF_ERR_MASK))
1531 s->flags |= SF_ERR_SRVCL;
1532 if (!(s->flags & SF_FINST_MASK))
1533 s->flags |= SF_FINST_H;
1534 return 0;
1535 }
1536
Christopher Faulet9768c262018-10-22 09:34:31 +02001537 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001539 if ((si_b->flags & SI_FL_L7_RETRY) &&
1540 (s->be->retry_type & PR_RE_TIMEOUT)) {
1541 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1542 return 0;
1543 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001544 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001546 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001547 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 }
1549
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 rep->analysers &= AN_RES_FLT_END;
1551 txn->status = 504;
1552 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001553 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554
1555 if (!(s->flags & SF_ERR_MASK))
1556 s->flags |= SF_ERR_SRVTO;
1557 if (!(s->flags & SF_FINST_MASK))
1558 s->flags |= SF_FINST_H;
1559 return 0;
1560 }
1561
Christopher Faulet9768c262018-10-22 09:34:31 +02001562 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001564 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1565 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001566 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001567 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568
1569 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001570 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001571 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572
1573 if (!(s->flags & SF_ERR_MASK))
1574 s->flags |= SF_ERR_CLICL;
1575 if (!(s->flags & SF_FINST_MASK))
1576 s->flags |= SF_FINST_H;
1577
1578 /* process_stream() will take care of the error */
1579 return 0;
1580 }
1581
Christopher Faulet9768c262018-10-22 09:34:31 +02001582 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001584 if ((si_b->flags & SI_FL_L7_RETRY) &&
1585 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1586 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1587 return 0;
1588 }
1589
Olivier Houchard6db16992019-05-17 15:40:49 +02001590 if (txn->flags & TX_NOT_FIRST)
1591 goto abort_keep_alive;
1592
Olivier Houcharda798bf52019-03-08 18:52:00 +01001593 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001594 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001595 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001596 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001597 }
1598
Christopher Faulete0768eb2018-10-03 16:38:02 +02001599 rep->analysers &= AN_RES_FLT_END;
1600 txn->status = 502;
1601 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001602 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001603
1604 if (!(s->flags & SF_ERR_MASK))
1605 s->flags |= SF_ERR_SRVCL;
1606 if (!(s->flags & SF_FINST_MASK))
1607 s->flags |= SF_FINST_H;
1608 return 0;
1609 }
1610
Christopher Faulet9768c262018-10-22 09:34:31 +02001611 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001613 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614 goto abort_keep_alive;
1615
Olivier Houcharda798bf52019-03-08 18:52:00 +01001616 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001617 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618
1619 if (!(s->flags & SF_ERR_MASK))
1620 s->flags |= SF_ERR_CLICL;
1621 if (!(s->flags & SF_FINST_MASK))
1622 s->flags |= SF_FINST_H;
1623
1624 /* process_stream() will take care of the error */
1625 return 0;
1626 }
1627
1628 channel_dont_close(rep);
1629 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1630 return 0;
1631 }
1632
1633 /* More interesting part now : we know that we have a complete
1634 * response which at least looks like HTTP. We have an indicator
1635 * of each header's length, so we can parse them quickly.
1636 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001637 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001638 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001639 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001640
Christopher Faulet9768c262018-10-22 09:34:31 +02001641 /* 0: we might have to print this header in debug mode */
1642 if (unlikely((global.mode & MODE_DEBUG) &&
1643 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1644 int32_t pos;
1645
Christopher Faulet03599112018-11-27 11:21:21 +01001646 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001647
Christopher Fauleta3f15502019-05-13 15:27:23 +02001648 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001649 struct htx_blk *blk = htx_get_blk(htx, pos);
1650 enum htx_blk_type type = htx_get_blk_type(blk);
1651
1652 if (type == HTX_BLK_EOH)
1653 break;
1654 if (type != HTX_BLK_HDR)
1655 continue;
1656
1657 htx_debug_hdr("srvhdr", s,
1658 htx_get_blk_name(htx, blk),
1659 htx_get_blk_value(htx, blk));
1660 }
1661 }
1662
Christopher Faulet03599112018-11-27 11:21:21 +01001663 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001664 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001665 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001666 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001667 if (sl->flags & HTX_SL_F_XFER_LEN) {
1668 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001669 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001670 if (sl->flags & HTX_SL_F_BODYLESS)
1671 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001672 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001673
1674 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675 if (n < 1 || n > 5)
1676 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001677
Christopher Faulete0768eb2018-10-03 16:38:02 +02001678 /* when the client triggers a 4xx from the server, it's most often due
1679 * to a missing object or permission. These events should be tracked
1680 * because if they happen often, it may indicate a brute force or a
1681 * vulnerability scan.
1682 */
1683 if (n == 4)
1684 stream_inc_http_err_ctr(s);
1685
1686 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001687 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001688
Christopher Faulete0768eb2018-10-03 16:38:02 +02001689 /* Adjust server's health based on status code. Note: status codes 501
1690 * and 505 are triggered on demand by client request, so we must not
1691 * count them as server failures.
1692 */
1693 if (objt_server(s->target)) {
1694 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001695 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001696 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001697 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001698 }
1699
1700 /*
1701 * We may be facing a 100-continue response, or any other informational
1702 * 1xx response which is non-final, in which case this is not the right
1703 * response, and we're waiting for the next one. Let's allow this response
1704 * to go to the client and wait for the next one. There's an exception for
1705 * 101 which is used later in the code to switch protocols.
1706 */
1707 if (txn->status < 200 &&
1708 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001709 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001710 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001711 msg->msg_state = HTTP_MSG_RPBEFORE;
Christopher Faulet6b0066e2019-09-03 15:23:54 +02001712 msg->flags = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713 txn->status = 0;
1714 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001715 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001716 }
1717
1718 /*
1719 * 2: check for cacheability.
1720 */
1721
1722 switch (txn->status) {
1723 case 200:
1724 case 203:
1725 case 204:
1726 case 206:
1727 case 300:
1728 case 301:
1729 case 404:
1730 case 405:
1731 case 410:
1732 case 414:
1733 case 501:
1734 break;
1735 default:
1736 /* RFC7231#6.1:
1737 * Responses with status codes that are defined as
1738 * cacheable by default (e.g., 200, 203, 204, 206,
1739 * 300, 301, 404, 405, 410, 414, and 501 in this
1740 * specification) can be reused by a cache with
1741 * heuristic expiration unless otherwise indicated
1742 * by the method definition or explicit cache
1743 * controls [RFC7234]; all other status codes are
1744 * not cacheable by default.
1745 */
1746 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1747 break;
1748 }
1749
1750 /*
1751 * 3: we may need to capture headers
1752 */
1753 s->logs.logwait &= ~LW_RESP;
1754 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001755 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001756
Christopher Faulet9768c262018-10-22 09:34:31 +02001757 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001758 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1759 txn->status == 101)) {
1760 /* Either we've established an explicit tunnel, or we're
1761 * switching the protocol. In both cases, we're very unlikely
1762 * to understand the next protocols. We have to switch to tunnel
1763 * mode, so that we transfer the request and responses then let
1764 * this protocol pass unmodified. When we later implement specific
1765 * parsers for such protocols, we'll want to check the Upgrade
1766 * header which contains information about that protocol for
1767 * responses with status 101 (eg: see RFC2817 about TLS).
1768 */
1769 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001770 }
1771
Christopher Faulet61608322018-11-23 16:23:45 +01001772 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1773 * 407 (Proxy-Authenticate) responses and set the connection to private
1774 */
1775 srv_conn = cs_conn(objt_cs(s->si[1].end));
1776 if (srv_conn) {
1777 struct ist hdr;
1778 struct http_hdr_ctx ctx;
1779
1780 if (txn->status == 401)
1781 hdr = ist("WWW-Authenticate");
1782 else if (txn->status == 407)
1783 hdr = ist("Proxy-Authenticate");
1784 else
1785 goto end;
1786
1787 ctx.blk = NULL;
1788 while (http_find_header(htx, hdr, &ctx, 0)) {
1789 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001790 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1791 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001792 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001793 }
Christopher Faulet61608322018-11-23 16:23:45 +01001794 }
1795 }
1796
1797 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001798 /* we want to have the response time before we start processing it */
1799 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1800
1801 /* end of job, return OK */
1802 rep->analysers &= ~an_bit;
1803 rep->analyse_exp = TICK_ETERNITY;
1804 channel_auto_close(rep);
1805 return 1;
1806
Christopher Faulet47365272018-10-31 17:40:50 +01001807 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001808 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001809 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001810 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001811 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001812 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001813 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001814 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001815 do_l7_retry(s, si_b) == 0)
1816 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001817 txn->status = 502;
1818 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001819 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001820 rep->analysers &= AN_RES_FLT_END;
1821
1822 if (!(s->flags & SF_ERR_MASK))
1823 s->flags |= SF_ERR_PRXCOND;
1824 if (!(s->flags & SF_FINST_MASK))
1825 s->flags |= SF_FINST_H;
1826 return 0;
1827
Christopher Faulete0768eb2018-10-03 16:38:02 +02001828 abort_keep_alive:
1829 /* A keep-alive request to the server failed on a network error.
1830 * The client is required to retry. We need to close without returning
1831 * any other information so that the client retries.
1832 */
1833 txn->status = 0;
1834 rep->analysers &= AN_RES_FLT_END;
1835 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001836 s->logs.logwait = 0;
1837 s->logs.level = 0;
1838 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001839 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001840 return 0;
1841}
1842
1843/* This function performs all the processing enabled for the current response.
1844 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1845 * and updates s->res.analysers. It might make sense to explode it into several
1846 * other functions. It works like process_request (see indications above).
1847 */
1848int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1849{
1850 struct session *sess = s->sess;
1851 struct http_txn *txn = s->txn;
1852 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001853 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001854 struct proxy *cur_proxy;
1855 struct cond_wordlist *wl;
1856 enum rule_result ret = HTTP_RULE_RES_CONT;
1857
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001858 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1859 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001860
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1862 now_ms, __FUNCTION__,
1863 s,
1864 rep,
1865 rep->rex, rep->wex,
1866 rep->flags,
1867 ci_data(rep),
1868 rep->analysers);
1869
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001870 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871
1872 /* The stats applet needs to adjust the Connection header but we don't
1873 * apply any filter there.
1874 */
1875 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1876 rep->analysers &= ~an_bit;
1877 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001878 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879 }
1880
1881 /*
1882 * We will have to evaluate the filters.
1883 * As opposed to version 1.2, now they will be evaluated in the
1884 * filters order and not in the header order. This means that
1885 * each filter has to be validated among all headers.
1886 *
1887 * Filters are tried with ->be first, then with ->fe if it is
1888 * different from ->be.
1889 *
1890 * Maybe we are in resume condiion. In this case I choose the
1891 * "struct proxy" which contains the rule list matching the resume
1892 * pointer. If none of theses "struct proxy" match, I initialise
1893 * the process with the first one.
1894 *
1895 * In fact, I check only correspondance betwwen the current list
1896 * pointer and the ->fe rule list. If it doesn't match, I initialize
1897 * the loop with the ->be.
1898 */
1899 if (s->current_rule_list == &sess->fe->http_res_rules)
1900 cur_proxy = sess->fe;
1901 else
1902 cur_proxy = s->be;
1903 while (1) {
1904 struct proxy *rule_set = cur_proxy;
1905
1906 /* evaluate http-response rules */
1907 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001908 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001909
1910 if (ret == HTTP_RULE_RES_BADREQ)
1911 goto return_srv_prx_502;
1912
1913 if (ret == HTTP_RULE_RES_DONE) {
1914 rep->analysers &= ~an_bit;
1915 rep->analyse_exp = TICK_ETERNITY;
1916 return 1;
1917 }
1918 }
1919
1920 /* we need to be called again. */
1921 if (ret == HTTP_RULE_RES_YIELD) {
1922 channel_dont_close(rep);
1923 return 0;
1924 }
1925
1926 /* try headers filters */
1927 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001928 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1929 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001930 }
1931
1932 /* has the response been denied ? */
1933 if (txn->flags & TX_SVDENY) {
1934 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001935 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001936
Olivier Houcharda798bf52019-03-08 18:52:00 +01001937 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1938 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001939 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001940 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001941 goto return_srv_prx_502;
1942 }
1943
1944 /* add response headers from the rule sets in the same order */
1945 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001946 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001947 if (txn->status < 200 && txn->status != 101)
1948 break;
1949 if (wl->cond) {
1950 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1951 ret = acl_pass(ret);
1952 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1953 ret = !ret;
1954 if (!ret)
1955 continue;
1956 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001957
1958 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1959 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001960 goto return_bad_resp;
1961 }
1962
1963 /* check whether we're already working on the frontend */
1964 if (cur_proxy == sess->fe)
1965 break;
1966 cur_proxy = sess->fe;
1967 }
1968
1969 /* After this point, this anayzer can't return yield, so we can
1970 * remove the bit corresponding to this analyzer from the list.
1971 *
1972 * Note that the intermediate returns and goto found previously
1973 * reset the analyzers.
1974 */
1975 rep->analysers &= ~an_bit;
1976 rep->analyse_exp = TICK_ETERNITY;
1977
1978 /* OK that's all we can do for 1xx responses */
1979 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001980 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001981
1982 /*
1983 * Now check for a server cookie.
1984 */
1985 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001986 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001987
1988 /*
1989 * Check for cache-control or pragma headers if required.
1990 */
1991 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1992 check_response_for_cacheability(s, rep);
1993
1994 /*
1995 * Add server cookie in the response if needed
1996 */
1997 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1998 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1999 (!(s->flags & SF_DIRECT) ||
2000 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2001 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2002 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2003 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2004 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2005 !(s->flags & SF_IGNORE_PRST)) {
2006 /* the server is known, it's not the one the client requested, or the
2007 * cookie's last seen date needs to be refreshed. We have to
2008 * insert a set-cookie here, except if we want to insert only on POST
2009 * requests and this one isn't. Note that servers which don't have cookies
2010 * (eg: some backup servers) will return a full cookie removal request.
2011 */
2012 if (!objt_server(s->target)->cookie) {
2013 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002014 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002015 s->be->cookie_name);
2016 }
2017 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002018 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002019
2020 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2021 /* emit last_date, which is mandatory */
2022 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2023 s30tob64((date.tv_sec+3) >> 2,
2024 trash.area + trash.data);
2025 trash.data += 5;
2026
2027 if (s->be->cookie_maxlife) {
2028 /* emit first_date, which is either the original one or
2029 * the current date.
2030 */
2031 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2032 s30tob64(txn->cookie_first_date ?
2033 txn->cookie_first_date >> 2 :
2034 (date.tv_sec+3) >> 2,
2035 trash.area + trash.data);
2036 trash.data += 5;
2037 }
2038 }
2039 chunk_appendf(&trash, "; path=/");
2040 }
2041
2042 if (s->be->cookie_domain)
2043 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2044
2045 if (s->be->ck_opts & PR_CK_HTTPONLY)
2046 chunk_appendf(&trash, "; HttpOnly");
2047
2048 if (s->be->ck_opts & PR_CK_SECURE)
2049 chunk_appendf(&trash, "; Secure");
2050
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002051 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002052 goto return_bad_resp;
2053
2054 txn->flags &= ~TX_SCK_MASK;
2055 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2056 /* the server did not change, only the date was updated */
2057 txn->flags |= TX_SCK_UPDATED;
2058 else
2059 txn->flags |= TX_SCK_INSERTED;
2060
2061 /* Here, we will tell an eventual cache on the client side that we don't
2062 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2063 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2064 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2065 */
2066 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2067
2068 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2069
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002070 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002071 goto return_bad_resp;
2072 }
2073 }
2074
2075 /*
2076 * Check if result will be cacheable with a cookie.
2077 * We'll block the response if security checks have caught
2078 * nasty things such as a cacheable cookie.
2079 */
2080 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2081 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2082 (s->be->options & PR_O_CHK_CACHE)) {
2083 /* we're in presence of a cacheable response containing
2084 * a set-cookie header. We'll block it as requested by
2085 * the 'checkcache' option, and send an alert.
2086 */
2087 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002088 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002089
Olivier Houcharda798bf52019-03-08 18:52:00 +01002090 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2091 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002092 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002093 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002094
2095 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2096 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2097 send_log(s->be, LOG_ALERT,
2098 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2099 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2100 goto return_srv_prx_502;
2101 }
2102
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002103 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002104 /* Always enter in the body analyzer */
2105 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2106 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2107
2108 /* if the user wants to log as soon as possible, without counting
2109 * bytes from the server, then this is the right moment. We have
2110 * to temporarily assign bytes_out to log what we currently have.
2111 */
2112 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2113 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002114 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002115 s->do_log(s);
2116 s->logs.bytes_out = 0;
2117 }
2118 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002119
2120 return_bad_resp:
2121 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002122 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002123 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002124 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002125 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002126
2127 return_srv_prx_502:
2128 rep->analysers &= AN_RES_FLT_END;
2129 txn->status = 502;
2130 s->logs.t_data = -1; /* was not a valid response */
2131 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002132 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002133 if (!(s->flags & SF_ERR_MASK))
2134 s->flags |= SF_ERR_PRXCOND;
2135 if (!(s->flags & SF_FINST_MASK))
2136 s->flags |= SF_FINST_H;
2137 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002138}
2139
2140/* This function is an analyser which forwards response body (including chunk
2141 * sizes if any). It is called as soon as we must forward, even if we forward
2142 * zero byte. The only situation where it must not be called is when we're in
2143 * tunnel mode and we want to forward till the close. It's used both to forward
2144 * remaining data and to resync after end of body. It expects the msg_state to
2145 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2146 * read more data, or 1 once we can go on with next request or end the stream.
2147 *
2148 * It is capable of compressing response data both in content-length mode and
2149 * in chunked mode. The state machines follows different flows depending on
2150 * whether content-length and chunked modes are used, since there are no
2151 * trailers in content-length :
2152 *
2153 * chk-mode cl-mode
2154 * ,----- BODY -----.
2155 * / \
2156 * V size > 0 V chk-mode
2157 * .--> SIZE -------------> DATA -------------> CRLF
2158 * | | size == 0 | last byte |
2159 * | v final crlf v inspected |
2160 * | TRAILERS -----------> DONE |
2161 * | |
2162 * `----------------------------------------------'
2163 *
2164 * Compression only happens in the DATA state, and must be flushed in final
2165 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2166 * is performed at once on final states for all bytes parsed, or when leaving
2167 * on missing data.
2168 */
2169int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2170{
2171 struct session *sess = s->sess;
2172 struct http_txn *txn = s->txn;
2173 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002174 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002175 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002176
2177 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2178 now_ms, __FUNCTION__,
2179 s,
2180 res,
2181 res->rex, res->wex,
2182 res->flags,
2183 ci_data(res),
2184 res->analysers);
2185
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002186 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187
2188 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002189 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190 /* Output closed while we were sending data. We must abort and
2191 * wake the other side up.
2192 */
2193 msg->err_state = msg->msg_state;
2194 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002195 htx_end_response(s);
2196 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197 return 1;
2198 }
2199
Christopher Faulet9768c262018-10-22 09:34:31 +02002200 if (msg->msg_state == HTTP_MSG_BODY)
2201 msg->msg_state = HTTP_MSG_DATA;
2202
Christopher Faulete0768eb2018-10-03 16:38:02 +02002203 /* in most states, we should abort in case of early close */
2204 channel_auto_close(res);
2205
Christopher Faulete0768eb2018-10-03 16:38:02 +02002206 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002207 if (res->to_forward == CHN_INFINITE_FORWARD) {
2208 if (res->flags & (CF_SHUTR|CF_EOI)) {
2209 msg->msg_state = HTTP_MSG_DONE;
2210 res->to_forward = 0;
2211 goto done;
2212 }
2213 }
2214 else {
2215 /* We can't process the buffer's contents yet */
2216 res->flags |= CF_WAKE_WRITE;
2217 goto missing_data_or_waiting;
2218 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002219 }
2220
Christopher Faulet9768c262018-10-22 09:34:31 +02002221 if (msg->msg_state >= HTTP_MSG_DONE)
2222 goto done;
2223
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002224 /* Forward input data. We get it by removing all outgoing data not
2225 * forwarded yet from HTX data size. If there are some data filters, we
2226 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002227 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002228 if (HAS_RSP_DATA_FILTERS(s)) {
2229 ret = flt_http_payload(s, msg, htx->data);
2230 if (ret < 0)
2231 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002232 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002233 }
2234 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002235 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002236 if (msg->flags & HTTP_MSGF_XFER_LEN)
2237 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002238 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002239
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002240 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2241 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2242 msg->msg_state = HTTP_MSG_TUNNEL;
2243 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 }
2245
Christopher Faulet9768c262018-10-22 09:34:31 +02002246 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002247 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2248 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002249 */
2250 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2251 goto missing_data_or_waiting;
2252
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002253 msg->msg_state = HTTP_MSG_ENDING;
2254 if (htx->data != co_data(res))
2255 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002256 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002257 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002258
2259 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002261 channel_dont_close(res);
2262
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002263 if (HAS_RSP_DATA_FILTERS(s)) {
2264 ret = flt_http_end(s, msg);
2265 if (ret <= 0) {
2266 if (!ret)
2267 goto missing_data_or_waiting;
2268 goto return_bad_res;
2269 }
2270 }
2271
Christopher Fauletf2824e62018-10-01 12:12:37 +02002272 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002273 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002274 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002275 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2276 if (res->flags & CF_SHUTW) {
2277 /* response errors are most likely due to the
2278 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002279 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002281 goto return_bad_res;
2282 }
2283 return 1;
2284 }
2285 return 0;
2286
2287 missing_data_or_waiting:
2288 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002289 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290
Christopher Faulet47365272018-10-31 17:40:50 +01002291 if (htx->flags & HTX_FL_PARSING_ERROR)
2292 goto return_bad_res;
2293
Christopher Faulete0768eb2018-10-03 16:38:02 +02002294 /* stop waiting for data if the input is closed before the end. If the
2295 * client side was already closed, it means that the client has aborted,
2296 * so we don't want to count this as a server abort. Otherwise it's a
2297 * server abort.
2298 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002299 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002301 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002303 if (htx_is_empty(htx))
2304 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 }
2306
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 /* When TE: chunked is used, we need to get there again to parse
2308 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002309 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2310 * are filters registered on the stream, we don't want to forward a
2311 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002312 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002313 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002314 channel_dont_close(res);
2315
2316 /* We know that more data are expected, but we couldn't send more that
2317 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2318 * system knows it must not set a PUSH on this first part. Interactive
2319 * modes are already handled by the stream sock layer. We must not do
2320 * this in content-length mode because it could present the MSG_MORE
2321 * flag with the last block of forwarded data, which would cause an
2322 * additional delay to be observed by the receiver.
2323 */
2324 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2325 res->flags |= CF_EXPECT_MORE;
2326
2327 /* the stream handler will take care of timeouts and errors */
2328 return 0;
2329
Christopher Faulet93e02d82019-03-08 14:18:50 +01002330 return_srv_abort:
2331 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2332 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002334 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2335 if (!(s->flags & SF_ERR_MASK))
2336 s->flags |= SF_ERR_SRVCL;
2337 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002338
Christopher Faulet93e02d82019-03-08 14:18:50 +01002339 return_cli_abort:
2340 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2341 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002343 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2344 if (!(s->flags & SF_ERR_MASK))
2345 s->flags |= SF_ERR_CLICL;
2346 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347
Christopher Faulet93e02d82019-03-08 14:18:50 +01002348 return_bad_res:
2349 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2350 if (objt_server(s->target)) {
2351 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2352 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2353 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002354 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002355 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002356
Christopher Faulet93e02d82019-03-08 14:18:50 +01002357 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002358 txn->rsp.err_state = txn->rsp.msg_state;
2359 txn->rsp.msg_state = HTTP_MSG_ERROR;
2360 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002361 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002362 res->analysers &= AN_RES_FLT_END;
2363 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 +02002364 if (!(s->flags & SF_FINST_MASK))
2365 s->flags |= SF_FINST_D;
2366 return 0;
2367}
2368
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002371 * as too large a request to build a valid response.
2372 */
2373int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2374{
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 struct channel *req = &s->req;
2376 struct channel *res = &s->res;
2377 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002378 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 struct ist status, reason, location;
2381 unsigned int flags;
2382 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002383 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002384
2385 chunk = alloc_trash_chunk();
2386 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002387 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
Christopher Faulet99daf282018-11-28 22:58:13 +01002389 /*
2390 * Create the location
2391 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002392 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002393 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002394 case REDIRECT_TYPE_SCHEME: {
2395 struct http_hdr_ctx ctx;
2396 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002397
Christopher Faulet99daf282018-11-28 22:58:13 +01002398 host = ist("");
2399 ctx.blk = NULL;
2400 if (http_find_header(htx, ist("Host"), &ctx, 0))
2401 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402
Christopher Faulet297fbb42019-05-13 14:41:27 +02002403 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 path = http_get_path(htx_sl_req_uri(sl));
2405 /* build message using path */
2406 if (path.ptr) {
2407 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2408 int qs = 0;
2409 while (qs < path.len) {
2410 if (*(path.ptr + qs) == '?') {
2411 path.len = qs;
2412 break;
2413 }
2414 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 }
2417 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002418 else
2419 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420
Christopher Faulet99daf282018-11-28 22:58:13 +01002421 if (rule->rdr_str) { /* this is an old "redirect" rule */
2422 /* add scheme */
2423 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2424 goto fail;
2425 }
2426 else {
2427 /* add scheme with executing log format */
2428 chunk->data += build_logline(s, chunk->area + chunk->data,
2429 chunk->size - chunk->data,
2430 &rule->rdr_fmt);
2431 }
2432 /* add "://" + host + path */
2433 if (!chunk_memcat(chunk, "://", 3) ||
2434 !chunk_memcat(chunk, host.ptr, host.len) ||
2435 !chunk_memcat(chunk, path.ptr, path.len))
2436 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002437
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 /* append a slash at the end of the location if needed and missing */
2439 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2440 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2441 if (chunk->data + 1 >= chunk->size)
2442 goto fail;
2443 chunk->area[chunk->data++] = '/';
2444 }
2445 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002447
Christopher Faulet99daf282018-11-28 22:58:13 +01002448 case REDIRECT_TYPE_PREFIX: {
2449 struct ist path;
2450
Christopher Faulet297fbb42019-05-13 14:41:27 +02002451 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 path = http_get_path(htx_sl_req_uri(sl));
2453 /* build message using path */
2454 if (path.ptr) {
2455 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2456 int qs = 0;
2457 while (qs < path.len) {
2458 if (*(path.ptr + qs) == '?') {
2459 path.len = qs;
2460 break;
2461 }
2462 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
2465 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002466 else
2467 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468
Christopher Faulet99daf282018-11-28 22:58:13 +01002469 if (rule->rdr_str) { /* this is an old "redirect" rule */
2470 /* add prefix. Note that if prefix == "/", we don't want to
2471 * add anything, otherwise it makes it hard for the user to
2472 * configure a self-redirection.
2473 */
2474 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2475 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2476 goto fail;
2477 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002478 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002479 else {
2480 /* add prefix with executing log format */
2481 chunk->data += build_logline(s, chunk->area + chunk->data,
2482 chunk->size - chunk->data,
2483 &rule->rdr_fmt);
2484 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002485
Christopher Faulet99daf282018-11-28 22:58:13 +01002486 /* add path */
2487 if (!chunk_memcat(chunk, path.ptr, path.len))
2488 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489
Christopher Faulet99daf282018-11-28 22:58:13 +01002490 /* append a slash at the end of the location if needed and missing */
2491 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2492 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2493 if (chunk->data + 1 >= chunk->size)
2494 goto fail;
2495 chunk->area[chunk->data++] = '/';
2496 }
2497 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002498 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002499 case REDIRECT_TYPE_LOCATION:
2500 default:
2501 if (rule->rdr_str) { /* this is an old "redirect" rule */
2502 /* add location */
2503 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2504 goto fail;
2505 }
2506 else {
2507 /* add location with executing log format */
2508 chunk->data += build_logline(s, chunk->area + chunk->data,
2509 chunk->size - chunk->data,
2510 &rule->rdr_fmt);
2511 }
2512 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002513 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002514 location = ist2(chunk->area, chunk->data);
2515
2516 /*
2517 * Create the 30x response
2518 */
2519 switch (rule->code) {
2520 case 308:
2521 status = ist("308");
2522 reason = ist("Permanent Redirect");
2523 break;
2524 case 307:
2525 status = ist("307");
2526 reason = ist("Temporary Redirect");
2527 break;
2528 case 303:
2529 status = ist("303");
2530 reason = ist("See Other");
2531 break;
2532 case 301:
2533 status = ist("301");
2534 reason = ist("Moved Permanently");
2535 break;
2536 case 302:
2537 default:
2538 status = ist("302");
2539 reason = ist("Found");
2540 break;
2541 }
2542
Christopher Faulet08e66462019-05-23 16:44:59 +02002543 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2544 close = 1;
2545
Christopher Faulet99daf282018-11-28 22:58:13 +01002546 htx = htx_from_buf(&res->buf);
2547 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2548 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2549 if (!sl)
2550 goto fail;
2551 sl->info.res.status = rule->code;
2552 s->txn->status = rule->code;
2553
Christopher Faulet08e66462019-05-23 16:44:59 +02002554 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2555 goto fail;
2556
2557 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002558 !htx_add_header(htx, ist("Location"), location))
2559 goto fail;
2560
2561 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2562 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2563 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002564 }
2565
2566 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002567 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2568 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002569 }
2570
Christopher Faulet99daf282018-11-28 22:58:13 +01002571 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2572 goto fail;
2573
Christopher Fauletf2824e62018-10-01 12:12:37 +02002574 /* let's log the request time */
2575 s->logs.tv_request = now;
2576
Christopher Faulet99daf282018-11-28 22:58:13 +01002577 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002578 c_adv(res, data);
2579 res->total += data;
2580
2581 channel_auto_read(req);
2582 channel_abort(req);
2583 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002584 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002585
2586 res->wex = tick_add_ifset(now_ms, res->wto);
2587 channel_auto_read(res);
2588 channel_auto_close(res);
2589 channel_shutr_now(res);
2590
2591 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002592
2593 if (!(s->flags & SF_ERR_MASK))
2594 s->flags |= SF_ERR_LOCAL;
2595 if (!(s->flags & SF_FINST_MASK))
2596 s->flags |= SF_FINST_R;
2597
Christopher Faulet99daf282018-11-28 22:58:13 +01002598 free_trash_chunk(chunk);
2599 return 1;
2600
2601 fail:
2602 /* If an error occurred, remove the incomplete HTTP response from the
2603 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002604 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002605 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002606 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002607}
2608
Christopher Faulet72333522018-10-24 11:25:02 +02002609int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2610 struct ist name, const char *str, struct my_regex *re, int action)
2611{
2612 struct http_hdr_ctx ctx;
2613 struct buffer *output = get_trash_chunk();
2614
2615 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2616 ctx.blk = NULL;
2617 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2618 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2619 continue;
2620
2621 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2622 if (output->data == -1)
2623 return -1;
2624 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2625 return -1;
2626 }
2627 return 0;
2628}
2629
2630static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2631 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2632{
2633 struct buffer *replace;
2634 int ret = -1;
2635
2636 replace = alloc_trash_chunk();
2637 if (!replace)
2638 goto leave;
2639
2640 replace->data = build_logline(s, replace->area, replace->size, fmt);
2641 if (replace->data >= replace->size - 1)
2642 goto leave;
2643
2644 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2645
2646 leave:
2647 free_trash_chunk(replace);
2648 return ret;
2649}
2650
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651
2652/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2653 * on success and -1 on error. The response channel is updated accordingly.
2654 */
2655static int htx_reply_103_early_hints(struct channel *res)
2656{
2657 struct htx *htx = htx_from_buf(&res->buf);
2658 size_t data;
2659
Christopher Faulet9869f932019-06-26 14:23:54 +02002660 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 /* If an error occurred during an Early-hint rule,
2662 * remove the incomplete HTTP 103 response from the
2663 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002664 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 return -1;
2666 }
2667
2668 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002669 c_adv(res, data);
2670 res->total += data;
2671 return 0;
2672}
2673
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674/*
2675 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2676 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002677 * If <early_hints> is 0, it is starts a new response by adding the start
2678 * line. If an error occurred -1 is returned. On success 0 is returned. The
2679 * channel is not updated here. It must be done calling the function
2680 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002681 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002682static 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 +01002683{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002684 struct channel *res = &s->res;
2685 struct htx *htx = htx_from_buf(&res->buf);
2686 struct buffer *value = alloc_trash_chunk();
2687
Christopher Faulet6eb92892018-11-15 16:39:29 +01002688 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002689 struct htx_sl *sl;
2690 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2691 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2692
2693 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2694 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2695 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002696 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002697 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002698 }
2699
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002700 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2701 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002702 goto fail;
2703
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002704 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002705 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002706
2707 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002708 /* If an error occurred during an Early-hint rule, remove the incomplete
2709 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002710 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002711 free_trash_chunk(value);
2712 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002713}
2714
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002715/* This function executes one of the set-{method,path,query,uri} actions. It
2716 * takes the string from the variable 'replace' with length 'len', then modifies
2717 * the relevant part of the request line accordingly. Then it updates various
2718 * pointers to the next elements which were moved, and the total buffer length.
2719 * It finds the action to be performed in p[2], previously filled by function
2720 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2721 * error, though this can be revisited when this code is finally exploited.
2722 *
2723 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2724 * query string and 3 to replace uri.
2725 *
2726 * In query string case, the mark question '?' must be set at the start of the
2727 * string by the caller, event if the replacement query string is empty.
2728 */
2729int htx_req_replace_stline(int action, const char *replace, int len,
2730 struct proxy *px, struct stream *s)
2731{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002732 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002733
2734 switch (action) {
2735 case 0: // method
2736 if (!http_replace_req_meth(htx, ist2(replace, len)))
2737 return -1;
2738 break;
2739
2740 case 1: // path
2741 if (!http_replace_req_path(htx, ist2(replace, len)))
2742 return -1;
2743 break;
2744
2745 case 2: // query
2746 if (!http_replace_req_query(htx, ist2(replace, len)))
2747 return -1;
2748 break;
2749
2750 case 3: // uri
2751 if (!http_replace_req_uri(htx, ist2(replace, len)))
2752 return -1;
2753 break;
2754
2755 default:
2756 return -1;
2757 }
2758 return 0;
2759}
2760
2761/* This function replace the HTTP status code and the associated message. The
2762 * variable <status> contains the new status code. This function never fails.
2763 */
2764void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2765{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002766 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002767 char *res;
2768
2769 chunk_reset(&trash);
2770 res = ultoa_o(status, trash.area, trash.size);
2771 trash.data = res - trash.area;
2772
2773 /* Do we have a custom reason format string? */
2774 if (reason == NULL)
2775 reason = http_get_reason(status);
2776
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002777 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002778 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2779}
2780
Christopher Faulet3e964192018-10-24 11:39:23 +02002781/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2782 * transaction <txn>. Returns the verdict of the first rule that prevents
2783 * further processing of the request (auth, deny, ...), and defaults to
2784 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2785 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2786 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2787 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2788 * status.
2789 */
2790static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2791 struct stream *s, int *deny_status)
2792{
2793 struct session *sess = strm_sess(s);
2794 struct http_txn *txn = s->txn;
2795 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002796 struct act_rule *rule;
2797 struct http_hdr_ctx ctx;
2798 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002799 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2800 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002801 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002802
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002803 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002804
2805 /* If "the current_rule_list" match the executed rule list, we are in
2806 * resume condition. If a resume is needed it is always in the action
2807 * and never in the ACL or converters. In this case, we initialise the
2808 * current rule, and go to the action execution point.
2809 */
2810 if (s->current_rule) {
2811 rule = s->current_rule;
2812 s->current_rule = NULL;
2813 if (s->current_rule_list == rules)
2814 goto resume_execution;
2815 }
2816 s->current_rule_list = rules;
2817
2818 list_for_each_entry(rule, rules, list) {
2819 /* check optional condition */
2820 if (rule->cond) {
2821 int ret;
2822
2823 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2824 ret = acl_pass(ret);
2825
2826 if (rule->cond->pol == ACL_COND_UNLESS)
2827 ret = !ret;
2828
2829 if (!ret) /* condition not matched */
2830 continue;
2831 }
2832
2833 act_flags |= ACT_FLAG_FIRST;
2834 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002835 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2836 early_hints = 0;
2837 if (htx_reply_103_early_hints(&s->res) == -1) {
2838 rule_ret = HTTP_RULE_RES_BADREQ;
2839 goto end;
2840 }
2841 }
2842
Christopher Faulet3e964192018-10-24 11:39:23 +02002843 switch (rule->action) {
2844 case ACT_ACTION_ALLOW:
2845 rule_ret = HTTP_RULE_RES_STOP;
2846 goto end;
2847
2848 case ACT_ACTION_DENY:
2849 if (deny_status)
2850 *deny_status = rule->deny_status;
2851 rule_ret = HTTP_RULE_RES_DENY;
2852 goto end;
2853
2854 case ACT_HTTP_REQ_TARPIT:
2855 txn->flags |= TX_CLTARPIT;
2856 if (deny_status)
2857 *deny_status = rule->deny_status;
2858 rule_ret = HTTP_RULE_RES_DENY;
2859 goto end;
2860
2861 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002862 /* Auth might be performed on regular http-req rules as well as on stats */
2863 auth_realm = rule->arg.auth.realm;
2864 if (!auth_realm) {
2865 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2866 auth_realm = STATS_DEFAULT_REALM;
2867 else
2868 auth_realm = px->id;
2869 }
2870 /* send 401/407 depending on whether we use a proxy or not. We still
2871 * count one error, because normal browsing won't significantly
2872 * increase the counter but brute force attempts will.
2873 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002874 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002875 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2876 rule_ret = HTTP_RULE_RES_BADREQ;
2877 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002878 goto end;
2879
2880 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002881 rule_ret = HTTP_RULE_RES_DONE;
2882 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2883 rule_ret = HTTP_RULE_RES_BADREQ;
2884 goto end;
2885
2886 case ACT_HTTP_SET_NICE:
2887 s->task->nice = rule->arg.nice;
2888 break;
2889
2890 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002891 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002892 break;
2893
2894 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002895 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002896 break;
2897
2898 case ACT_HTTP_SET_LOGL:
2899 s->logs.level = rule->arg.loglevel;
2900 break;
2901
2902 case ACT_HTTP_REPLACE_HDR:
2903 case ACT_HTTP_REPLACE_VAL:
2904 if (htx_transform_header(s, &s->req, htx,
2905 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2906 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002907 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002908 rule_ret = HTTP_RULE_RES_BADREQ;
2909 goto end;
2910 }
2911 break;
2912
2913 case ACT_HTTP_DEL_HDR:
2914 /* remove all occurrences of the header */
2915 ctx.blk = NULL;
2916 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2917 http_remove_header(htx, &ctx);
2918 break;
2919
2920 case ACT_HTTP_SET_HDR:
2921 case ACT_HTTP_ADD_HDR: {
2922 /* The scope of the trash buffer must be limited to this function. The
2923 * build_logline() function can execute a lot of other function which
2924 * can use the trash buffer. So for limiting the scope of this global
2925 * buffer, we build first the header value using build_logline, and
2926 * after we store the header name.
2927 */
2928 struct buffer *replace;
2929 struct ist n, v;
2930
2931 replace = alloc_trash_chunk();
2932 if (!replace) {
2933 rule_ret = HTTP_RULE_RES_BADREQ;
2934 goto end;
2935 }
2936
2937 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2938 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2939 v = ist2(replace->area, replace->data);
2940
2941 if (rule->action == ACT_HTTP_SET_HDR) {
2942 /* remove all occurrences of the header */
2943 ctx.blk = NULL;
2944 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2945 http_remove_header(htx, &ctx);
2946 }
2947
2948 if (!http_add_header(htx, n, v)) {
2949 static unsigned char rate_limit = 0;
2950
2951 if ((rate_limit++ & 255) == 0) {
2952 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);
2953 }
2954
Olivier Houcharda798bf52019-03-08 18:52:00 +01002955 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002956 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002957 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002958 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002959 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002960 }
2961 free_trash_chunk(replace);
2962 break;
2963 }
2964
2965 case ACT_HTTP_DEL_ACL:
2966 case ACT_HTTP_DEL_MAP: {
2967 struct pat_ref *ref;
2968 struct buffer *key;
2969
2970 /* collect reference */
2971 ref = pat_ref_lookup(rule->arg.map.ref);
2972 if (!ref)
2973 continue;
2974
2975 /* allocate key */
2976 key = alloc_trash_chunk();
2977 if (!key) {
2978 rule_ret = HTTP_RULE_RES_BADREQ;
2979 goto end;
2980 }
2981
2982 /* collect key */
2983 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2984 key->area[key->data] = '\0';
2985
2986 /* perform update */
2987 /* returned code: 1=ok, 0=ko */
2988 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2989 pat_ref_delete(ref, key->area);
2990 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2991
2992 free_trash_chunk(key);
2993 break;
2994 }
2995
2996 case ACT_HTTP_ADD_ACL: {
2997 struct pat_ref *ref;
2998 struct buffer *key;
2999
3000 /* collect reference */
3001 ref = pat_ref_lookup(rule->arg.map.ref);
3002 if (!ref)
3003 continue;
3004
3005 /* allocate key */
3006 key = alloc_trash_chunk();
3007 if (!key) {
3008 rule_ret = HTTP_RULE_RES_BADREQ;
3009 goto end;
3010 }
3011
3012 /* collect key */
3013 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3014 key->area[key->data] = '\0';
3015
3016 /* perform update */
3017 /* add entry only if it does not already exist */
3018 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3019 if (pat_ref_find_elt(ref, key->area) == NULL)
3020 pat_ref_add(ref, key->area, NULL, NULL);
3021 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3022
3023 free_trash_chunk(key);
3024 break;
3025 }
3026
3027 case ACT_HTTP_SET_MAP: {
3028 struct pat_ref *ref;
3029 struct buffer *key, *value;
3030
3031 /* collect reference */
3032 ref = pat_ref_lookup(rule->arg.map.ref);
3033 if (!ref)
3034 continue;
3035
3036 /* allocate key */
3037 key = alloc_trash_chunk();
3038 if (!key) {
3039 rule_ret = HTTP_RULE_RES_BADREQ;
3040 goto end;
3041 }
3042
3043 /* allocate value */
3044 value = alloc_trash_chunk();
3045 if (!value) {
3046 free_trash_chunk(key);
3047 rule_ret = HTTP_RULE_RES_BADREQ;
3048 goto end;
3049 }
3050
3051 /* collect key */
3052 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3053 key->area[key->data] = '\0';
3054
3055 /* collect value */
3056 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3057 value->area[value->data] = '\0';
3058
3059 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003060 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003061 if (pat_ref_find_elt(ref, key->area) != NULL)
3062 /* update entry if it exists */
3063 pat_ref_set(ref, key->area, value->area, NULL);
3064 else
3065 /* insert a new entry */
3066 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003067 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003068 free_trash_chunk(key);
3069 free_trash_chunk(value);
3070 break;
3071 }
3072
3073 case ACT_HTTP_EARLY_HINT:
3074 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3075 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003076 early_hints = htx_add_early_hint_header(s, early_hints,
3077 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003078 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003079 if (early_hints == -1) {
3080 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003081 goto end;
3082 }
3083 break;
3084
3085 case ACT_CUSTOM:
3086 if ((s->req.flags & CF_READ_ERROR) ||
3087 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003088 (px->options & PR_O_ABRT_CLOSE)))
3089 act_flags |= ACT_FLAG_FINAL;
3090
3091 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3092 case ACT_RET_ERR:
3093 case ACT_RET_CONT:
3094 break;
3095 case ACT_RET_STOP:
Christopher Faulet4629d082019-07-04 11:27:15 +02003096 rule_ret = HTTP_RULE_RES_STOP;
3097 goto end;
3098 case ACT_RET_DONE:
Christopher Faulet3e964192018-10-24 11:39:23 +02003099 rule_ret = HTTP_RULE_RES_DONE;
3100 goto end;
3101 case ACT_RET_YIELD:
3102 s->current_rule = rule;
3103 rule_ret = HTTP_RULE_RES_YIELD;
3104 goto end;
3105 }
3106 break;
3107
3108 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3109 /* Note: only the first valid tracking parameter of each
3110 * applies.
3111 */
3112
3113 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3114 struct stktable *t;
3115 struct stksess *ts;
3116 struct stktable_key *key;
3117 void *ptr1, *ptr2;
3118
3119 t = rule->arg.trk_ctr.table.t;
3120 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3121 rule->arg.trk_ctr.expr, NULL);
3122
3123 if (key && (ts = stktable_get_entry(t, key))) {
3124 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3125
3126 /* let's count a new HTTP request as it's the first time we do it */
3127 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3128 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3129 if (ptr1 || ptr2) {
3130 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3131
3132 if (ptr1)
3133 stktable_data_cast(ptr1, http_req_cnt)++;
3134
3135 if (ptr2)
3136 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3137 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3138
3139 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3140
3141 /* If data was modified, we need to touch to re-schedule sync */
3142 stktable_touch_local(t, ts, 0);
3143 }
3144
3145 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3146 if (sess->fe != s->be)
3147 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3148 }
3149 }
3150 break;
3151
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003152 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003153 default:
3154 break;
3155 }
3156 }
3157
3158 end:
3159 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003160 if (htx_reply_103_early_hints(&s->res) == -1)
3161 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003162 }
3163
3164 /* we reached the end of the rules, nothing to report */
3165 return rule_ret;
3166}
3167
3168/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3169 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3170 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3171 * is returned, the process can continue the evaluation of next rule list. If
3172 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3173 * is returned, it means the operation could not be processed and a server error
3174 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3175 * deny rule. If *YIELD is returned, the caller must call again the function
3176 * with the same context.
3177 */
3178static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3179 struct stream *s)
3180{
3181 struct session *sess = strm_sess(s);
3182 struct http_txn *txn = s->txn;
3183 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003184 struct act_rule *rule;
3185 struct http_hdr_ctx ctx;
3186 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3187 int act_flags = 0;
3188
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003189 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003190
3191 /* If "the current_rule_list" match the executed rule list, we are in
3192 * resume condition. If a resume is needed it is always in the action
3193 * and never in the ACL or converters. In this case, we initialise the
3194 * current rule, and go to the action execution point.
3195 */
3196 if (s->current_rule) {
3197 rule = s->current_rule;
3198 s->current_rule = NULL;
3199 if (s->current_rule_list == rules)
3200 goto resume_execution;
3201 }
3202 s->current_rule_list = rules;
3203
3204 list_for_each_entry(rule, rules, list) {
3205 /* check optional condition */
3206 if (rule->cond) {
3207 int ret;
3208
3209 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3210 ret = acl_pass(ret);
3211
3212 if (rule->cond->pol == ACL_COND_UNLESS)
3213 ret = !ret;
3214
3215 if (!ret) /* condition not matched */
3216 continue;
3217 }
3218
3219 act_flags |= ACT_FLAG_FIRST;
3220resume_execution:
3221 switch (rule->action) {
3222 case ACT_ACTION_ALLOW:
3223 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3224 goto end;
3225
3226 case ACT_ACTION_DENY:
3227 txn->flags |= TX_SVDENY;
3228 rule_ret = HTTP_RULE_RES_STOP;
3229 goto end;
3230
3231 case ACT_HTTP_SET_NICE:
3232 s->task->nice = rule->arg.nice;
3233 break;
3234
3235 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003236 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003237 break;
3238
3239 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003240 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003241 break;
3242
3243 case ACT_HTTP_SET_LOGL:
3244 s->logs.level = rule->arg.loglevel;
3245 break;
3246
3247 case ACT_HTTP_REPLACE_HDR:
3248 case ACT_HTTP_REPLACE_VAL:
3249 if (htx_transform_header(s, &s->res, htx,
3250 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3251 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003252 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003253 rule_ret = HTTP_RULE_RES_BADREQ;
3254 goto end;
3255 }
3256 break;
3257
3258 case ACT_HTTP_DEL_HDR:
3259 /* remove all occurrences of the header */
3260 ctx.blk = NULL;
3261 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3262 http_remove_header(htx, &ctx);
3263 break;
3264
3265 case ACT_HTTP_SET_HDR:
3266 case ACT_HTTP_ADD_HDR: {
3267 struct buffer *replace;
3268 struct ist n, v;
3269
3270 replace = alloc_trash_chunk();
3271 if (!replace) {
3272 rule_ret = HTTP_RULE_RES_BADREQ;
3273 goto end;
3274 }
3275
3276 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3277 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3278 v = ist2(replace->area, replace->data);
3279
3280 if (rule->action == ACT_HTTP_SET_HDR) {
3281 /* remove all occurrences of the header */
3282 ctx.blk = NULL;
3283 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3284 http_remove_header(htx, &ctx);
3285 }
3286
3287 if (!http_add_header(htx, n, v)) {
3288 static unsigned char rate_limit = 0;
3289
3290 if ((rate_limit++ & 255) == 0) {
3291 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);
3292 }
3293
Olivier Houcharda798bf52019-03-08 18:52:00 +01003294 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003295 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003296 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003297 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003298 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003299 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003300 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003301 }
3302 free_trash_chunk(replace);
3303 break;
3304 }
3305
3306 case ACT_HTTP_DEL_ACL:
3307 case ACT_HTTP_DEL_MAP: {
3308 struct pat_ref *ref;
3309 struct buffer *key;
3310
3311 /* collect reference */
3312 ref = pat_ref_lookup(rule->arg.map.ref);
3313 if (!ref)
3314 continue;
3315
3316 /* allocate key */
3317 key = alloc_trash_chunk();
3318 if (!key) {
3319 rule_ret = HTTP_RULE_RES_BADREQ;
3320 goto end;
3321 }
3322
3323 /* collect key */
3324 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3325 key->area[key->data] = '\0';
3326
3327 /* perform update */
3328 /* returned code: 1=ok, 0=ko */
3329 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3330 pat_ref_delete(ref, key->area);
3331 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3332
3333 free_trash_chunk(key);
3334 break;
3335 }
3336
3337 case ACT_HTTP_ADD_ACL: {
3338 struct pat_ref *ref;
3339 struct buffer *key;
3340
3341 /* collect reference */
3342 ref = pat_ref_lookup(rule->arg.map.ref);
3343 if (!ref)
3344 continue;
3345
3346 /* allocate key */
3347 key = alloc_trash_chunk();
3348 if (!key) {
3349 rule_ret = HTTP_RULE_RES_BADREQ;
3350 goto end;
3351 }
3352
3353 /* collect key */
3354 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3355 key->area[key->data] = '\0';
3356
3357 /* perform update */
3358 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003359 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003360 if (pat_ref_find_elt(ref, key->area) == NULL)
3361 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003362 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003363 free_trash_chunk(key);
3364 break;
3365 }
3366
3367 case ACT_HTTP_SET_MAP: {
3368 struct pat_ref *ref;
3369 struct buffer *key, *value;
3370
3371 /* collect reference */
3372 ref = pat_ref_lookup(rule->arg.map.ref);
3373 if (!ref)
3374 continue;
3375
3376 /* allocate key */
3377 key = alloc_trash_chunk();
3378 if (!key) {
3379 rule_ret = HTTP_RULE_RES_BADREQ;
3380 goto end;
3381 }
3382
3383 /* allocate value */
3384 value = alloc_trash_chunk();
3385 if (!value) {
3386 free_trash_chunk(key);
3387 rule_ret = HTTP_RULE_RES_BADREQ;
3388 goto end;
3389 }
3390
3391 /* collect key */
3392 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3393 key->area[key->data] = '\0';
3394
3395 /* collect value */
3396 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3397 value->area[value->data] = '\0';
3398
3399 /* perform update */
3400 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3401 if (pat_ref_find_elt(ref, key->area) != NULL)
3402 /* update entry if it exists */
3403 pat_ref_set(ref, key->area, value->area, NULL);
3404 else
3405 /* insert a new entry */
3406 pat_ref_add(ref, key->area, value->area, NULL);
3407 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3408 free_trash_chunk(key);
3409 free_trash_chunk(value);
3410 break;
3411 }
3412
3413 case ACT_HTTP_REDIR:
3414 rule_ret = HTTP_RULE_RES_DONE;
3415 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3416 rule_ret = HTTP_RULE_RES_BADREQ;
3417 goto end;
3418
3419 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3420 /* Note: only the first valid tracking parameter of each
3421 * applies.
3422 */
3423 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3424 struct stktable *t;
3425 struct stksess *ts;
3426 struct stktable_key *key;
3427 void *ptr;
3428
3429 t = rule->arg.trk_ctr.table.t;
3430 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3431 rule->arg.trk_ctr.expr, NULL);
3432
3433 if (key && (ts = stktable_get_entry(t, key))) {
3434 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3435
3436 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3437
3438 /* let's count a new HTTP request as it's the first time we do it */
3439 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3440 if (ptr)
3441 stktable_data_cast(ptr, http_req_cnt)++;
3442
3443 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3444 if (ptr)
3445 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3446 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3447
3448 /* When the client triggers a 4xx from the server, it's most often due
3449 * to a missing object or permission. These events should be tracked
3450 * because if they happen often, it may indicate a brute force or a
3451 * vulnerability scan. Normally this is done when receiving the response
3452 * but here we're tracking after this ought to have been done so we have
3453 * to do it on purpose.
3454 */
3455 if ((unsigned)(txn->status - 400) < 100) {
3456 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3457 if (ptr)
3458 stktable_data_cast(ptr, http_err_cnt)++;
3459
3460 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3461 if (ptr)
3462 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3463 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3464 }
3465
3466 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3467
3468 /* If data was modified, we need to touch to re-schedule sync */
3469 stktable_touch_local(t, ts, 0);
3470
3471 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3472 if (sess->fe != s->be)
3473 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3474 }
3475 }
3476 break;
3477
3478 case ACT_CUSTOM:
3479 if ((s->req.flags & CF_READ_ERROR) ||
3480 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003481 (px->options & PR_O_ABRT_CLOSE)))
3482 act_flags |= ACT_FLAG_FINAL;
3483
3484 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3485 case ACT_RET_ERR:
3486 case ACT_RET_CONT:
3487 break;
3488 case ACT_RET_STOP:
3489 rule_ret = HTTP_RULE_RES_STOP;
3490 goto end;
Christopher Faulet4629d082019-07-04 11:27:15 +02003491 case ACT_RET_DONE:
3492 rule_ret = HTTP_RULE_RES_DONE;
3493 goto end;
Christopher Faulet3e964192018-10-24 11:39:23 +02003494 case ACT_RET_YIELD:
3495 s->current_rule = rule;
3496 rule_ret = HTTP_RULE_RES_YIELD;
3497 goto end;
3498 }
3499 break;
3500
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003501 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003502 default:
3503 break;
3504 }
3505 }
3506
3507 end:
3508 /* we reached the end of the rules, nothing to report */
3509 return rule_ret;
3510}
3511
Christopher Faulet33640082018-10-24 11:53:01 +02003512/* Iterate the same filter through all request headers.
3513 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3514 * Since it can manage the switch to another backend, it updates the per-proxy
3515 * DENY stats.
3516 */
3517static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3518{
3519 struct http_txn *txn = s->txn;
3520 struct htx *htx;
3521 struct buffer *hdr = get_trash_chunk();
3522 int32_t pos;
3523
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003524 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003525
Christopher Fauleta3f15502019-05-13 15:27:23 +02003526 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003527 struct htx_blk *blk = htx_get_blk(htx, pos);
3528 enum htx_blk_type type;
3529 struct ist n, v;
3530
3531 next_hdr:
3532 type = htx_get_blk_type(blk);
3533 if (type == HTX_BLK_EOH)
3534 break;
3535 if (type != HTX_BLK_HDR)
3536 continue;
3537
3538 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3539 return 1;
3540 else if (unlikely(txn->flags & TX_CLALLOW) &&
3541 (exp->action == ACT_ALLOW ||
3542 exp->action == ACT_DENY ||
3543 exp->action == ACT_TARPIT))
3544 return 0;
3545
3546 n = htx_get_blk_name(htx, blk);
3547 v = htx_get_blk_value(htx, blk);
3548
Christopher Faulet02e771a2019-02-26 15:36:05 +01003549 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003550 hdr->area[hdr->data++] = ':';
3551 hdr->area[hdr->data++] = ' ';
3552 chunk_memcat(hdr, v.ptr, v.len);
3553
3554 /* Now we have one header in <hdr> */
3555
3556 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3557 struct http_hdr_ctx ctx;
3558 int len;
3559
3560 switch (exp->action) {
3561 case ACT_ALLOW:
3562 txn->flags |= TX_CLALLOW;
3563 goto end;
3564
3565 case ACT_DENY:
3566 txn->flags |= TX_CLDENY;
3567 goto end;
3568
3569 case ACT_TARPIT:
3570 txn->flags |= TX_CLTARPIT;
3571 goto end;
3572
3573 case ACT_REPLACE:
3574 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3575 if (len < 0)
3576 return -1;
3577
3578 http_parse_header(ist2(trash.area, len), &n, &v);
3579 ctx.blk = blk;
3580 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003581 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003582 if (!http_replace_header(htx, &ctx, n, v))
3583 return -1;
3584 if (!ctx.blk)
3585 goto end;
3586 pos = htx_get_blk_pos(htx, blk);
3587 break;
3588
3589 case ACT_REMOVE:
3590 ctx.blk = blk;
3591 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003592 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003593 if (!http_remove_header(htx, &ctx))
3594 return -1;
3595 if (!ctx.blk)
3596 goto end;
3597 pos = htx_get_blk_pos(htx, blk);
3598 goto next_hdr;
3599
3600 }
3601 }
3602 }
3603 end:
3604 return 0;
3605}
3606
3607/* Apply the filter to the request line.
3608 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3609 * or -1 if a replacement resulted in an invalid request line.
3610 * Since it can manage the switch to another backend, it updates the per-proxy
3611 * DENY stats.
3612 */
3613static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3614{
3615 struct http_txn *txn = s->txn;
3616 struct htx *htx;
3617 struct buffer *reqline = get_trash_chunk();
3618 int done;
3619
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003620 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003621
3622 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3623 return 1;
3624 else if (unlikely(txn->flags & TX_CLALLOW) &&
3625 (exp->action == ACT_ALLOW ||
3626 exp->action == ACT_DENY ||
3627 exp->action == ACT_TARPIT))
3628 return 0;
3629 else if (exp->action == ACT_REMOVE)
3630 return 0;
3631
3632 done = 0;
3633
Christopher Faulet297fbb42019-05-13 14:41:27 +02003634 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003635
3636 /* Now we have the request line between cur_ptr and cur_end */
3637 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003638 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003639 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003640 int len;
3641
3642 switch (exp->action) {
3643 case ACT_ALLOW:
3644 txn->flags |= TX_CLALLOW;
3645 done = 1;
3646 break;
3647
3648 case ACT_DENY:
3649 txn->flags |= TX_CLDENY;
3650 done = 1;
3651 break;
3652
3653 case ACT_TARPIT:
3654 txn->flags |= TX_CLTARPIT;
3655 done = 1;
3656 break;
3657
3658 case ACT_REPLACE:
3659 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3660 if (len < 0)
3661 return -1;
3662
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003663 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3664 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3665 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003666 return -1;
3667 done = 1;
3668 break;
3669 }
3670 }
3671 return done;
3672}
3673
3674/*
3675 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3676 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3677 * unparsable request. Since it can manage the switch to another backend, it
3678 * updates the per-proxy DENY stats.
3679 */
3680static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3681{
3682 struct session *sess = s->sess;
3683 struct http_txn *txn = s->txn;
3684 struct hdr_exp *exp;
3685
3686 for (exp = px->req_exp; exp; exp = exp->next) {
3687 int ret;
3688
3689 /*
3690 * The interleaving of transformations and verdicts
3691 * makes it difficult to decide to continue or stop
3692 * the evaluation.
3693 */
3694
3695 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3696 break;
3697
3698 if ((txn->flags & TX_CLALLOW) &&
3699 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3700 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3701 continue;
3702
3703 /* if this filter had a condition, evaluate it now and skip to
3704 * next filter if the condition does not match.
3705 */
3706 if (exp->cond) {
3707 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3708 ret = acl_pass(ret);
3709 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3710 ret = !ret;
3711
3712 if (!ret)
3713 continue;
3714 }
3715
3716 /* Apply the filter to the request line. */
3717 ret = htx_apply_filter_to_req_line(s, req, exp);
3718 if (unlikely(ret < 0))
3719 return -1;
3720
3721 if (likely(ret == 0)) {
3722 /* The filter did not match the request, it can be
3723 * iterated through all headers.
3724 */
3725 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3726 return -1;
3727 }
3728 }
3729 return 0;
3730}
3731
3732/* Iterate the same filter through all response headers contained in <res>.
3733 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3734 */
3735static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3736{
3737 struct http_txn *txn = s->txn;
3738 struct htx *htx;
3739 struct buffer *hdr = get_trash_chunk();
3740 int32_t pos;
3741
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003742 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003743
Christopher Fauleta3f15502019-05-13 15:27:23 +02003744 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003745 struct htx_blk *blk = htx_get_blk(htx, pos);
3746 enum htx_blk_type type;
3747 struct ist n, v;
3748
3749 next_hdr:
3750 type = htx_get_blk_type(blk);
3751 if (type == HTX_BLK_EOH)
3752 break;
3753 if (type != HTX_BLK_HDR)
3754 continue;
3755
3756 if (unlikely(txn->flags & TX_SVDENY))
3757 return 1;
3758 else if (unlikely(txn->flags & TX_SVALLOW) &&
3759 (exp->action == ACT_ALLOW ||
3760 exp->action == ACT_DENY))
3761 return 0;
3762
3763 n = htx_get_blk_name(htx, blk);
3764 v = htx_get_blk_value(htx, blk);
3765
Christopher Faulet02e771a2019-02-26 15:36:05 +01003766 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003767 hdr->area[hdr->data++] = ':';
3768 hdr->area[hdr->data++] = ' ';
3769 chunk_memcat(hdr, v.ptr, v.len);
3770
3771 /* Now we have one header in <hdr> */
3772
3773 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3774 struct http_hdr_ctx ctx;
3775 int len;
3776
3777 switch (exp->action) {
3778 case ACT_ALLOW:
3779 txn->flags |= TX_SVALLOW;
3780 goto end;
3781 break;
3782
3783 case ACT_DENY:
3784 txn->flags |= TX_SVDENY;
3785 goto end;
3786 break;
3787
3788 case ACT_REPLACE:
3789 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3790 if (len < 0)
3791 return -1;
3792
3793 http_parse_header(ist2(trash.area, len), &n, &v);
3794 ctx.blk = blk;
3795 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003796 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003797 if (!http_replace_header(htx, &ctx, n, v))
3798 return -1;
3799 if (!ctx.blk)
3800 goto end;
3801 pos = htx_get_blk_pos(htx, blk);
3802 break;
3803
3804 case ACT_REMOVE:
3805 ctx.blk = blk;
3806 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003807 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003808 if (!http_remove_header(htx, &ctx))
3809 return -1;
3810 if (!ctx.blk)
3811 goto end;
3812 pos = htx_get_blk_pos(htx, blk);
3813 goto next_hdr;
3814 }
3815 }
3816
3817 }
3818 end:
3819 return 0;
3820}
3821
3822/* Apply the filter to the status line in the response buffer <res>.
3823 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3824 * or -1 if a replacement resulted in an invalid status line.
3825 */
3826static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3827{
3828 struct http_txn *txn = s->txn;
3829 struct htx *htx;
3830 struct buffer *resline = get_trash_chunk();
3831 int done;
3832
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003833 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003834
3835 if (unlikely(txn->flags & TX_SVDENY))
3836 return 1;
3837 else if (unlikely(txn->flags & TX_SVALLOW) &&
3838 (exp->action == ACT_ALLOW ||
3839 exp->action == ACT_DENY))
3840 return 0;
3841 else if (exp->action == ACT_REMOVE)
3842 return 0;
3843
3844 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003845 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003846
3847 /* Now we have the status line between cur_ptr and cur_end */
3848 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003849 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003850 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003851 int len;
3852
3853 switch (exp->action) {
3854 case ACT_ALLOW:
3855 txn->flags |= TX_SVALLOW;
3856 done = 1;
3857 break;
3858
3859 case ACT_DENY:
3860 txn->flags |= TX_SVDENY;
3861 done = 1;
3862 break;
3863
3864 case ACT_REPLACE:
3865 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3866 if (len < 0)
3867 return -1;
3868
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003869 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3870 sl->info.res.status = strl2ui(code.ptr, code.len);
3871 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003872 return -1;
3873
3874 done = 1;
3875 return 1;
3876 }
3877 }
3878 return done;
3879}
3880
3881/*
3882 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3883 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3884 * unparsable response.
3885 */
3886static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3887{
3888 struct session *sess = s->sess;
3889 struct http_txn *txn = s->txn;
3890 struct hdr_exp *exp;
3891
3892 for (exp = px->rsp_exp; exp; exp = exp->next) {
3893 int ret;
3894
3895 /*
3896 * The interleaving of transformations and verdicts
3897 * makes it difficult to decide to continue or stop
3898 * the evaluation.
3899 */
3900
3901 if (txn->flags & TX_SVDENY)
3902 break;
3903
3904 if ((txn->flags & TX_SVALLOW) &&
3905 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3906 exp->action == ACT_PASS)) {
3907 exp = exp->next;
3908 continue;
3909 }
3910
3911 /* if this filter had a condition, evaluate it now and skip to
3912 * next filter if the condition does not match.
3913 */
3914 if (exp->cond) {
3915 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3916 ret = acl_pass(ret);
3917 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3918 ret = !ret;
3919 if (!ret)
3920 continue;
3921 }
3922
3923 /* Apply the filter to the status line. */
3924 ret = htx_apply_filter_to_sts_line(s, res, exp);
3925 if (unlikely(ret < 0))
3926 return -1;
3927
3928 if (likely(ret == 0)) {
3929 /* The filter did not match the response, it can be
3930 * iterated through all headers.
3931 */
3932 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3933 return -1;
3934 }
3935 }
3936 return 0;
3937}
3938
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003939/*
3940 * Manage client-side cookie. It can impact performance by about 2% so it is
3941 * desirable to call it only when needed. This code is quite complex because
3942 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3943 * highly recommended not to touch this part without a good reason !
3944 */
3945static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3946{
3947 struct session *sess = s->sess;
3948 struct http_txn *txn = s->txn;
3949 struct htx *htx;
3950 struct http_hdr_ctx ctx;
3951 char *hdr_beg, *hdr_end, *del_from;
3952 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3953 int preserve_hdr;
3954
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003955 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003956 ctx.blk = NULL;
3957 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02003958 int is_first = 1;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003959 del_from = NULL; /* nothing to be deleted */
3960 preserve_hdr = 0; /* assume we may kill the whole header */
3961
3962 /* Now look for cookies. Conforming to RFC2109, we have to support
3963 * attributes whose name begin with a '$', and associate them with
3964 * the right cookie, if we want to delete this cookie.
3965 * So there are 3 cases for each cookie read :
3966 * 1) it's a special attribute, beginning with a '$' : ignore it.
3967 * 2) it's a server id cookie that we *MAY* want to delete : save
3968 * some pointers on it (last semi-colon, beginning of cookie...)
3969 * 3) it's an application cookie : we *MAY* have to delete a previous
3970 * "special" cookie.
3971 * At the end of loop, if a "special" cookie remains, we may have to
3972 * remove it. If no application cookie persists in the header, we
3973 * *MUST* delete it.
3974 *
3975 * Note: RFC2965 is unclear about the processing of spaces around
3976 * the equal sign in the ATTR=VALUE form. A careful inspection of
3977 * the RFC explicitly allows spaces before it, and not within the
3978 * tokens (attrs or values). An inspection of RFC2109 allows that
3979 * too but section 10.1.3 lets one think that spaces may be allowed
3980 * after the equal sign too, resulting in some (rare) buggy
3981 * implementations trying to do that. So let's do what servers do.
3982 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3983 * allowed quoted strings in values, with any possible character
3984 * after a backslash, including control chars and delimitors, which
3985 * causes parsing to become ambiguous. Browsers also allow spaces
3986 * within values even without quotes.
3987 *
3988 * We have to keep multiple pointers in order to support cookie
3989 * removal at the beginning, middle or end of header without
3990 * corrupting the header. All of these headers are valid :
3991 *
3992 * hdr_beg hdr_end
3993 * | |
3994 * v |
3995 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3996 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3997 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3998 * | | | | | | |
3999 * | | | | | | |
4000 * | | | | | | +--> next
4001 * | | | | | +----> val_end
4002 * | | | | +-----------> val_beg
4003 * | | | +--------------> equal
4004 * | | +----------------> att_end
4005 * | +---------------------> att_beg
4006 * +--------------------------> prev
4007 *
4008 */
4009 hdr_beg = ctx.value.ptr;
4010 hdr_end = hdr_beg + ctx.value.len;
4011 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4012 /* Iterate through all cookies on this line */
4013
4014 /* find att_beg */
4015 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004016 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004017 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004018 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004019
4020 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4021 att_beg++;
4022
4023 /* find att_end : this is the first character after the last non
4024 * space before the equal. It may be equal to hdr_end.
4025 */
4026 equal = att_end = att_beg;
4027 while (equal < hdr_end) {
4028 if (*equal == '=' || *equal == ',' || *equal == ';')
4029 break;
4030 if (HTTP_IS_SPHT(*equal++))
4031 continue;
4032 att_end = equal;
4033 }
4034
4035 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4036 * is between <att_beg> and <equal>, both may be identical.
4037 */
4038 /* look for end of cookie if there is an equal sign */
4039 if (equal < hdr_end && *equal == '=') {
4040 /* look for the beginning of the value */
4041 val_beg = equal + 1;
4042 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4043 val_beg++;
4044
4045 /* find the end of the value, respecting quotes */
4046 next = http_find_cookie_value_end(val_beg, hdr_end);
4047
4048 /* make val_end point to the first white space or delimitor after the value */
4049 val_end = next;
4050 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4051 val_end--;
4052 }
4053 else
4054 val_beg = val_end = next = equal;
4055
4056 /* We have nothing to do with attributes beginning with
4057 * '$'. However, they will automatically be removed if a
4058 * header before them is removed, since they're supposed
4059 * to be linked together.
4060 */
4061 if (*att_beg == '$')
4062 continue;
4063
4064 /* Ignore cookies with no equal sign */
4065 if (equal == next) {
4066 /* This is not our cookie, so we must preserve it. But if we already
4067 * scheduled another cookie for removal, we cannot remove the
4068 * complete header, but we can remove the previous block itself.
4069 */
4070 preserve_hdr = 1;
4071 if (del_from != NULL) {
4072 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4073 val_end += delta;
4074 next += delta;
4075 hdr_end += delta;
4076 prev = del_from;
4077 del_from = NULL;
4078 }
4079 continue;
4080 }
4081
4082 /* if there are spaces around the equal sign, we need to
4083 * strip them otherwise we'll get trouble for cookie captures,
4084 * or even for rewrites. Since this happens extremely rarely,
4085 * it does not hurt performance.
4086 */
4087 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4088 int stripped_before = 0;
4089 int stripped_after = 0;
4090
4091 if (att_end != equal) {
4092 memmove(att_end, equal, hdr_end - equal);
4093 stripped_before = (att_end - equal);
4094 equal += stripped_before;
4095 val_beg += stripped_before;
4096 }
4097
4098 if (val_beg > equal + 1) {
4099 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4100 stripped_after = (equal + 1) - val_beg;
4101 val_beg += stripped_after;
4102 stripped_before += stripped_after;
4103 }
4104
4105 val_end += stripped_before;
4106 next += stripped_before;
4107 hdr_end += stripped_before;
4108 }
4109 /* now everything is as on the diagram above */
4110
4111 /* First, let's see if we want to capture this cookie. We check
4112 * that we don't already have a client side cookie, because we
4113 * can only capture one. Also as an optimisation, we ignore
4114 * cookies shorter than the declared name.
4115 */
4116 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4117 (val_end - att_beg >= sess->fe->capture_namelen) &&
4118 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4119 int log_len = val_end - att_beg;
4120
4121 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4122 ha_alert("HTTP logging : out of memory.\n");
4123 } else {
4124 if (log_len > sess->fe->capture_len)
4125 log_len = sess->fe->capture_len;
4126 memcpy(txn->cli_cookie, att_beg, log_len);
4127 txn->cli_cookie[log_len] = 0;
4128 }
4129 }
4130
4131 /* Persistence cookies in passive, rewrite or insert mode have the
4132 * following form :
4133 *
4134 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4135 *
4136 * For cookies in prefix mode, the form is :
4137 *
4138 * Cookie: NAME=SRV~VALUE
4139 */
4140 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4141 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4142 struct server *srv = s->be->srv;
4143 char *delim;
4144
4145 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4146 * have the server ID between val_beg and delim, and the original cookie between
4147 * delim+1 and val_end. Otherwise, delim==val_end :
4148 *
4149 * hdr_beg
4150 * |
4151 * v
4152 * NAME=SRV; # in all but prefix modes
4153 * NAME=SRV~OPAQUE ; # in prefix mode
4154 * || || | |+-> next
4155 * || || | +--> val_end
4156 * || || +---------> delim
4157 * || |+------------> val_beg
4158 * || +-------------> att_end = equal
4159 * |+-----------------> att_beg
4160 * +------------------> prev
4161 *
4162 */
4163 if (s->be->ck_opts & PR_CK_PFX) {
4164 for (delim = val_beg; delim < val_end; delim++)
4165 if (*delim == COOKIE_DELIM)
4166 break;
4167 }
4168 else {
4169 char *vbar1;
4170 delim = val_end;
4171 /* Now check if the cookie contains a date field, which would
4172 * appear after a vertical bar ('|') just after the server name
4173 * and before the delimiter.
4174 */
4175 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4176 if (vbar1) {
4177 /* OK, so left of the bar is the server's cookie and
4178 * right is the last seen date. It is a base64 encoded
4179 * 30-bit value representing the UNIX date since the
4180 * epoch in 4-second quantities.
4181 */
4182 int val;
4183 delim = vbar1++;
4184 if (val_end - vbar1 >= 5) {
4185 val = b64tos30(vbar1);
4186 if (val > 0)
4187 txn->cookie_last_date = val << 2;
4188 }
4189 /* look for a second vertical bar */
4190 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4191 if (vbar1 && (val_end - vbar1 > 5)) {
4192 val = b64tos30(vbar1 + 1);
4193 if (val > 0)
4194 txn->cookie_first_date = val << 2;
4195 }
4196 }
4197 }
4198
4199 /* if the cookie has an expiration date and the proxy wants to check
4200 * it, then we do that now. We first check if the cookie is too old,
4201 * then only if it has expired. We detect strict overflow because the
4202 * time resolution here is not great (4 seconds). Cookies with dates
4203 * in the future are ignored if their offset is beyond one day. This
4204 * allows an admin to fix timezone issues without expiring everyone
4205 * and at the same time avoids keeping unwanted side effects for too
4206 * long.
4207 */
4208 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4209 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4210 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4211 txn->flags &= ~TX_CK_MASK;
4212 txn->flags |= TX_CK_OLD;
4213 delim = val_beg; // let's pretend we have not found the cookie
4214 txn->cookie_first_date = 0;
4215 txn->cookie_last_date = 0;
4216 }
4217 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4218 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4219 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4220 txn->flags &= ~TX_CK_MASK;
4221 txn->flags |= TX_CK_EXPIRED;
4222 delim = val_beg; // let's pretend we have not found the cookie
4223 txn->cookie_first_date = 0;
4224 txn->cookie_last_date = 0;
4225 }
4226
4227 /* Here, we'll look for the first running server which supports the cookie.
4228 * This allows to share a same cookie between several servers, for example
4229 * to dedicate backup servers to specific servers only.
4230 * However, to prevent clients from sticking to cookie-less backup server
4231 * when they have incidentely learned an empty cookie, we simply ignore
4232 * empty cookies and mark them as invalid.
4233 * The same behaviour is applied when persistence must be ignored.
4234 */
4235 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4236 srv = NULL;
4237
4238 while (srv) {
4239 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4240 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4241 if ((srv->cur_state != SRV_ST_STOPPED) ||
4242 (s->be->options & PR_O_PERSIST) ||
4243 (s->flags & SF_FORCE_PRST)) {
4244 /* we found the server and we can use it */
4245 txn->flags &= ~TX_CK_MASK;
4246 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4247 s->flags |= SF_DIRECT | SF_ASSIGNED;
4248 s->target = &srv->obj_type;
4249 break;
4250 } else {
4251 /* we found a server, but it's down,
4252 * mark it as such and go on in case
4253 * another one is available.
4254 */
4255 txn->flags &= ~TX_CK_MASK;
4256 txn->flags |= TX_CK_DOWN;
4257 }
4258 }
4259 srv = srv->next;
4260 }
4261
4262 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4263 /* no server matched this cookie or we deliberately skipped it */
4264 txn->flags &= ~TX_CK_MASK;
4265 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4266 txn->flags |= TX_CK_UNUSED;
4267 else
4268 txn->flags |= TX_CK_INVALID;
4269 }
4270
4271 /* depending on the cookie mode, we may have to either :
4272 * - delete the complete cookie if we're in insert+indirect mode, so that
4273 * the server never sees it ;
4274 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004275 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004276 * if we're in cookie prefix mode
4277 */
4278 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4279 int delta; /* negative */
4280
4281 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4282 delta = val_beg - (delim + 1);
4283 val_end += delta;
4284 next += delta;
4285 hdr_end += delta;
4286 del_from = NULL;
4287 preserve_hdr = 1; /* we want to keep this cookie */
4288 }
4289 else if (del_from == NULL &&
4290 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4291 del_from = prev;
4292 }
4293 }
4294 else {
4295 /* This is not our cookie, so we must preserve it. But if we already
4296 * scheduled another cookie for removal, we cannot remove the
4297 * complete header, but we can remove the previous block itself.
4298 */
4299 preserve_hdr = 1;
4300
4301 if (del_from != NULL) {
4302 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4303 if (att_beg >= del_from)
4304 att_beg += delta;
4305 if (att_end >= del_from)
4306 att_end += delta;
4307 val_beg += delta;
4308 val_end += delta;
4309 next += delta;
4310 hdr_end += delta;
4311 prev = del_from;
4312 del_from = NULL;
4313 }
4314 }
4315
4316 /* continue with next cookie on this header line */
4317 att_beg = next;
4318 } /* for each cookie */
4319
4320
4321 /* There are no more cookies on this line.
4322 * We may still have one (or several) marked for deletion at the
4323 * end of the line. We must do this now in two ways :
4324 * - if some cookies must be preserved, we only delete from the
4325 * mark to the end of line ;
4326 * - if nothing needs to be preserved, simply delete the whole header
4327 */
4328 if (del_from) {
4329 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4330 }
4331 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004332 if (hdr_beg != hdr_end)
4333 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004334 else
4335 http_remove_header(htx, &ctx);
4336 }
4337 } /* for each "Cookie header */
4338}
4339
4340/*
4341 * Manage server-side cookies. It can impact performance by about 2% so it is
4342 * desirable to call it only when needed. This function is also used when we
4343 * just need to know if there is a cookie (eg: for check-cache).
4344 */
4345static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4346{
4347 struct session *sess = s->sess;
4348 struct http_txn *txn = s->txn;
4349 struct htx *htx;
4350 struct http_hdr_ctx ctx;
4351 struct server *srv;
4352 char *hdr_beg, *hdr_end;
4353 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004354 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004355
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004356 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004357
4358 ctx.blk = NULL;
4359 while (1) {
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004360 int is_first = 1;
4361
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004362 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4363 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4364 break;
4365 is_cookie2 = 1;
4366 }
4367
4368 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4369 * <prev> points to the colon.
4370 */
4371 txn->flags |= TX_SCK_PRESENT;
4372
4373 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4374 * check-cache is enabled) and we are not interested in checking
4375 * them. Warning, the cookie capture is declared in the frontend.
4376 */
4377 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4378 break;
4379
4380 /* OK so now we know we have to process this response cookie.
4381 * The format of the Set-Cookie header is slightly different
4382 * from the format of the Cookie header in that it does not
4383 * support the comma as a cookie delimiter (thus the header
4384 * cannot be folded) because the Expires attribute described in
4385 * the original Netscape's spec may contain an unquoted date
4386 * with a comma inside. We have to live with this because
4387 * many browsers don't support Max-Age and some browsers don't
4388 * support quoted strings. However the Set-Cookie2 header is
4389 * clean.
4390 *
4391 * We have to keep multiple pointers in order to support cookie
4392 * removal at the beginning, middle or end of header without
4393 * corrupting the header (in case of set-cookie2). A special
4394 * pointer, <scav> points to the beginning of the set-cookie-av
4395 * fields after the first semi-colon. The <next> pointer points
4396 * either to the end of line (set-cookie) or next unquoted comma
4397 * (set-cookie2). All of these headers are valid :
4398 *
4399 * hdr_beg hdr_end
4400 * | |
4401 * v |
4402 * NAME1 = VALUE 1 ; Secure; Path="/" |
4403 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4404 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4405 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4406 * | | | | | | | |
4407 * | | | | | | | +-> next
4408 * | | | | | | +------------> scav
4409 * | | | | | +--------------> val_end
4410 * | | | | +--------------------> val_beg
4411 * | | | +----------------------> equal
4412 * | | +------------------------> att_end
4413 * | +----------------------------> att_beg
4414 * +------------------------------> prev
4415 * -------------------------------> hdr_beg
4416 */
4417 hdr_beg = ctx.value.ptr;
4418 hdr_end = hdr_beg + ctx.value.len;
4419 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4420
4421 /* Iterate through all cookies on this line */
4422
4423 /* find att_beg */
4424 att_beg = prev;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004425 if (!is_first)
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004426 att_beg++;
Olivier Houchardfc7f52e2019-07-22 17:43:46 +02004427 is_first = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004428
4429 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4430 att_beg++;
4431
4432 /* find att_end : this is the first character after the last non
4433 * space before the equal. It may be equal to hdr_end.
4434 */
4435 equal = att_end = att_beg;
4436
4437 while (equal < hdr_end) {
4438 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4439 break;
4440 if (HTTP_IS_SPHT(*equal++))
4441 continue;
4442 att_end = equal;
4443 }
4444
4445 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4446 * is between <att_beg> and <equal>, both may be identical.
4447 */
4448
4449 /* look for end of cookie if there is an equal sign */
4450 if (equal < hdr_end && *equal == '=') {
4451 /* look for the beginning of the value */
4452 val_beg = equal + 1;
4453 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4454 val_beg++;
4455
4456 /* find the end of the value, respecting quotes */
4457 next = http_find_cookie_value_end(val_beg, hdr_end);
4458
4459 /* make val_end point to the first white space or delimitor after the value */
4460 val_end = next;
4461 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4462 val_end--;
4463 }
4464 else {
4465 /* <equal> points to next comma, semi-colon or EOL */
4466 val_beg = val_end = next = equal;
4467 }
4468
4469 if (next < hdr_end) {
4470 /* Set-Cookie2 supports multiple cookies, and <next> points to
4471 * a colon or semi-colon before the end. So skip all attr-value
4472 * pairs and look for the next comma. For Set-Cookie, since
4473 * commas are permitted in values, skip to the end.
4474 */
4475 if (is_cookie2)
4476 next = http_find_hdr_value_end(next, hdr_end);
4477 else
4478 next = hdr_end;
4479 }
4480
4481 /* Now everything is as on the diagram above */
4482
4483 /* Ignore cookies with no equal sign */
4484 if (equal == val_end)
4485 continue;
4486
4487 /* If there are spaces around the equal sign, we need to
4488 * strip them otherwise we'll get trouble for cookie captures,
4489 * or even for rewrites. Since this happens extremely rarely,
4490 * it does not hurt performance.
4491 */
4492 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4493 int stripped_before = 0;
4494 int stripped_after = 0;
4495
4496 if (att_end != equal) {
4497 memmove(att_end, equal, hdr_end - equal);
4498 stripped_before = (att_end - equal);
4499 equal += stripped_before;
4500 val_beg += stripped_before;
4501 }
4502
4503 if (val_beg > equal + 1) {
4504 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4505 stripped_after = (equal + 1) - val_beg;
4506 val_beg += stripped_after;
4507 stripped_before += stripped_after;
4508 }
4509
4510 val_end += stripped_before;
4511 next += stripped_before;
4512 hdr_end += stripped_before;
4513
Christopher Faulet41dc8432019-06-18 09:49:16 +02004514 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004515 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004516 }
4517
4518 /* First, let's see if we want to capture this cookie. We check
4519 * that we don't already have a server side cookie, because we
4520 * can only capture one. Also as an optimisation, we ignore
4521 * cookies shorter than the declared name.
4522 */
4523 if (sess->fe->capture_name != NULL &&
4524 txn->srv_cookie == NULL &&
4525 (val_end - att_beg >= sess->fe->capture_namelen) &&
4526 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4527 int log_len = val_end - att_beg;
4528 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4529 ha_alert("HTTP logging : out of memory.\n");
4530 }
4531 else {
4532 if (log_len > sess->fe->capture_len)
4533 log_len = sess->fe->capture_len;
4534 memcpy(txn->srv_cookie, att_beg, log_len);
4535 txn->srv_cookie[log_len] = 0;
4536 }
4537 }
4538
4539 srv = objt_server(s->target);
4540 /* now check if we need to process it for persistence */
4541 if (!(s->flags & SF_IGNORE_PRST) &&
4542 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4543 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4544 /* assume passive cookie by default */
4545 txn->flags &= ~TX_SCK_MASK;
4546 txn->flags |= TX_SCK_FOUND;
4547
4548 /* If the cookie is in insert mode on a known server, we'll delete
4549 * this occurrence because we'll insert another one later.
4550 * We'll delete it too if the "indirect" option is set and we're in
4551 * a direct access.
4552 */
4553 if (s->be->ck_opts & PR_CK_PSV) {
4554 /* The "preserve" flag was set, we don't want to touch the
4555 * server's cookie.
4556 */
4557 }
4558 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4559 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4560 /* this cookie must be deleted */
4561 if (prev == hdr_beg && next == hdr_end) {
4562 /* whole header */
4563 http_remove_header(htx, &ctx);
4564 /* note: while both invalid now, <next> and <hdr_end>
4565 * are still equal, so the for() will stop as expected.
4566 */
4567 } else {
4568 /* just remove the value */
4569 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4570 next = prev;
4571 hdr_end += delta;
4572 }
4573 txn->flags &= ~TX_SCK_MASK;
4574 txn->flags |= TX_SCK_DELETED;
4575 /* and go on with next cookie */
4576 }
4577 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4578 /* replace bytes val_beg->val_end with the cookie name associated
4579 * with this server since we know it.
4580 */
4581 int sliding, delta;
4582
4583 ctx.value = ist2(val_beg, val_end - val_beg);
4584 ctx.lws_before = ctx.lws_after = 0;
4585 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4586 delta = srv->cklen - (val_end - val_beg);
4587 sliding = (ctx.value.ptr - val_beg);
4588 hdr_beg += sliding;
4589 val_beg += sliding;
4590 next += sliding + delta;
4591 hdr_end += sliding + delta;
4592
4593 txn->flags &= ~TX_SCK_MASK;
4594 txn->flags |= TX_SCK_REPLACED;
4595 }
4596 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4597 /* insert the cookie name associated with this server
4598 * before existing cookie, and insert a delimiter between them..
4599 */
4600 int sliding, delta;
4601 ctx.value = ist2(val_beg, 0);
4602 ctx.lws_before = ctx.lws_after = 0;
4603 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4604 delta = srv->cklen + 1;
4605 sliding = (ctx.value.ptr - val_beg);
4606 hdr_beg += sliding;
4607 val_beg += sliding;
4608 next += sliding + delta;
4609 hdr_end += sliding + delta;
4610
4611 val_beg[srv->cklen] = COOKIE_DELIM;
4612 txn->flags &= ~TX_SCK_MASK;
4613 txn->flags |= TX_SCK_REPLACED;
4614 }
4615 }
4616 /* that's done for this cookie, check the next one on the same
4617 * line when next != hdr_end (only if is_cookie2).
4618 */
4619 }
4620 }
4621}
4622
Christopher Faulet25a02f62018-10-24 12:00:25 +02004623/*
4624 * Parses the Cache-Control and Pragma request header fields to determine if
4625 * the request may be served from the cache and/or if it is cacheable. Updates
4626 * s->txn->flags.
4627 */
4628void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4629{
4630 struct http_txn *txn = s->txn;
4631 struct htx *htx;
4632 int32_t pos;
4633 int pragma_found, cc_found, i;
4634
4635 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4636 return; /* nothing more to do here */
4637
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004638 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004639 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004640 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004641 struct htx_blk *blk = htx_get_blk(htx, pos);
4642 enum htx_blk_type type = htx_get_blk_type(blk);
4643 struct ist n, v;
4644
4645 if (type == HTX_BLK_EOH)
4646 break;
4647 if (type != HTX_BLK_HDR)
4648 continue;
4649
4650 n = htx_get_blk_name(htx, blk);
4651 v = htx_get_blk_value(htx, blk);
4652
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004653 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004654 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4655 pragma_found = 1;
4656 continue;
4657 }
4658 }
4659
4660 /* Don't use the cache and don't try to store if we found the
4661 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004662 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004663 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4664 txn->flags |= TX_CACHE_IGNORE;
4665 continue;
4666 }
4667
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004668 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004669 continue;
4670
4671 /* OK, right now we know we have a cache-control header */
4672 cc_found = 1;
4673 if (!v.len) /* no info */
4674 continue;
4675
4676 i = 0;
4677 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4678 !isspace((unsigned char)*(v.ptr+i)))
4679 i++;
4680
4681 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4682 * values after max-age, max-stale nor min-fresh, we simply don't
4683 * use the cache when they're specified.
4684 */
4685 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4686 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4687 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4688 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4689 txn->flags |= TX_CACHE_IGNORE;
4690 continue;
4691 }
4692
4693 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4694 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4695 continue;
4696 }
4697 }
4698
4699 /* RFC7234#5.4:
4700 * When the Cache-Control header field is also present and
4701 * understood in a request, Pragma is ignored.
4702 * When the Cache-Control header field is not present in a
4703 * request, caches MUST consider the no-cache request
4704 * pragma-directive as having the same effect as if
4705 * "Cache-Control: no-cache" were present.
4706 */
4707 if (!cc_found && pragma_found)
4708 txn->flags |= TX_CACHE_IGNORE;
4709}
4710
4711/*
4712 * Check if response is cacheable or not. Updates s->txn->flags.
4713 */
4714void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4715{
4716 struct http_txn *txn = s->txn;
4717 struct htx *htx;
4718 int32_t pos;
4719 int i;
4720
4721 if (txn->status < 200) {
4722 /* do not try to cache interim responses! */
4723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 return;
4725 }
4726
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004727 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004728 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004729 struct htx_blk *blk = htx_get_blk(htx, pos);
4730 enum htx_blk_type type = htx_get_blk_type(blk);
4731 struct ist n, v;
4732
4733 if (type == HTX_BLK_EOH)
4734 break;
4735 if (type != HTX_BLK_HDR)
4736 continue;
4737
4738 n = htx_get_blk_name(htx, blk);
4739 v = htx_get_blk_value(htx, blk);
4740
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004741 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004742 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4743 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4744 return;
4745 }
4746 }
4747
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004748 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004749 continue;
4750
4751 /* OK, right now we know we have a cache-control header */
4752 if (!v.len) /* no info */
4753 continue;
4754
4755 i = 0;
4756 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4757 !isspace((unsigned char)*(v.ptr+i)))
4758 i++;
4759
4760 /* we have a complete value between v.ptr and (v.ptr+i) */
4761 if (i < v.len && *(v.ptr + i) == '=') {
4762 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4763 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4764 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4765 continue;
4766 }
4767
4768 /* we have something of the form no-cache="set-cookie" */
4769 if ((v.len >= 21) &&
4770 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4771 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4772 txn->flags &= ~TX_CACHE_COOK;
4773 continue;
4774 }
4775
4776 /* OK, so we know that either p2 points to the end of string or to a comma */
4777 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4778 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4779 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4780 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4781 return;
4782 }
4783
4784 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4785 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4786 continue;
4787 }
4788 }
4789}
4790
Christopher Faulet64159df2018-10-24 21:15:35 +02004791/* send a server's name with an outgoing request over an established connection.
4792 * Note: this function is designed to be called once the request has been
4793 * scheduled for being forwarded. This is the reason why the number of forwarded
4794 * bytes have to be adjusted.
4795 */
4796int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4797{
4798 struct htx *htx;
4799 struct http_hdr_ctx ctx;
4800 struct ist hdr;
4801 uint32_t data;
4802
4803 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004804 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004805 data = htx->data;
4806
4807 ctx.blk = NULL;
4808 while (http_find_header(htx, hdr, &ctx, 1))
4809 http_remove_header(htx, &ctx);
4810 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4811
4812 if (co_data(&s->req)) {
4813 if (data >= htx->data)
4814 c_rew(&s->req, data - htx->data);
4815 else
4816 c_adv(&s->req, htx->data - data);
4817 }
4818 return 0;
4819}
4820
Christopher Faulet377c5a52018-10-24 21:21:30 +02004821/*
4822 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4823 * for the current backend.
4824 *
4825 * It is assumed that the request is either a HEAD, GET, or POST and that the
4826 * uri_auth field is valid.
4827 *
4828 * Returns 1 if stats should be provided, otherwise 0.
4829 */
4830static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4831{
4832 struct uri_auth *uri_auth = backend->uri_auth;
4833 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004834 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004835 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004836
4837 if (!uri_auth)
4838 return 0;
4839
4840 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4841 return 0;
4842
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004843 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004844 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004845 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004846
4847 /* check URI size */
4848 if (uri_auth->uri_len > uri.len)
4849 return 0;
4850
4851 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4852 return 0;
4853
4854 return 1;
4855}
4856
4857/* This function prepares an applet to handle the stats. It can deal with the
4858 * "100-continue" expectation, check that admin rules are met for POST requests,
4859 * and program a response message if something was unexpected. It cannot fail
4860 * and always relies on the stats applet to complete the job. It does not touch
4861 * analysers nor counters, which are left to the caller. It does not touch
4862 * s->target which is supposed to already point to the stats applet. The caller
4863 * is expected to have already assigned an appctx to the stream.
4864 */
4865static int htx_handle_stats(struct stream *s, struct channel *req)
4866{
4867 struct stats_admin_rule *stats_admin_rule;
4868 struct stream_interface *si = &s->si[1];
4869 struct session *sess = s->sess;
4870 struct http_txn *txn = s->txn;
4871 struct http_msg *msg = &txn->req;
4872 struct uri_auth *uri_auth = s->be->uri_auth;
4873 const char *h, *lookup, *end;
4874 struct appctx *appctx;
4875 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004876 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004877
4878 appctx = si_appctx(si);
4879 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4880 appctx->st1 = appctx->st2 = 0;
4881 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4882 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4883 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4884 appctx->ctx.stats.flags |= STAT_CHUNKED;
4885
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004886 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004887 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004888 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4889 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004890
4891 for (h = lookup; h <= end - 3; h++) {
4892 if (memcmp(h, ";up", 3) == 0) {
4893 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4894 break;
4895 }
4896 }
4897
4898 if (uri_auth->refresh) {
4899 for (h = lookup; h <= end - 10; h++) {
4900 if (memcmp(h, ";norefresh", 10) == 0) {
4901 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4902 break;
4903 }
4904 }
4905 }
4906
4907 for (h = lookup; h <= end - 4; h++) {
4908 if (memcmp(h, ";csv", 4) == 0) {
4909 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4910 break;
4911 }
4912 }
4913
4914 for (h = lookup; h <= end - 6; h++) {
4915 if (memcmp(h, ";typed", 6) == 0) {
4916 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4917 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4918 break;
4919 }
4920 }
4921
4922 for (h = lookup; h <= end - 8; h++) {
4923 if (memcmp(h, ";st=", 4) == 0) {
4924 int i;
4925 h += 4;
4926 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4927 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4928 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4929 appctx->ctx.stats.st_code = i;
4930 break;
4931 }
4932 }
4933 break;
4934 }
4935 }
4936
4937 appctx->ctx.stats.scope_str = 0;
4938 appctx->ctx.stats.scope_len = 0;
4939 for (h = lookup; h <= end - 8; h++) {
4940 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4941 int itx = 0;
4942 const char *h2;
4943 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4944 const char *err;
4945
4946 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4947 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004948 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4949 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004950 if (*h == ';' || *h == '&' || *h == ' ')
4951 break;
4952 itx++;
4953 h++;
4954 }
4955
4956 if (itx > STAT_SCOPE_TXT_MAXLEN)
4957 itx = STAT_SCOPE_TXT_MAXLEN;
4958 appctx->ctx.stats.scope_len = itx;
4959
4960 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4961 memcpy(scope_txt, h2, itx);
4962 scope_txt[itx] = '\0';
4963 err = invalid_char(scope_txt);
4964 if (err) {
4965 /* bad char in search text => clear scope */
4966 appctx->ctx.stats.scope_str = 0;
4967 appctx->ctx.stats.scope_len = 0;
4968 }
4969 break;
4970 }
4971 }
4972
4973 /* now check whether we have some admin rules for this request */
4974 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4975 int ret = 1;
4976
4977 if (stats_admin_rule->cond) {
4978 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4979 ret = acl_pass(ret);
4980 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4981 ret = !ret;
4982 }
4983
4984 if (ret) {
4985 /* no rule, or the rule matches */
4986 appctx->ctx.stats.flags |= STAT_ADMIN;
4987 break;
4988 }
4989 }
4990
Christopher Faulet5d45e382019-02-27 15:15:23 +01004991 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4992 appctx->st0 = STAT_HTTP_HEAD;
4993 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet69af2522019-08-15 22:26:48 +02004994 if (appctx->ctx.stats.flags & STAT_ADMIN) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004995 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet69af2522019-08-15 22:26:48 +02004996 if (msg->msg_state < HTTP_MSG_DATA)
4997 req->analysers |= AN_REQ_HTTP_BODY;
4998 }
Christopher Faulet377c5a52018-10-24 21:21:30 +02004999 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005000 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02005001 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5002 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
5003 appctx->st0 = STAT_HTTP_LAST;
5004 }
5005 }
5006 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01005007 /* Unsupported method */
5008 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
5009 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
5010 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02005011 }
5012
5013 s->task->nice = -32; /* small boost for HTTP statistics */
5014 return 1;
5015}
5016
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005017void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
5018{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005019 struct channel *req = &s->req;
5020 struct channel *res = &s->res;
5021 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005022 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005023 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005024 struct ist path, location;
5025 unsigned int flags;
5026 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005027
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005028 /*
5029 * Create the location
5030 */
5031 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005032
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005033 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005034 /* special prefix "/" means don't change URL */
5035 srv = __objt_server(s->target);
5036 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5037 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5038 return;
5039 }
5040
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005041 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005042 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005043 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005044 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045 if (!path.ptr)
5046 return;
5047
5048 if (!chunk_memcat(&trash, path.ptr, path.len))
5049 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005052 /*
5053 * Create the 302 respone
5054 */
5055 htx = htx_from_buf(&res->buf);
5056 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5057 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5058 ist("HTTP/1.1"), ist("302"), ist("Found"));
5059 if (!sl)
5060 goto fail;
5061 sl->info.res.status = 302;
5062 s->txn->status = 302;
5063
5064 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5065 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5066 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5067 !htx_add_header(htx, ist("Location"), location))
5068 goto fail;
5069
5070 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5071 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005072
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005073 /*
5074 * Send the message
5075 */
5076 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005077 c_adv(res, data);
5078 res->total += data;
5079
5080 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005081 si_shutr(si);
5082 si_shutw(si);
5083 si->err_type = SI_ET_NONE;
5084 si->state = SI_ST_CLO;
5085
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005086 channel_auto_read(req);
5087 channel_abort(req);
5088 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005089 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005090 channel_auto_read(res);
5091 channel_auto_close(res);
5092
5093 if (!(s->flags & SF_ERR_MASK))
5094 s->flags |= SF_ERR_LOCAL;
5095 if (!(s->flags & SF_FINST_MASK))
5096 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005097
5098 /* FIXME: we should increase a counter of redirects per server and per backend. */
5099 srv_inc_sess_ctr(srv);
5100 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005101 return;
5102
5103 fail:
5104 /* If an error occurred, remove the incomplete HTTP response from the
5105 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005106 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005107}
5108
Christopher Fauletf2824e62018-10-01 12:12:37 +02005109/* This function terminates the request because it was completly analyzed or
5110 * because an error was triggered during the body forwarding.
5111 */
5112static void htx_end_request(struct stream *s)
5113{
5114 struct channel *chn = &s->req;
5115 struct http_txn *txn = s->txn;
5116
5117 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5118 now_ms, __FUNCTION__, s,
5119 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5120 s->req.analysers, s->res.analysers);
5121
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005122 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5123 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005124 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005125 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005126 goto end;
5127 }
5128
5129 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5130 return;
5131
5132 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005133 /* No need to read anymore, the request was completely parsed.
5134 * We can shut the read side unless we want to abort_on_close,
5135 * or we have a POST request. The issue with POST requests is
5136 * that some browsers still send a CRLF after the request, and
5137 * this CRLF must be read so that it does not remain in the kernel
5138 * buffers, otherwise a close could cause an RST on some systems
5139 * (eg: Linux).
5140 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005141 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005142 channel_dont_read(chn);
5143
5144 /* if the server closes the connection, we want to immediately react
5145 * and close the socket to save packets and syscalls.
5146 */
5147 s->si[1].flags |= SI_FL_NOHALF;
5148
5149 /* In any case we've finished parsing the request so we must
5150 * disable Nagle when sending data because 1) we're not going
5151 * to shut this side, and 2) the server is waiting for us to
5152 * send pending data.
5153 */
5154 chn->flags |= CF_NEVER_WAIT;
5155
Christopher Fauletd01ce402019-01-02 17:44:13 +01005156 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5157 /* The server has not finished to respond, so we
5158 * don't want to move in order not to upset it.
5159 */
5160 return;
5161 }
5162
Christopher Fauletf2824e62018-10-01 12:12:37 +02005163 /* When we get here, it means that both the request and the
5164 * response have finished receiving. Depending on the connection
5165 * mode, we'll have to wait for the last bytes to leave in either
5166 * direction, and sometimes for a close to be effective.
5167 */
5168 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5169 /* Tunnel mode will not have any analyser so it needs to
5170 * poll for reads.
5171 */
5172 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005173 if (b_data(&chn->buf))
5174 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005175 txn->req.msg_state = HTTP_MSG_TUNNEL;
5176 }
5177 else {
5178 /* we're not expecting any new data to come for this
5179 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005180 *
5181 * However, there is an exception if the response
5182 * length is undefined. In this case, we need to wait
5183 * the close from the server. The response will be
5184 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005185 */
5186 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5187 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005188 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005189
5190 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5191 channel_shutr_now(chn);
5192 channel_shutw_now(chn);
5193 }
5194 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 goto check_channel_flags;
5196 }
5197
5198 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5199 http_msg_closing:
5200 /* nothing else to forward, just waiting for the output buffer
5201 * to be empty and for the shutw_now to take effect.
5202 */
5203 if (channel_is_empty(chn)) {
5204 txn->req.msg_state = HTTP_MSG_CLOSED;
5205 goto http_msg_closed;
5206 }
5207 else if (chn->flags & CF_SHUTW) {
5208 txn->req.err_state = txn->req.msg_state;
5209 txn->req.msg_state = HTTP_MSG_ERROR;
5210 goto end;
5211 }
5212 return;
5213 }
5214
5215 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5216 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005217 /* if we don't know whether the server will close, we need to hard close */
5218 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5219 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005220 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005221 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005222 channel_dont_read(chn);
5223 goto end;
5224 }
5225
5226 check_channel_flags:
5227 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5228 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5229 /* if we've just closed an output, let's switch */
5230 txn->req.msg_state = HTTP_MSG_CLOSING;
5231 goto http_msg_closing;
5232 }
5233
5234 end:
5235 chn->analysers &= AN_REQ_FLT_END;
5236 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5237 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5238 channel_auto_close(chn);
5239 channel_auto_read(chn);
5240}
5241
5242
5243/* This function terminates the response because it was completly analyzed or
5244 * because an error was triggered during the body forwarding.
5245 */
5246static void htx_end_response(struct stream *s)
5247{
5248 struct channel *chn = &s->res;
5249 struct http_txn *txn = s->txn;
5250
5251 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5252 now_ms, __FUNCTION__, s,
5253 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5254 s->req.analysers, s->res.analysers);
5255
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005256 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5257 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005258 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005259 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005260 goto end;
5261 }
5262
5263 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5264 return;
5265
5266 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5267 /* In theory, we don't need to read anymore, but we must
5268 * still monitor the server connection for a possible close
5269 * while the request is being uploaded, so we don't disable
5270 * reading.
5271 */
5272 /* channel_dont_read(chn); */
5273
5274 if (txn->req.msg_state < HTTP_MSG_DONE) {
5275 /* The client seems to still be sending data, probably
5276 * because we got an error response during an upload.
5277 * We have the choice of either breaking the connection
5278 * or letting it pass through. Let's do the later.
5279 */
5280 return;
5281 }
5282
5283 /* When we get here, it means that both the request and the
5284 * response have finished receiving. Depending on the connection
5285 * mode, we'll have to wait for the last bytes to leave in either
5286 * direction, and sometimes for a close to be effective.
5287 */
5288 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5289 channel_auto_read(chn);
5290 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005291 if (b_data(&chn->buf))
5292 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005293 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5294 }
5295 else {
5296 /* we're not expecting any new data to come for this
5297 * transaction, so we can close it.
5298 */
5299 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5300 channel_shutr_now(chn);
5301 channel_shutw_now(chn);
5302 }
5303 }
5304 goto check_channel_flags;
5305 }
5306
5307 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5308 http_msg_closing:
5309 /* nothing else to forward, just waiting for the output buffer
5310 * to be empty and for the shutw_now to take effect.
5311 */
5312 if (channel_is_empty(chn)) {
5313 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5314 goto http_msg_closed;
5315 }
5316 else if (chn->flags & CF_SHUTW) {
5317 txn->rsp.err_state = txn->rsp.msg_state;
5318 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005319 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005320 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005321 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005322 goto end;
5323 }
5324 return;
5325 }
5326
5327 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5328 http_msg_closed:
5329 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005330 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005331 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005332 goto end;
5333 }
5334
5335 check_channel_flags:
5336 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5337 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5338 /* if we've just closed an output, let's switch */
5339 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5340 goto http_msg_closing;
5341 }
5342
5343 end:
5344 chn->analysers &= AN_RES_FLT_END;
5345 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5346 chn->analysers |= AN_RES_FLT_XFER_DATA;
5347 channel_auto_close(chn);
5348 channel_auto_read(chn);
5349}
5350
Christopher Faulet0f226952018-10-22 09:29:56 +02005351void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5352 int finst, const struct buffer *msg)
5353{
5354 channel_auto_read(si_oc(si));
5355 channel_abort(si_oc(si));
5356 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005357 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005358 channel_auto_close(si_ic(si));
5359 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005360
5361 /* <msg> is an HTX structure. So we copy it in the response's
5362 * channel */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005363 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005364 struct channel *chn = si_ic(si);
5365 struct htx *htx;
5366
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005367 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005368 chn->buf.data = msg->data;
5369 memcpy(chn->buf.area, msg->area, msg->data);
5370 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005371 c_adv(chn, htx->data);
5372 chn->total += htx->data;
5373 }
5374 if (!(s->flags & SF_ERR_MASK))
5375 s->flags |= err;
5376 if (!(s->flags & SF_FINST_MASK))
5377 s->flags |= finst;
5378}
5379
5380void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5381{
5382 channel_auto_read(&s->req);
5383 channel_abort(&s->req);
5384 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005385 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5386 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005387
5388 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005389
5390 /* <msg> is an HTX structure. So we copy it in the response's
5391 * channel */
5392 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet2f8ef7c2019-07-22 16:41:43 +02005393 if (msg && !b_is_null(msg)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005394 struct channel *chn = &s->res;
5395 struct htx *htx;
5396
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005397 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005398 chn->buf.data = msg->data;
5399 memcpy(chn->buf.area, msg->area, msg->data);
5400 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005401 c_adv(chn, htx->data);
5402 chn->total += htx->data;
5403 }
5404
5405 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5406 channel_auto_read(&s->res);
5407 channel_auto_close(&s->res);
5408 channel_shutr_now(&s->res);
5409}
5410
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005411struct buffer *htx_error_message(struct stream *s)
5412{
5413 const int msgnum = http_get_status_idx(s->txn->status);
5414
5415 if (s->be->errmsg[msgnum].area)
5416 return &s->be->errmsg[msgnum];
5417 else if (strm_fe(s)->errmsg[msgnum].area)
5418 return &strm_fe(s)->errmsg[msgnum];
5419 else
5420 return &htx_err_chunks[msgnum];
5421}
5422
5423
Christopher Faulet4a28a532019-03-01 11:19:40 +01005424/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5425 * on success and -1 on error.
5426 */
5427static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5428{
5429 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5430 * then we must send an HTTP/1.1 100 Continue intermediate response.
5431 */
5432 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5433 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5434 struct ist hdr = { .ptr = "Expect", .len = 6 };
5435 struct http_hdr_ctx ctx;
5436
5437 ctx.blk = NULL;
5438 /* Expect is allowed in 1.1, look for it */
5439 if (http_find_header(htx, hdr, &ctx, 0) &&
5440 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5441 if (htx_reply_100_continue(s) == -1)
5442 return -1;
5443 http_remove_header(htx, &ctx);
5444 }
5445 }
5446 return 0;
5447}
5448
Christopher Faulet23a3c792018-11-28 10:01:23 +01005449/* Send a 100-Continue response to the client. It returns 0 on success and -1
5450 * on error. The response channel is updated accordingly.
5451 */
5452static int htx_reply_100_continue(struct stream *s)
5453{
5454 struct channel *res = &s->res;
5455 struct htx *htx = htx_from_buf(&res->buf);
5456 struct htx_sl *sl;
5457 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5458 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5459 size_t data;
5460
5461 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5462 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5463 if (!sl)
5464 goto fail;
5465 sl->info.res.status = 100;
5466
Christopher Faulet9869f932019-06-26 14:23:54 +02005467 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005468 goto fail;
5469
5470 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005471 c_adv(res, data);
5472 res->total += data;
5473 return 0;
5474
5475 fail:
5476 /* If an error occurred, remove the incomplete HTTP response from the
5477 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005478 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005479 return -1;
5480}
5481
Christopher Faulet12c51e22018-11-28 15:59:42 +01005482
5483/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5484 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5485 * error. The response channel is updated accordingly.
5486 */
5487static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5488{
5489 struct channel *res = &s->res;
5490 struct htx *htx = htx_from_buf(&res->buf);
5491 struct htx_sl *sl;
5492 struct ist code, body;
5493 int status;
5494 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5495 size_t data;
5496
5497 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5498 status = 401;
5499 code = ist("401");
5500 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5501 "You need a valid user and password to access this content.\n"
5502 "</body></html>\n");
5503 }
5504 else {
5505 status = 407;
5506 code = ist("407");
5507 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5508 "You need a valid user and password to access this content.\n"
5509 "</body></html>\n");
5510 }
5511
5512 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5513 ist("HTTP/1.1"), code, ist("Unauthorized"));
5514 if (!sl)
5515 goto fail;
5516 sl->info.res.status = status;
5517 s->txn->status = status;
5518
5519 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5520 goto fail;
5521
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005522 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5523 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005524 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005525 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5526 goto fail;
5527 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5528 goto fail;
5529 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005530 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005531 if (!htx_add_endof(htx, HTX_BLK_EOH))
5532 goto fail;
5533
5534 while (body.len) {
5535 size_t sent = htx_add_data(htx, body);
5536 if (!sent)
5537 goto fail;
5538 body.ptr += sent;
5539 body.len -= sent;
5540 }
5541
5542 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005543 goto fail;
5544
5545 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005546 c_adv(res, data);
5547 res->total += data;
5548
5549 channel_auto_read(&s->req);
5550 channel_abort(&s->req);
5551 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005552 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005553
5554 res->wex = tick_add_ifset(now_ms, res->wto);
5555 channel_auto_read(res);
5556 channel_auto_close(res);
5557 channel_shutr_now(res);
5558 return 0;
5559
5560 fail:
5561 /* If an error occurred, remove the incomplete HTTP response from the
5562 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005563 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005564 return -1;
5565}
5566
Christopher Faulet0f226952018-10-22 09:29:56 +02005567/*
5568 * Capture headers from message <htx> according to header list <cap_hdr>, and
5569 * fill the <cap> pointers appropriately.
5570 */
5571static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5572{
5573 struct cap_hdr *h;
5574 int32_t pos;
5575
Christopher Fauleta3f15502019-05-13 15:27:23 +02005576 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005577 struct htx_blk *blk = htx_get_blk(htx, pos);
5578 enum htx_blk_type type = htx_get_blk_type(blk);
5579 struct ist n, v;
5580
5581 if (type == HTX_BLK_EOH)
5582 break;
5583 if (type != HTX_BLK_HDR)
5584 continue;
5585
5586 n = htx_get_blk_name(htx, blk);
5587
5588 for (h = cap_hdr; h; h = h->next) {
5589 if (h->namelen && (h->namelen == n.len) &&
5590 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5591 if (cap[h->index] == NULL)
5592 cap[h->index] =
5593 pool_alloc(h->pool);
5594
5595 if (cap[h->index] == NULL) {
5596 ha_alert("HTTP capture : out of memory.\n");
5597 break;
5598 }
5599
5600 v = htx_get_blk_value(htx, blk);
5601 if (v.len > h->len)
5602 v.len = h->len;
5603
5604 memcpy(cap[h->index], v.ptr, v.len);
5605 cap[h->index][v.len]=0;
5606 }
5607 }
5608 }
5609}
5610
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005611/* Delete a value in a header between delimiters <from> and <next>. The header
5612 * itself is delimited by <start> and <end> pointers. The number of characters
5613 * displaced is returned, and the pointer to the first delimiter is updated if
5614 * required. The function tries as much as possible to respect the following
5615 * principles :
5616 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5617 * in which case <next> is simply removed
5618 * - set exactly one space character after the new first delimiter, unless there
5619 * are not enough characters in the block being moved to do so.
5620 * - remove unneeded spaces before the previous delimiter and after the new
5621 * one.
5622 *
5623 * It is the caller's responsibility to ensure that :
5624 * - <from> points to a valid delimiter or <start> ;
5625 * - <next> points to a valid delimiter or <end> ;
5626 * - there are non-space chars before <from>.
5627 */
5628static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5629{
5630 char *prev = *from;
5631
5632 if (prev == start) {
5633 /* We're removing the first value. eat the semicolon, if <next>
5634 * is lower than <end> */
5635 if (next < end)
5636 next++;
5637
5638 while (next < end && HTTP_IS_SPHT(*next))
5639 next++;
5640 }
5641 else {
5642 /* Remove useless spaces before the old delimiter. */
5643 while (HTTP_IS_SPHT(*(prev-1)))
5644 prev--;
5645 *from = prev;
5646
5647 /* copy the delimiter and if possible a space if we're
5648 * not at the end of the line.
5649 */
5650 if (next < end) {
5651 *prev++ = *next++;
5652 if (prev + 1 < next)
5653 *prev++ = ' ';
5654 while (next < end && HTTP_IS_SPHT(*next))
5655 next++;
5656 }
5657 }
5658 memmove(prev, next, end - next);
5659 return (prev - next);
5660}
5661
Christopher Faulet0f226952018-10-22 09:29:56 +02005662
5663/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005664 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005665 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005666static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005667{
5668 struct ist dst = ist2(str, 0);
5669
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005670 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005671 goto end;
5672 if (dst.len + 1 > len)
5673 goto end;
5674 dst.ptr[dst.len++] = ' ';
5675
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005676 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005677 goto end;
5678 if (dst.len + 1 > len)
5679 goto end;
5680 dst.ptr[dst.len++] = ' ';
5681
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005682 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005683 end:
5684 return dst.len;
5685}
5686
Christopher Fauletf0523542018-10-24 11:06:58 +02005687/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005688 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005689 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005690static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005691{
5692 struct ist dst = ist2(str, 0);
5693
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005694 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005695 goto end;
5696 if (dst.len + 1 > len)
5697 goto end;
5698 dst.ptr[dst.len++] = ' ';
5699
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005700 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005701 goto end;
5702 if (dst.len + 1 > len)
5703 goto end;
5704 dst.ptr[dst.len++] = ' ';
5705
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005707 end:
5708 return dst.len;
5709}
5710
5711
Christopher Faulet0f226952018-10-22 09:29:56 +02005712/*
5713 * Print a debug line with a start line.
5714 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005715static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005716{
5717 struct session *sess = strm_sess(s);
5718 int max;
5719
5720 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5721 dir,
5722 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5723 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5724
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005725 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005726 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005727 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005728 trash.area[trash.data++] = ' ';
5729
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005730 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005731 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005732 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005733 trash.area[trash.data++] = ' ';
5734
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005735 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005736 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005737 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005738 trash.area[trash.data++] = '\n';
5739
5740 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5741}
5742
5743/*
5744 * Print a debug line with a header.
5745 */
5746static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5747{
5748 struct session *sess = strm_sess(s);
5749 int max;
5750
5751 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5752 dir,
5753 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5754 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5755
5756 max = n.len;
5757 UBOUND(max, trash.size - trash.data - 3);
5758 chunk_memcat(&trash, n.ptr, max);
5759 trash.area[trash.data++] = ':';
5760 trash.area[trash.data++] = ' ';
5761
5762 max = v.len;
5763 UBOUND(max, trash.size - trash.data - 1);
5764 chunk_memcat(&trash, v.ptr, max);
5765 trash.area[trash.data++] = '\n';
5766
5767 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5768}
5769
5770
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005771__attribute__((constructor))
5772static void __htx_protocol_init(void)
5773{
5774}
5775
5776
5777/*
5778 * Local variables:
5779 * c-indent-level: 8
5780 * c-basic-offset: 8
5781 * End:
5782 */