blob: 6cbd33b9b36294e4b6355ae50e8bfeeae463caf3 [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 Fauletff2759f2018-10-24 11:13:16 +0200543 if (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);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200808 }
809
810 /*
811 * 7: Now we can work with the cookies.
812 * Note that doing so might move headers in the request, but
813 * the fields will stay coherent and the URI will not move.
814 * This should only be performed in the backend.
815 */
816 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100817 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818
819 /* add unique-id if "header-unique-id" is specified */
820
821 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
822 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
823 goto return_bad_req;
824 s->unique_id[0] = '\0';
825 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
826 }
827
828 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200829 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
830 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
831
832 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200833 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200834 }
835
836 /*
837 * 9: add X-Forwarded-For if either the frontend or the backend
838 * asks for it.
839 */
840 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200841 struct http_hdr_ctx ctx = { .blk = NULL };
842 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
843 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
844
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200846 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 /* The header is set to be added only if none is present
848 * and we found it, so don't do anything.
849 */
850 }
851 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
852 /* Add an X-Forwarded-For header unless the source IP is
853 * in the 'except' network range.
854 */
855 if ((!sess->fe->except_mask.s_addr ||
856 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
857 != sess->fe->except_net.s_addr) &&
858 (!s->be->except_mask.s_addr ||
859 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
860 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200861 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200862
863 /* Note: we rely on the backend to get the header name to be used for
864 * x-forwarded-for, because the header is really meant for the backends.
865 * However, if the backend did not specify any option, we have to rely
866 * on the frontend's header name.
867 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200868 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
869 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200870 goto return_bad_req;
871 }
872 }
873 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
874 /* FIXME: for the sake of completeness, we should also support
875 * 'except' here, although it is mostly useless in this case.
876 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200877 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200878
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 inet_ntop(AF_INET6,
880 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
881 pn, sizeof(pn));
882
883 /* Note: we rely on the backend to get the header name to be used for
884 * x-forwarded-for, because the header is really meant for the backends.
885 * However, if the backend did not specify any option, we have to rely
886 * on the frontend's header name.
887 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200888 chunk_printf(&trash, "%s", pn);
889 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200890 goto return_bad_req;
891 }
892 }
893
894 /*
895 * 10: add X-Original-To if either the frontend or the backend
896 * asks for it.
897 */
898 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
899
900 /* FIXME: don't know if IPv6 can handle that case too. */
901 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
902 /* Add an X-Original-To header unless the destination IP is
903 * in the 'except' network range.
904 */
905 conn_get_to_addr(cli_conn);
906
907 if (cli_conn->addr.to.ss_family == AF_INET &&
908 ((!sess->fe->except_mask_to.s_addr ||
909 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
910 != sess->fe->except_to.s_addr) &&
911 (!s->be->except_mask_to.s_addr ||
912 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
913 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200914 struct ist hdr;
915 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200916
917 /* Note: we rely on the backend to get the header name to be used for
918 * x-original-to, because the header is really meant for the backends.
919 * However, if the backend did not specify any option, we have to rely
920 * on the frontend's header name.
921 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200922 if (s->be->orgto_hdr_len)
923 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
924 else
925 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200926
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200927 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
928 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200929 goto return_bad_req;
930 }
931 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200932 }
933
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 /* If we have no server assigned yet and we're balancing on url_param
935 * with a POST request, we may be interested in checking the body for
936 * that parameter. This will be done in another analyser.
937 */
938 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100939 s->txn->meth == HTTP_METH_POST &&
940 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 channel_dont_connect(req);
942 req->analysers |= AN_REQ_HTTP_BODY;
943 }
944
945 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
946 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100947
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 /* We expect some data from the client. Unless we know for sure
949 * we already have a full request, we have to re-enable quick-ack
950 * in case we previously disabled it, otherwise we might cause
951 * the client to delay further data.
952 */
953 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200954 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100955 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200956
957 /*************************************************************
958 * OK, that's finished for the headers. We have done what we *
959 * could. Let's switch to the DATA state. *
960 ************************************************************/
961 req->analyse_exp = TICK_ETERNITY;
962 req->analysers &= ~an_bit;
963
964 s->logs.tv_request = now;
965 /* OK let's go on with the BODY now */
966 return 1;
967
968 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200969 txn->req.err_state = txn->req.msg_state;
970 txn->req.msg_state = HTTP_MSG_ERROR;
971 txn->status = 400;
972 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100973 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200974
Olivier Houcharda798bf52019-03-08 18:52:00 +0100975 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100977 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978
979 if (!(s->flags & SF_ERR_MASK))
980 s->flags |= SF_ERR_PRXCOND;
981 if (!(s->flags & SF_FINST_MASK))
982 s->flags |= SF_FINST_R;
983 return 0;
984}
985
986/* This function is an analyser which processes the HTTP tarpit. It always
987 * returns zero, at the beginning because it prevents any other processing
988 * from occurring, and at the end because it terminates the request.
989 */
990int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
991{
992 struct http_txn *txn = s->txn;
993
994 /* This connection is being tarpitted. The CLIENT side has
995 * already set the connect expiration date to the right
996 * timeout. We just have to check that the client is still
997 * there and that the timeout has not expired.
998 */
999 channel_dont_connect(req);
1000 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1001 !tick_is_expired(req->analyse_exp, now_ms))
1002 return 0;
1003
1004 /* We will set the queue timer to the time spent, just for
1005 * logging purposes. We fake a 500 server error, so that the
1006 * attacker will not suspect his connection has been tarpitted.
1007 * It will not cause trouble to the logs because we can exclude
1008 * the tarpitted connections by filtering on the 'PT' status flags.
1009 */
1010 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1011
1012 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001013 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001014
1015 req->analysers &= AN_REQ_FLT_END;
1016 req->analyse_exp = TICK_ETERNITY;
1017
1018 if (!(s->flags & SF_ERR_MASK))
1019 s->flags |= SF_ERR_PRXCOND;
1020 if (!(s->flags & SF_FINST_MASK))
1021 s->flags |= SF_FINST_T;
1022 return 0;
1023}
1024
1025/* This function is an analyser which waits for the HTTP request body. It waits
1026 * for either the buffer to be full, or the full advertised contents to have
1027 * reached the buffer. It must only be called after the standard HTTP request
1028 * processing has occurred, because it expects the request to be parsed and will
1029 * look for the Expect header. It may send a 100-Continue interim response. It
1030 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1031 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1032 * needs to read more data, or 1 once it has completed its analysis.
1033 */
1034int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1035{
1036 struct session *sess = s->sess;
1037 struct http_txn *txn = s->txn;
1038 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001039 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001040
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041
1042 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1043 now_ms, __FUNCTION__,
1044 s,
1045 req,
1046 req->rex, req->wex,
1047 req->flags,
1048 ci_data(req),
1049 req->analysers);
1050
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001051 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001052
Willy Tarreau4236f032019-03-05 10:43:32 +01001053 if (htx->flags & HTX_FL_PARSING_ERROR)
1054 goto return_bad_req;
1055
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
Christopher Faulet4a28a532019-03-01 11:19:40 +01001066 if (htx_handle_expect_hdr(s, htx, msg) == -1)
1067 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 }
1069
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001070 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1073 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Faulet54b5e212019-06-04 10:08:28 +02001075 if (htx_get_tail_type(htx) > HTX_BLK_DATA ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001076 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001077 goto http_end;
1078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1081 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001082 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
1084 if (!(s->flags & SF_ERR_MASK))
1085 s->flags |= SF_ERR_CLITO;
1086 if (!(s->flags & SF_FINST_MASK))
1087 s->flags |= SF_FINST_D;
1088 goto return_err_msg;
1089 }
1090
1091 /* we get here if we need to wait for more data */
1092 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1093 /* Not enough data. We'll re-use the http-request
1094 * timeout here. Ideally, we should set the timeout
1095 * relative to the accept() date. We just set the
1096 * request timeout once at the beginning of the
1097 * request.
1098 */
1099 channel_dont_connect(req);
1100 if (!tick_isset(req->analyse_exp))
1101 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1102 return 0;
1103 }
1104
1105 http_end:
1106 /* The situation will not evolve, so let's give up on the analysis. */
1107 s->logs.tv_request = now; /* update the request timer to reflect full request */
1108 req->analysers &= ~an_bit;
1109 req->analyse_exp = TICK_ETERNITY;
1110 return 1;
1111
1112 return_bad_req: /* let's centralize all bad requests */
1113 txn->req.err_state = txn->req.msg_state;
1114 txn->req.msg_state = HTTP_MSG_ERROR;
1115 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001116 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001117
1118 if (!(s->flags & SF_ERR_MASK))
1119 s->flags |= SF_ERR_PRXCOND;
1120 if (!(s->flags & SF_FINST_MASK))
1121 s->flags |= SF_FINST_R;
1122
1123 return_err_msg:
1124 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001125 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001126 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001127 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001128 return 0;
1129}
1130
1131/* This function is an analyser which forwards request body (including chunk
1132 * sizes if any). It is called as soon as we must forward, even if we forward
1133 * zero byte. The only situation where it must not be called is when we're in
1134 * tunnel mode and we want to forward till the close. It's used both to forward
1135 * remaining data and to resync after end of body. It expects the msg_state to
1136 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1137 * read more data, or 1 once we can go on with next request or end the stream.
1138 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1139 * bytes of pending data + the headers if not already done.
1140 */
1141int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1142{
1143 struct session *sess = s->sess;
1144 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001145 struct http_msg *msg = &txn->req;
1146 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001147 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001148 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001149
1150 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1151 now_ms, __FUNCTION__,
1152 s,
1153 req,
1154 req->rex, req->wex,
1155 req->flags,
1156 ci_data(req),
1157 req->analysers);
1158
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001159 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001160
1161 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1162 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1163 /* Output closed while we were sending data. We must abort and
1164 * wake the other side up.
1165 */
1166 msg->err_state = msg->msg_state;
1167 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001168 htx_end_request(s);
1169 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001170 return 1;
1171 }
1172
1173 /* Note that we don't have to send 100-continue back because we don't
1174 * need the data to complete our job, and it's up to the server to
1175 * decide whether to return 100, 417 or anything else in return of
1176 * an "Expect: 100-continue" header.
1177 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001178 if (msg->msg_state == HTTP_MSG_BODY)
1179 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001180
1181 /* Some post-connect processing might want us to refrain from starting to
1182 * forward data. Currently, the only reason for this is "balance url_param"
1183 * whichs need to parse/process the request after we've enabled forwarding.
1184 */
1185 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1186 if (!(s->res.flags & CF_READ_ATTACHED)) {
1187 channel_auto_connect(req);
1188 req->flags |= CF_WAKE_CONNECT;
1189 channel_dont_close(req); /* don't fail on early shutr */
1190 goto waiting;
1191 }
1192 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1193 }
1194
1195 /* in most states, we should abort in case of early close */
1196 channel_auto_close(req);
1197
1198 if (req->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01001199 if (req->to_forward == CHN_INFINITE_FORWARD) {
1200 if (req->flags & (CF_SHUTR|CF_EOI)) {
1201 msg->msg_state = HTTP_MSG_DONE;
1202 req->to_forward = 0;
1203 goto done;
1204 }
1205 }
1206 else {
1207 /* We can't process the buffer's contents yet */
1208 req->flags |= CF_WAKE_WRITE;
1209 goto missing_data_or_waiting;
1210 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001211 }
1212
Christopher Faulet9768c262018-10-22 09:34:31 +02001213 if (msg->msg_state >= HTTP_MSG_DONE)
1214 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001215 /* Forward input data. We get it by removing all outgoing data not
1216 * forwarded yet from HTX data size. If there are some data filters, we
1217 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001218 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001219 if (HAS_REQ_DATA_FILTERS(s)) {
1220 ret = flt_http_payload(s, msg, htx->data);
1221 if (ret < 0)
1222 goto return_bad_req;
Christopher Faulet421e7692019-06-13 11:16:45 +02001223 c_adv(req, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 }
1225 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02001226 c_adv(req, htx->data - co_data(req));
Christopher Faulet66af0b22019-03-22 14:54:52 +01001227 if (msg->flags & HTTP_MSGF_XFER_LEN)
1228 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001229 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001230
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001231 if (txn->meth == HTTP_METH_CONNECT) {
1232 msg->msg_state = HTTP_MSG_TUNNEL;
1233 goto done;
1234 }
1235
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001236
Christopher Faulet9768c262018-10-22 09:34:31 +02001237 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001238 * in HTTP_MSG_ENDING state. Then if all data was marked to be
1239 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02001240 */
1241 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1242 goto missing_data_or_waiting;
1243
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001244 msg->msg_state = HTTP_MSG_ENDING;
1245 if (htx->data != co_data(req))
1246 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02001247 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001248 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001249
1250 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001251 /* other states, DONE...TUNNEL */
1252 /* we don't want to forward closes on DONE except in tunnel mode. */
1253 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1254 channel_dont_close(req);
1255
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001256 if (HAS_REQ_DATA_FILTERS(s)) {
1257 ret = flt_http_end(s, msg);
1258 if (ret <= 0) {
1259 if (!ret)
1260 goto missing_data_or_waiting;
1261 goto return_bad_req;
1262 }
1263 }
1264
Christopher Fauletf2824e62018-10-01 12:12:37 +02001265 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001266 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001267 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001268 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1269 if (req->flags & CF_SHUTW) {
1270 /* request errors are most likely due to the
1271 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001272 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001273 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 goto return_bad_req;
1275 }
1276 return 1;
1277 }
1278
1279 /* If "option abortonclose" is set on the backend, we want to monitor
1280 * the client's connection and forward any shutdown notification to the
1281 * server, which will decide whether to close or to go on processing the
1282 * request. We only do that in tunnel mode, and not in other modes since
1283 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001284 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001285 channel_auto_read(req);
1286 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1287 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1288 s->si[1].flags |= SI_FL_NOLINGER;
1289 channel_auto_close(req);
1290 }
1291 else if (s->txn->meth == HTTP_METH_POST) {
1292 /* POST requests may require to read extra CRLF sent by broken
1293 * browsers and which could cause an RST to be sent upon close
1294 * on some systems (eg: Linux). */
1295 channel_auto_read(req);
1296 }
1297 return 0;
1298
1299 missing_data_or_waiting:
1300 /* stop waiting for data if the input is closed before the end */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02001301 if (msg->msg_state < HTTP_MSG_ENDING && req->flags & CF_SHUTR)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001302 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001303
1304 waiting:
1305 /* waiting for the last bits to leave the buffer */
1306 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001307 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001308
Christopher Faulet47365272018-10-31 17:40:50 +01001309 if (htx->flags & HTX_FL_PARSING_ERROR)
1310 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001311
Christopher Faulete0768eb2018-10-03 16:38:02 +02001312 /* When TE: chunked is used, we need to get there again to parse remaining
1313 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1314 * And when content-length is used, we never want to let the possible
1315 * shutdown be forwarded to the other side, as the state machine will
1316 * take care of it once the client responds. It's also important to
1317 * prevent TIME_WAITs from accumulating on the backend side, and for
1318 * HTTP/2 where the last frame comes with a shutdown.
1319 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001320 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321 channel_dont_close(req);
1322
1323 /* We know that more data are expected, but we couldn't send more that
1324 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1325 * system knows it must not set a PUSH on this first part. Interactive
1326 * modes are already handled by the stream sock layer. We must not do
1327 * this in content-length mode because it could present the MSG_MORE
1328 * flag with the last block of forwarded data, which would cause an
1329 * additional delay to be observed by the receiver.
1330 */
1331 if (msg->flags & HTTP_MSGF_TE_CHNK)
1332 req->flags |= CF_EXPECT_MORE;
1333
1334 return 0;
1335
Christopher Faulet93e02d82019-03-08 14:18:50 +01001336 return_cli_abort:
1337 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1338 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1339 if (objt_server(s->target))
1340 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1341 if (!(s->flags & SF_ERR_MASK))
1342 s->flags |= SF_ERR_CLICL;
1343 status = 400;
1344 goto return_error;
1345
1346 return_srv_abort:
1347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1348 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1349 if (objt_server(s->target))
1350 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1351 if (!(s->flags & SF_ERR_MASK))
1352 s->flags |= SF_ERR_SRVCL;
1353 status = 502;
1354 goto return_error;
1355
1356 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001357 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001359 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001361 s->flags |= SF_ERR_CLICL;
1362 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363
Christopher Faulet93e02d82019-03-08 14:18:50 +01001364 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 txn->req.err_state = txn->req.msg_state;
1366 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001367 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001369 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001371 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001372 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 }
1374 req->analysers &= AN_REQ_FLT_END;
1375 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 +01001376 if (!(s->flags & SF_FINST_MASK))
1377 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001378 return 0;
1379}
1380
Olivier Houcharda254a372019-04-05 15:30:12 +02001381/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1382/* Returns 0 if we can attempt to retry, -1 otherwise */
1383static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1384{
1385 struct channel *req, *res;
1386 int co_data;
1387
1388 si->conn_retries--;
1389 if (si->conn_retries < 0)
1390 return -1;
1391
Willy Tarreau223995e2019-05-04 10:38:31 +02001392 if (objt_server(s->target))
1393 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1394 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1395
Olivier Houcharda254a372019-04-05 15:30:12 +02001396 req = &s->req;
1397 res = &s->res;
1398 /* Remove any write error from the request, and read error from the response */
1399 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1400 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1401 res->analysers = 0;
1402 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1403 si->state = SI_ST_REQ;
1404 si->exp = TICK_ETERNITY;
1405 res->rex = TICK_ETERNITY;
1406 res->to_forward = 0;
1407 res->analyse_exp = TICK_ETERNITY;
1408 res->total = 0;
1409 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1410 si_release_endpoint(&s->si[1]);
1411 b_free(&req->buf);
1412 /* Swap the L7 buffer with the channel buffer */
1413 /* We know we stored the co_data as b_data, so get it there */
1414 co_data = b_data(&si->l7_buffer);
1415 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1416 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1417
1418 co_set_data(req, co_data);
1419 b_reset(&res->buf);
1420 co_set_data(res, 0);
1421 return 0;
1422}
1423
Christopher Faulete0768eb2018-10-03 16:38:02 +02001424/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1425 * processing can continue on next analysers, or zero if it either needs more
1426 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1427 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1428 * when it has nothing left to do, and may remove any analyser when it wants to
1429 * abort.
1430 */
1431int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1432{
Christopher Faulet9768c262018-10-22 09:34:31 +02001433 /*
1434 * We will analyze a complete HTTP response to check the its syntax.
1435 *
1436 * Once the start line and all headers are received, we may perform a
1437 * capture of the error (if any), and we will set a few fields. We also
1438 * logging and finally headers capture.
1439 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001440 struct session *sess = s->sess;
1441 struct http_txn *txn = s->txn;
1442 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001443 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001444 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001445 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001446 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001447 int n;
1448
1449 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1450 now_ms, __FUNCTION__,
1451 s,
1452 rep,
1453 rep->rex, rep->wex,
1454 rep->flags,
1455 ci_data(rep),
1456 rep->analysers);
1457
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001458 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001459
Willy Tarreau4236f032019-03-05 10:43:32 +01001460 /* Parsing errors are caught here */
1461 if (htx->flags & HTX_FL_PARSING_ERROR)
1462 goto return_bad_res;
1463
Christopher Faulete0768eb2018-10-03 16:38:02 +02001464 /*
1465 * Now we quickly check if we have found a full valid response.
1466 * If not so, we check the FD and buffer states before leaving.
1467 * A full response is indicated by the fact that we have seen
1468 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1469 * responses are checked first.
1470 *
1471 * Depending on whether the client is still there or not, we
1472 * may send an error response back or not. Note that normally
1473 * we should only check for HTTP status there, and check I/O
1474 * errors somewhere else.
1475 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001476 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001477 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001478 /* 1: have we encountered a read error ? */
1479 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001480 struct connection *conn = NULL;
1481
Olivier Houchard865d8392019-05-03 22:46:27 +02001482 if (objt_cs(s->si[1].end))
1483 conn = objt_cs(s->si[1].end)->conn;
1484
1485 if (si_b->flags & SI_FL_L7_RETRY &&
1486 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001487 /* If we arrive here, then CF_READ_ERROR was
1488 * set by si_cs_recv() because we matched a
1489 * status, overwise it would have removed
1490 * the SI_FL_L7_RETRY flag, so it's ok not
1491 * to check s->be->retry_type.
1492 */
1493 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1494 return 0;
1495 }
1496
Olivier Houchard6db16992019-05-17 15:40:49 +02001497 if (txn->flags & TX_NOT_FIRST)
1498 goto abort_keep_alive;
1499
Olivier Houcharda798bf52019-03-08 18:52:00 +01001500 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001502 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001503 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001504 }
1505
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 rep->analysers &= AN_RES_FLT_END;
1507 txn->status = 502;
1508
1509 /* Check to see if the server refused the early data.
1510 * If so, just send a 425
1511 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001512 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1513 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001514 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001515 do_l7_retry(s, si_b) == 0)
1516 return 0;
1517 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518 }
1519
1520 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001521 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522
1523 if (!(s->flags & SF_ERR_MASK))
1524 s->flags |= SF_ERR_SRVCL;
1525 if (!(s->flags & SF_FINST_MASK))
1526 s->flags |= SF_FINST_H;
1527 return 0;
1528 }
1529
Christopher Faulet9768c262018-10-22 09:34:31 +02001530 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001532 if ((si_b->flags & SI_FL_L7_RETRY) &&
1533 (s->be->retry_type & PR_RE_TIMEOUT)) {
1534 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1535 return 0;
1536 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001537 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001539 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001540 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 }
1542
Christopher Faulete0768eb2018-10-03 16:38:02 +02001543 rep->analysers &= AN_RES_FLT_END;
1544 txn->status = 504;
1545 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001546 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547
1548 if (!(s->flags & SF_ERR_MASK))
1549 s->flags |= SF_ERR_SRVTO;
1550 if (!(s->flags & SF_FINST_MASK))
1551 s->flags |= SF_FINST_H;
1552 return 0;
1553 }
1554
Christopher Faulet9768c262018-10-22 09:34:31 +02001555 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1558 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001560 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561
1562 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565
1566 if (!(s->flags & SF_ERR_MASK))
1567 s->flags |= SF_ERR_CLICL;
1568 if (!(s->flags & SF_FINST_MASK))
1569 s->flags |= SF_FINST_H;
1570
1571 /* process_stream() will take care of the error */
1572 return 0;
1573 }
1574
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001577 if ((si_b->flags & SI_FL_L7_RETRY) &&
1578 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1579 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1580 return 0;
1581 }
1582
Olivier Houchard6db16992019-05-17 15:40:49 +02001583 if (txn->flags & TX_NOT_FIRST)
1584 goto abort_keep_alive;
1585
Olivier Houcharda798bf52019-03-08 18:52:00 +01001586 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001588 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001589 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001590 }
1591
Christopher Faulete0768eb2018-10-03 16:38:02 +02001592 rep->analysers &= AN_RES_FLT_END;
1593 txn->status = 502;
1594 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001595 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596
1597 if (!(s->flags & SF_ERR_MASK))
1598 s->flags |= SF_ERR_SRVCL;
1599 if (!(s->flags & SF_FINST_MASK))
1600 s->flags |= SF_FINST_H;
1601 return 0;
1602 }
1603
Christopher Faulet9768c262018-10-22 09:34:31 +02001604 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001605 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001606 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 goto abort_keep_alive;
1608
Olivier Houcharda798bf52019-03-08 18:52:00 +01001609 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001610 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001611
1612 if (!(s->flags & SF_ERR_MASK))
1613 s->flags |= SF_ERR_CLICL;
1614 if (!(s->flags & SF_FINST_MASK))
1615 s->flags |= SF_FINST_H;
1616
1617 /* process_stream() will take care of the error */
1618 return 0;
1619 }
1620
1621 channel_dont_close(rep);
1622 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1623 return 0;
1624 }
1625
1626 /* More interesting part now : we know that we have a complete
1627 * response which at least looks like HTTP. We have an indicator
1628 * of each header's length, so we can parse them quickly.
1629 */
1630
Christopher Faulet9768c262018-10-22 09:34:31 +02001631 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001632 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001633 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634
Christopher Faulet9768c262018-10-22 09:34:31 +02001635 /* 0: we might have to print this header in debug mode */
1636 if (unlikely((global.mode & MODE_DEBUG) &&
1637 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1638 int32_t pos;
1639
Christopher Faulet03599112018-11-27 11:21:21 +01001640 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001641
Christopher Fauleta3f15502019-05-13 15:27:23 +02001642 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001643 struct htx_blk *blk = htx_get_blk(htx, pos);
1644 enum htx_blk_type type = htx_get_blk_type(blk);
1645
1646 if (type == HTX_BLK_EOH)
1647 break;
1648 if (type != HTX_BLK_HDR)
1649 continue;
1650
1651 htx_debug_hdr("srvhdr", s,
1652 htx_get_blk_name(htx, blk),
1653 htx_get_blk_value(htx, blk));
1654 }
1655 }
1656
Christopher Faulet03599112018-11-27 11:21:21 +01001657 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001658 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001659 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001660 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001661 if (sl->flags & HTX_SL_F_XFER_LEN) {
1662 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001663 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001664 if (sl->flags & HTX_SL_F_BODYLESS)
1665 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001666 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001667
1668 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001669 if (n < 1 || n > 5)
1670 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001671
Christopher Faulete0768eb2018-10-03 16:38:02 +02001672 /* when the client triggers a 4xx from the server, it's most often due
1673 * to a missing object or permission. These events should be tracked
1674 * because if they happen often, it may indicate a brute force or a
1675 * vulnerability scan.
1676 */
1677 if (n == 4)
1678 stream_inc_http_err_ctr(s);
1679
1680 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001681 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001682
Christopher Faulete0768eb2018-10-03 16:38:02 +02001683 /* Adjust server's health based on status code. Note: status codes 501
1684 * and 505 are triggered on demand by client request, so we must not
1685 * count them as server failures.
1686 */
1687 if (objt_server(s->target)) {
1688 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001689 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001690 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001691 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001692 }
1693
1694 /*
1695 * We may be facing a 100-continue response, or any other informational
1696 * 1xx response which is non-final, in which case this is not the right
1697 * response, and we're waiting for the next one. Let's allow this response
1698 * to go to the client and wait for the next one. There's an exception for
1699 * 101 which is used later in the code to switch protocols.
1700 */
1701 if (txn->status < 200 &&
1702 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001703 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet421e7692019-06-13 11:16:45 +02001704 htx->first = channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705 msg->msg_state = HTTP_MSG_RPBEFORE;
1706 txn->status = 0;
1707 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001708 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001709 }
1710
1711 /*
1712 * 2: check for cacheability.
1713 */
1714
1715 switch (txn->status) {
1716 case 200:
1717 case 203:
1718 case 204:
1719 case 206:
1720 case 300:
1721 case 301:
1722 case 404:
1723 case 405:
1724 case 410:
1725 case 414:
1726 case 501:
1727 break;
1728 default:
1729 /* RFC7231#6.1:
1730 * Responses with status codes that are defined as
1731 * cacheable by default (e.g., 200, 203, 204, 206,
1732 * 300, 301, 404, 405, 410, 414, and 501 in this
1733 * specification) can be reused by a cache with
1734 * heuristic expiration unless otherwise indicated
1735 * by the method definition or explicit cache
1736 * controls [RFC7234]; all other status codes are
1737 * not cacheable by default.
1738 */
1739 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1740 break;
1741 }
1742
1743 /*
1744 * 3: we may need to capture headers
1745 */
1746 s->logs.logwait &= ~LW_RESP;
1747 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001748 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001749
Christopher Faulet9768c262018-10-22 09:34:31 +02001750 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001751 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1752 txn->status == 101)) {
1753 /* Either we've established an explicit tunnel, or we're
1754 * switching the protocol. In both cases, we're very unlikely
1755 * to understand the next protocols. We have to switch to tunnel
1756 * mode, so that we transfer the request and responses then let
1757 * this protocol pass unmodified. When we later implement specific
1758 * parsers for such protocols, we'll want to check the Upgrade
1759 * header which contains information about that protocol for
1760 * responses with status 101 (eg: see RFC2817 about TLS).
1761 */
1762 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001763 }
1764
Christopher Faulet61608322018-11-23 16:23:45 +01001765 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1766 * 407 (Proxy-Authenticate) responses and set the connection to private
1767 */
1768 srv_conn = cs_conn(objt_cs(s->si[1].end));
1769 if (srv_conn) {
1770 struct ist hdr;
1771 struct http_hdr_ctx ctx;
1772
1773 if (txn->status == 401)
1774 hdr = ist("WWW-Authenticate");
1775 else if (txn->status == 407)
1776 hdr = ist("Proxy-Authenticate");
1777 else
1778 goto end;
1779
1780 ctx.blk = NULL;
1781 while (http_find_header(htx, hdr, &ctx, 0)) {
1782 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
Olivier Houchard250031e2019-05-29 15:01:50 +02001783 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4))) {
1784 sess->flags |= SESS_FL_PREFER_LAST;
Christopher Faulet61608322018-11-23 16:23:45 +01001785 srv_conn->flags |= CO_FL_PRIVATE;
Olivier Houchard250031e2019-05-29 15:01:50 +02001786 }
Christopher Faulet61608322018-11-23 16:23:45 +01001787 }
1788 }
1789
1790 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791 /* we want to have the response time before we start processing it */
1792 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1793
1794 /* end of job, return OK */
1795 rep->analysers &= ~an_bit;
1796 rep->analyse_exp = TICK_ETERNITY;
1797 channel_auto_close(rep);
1798 return 1;
1799
Christopher Faulet47365272018-10-31 17:40:50 +01001800 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001801 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001802 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001803 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001804 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001805 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001806 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001807 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001808 do_l7_retry(s, si_b) == 0)
1809 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001810 txn->status = 502;
1811 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001812 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001813 rep->analysers &= AN_RES_FLT_END;
1814
1815 if (!(s->flags & SF_ERR_MASK))
1816 s->flags |= SF_ERR_PRXCOND;
1817 if (!(s->flags & SF_FINST_MASK))
1818 s->flags |= SF_FINST_H;
1819 return 0;
1820
Christopher Faulete0768eb2018-10-03 16:38:02 +02001821 abort_keep_alive:
1822 /* A keep-alive request to the server failed on a network error.
1823 * The client is required to retry. We need to close without returning
1824 * any other information so that the client retries.
1825 */
1826 txn->status = 0;
1827 rep->analysers &= AN_RES_FLT_END;
1828 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001829 s->logs.logwait = 0;
1830 s->logs.level = 0;
1831 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001832 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001833 return 0;
1834}
1835
1836/* This function performs all the processing enabled for the current response.
1837 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1838 * and updates s->res.analysers. It might make sense to explode it into several
1839 * other functions. It works like process_request (see indications above).
1840 */
1841int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1842{
1843 struct session *sess = s->sess;
1844 struct http_txn *txn = s->txn;
1845 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001846 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001847 struct proxy *cur_proxy;
1848 struct cond_wordlist *wl;
1849 enum rule_result ret = HTTP_RULE_RES_CONT;
1850
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001851 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1852 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001853
Christopher Faulete0768eb2018-10-03 16:38:02 +02001854 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1855 now_ms, __FUNCTION__,
1856 s,
1857 rep,
1858 rep->rex, rep->wex,
1859 rep->flags,
1860 ci_data(rep),
1861 rep->analysers);
1862
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001863 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001864
1865 /* The stats applet needs to adjust the Connection header but we don't
1866 * apply any filter there.
1867 */
1868 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1869 rep->analysers &= ~an_bit;
1870 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001871 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001872 }
1873
1874 /*
1875 * We will have to evaluate the filters.
1876 * As opposed to version 1.2, now they will be evaluated in the
1877 * filters order and not in the header order. This means that
1878 * each filter has to be validated among all headers.
1879 *
1880 * Filters are tried with ->be first, then with ->fe if it is
1881 * different from ->be.
1882 *
1883 * Maybe we are in resume condiion. In this case I choose the
1884 * "struct proxy" which contains the rule list matching the resume
1885 * pointer. If none of theses "struct proxy" match, I initialise
1886 * the process with the first one.
1887 *
1888 * In fact, I check only correspondance betwwen the current list
1889 * pointer and the ->fe rule list. If it doesn't match, I initialize
1890 * the loop with the ->be.
1891 */
1892 if (s->current_rule_list == &sess->fe->http_res_rules)
1893 cur_proxy = sess->fe;
1894 else
1895 cur_proxy = s->be;
1896 while (1) {
1897 struct proxy *rule_set = cur_proxy;
1898
1899 /* evaluate http-response rules */
1900 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001901 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001902
1903 if (ret == HTTP_RULE_RES_BADREQ)
1904 goto return_srv_prx_502;
1905
1906 if (ret == HTTP_RULE_RES_DONE) {
1907 rep->analysers &= ~an_bit;
1908 rep->analyse_exp = TICK_ETERNITY;
1909 return 1;
1910 }
1911 }
1912
1913 /* we need to be called again. */
1914 if (ret == HTTP_RULE_RES_YIELD) {
1915 channel_dont_close(rep);
1916 return 0;
1917 }
1918
1919 /* try headers filters */
1920 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001921 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1922 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001923 }
1924
1925 /* has the response been denied ? */
1926 if (txn->flags & TX_SVDENY) {
1927 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001928 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001929
Olivier Houcharda798bf52019-03-08 18:52:00 +01001930 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1931 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001932 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001933 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001934 goto return_srv_prx_502;
1935 }
1936
1937 /* add response headers from the rule sets in the same order */
1938 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001939 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001940 if (txn->status < 200 && txn->status != 101)
1941 break;
1942 if (wl->cond) {
1943 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1944 ret = acl_pass(ret);
1945 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1946 ret = !ret;
1947 if (!ret)
1948 continue;
1949 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001950
1951 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1952 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001953 goto return_bad_resp;
1954 }
1955
1956 /* check whether we're already working on the frontend */
1957 if (cur_proxy == sess->fe)
1958 break;
1959 cur_proxy = sess->fe;
1960 }
1961
1962 /* After this point, this anayzer can't return yield, so we can
1963 * remove the bit corresponding to this analyzer from the list.
1964 *
1965 * Note that the intermediate returns and goto found previously
1966 * reset the analyzers.
1967 */
1968 rep->analysers &= ~an_bit;
1969 rep->analyse_exp = TICK_ETERNITY;
1970
1971 /* OK that's all we can do for 1xx responses */
1972 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001973 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001974
1975 /*
1976 * Now check for a server cookie.
1977 */
1978 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001979 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001980
1981 /*
1982 * Check for cache-control or pragma headers if required.
1983 */
1984 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1985 check_response_for_cacheability(s, rep);
1986
1987 /*
1988 * Add server cookie in the response if needed
1989 */
1990 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1991 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1992 (!(s->flags & SF_DIRECT) ||
1993 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1994 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1995 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1996 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1997 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1998 !(s->flags & SF_IGNORE_PRST)) {
1999 /* the server is known, it's not the one the client requested, or the
2000 * cookie's last seen date needs to be refreshed. We have to
2001 * insert a set-cookie here, except if we want to insert only on POST
2002 * requests and this one isn't. Note that servers which don't have cookies
2003 * (eg: some backup servers) will return a full cookie removal request.
2004 */
2005 if (!objt_server(s->target)->cookie) {
2006 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002007 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002008 s->be->cookie_name);
2009 }
2010 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002011 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002012
2013 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2014 /* emit last_date, which is mandatory */
2015 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2016 s30tob64((date.tv_sec+3) >> 2,
2017 trash.area + trash.data);
2018 trash.data += 5;
2019
2020 if (s->be->cookie_maxlife) {
2021 /* emit first_date, which is either the original one or
2022 * the current date.
2023 */
2024 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2025 s30tob64(txn->cookie_first_date ?
2026 txn->cookie_first_date >> 2 :
2027 (date.tv_sec+3) >> 2,
2028 trash.area + trash.data);
2029 trash.data += 5;
2030 }
2031 }
2032 chunk_appendf(&trash, "; path=/");
2033 }
2034
2035 if (s->be->cookie_domain)
2036 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2037
2038 if (s->be->ck_opts & PR_CK_HTTPONLY)
2039 chunk_appendf(&trash, "; HttpOnly");
2040
2041 if (s->be->ck_opts & PR_CK_SECURE)
2042 chunk_appendf(&trash, "; Secure");
2043
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002044 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002045 goto return_bad_resp;
2046
2047 txn->flags &= ~TX_SCK_MASK;
2048 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2049 /* the server did not change, only the date was updated */
2050 txn->flags |= TX_SCK_UPDATED;
2051 else
2052 txn->flags |= TX_SCK_INSERTED;
2053
2054 /* Here, we will tell an eventual cache on the client side that we don't
2055 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2056 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2057 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2058 */
2059 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2060
2061 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2062
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002063 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002064 goto return_bad_resp;
2065 }
2066 }
2067
2068 /*
2069 * Check if result will be cacheable with a cookie.
2070 * We'll block the response if security checks have caught
2071 * nasty things such as a cacheable cookie.
2072 */
2073 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2074 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2075 (s->be->options & PR_O_CHK_CACHE)) {
2076 /* we're in presence of a cacheable response containing
2077 * a set-cookie header. We'll block it as requested by
2078 * the 'checkcache' option, and send an alert.
2079 */
2080 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002081 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082
Olivier Houcharda798bf52019-03-08 18:52:00 +01002083 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2084 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002085 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002086 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002087
2088 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2089 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2090 send_log(s->be, LOG_ALERT,
2091 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2092 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2093 goto return_srv_prx_502;
2094 }
2095
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002096 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002097 /* Always enter in the body analyzer */
2098 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2099 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2100
2101 /* if the user wants to log as soon as possible, without counting
2102 * bytes from the server, then this is the right moment. We have
2103 * to temporarily assign bytes_out to log what we currently have.
2104 */
2105 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2106 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002107 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002108 s->do_log(s);
2109 s->logs.bytes_out = 0;
2110 }
2111 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112
2113 return_bad_resp:
2114 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002115 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002116 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002117 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002118 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002119
2120 return_srv_prx_502:
2121 rep->analysers &= AN_RES_FLT_END;
2122 txn->status = 502;
2123 s->logs.t_data = -1; /* was not a valid response */
2124 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002125 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002126 if (!(s->flags & SF_ERR_MASK))
2127 s->flags |= SF_ERR_PRXCOND;
2128 if (!(s->flags & SF_FINST_MASK))
2129 s->flags |= SF_FINST_H;
2130 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002131}
2132
2133/* This function is an analyser which forwards response body (including chunk
2134 * sizes if any). It is called as soon as we must forward, even if we forward
2135 * zero byte. The only situation where it must not be called is when we're in
2136 * tunnel mode and we want to forward till the close. It's used both to forward
2137 * remaining data and to resync after end of body. It expects the msg_state to
2138 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2139 * read more data, or 1 once we can go on with next request or end the stream.
2140 *
2141 * It is capable of compressing response data both in content-length mode and
2142 * in chunked mode. The state machines follows different flows depending on
2143 * whether content-length and chunked modes are used, since there are no
2144 * trailers in content-length :
2145 *
2146 * chk-mode cl-mode
2147 * ,----- BODY -----.
2148 * / \
2149 * V size > 0 V chk-mode
2150 * .--> SIZE -------------> DATA -------------> CRLF
2151 * | | size == 0 | last byte |
2152 * | v final crlf v inspected |
2153 * | TRAILERS -----------> DONE |
2154 * | |
2155 * `----------------------------------------------'
2156 *
2157 * Compression only happens in the DATA state, and must be flushed in final
2158 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2159 * is performed at once on final states for all bytes parsed, or when leaving
2160 * on missing data.
2161 */
2162int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2163{
2164 struct session *sess = s->sess;
2165 struct http_txn *txn = s->txn;
2166 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002167 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002169
2170 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2171 now_ms, __FUNCTION__,
2172 s,
2173 res,
2174 res->rex, res->wex,
2175 res->flags,
2176 ci_data(res),
2177 res->analysers);
2178
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002179 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002180
2181 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002182 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002183 /* Output closed while we were sending data. We must abort and
2184 * wake the other side up.
2185 */
2186 msg->err_state = msg->msg_state;
2187 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002188 htx_end_response(s);
2189 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190 return 1;
2191 }
2192
Christopher Faulet9768c262018-10-22 09:34:31 +02002193 if (msg->msg_state == HTTP_MSG_BODY)
2194 msg->msg_state = HTTP_MSG_DATA;
2195
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 /* in most states, we should abort in case of early close */
2197 channel_auto_close(res);
2198
Christopher Faulete0768eb2018-10-03 16:38:02 +02002199 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002200 if (res->to_forward == CHN_INFINITE_FORWARD) {
2201 if (res->flags & (CF_SHUTR|CF_EOI)) {
2202 msg->msg_state = HTTP_MSG_DONE;
2203 res->to_forward = 0;
2204 goto done;
2205 }
2206 }
2207 else {
2208 /* We can't process the buffer's contents yet */
2209 res->flags |= CF_WAKE_WRITE;
2210 goto missing_data_or_waiting;
2211 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 }
2213
Christopher Faulet9768c262018-10-22 09:34:31 +02002214 if (msg->msg_state >= HTTP_MSG_DONE)
2215 goto done;
2216
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002217 /* Forward input data. We get it by removing all outgoing data not
2218 * forwarded yet from HTX data size. If there are some data filters, we
2219 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002220 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002221 if (HAS_RSP_DATA_FILTERS(s)) {
2222 ret = flt_http_payload(s, msg, htx->data);
2223 if (ret < 0)
2224 goto return_bad_res;
Christopher Faulet421e7692019-06-13 11:16:45 +02002225 c_adv(res, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002226 }
2227 else {
Christopher Faulet421e7692019-06-13 11:16:45 +02002228 c_adv(res, htx->data - co_data(res));
Christopher Faulet66af0b22019-03-22 14:54:52 +01002229 if (msg->flags & HTTP_MSGF_XFER_LEN)
2230 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002231 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002232
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002233 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2234 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2235 msg->msg_state = HTTP_MSG_TUNNEL;
2236 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 }
2238
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 /* Check if the end-of-message is reached and if so, switch the message
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002240 * in HTTP_MSG_ENDING state. Then if all data was marked to be
2241 * forwarded, set the state to HTTP_MSG_DONE.
Christopher Faulet9768c262018-10-22 09:34:31 +02002242 */
2243 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2244 goto missing_data_or_waiting;
2245
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002246 msg->msg_state = HTTP_MSG_ENDING;
2247 if (htx->data != co_data(res))
2248 goto missing_data_or_waiting;
Christopher Faulet9768c262018-10-22 09:34:31 +02002249 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002250 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002251
2252 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002254 channel_dont_close(res);
2255
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002256 if (HAS_RSP_DATA_FILTERS(s)) {
2257 ret = flt_http_end(s, msg);
2258 if (ret <= 0) {
2259 if (!ret)
2260 goto missing_data_or_waiting;
2261 goto return_bad_res;
2262 }
2263 }
2264
Christopher Fauletf2824e62018-10-01 12:12:37 +02002265 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002267 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2269 if (res->flags & CF_SHUTW) {
2270 /* response errors are most likely due to the
2271 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002272 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002273 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274 goto return_bad_res;
2275 }
2276 return 1;
2277 }
2278 return 0;
2279
2280 missing_data_or_waiting:
2281 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002282 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283
Christopher Faulet47365272018-10-31 17:40:50 +01002284 if (htx->flags & HTX_FL_PARSING_ERROR)
2285 goto return_bad_res;
2286
Christopher Faulete0768eb2018-10-03 16:38:02 +02002287 /* stop waiting for data if the input is closed before the end. If the
2288 * client side was already closed, it means that the client has aborted,
2289 * so we don't want to count this as a server abort. Otherwise it's a
2290 * server abort.
2291 */
Christopher Fauletd20fdb02019-06-13 16:43:22 +02002292 if (msg->msg_state < HTTP_MSG_ENDING && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002294 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002296 if (htx_is_empty(htx))
2297 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 }
2299
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 /* When TE: chunked is used, we need to get there again to parse
2301 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002302 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2303 * are filters registered on the stream, we don't want to forward a
2304 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002305 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002306 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 channel_dont_close(res);
2308
2309 /* We know that more data are expected, but we couldn't send more that
2310 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2311 * system knows it must not set a PUSH on this first part. Interactive
2312 * modes are already handled by the stream sock layer. We must not do
2313 * this in content-length mode because it could present the MSG_MORE
2314 * flag with the last block of forwarded data, which would cause an
2315 * additional delay to be observed by the receiver.
2316 */
2317 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2318 res->flags |= CF_EXPECT_MORE;
2319
2320 /* the stream handler will take care of timeouts and errors */
2321 return 0;
2322
Christopher Faulet93e02d82019-03-08 14:18:50 +01002323 return_srv_abort:
2324 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2325 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002326 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002327 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2328 if (!(s->flags & SF_ERR_MASK))
2329 s->flags |= SF_ERR_SRVCL;
2330 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331
Christopher Faulet93e02d82019-03-08 14:18:50 +01002332 return_cli_abort:
2333 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2334 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002335 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002336 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2337 if (!(s->flags & SF_ERR_MASK))
2338 s->flags |= SF_ERR_CLICL;
2339 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002340
Christopher Faulet93e02d82019-03-08 14:18:50 +01002341 return_bad_res:
2342 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2343 if (objt_server(s->target)) {
2344 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2345 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2346 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002347 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002348 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002349
Christopher Faulet93e02d82019-03-08 14:18:50 +01002350 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002351 txn->rsp.err_state = txn->rsp.msg_state;
2352 txn->rsp.msg_state = HTTP_MSG_ERROR;
2353 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002354 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002355 res->analysers &= AN_RES_FLT_END;
2356 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 +02002357 if (!(s->flags & SF_FINST_MASK))
2358 s->flags |= SF_FINST_D;
2359 return 0;
2360}
2361
Christopher Fauletf2824e62018-10-01 12:12:37 +02002362/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002363 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002364 * as too large a request to build a valid response.
2365 */
2366int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2367{
Christopher Faulet99daf282018-11-28 22:58:13 +01002368 struct channel *req = &s->req;
2369 struct channel *res = &s->res;
2370 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002371 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 struct ist status, reason, location;
2374 unsigned int flags;
2375 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002376 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002377
2378 chunk = alloc_trash_chunk();
2379 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002381
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 /*
2383 * Create the location
2384 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002385 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002387 case REDIRECT_TYPE_SCHEME: {
2388 struct http_hdr_ctx ctx;
2389 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 host = ist("");
2392 ctx.blk = NULL;
2393 if (http_find_header(htx, ist("Host"), &ctx, 0))
2394 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395
Christopher Faulet297fbb42019-05-13 14:41:27 +02002396 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002397 path = http_get_path(htx_sl_req_uri(sl));
2398 /* build message using path */
2399 if (path.ptr) {
2400 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2401 int qs = 0;
2402 while (qs < path.len) {
2403 if (*(path.ptr + qs) == '?') {
2404 path.len = qs;
2405 break;
2406 }
2407 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002408 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409 }
2410 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002411 else
2412 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002413
Christopher Faulet99daf282018-11-28 22:58:13 +01002414 if (rule->rdr_str) { /* this is an old "redirect" rule */
2415 /* add scheme */
2416 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2417 goto fail;
2418 }
2419 else {
2420 /* add scheme with executing log format */
2421 chunk->data += build_logline(s, chunk->area + chunk->data,
2422 chunk->size - chunk->data,
2423 &rule->rdr_fmt);
2424 }
2425 /* add "://" + host + path */
2426 if (!chunk_memcat(chunk, "://", 3) ||
2427 !chunk_memcat(chunk, host.ptr, host.len) ||
2428 !chunk_memcat(chunk, path.ptr, path.len))
2429 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430
Christopher Faulet99daf282018-11-28 22:58:13 +01002431 /* append a slash at the end of the location if needed and missing */
2432 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2433 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2434 if (chunk->data + 1 >= chunk->size)
2435 goto fail;
2436 chunk->area[chunk->data++] = '/';
2437 }
2438 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002440
Christopher Faulet99daf282018-11-28 22:58:13 +01002441 case REDIRECT_TYPE_PREFIX: {
2442 struct ist path;
2443
Christopher Faulet297fbb42019-05-13 14:41:27 +02002444 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 path = http_get_path(htx_sl_req_uri(sl));
2446 /* build message using path */
2447 if (path.ptr) {
2448 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2449 int qs = 0;
2450 while (qs < path.len) {
2451 if (*(path.ptr + qs) == '?') {
2452 path.len = qs;
2453 break;
2454 }
2455 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002457 }
2458 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002459 else
2460 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002461
Christopher Faulet99daf282018-11-28 22:58:13 +01002462 if (rule->rdr_str) { /* this is an old "redirect" rule */
2463 /* add prefix. Note that if prefix == "/", we don't want to
2464 * add anything, otherwise it makes it hard for the user to
2465 * configure a self-redirection.
2466 */
2467 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2468 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2469 goto fail;
2470 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002472 else {
2473 /* add prefix with executing log format */
2474 chunk->data += build_logline(s, chunk->area + chunk->data,
2475 chunk->size - chunk->data,
2476 &rule->rdr_fmt);
2477 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002478
Christopher Faulet99daf282018-11-28 22:58:13 +01002479 /* add path */
2480 if (!chunk_memcat(chunk, path.ptr, path.len))
2481 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002482
Christopher Faulet99daf282018-11-28 22:58:13 +01002483 /* append a slash at the end of the location if needed and missing */
2484 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2485 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2486 if (chunk->data + 1 >= chunk->size)
2487 goto fail;
2488 chunk->area[chunk->data++] = '/';
2489 }
2490 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002491 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002492 case REDIRECT_TYPE_LOCATION:
2493 default:
2494 if (rule->rdr_str) { /* this is an old "redirect" rule */
2495 /* add location */
2496 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2497 goto fail;
2498 }
2499 else {
2500 /* add location with executing log format */
2501 chunk->data += build_logline(s, chunk->area + chunk->data,
2502 chunk->size - chunk->data,
2503 &rule->rdr_fmt);
2504 }
2505 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002506 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002507 location = ist2(chunk->area, chunk->data);
2508
2509 /*
2510 * Create the 30x response
2511 */
2512 switch (rule->code) {
2513 case 308:
2514 status = ist("308");
2515 reason = ist("Permanent Redirect");
2516 break;
2517 case 307:
2518 status = ist("307");
2519 reason = ist("Temporary Redirect");
2520 break;
2521 case 303:
2522 status = ist("303");
2523 reason = ist("See Other");
2524 break;
2525 case 301:
2526 status = ist("301");
2527 reason = ist("Moved Permanently");
2528 break;
2529 case 302:
2530 default:
2531 status = ist("302");
2532 reason = ist("Found");
2533 break;
2534 }
2535
Christopher Faulet08e66462019-05-23 16:44:59 +02002536 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2537 close = 1;
2538
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 htx = htx_from_buf(&res->buf);
2540 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2541 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2542 if (!sl)
2543 goto fail;
2544 sl->info.res.status = rule->code;
2545 s->txn->status = rule->code;
2546
Christopher Faulet08e66462019-05-23 16:44:59 +02002547 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2548 goto fail;
2549
2550 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002551 !htx_add_header(htx, ist("Location"), location))
2552 goto fail;
2553
2554 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2555 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2556 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002557 }
2558
2559 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002560 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2561 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002562 }
2563
Christopher Faulet99daf282018-11-28 22:58:13 +01002564 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2565 goto fail;
2566
Christopher Fauletf2824e62018-10-01 12:12:37 +02002567 /* let's log the request time */
2568 s->logs.tv_request = now;
2569
Christopher Faulet99daf282018-11-28 22:58:13 +01002570 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002571 c_adv(res, data);
2572 res->total += data;
2573
2574 channel_auto_read(req);
2575 channel_abort(req);
2576 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002577 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002578
2579 res->wex = tick_add_ifset(now_ms, res->wto);
2580 channel_auto_read(res);
2581 channel_auto_close(res);
2582 channel_shutr_now(res);
2583
2584 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002585
2586 if (!(s->flags & SF_ERR_MASK))
2587 s->flags |= SF_ERR_LOCAL;
2588 if (!(s->flags & SF_FINST_MASK))
2589 s->flags |= SF_FINST_R;
2590
Christopher Faulet99daf282018-11-28 22:58:13 +01002591 free_trash_chunk(chunk);
2592 return 1;
2593
2594 fail:
2595 /* If an error occurred, remove the incomplete HTTP response from the
2596 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002597 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002598 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002599 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002600}
2601
Christopher Faulet72333522018-10-24 11:25:02 +02002602int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2603 struct ist name, const char *str, struct my_regex *re, int action)
2604{
2605 struct http_hdr_ctx ctx;
2606 struct buffer *output = get_trash_chunk();
2607
2608 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2609 ctx.blk = NULL;
2610 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2611 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2612 continue;
2613
2614 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2615 if (output->data == -1)
2616 return -1;
2617 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2618 return -1;
2619 }
2620 return 0;
2621}
2622
2623static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2624 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2625{
2626 struct buffer *replace;
2627 int ret = -1;
2628
2629 replace = alloc_trash_chunk();
2630 if (!replace)
2631 goto leave;
2632
2633 replace->data = build_logline(s, replace->area, replace->size, fmt);
2634 if (replace->data >= replace->size - 1)
2635 goto leave;
2636
2637 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2638
2639 leave:
2640 free_trash_chunk(replace);
2641 return ret;
2642}
2643
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002644
2645/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2646 * on success and -1 on error. The response channel is updated accordingly.
2647 */
2648static int htx_reply_103_early_hints(struct channel *res)
2649{
2650 struct htx *htx = htx_from_buf(&res->buf);
2651 size_t data;
2652
Christopher Faulet9869f932019-06-26 14:23:54 +02002653 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 /* If an error occurred during an Early-hint rule,
2655 * remove the incomplete HTTP 103 response from the
2656 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002657 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 return -1;
2659 }
2660
2661 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 c_adv(res, data);
2663 res->total += data;
2664 return 0;
2665}
2666
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667/*
2668 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2669 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 * If <early_hints> is 0, it is starts a new response by adding the start
2671 * line. If an error occurred -1 is returned. On success 0 is returned. The
2672 * channel is not updated here. It must be done calling the function
2673 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002675static 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 +01002676{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002677 struct channel *res = &s->res;
2678 struct htx *htx = htx_from_buf(&res->buf);
2679 struct buffer *value = alloc_trash_chunk();
2680
Christopher Faulet6eb92892018-11-15 16:39:29 +01002681 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002682 struct htx_sl *sl;
2683 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2684 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2685
2686 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2687 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2688 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002689 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002691 }
2692
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002693 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2694 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002695 goto fail;
2696
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002697 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002698 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002699
2700 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002701 /* If an error occurred during an Early-hint rule, remove the incomplete
2702 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002703 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002704 free_trash_chunk(value);
2705 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002706}
2707
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002708/* This function executes one of the set-{method,path,query,uri} actions. It
2709 * takes the string from the variable 'replace' with length 'len', then modifies
2710 * the relevant part of the request line accordingly. Then it updates various
2711 * pointers to the next elements which were moved, and the total buffer length.
2712 * It finds the action to be performed in p[2], previously filled by function
2713 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2714 * error, though this can be revisited when this code is finally exploited.
2715 *
2716 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2717 * query string and 3 to replace uri.
2718 *
2719 * In query string case, the mark question '?' must be set at the start of the
2720 * string by the caller, event if the replacement query string is empty.
2721 */
2722int htx_req_replace_stline(int action, const char *replace, int len,
2723 struct proxy *px, struct stream *s)
2724{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002725 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002726
2727 switch (action) {
2728 case 0: // method
2729 if (!http_replace_req_meth(htx, ist2(replace, len)))
2730 return -1;
2731 break;
2732
2733 case 1: // path
2734 if (!http_replace_req_path(htx, ist2(replace, len)))
2735 return -1;
2736 break;
2737
2738 case 2: // query
2739 if (!http_replace_req_query(htx, ist2(replace, len)))
2740 return -1;
2741 break;
2742
2743 case 3: // uri
2744 if (!http_replace_req_uri(htx, ist2(replace, len)))
2745 return -1;
2746 break;
2747
2748 default:
2749 return -1;
2750 }
2751 return 0;
2752}
2753
2754/* This function replace the HTTP status code and the associated message. The
2755 * variable <status> contains the new status code. This function never fails.
2756 */
2757void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2758{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002759 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002760 char *res;
2761
2762 chunk_reset(&trash);
2763 res = ultoa_o(status, trash.area, trash.size);
2764 trash.data = res - trash.area;
2765
2766 /* Do we have a custom reason format string? */
2767 if (reason == NULL)
2768 reason = http_get_reason(status);
2769
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002770 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002771 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2772}
2773
Christopher Faulet3e964192018-10-24 11:39:23 +02002774/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2775 * transaction <txn>. Returns the verdict of the first rule that prevents
2776 * further processing of the request (auth, deny, ...), and defaults to
2777 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2778 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2779 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2780 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2781 * status.
2782 */
2783static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2784 struct stream *s, int *deny_status)
2785{
2786 struct session *sess = strm_sess(s);
2787 struct http_txn *txn = s->txn;
2788 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002789 struct act_rule *rule;
2790 struct http_hdr_ctx ctx;
2791 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002792 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2793 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002794 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002795
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002796 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002797
2798 /* If "the current_rule_list" match the executed rule list, we are in
2799 * resume condition. If a resume is needed it is always in the action
2800 * and never in the ACL or converters. In this case, we initialise the
2801 * current rule, and go to the action execution point.
2802 */
2803 if (s->current_rule) {
2804 rule = s->current_rule;
2805 s->current_rule = NULL;
2806 if (s->current_rule_list == rules)
2807 goto resume_execution;
2808 }
2809 s->current_rule_list = rules;
2810
2811 list_for_each_entry(rule, rules, list) {
2812 /* check optional condition */
2813 if (rule->cond) {
2814 int ret;
2815
2816 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2817 ret = acl_pass(ret);
2818
2819 if (rule->cond->pol == ACL_COND_UNLESS)
2820 ret = !ret;
2821
2822 if (!ret) /* condition not matched */
2823 continue;
2824 }
2825
2826 act_flags |= ACT_FLAG_FIRST;
2827 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002828 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2829 early_hints = 0;
2830 if (htx_reply_103_early_hints(&s->res) == -1) {
2831 rule_ret = HTTP_RULE_RES_BADREQ;
2832 goto end;
2833 }
2834 }
2835
Christopher Faulet3e964192018-10-24 11:39:23 +02002836 switch (rule->action) {
2837 case ACT_ACTION_ALLOW:
2838 rule_ret = HTTP_RULE_RES_STOP;
2839 goto end;
2840
2841 case ACT_ACTION_DENY:
2842 if (deny_status)
2843 *deny_status = rule->deny_status;
2844 rule_ret = HTTP_RULE_RES_DENY;
2845 goto end;
2846
2847 case ACT_HTTP_REQ_TARPIT:
2848 txn->flags |= TX_CLTARPIT;
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_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002855 /* Auth might be performed on regular http-req rules as well as on stats */
2856 auth_realm = rule->arg.auth.realm;
2857 if (!auth_realm) {
2858 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2859 auth_realm = STATS_DEFAULT_REALM;
2860 else
2861 auth_realm = px->id;
2862 }
2863 /* send 401/407 depending on whether we use a proxy or not. We still
2864 * count one error, because normal browsing won't significantly
2865 * increase the counter but brute force attempts will.
2866 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002867 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002868 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2869 rule_ret = HTTP_RULE_RES_BADREQ;
2870 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002871 goto end;
2872
2873 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002874 rule_ret = HTTP_RULE_RES_DONE;
2875 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2876 rule_ret = HTTP_RULE_RES_BADREQ;
2877 goto end;
2878
2879 case ACT_HTTP_SET_NICE:
2880 s->task->nice = rule->arg.nice;
2881 break;
2882
2883 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002884 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002885 break;
2886
2887 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002888 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002889 break;
2890
2891 case ACT_HTTP_SET_LOGL:
2892 s->logs.level = rule->arg.loglevel;
2893 break;
2894
2895 case ACT_HTTP_REPLACE_HDR:
2896 case ACT_HTTP_REPLACE_VAL:
2897 if (htx_transform_header(s, &s->req, htx,
2898 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2899 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002900 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002901 rule_ret = HTTP_RULE_RES_BADREQ;
2902 goto end;
2903 }
2904 break;
2905
2906 case ACT_HTTP_DEL_HDR:
2907 /* remove all occurrences of the header */
2908 ctx.blk = NULL;
2909 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2910 http_remove_header(htx, &ctx);
2911 break;
2912
2913 case ACT_HTTP_SET_HDR:
2914 case ACT_HTTP_ADD_HDR: {
2915 /* The scope of the trash buffer must be limited to this function. The
2916 * build_logline() function can execute a lot of other function which
2917 * can use the trash buffer. So for limiting the scope of this global
2918 * buffer, we build first the header value using build_logline, and
2919 * after we store the header name.
2920 */
2921 struct buffer *replace;
2922 struct ist n, v;
2923
2924 replace = alloc_trash_chunk();
2925 if (!replace) {
2926 rule_ret = HTTP_RULE_RES_BADREQ;
2927 goto end;
2928 }
2929
2930 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2931 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2932 v = ist2(replace->area, replace->data);
2933
2934 if (rule->action == ACT_HTTP_SET_HDR) {
2935 /* remove all occurrences of the header */
2936 ctx.blk = NULL;
2937 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2938 http_remove_header(htx, &ctx);
2939 }
2940
2941 if (!http_add_header(htx, n, v)) {
2942 static unsigned char rate_limit = 0;
2943
2944 if ((rate_limit++ & 255) == 0) {
2945 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);
2946 }
2947
Olivier Houcharda798bf52019-03-08 18:52:00 +01002948 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002949 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002950 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002951 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002952 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002953 }
2954 free_trash_chunk(replace);
2955 break;
2956 }
2957
2958 case ACT_HTTP_DEL_ACL:
2959 case ACT_HTTP_DEL_MAP: {
2960 struct pat_ref *ref;
2961 struct buffer *key;
2962
2963 /* collect reference */
2964 ref = pat_ref_lookup(rule->arg.map.ref);
2965 if (!ref)
2966 continue;
2967
2968 /* allocate key */
2969 key = alloc_trash_chunk();
2970 if (!key) {
2971 rule_ret = HTTP_RULE_RES_BADREQ;
2972 goto end;
2973 }
2974
2975 /* collect key */
2976 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2977 key->area[key->data] = '\0';
2978
2979 /* perform update */
2980 /* returned code: 1=ok, 0=ko */
2981 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2982 pat_ref_delete(ref, key->area);
2983 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2984
2985 free_trash_chunk(key);
2986 break;
2987 }
2988
2989 case ACT_HTTP_ADD_ACL: {
2990 struct pat_ref *ref;
2991 struct buffer *key;
2992
2993 /* collect reference */
2994 ref = pat_ref_lookup(rule->arg.map.ref);
2995 if (!ref)
2996 continue;
2997
2998 /* allocate key */
2999 key = alloc_trash_chunk();
3000 if (!key) {
3001 rule_ret = HTTP_RULE_RES_BADREQ;
3002 goto end;
3003 }
3004
3005 /* collect key */
3006 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3007 key->area[key->data] = '\0';
3008
3009 /* perform update */
3010 /* add entry only if it does not already exist */
3011 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3012 if (pat_ref_find_elt(ref, key->area) == NULL)
3013 pat_ref_add(ref, key->area, NULL, NULL);
3014 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3015
3016 free_trash_chunk(key);
3017 break;
3018 }
3019
3020 case ACT_HTTP_SET_MAP: {
3021 struct pat_ref *ref;
3022 struct buffer *key, *value;
3023
3024 /* collect reference */
3025 ref = pat_ref_lookup(rule->arg.map.ref);
3026 if (!ref)
3027 continue;
3028
3029 /* allocate key */
3030 key = alloc_trash_chunk();
3031 if (!key) {
3032 rule_ret = HTTP_RULE_RES_BADREQ;
3033 goto end;
3034 }
3035
3036 /* allocate value */
3037 value = alloc_trash_chunk();
3038 if (!value) {
3039 free_trash_chunk(key);
3040 rule_ret = HTTP_RULE_RES_BADREQ;
3041 goto end;
3042 }
3043
3044 /* collect key */
3045 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3046 key->area[key->data] = '\0';
3047
3048 /* collect value */
3049 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3050 value->area[value->data] = '\0';
3051
3052 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003053 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003054 if (pat_ref_find_elt(ref, key->area) != NULL)
3055 /* update entry if it exists */
3056 pat_ref_set(ref, key->area, value->area, NULL);
3057 else
3058 /* insert a new entry */
3059 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003060 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003061 free_trash_chunk(key);
3062 free_trash_chunk(value);
3063 break;
3064 }
3065
3066 case ACT_HTTP_EARLY_HINT:
3067 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3068 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003069 early_hints = htx_add_early_hint_header(s, early_hints,
3070 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003071 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003072 if (early_hints == -1) {
3073 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003074 goto end;
3075 }
3076 break;
3077
3078 case ACT_CUSTOM:
3079 if ((s->req.flags & CF_READ_ERROR) ||
3080 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003081 (px->options & PR_O_ABRT_CLOSE)))
3082 act_flags |= ACT_FLAG_FINAL;
3083
3084 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3085 case ACT_RET_ERR:
3086 case ACT_RET_CONT:
3087 break;
3088 case ACT_RET_STOP:
3089 rule_ret = HTTP_RULE_RES_DONE;
3090 goto end;
3091 case ACT_RET_YIELD:
3092 s->current_rule = rule;
3093 rule_ret = HTTP_RULE_RES_YIELD;
3094 goto end;
3095 }
3096 break;
3097
3098 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3099 /* Note: only the first valid tracking parameter of each
3100 * applies.
3101 */
3102
3103 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3104 struct stktable *t;
3105 struct stksess *ts;
3106 struct stktable_key *key;
3107 void *ptr1, *ptr2;
3108
3109 t = rule->arg.trk_ctr.table.t;
3110 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3111 rule->arg.trk_ctr.expr, NULL);
3112
3113 if (key && (ts = stktable_get_entry(t, key))) {
3114 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3115
3116 /* let's count a new HTTP request as it's the first time we do it */
3117 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3118 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3119 if (ptr1 || ptr2) {
3120 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3121
3122 if (ptr1)
3123 stktable_data_cast(ptr1, http_req_cnt)++;
3124
3125 if (ptr2)
3126 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3127 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3128
3129 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3130
3131 /* If data was modified, we need to touch to re-schedule sync */
3132 stktable_touch_local(t, ts, 0);
3133 }
3134
3135 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3136 if (sess->fe != s->be)
3137 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3138 }
3139 }
3140 break;
3141
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003142 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003143 default:
3144 break;
3145 }
3146 }
3147
3148 end:
3149 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003150 if (htx_reply_103_early_hints(&s->res) == -1)
3151 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003152 }
3153
3154 /* we reached the end of the rules, nothing to report */
3155 return rule_ret;
3156}
3157
3158/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3159 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3160 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3161 * is returned, the process can continue the evaluation of next rule list. If
3162 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3163 * is returned, it means the operation could not be processed and a server error
3164 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3165 * deny rule. If *YIELD is returned, the caller must call again the function
3166 * with the same context.
3167 */
3168static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3169 struct stream *s)
3170{
3171 struct session *sess = strm_sess(s);
3172 struct http_txn *txn = s->txn;
3173 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003174 struct act_rule *rule;
3175 struct http_hdr_ctx ctx;
3176 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3177 int act_flags = 0;
3178
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003179 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003180
3181 /* If "the current_rule_list" match the executed rule list, we are in
3182 * resume condition. If a resume is needed it is always in the action
3183 * and never in the ACL or converters. In this case, we initialise the
3184 * current rule, and go to the action execution point.
3185 */
3186 if (s->current_rule) {
3187 rule = s->current_rule;
3188 s->current_rule = NULL;
3189 if (s->current_rule_list == rules)
3190 goto resume_execution;
3191 }
3192 s->current_rule_list = rules;
3193
3194 list_for_each_entry(rule, rules, list) {
3195 /* check optional condition */
3196 if (rule->cond) {
3197 int ret;
3198
3199 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3200 ret = acl_pass(ret);
3201
3202 if (rule->cond->pol == ACL_COND_UNLESS)
3203 ret = !ret;
3204
3205 if (!ret) /* condition not matched */
3206 continue;
3207 }
3208
3209 act_flags |= ACT_FLAG_FIRST;
3210resume_execution:
3211 switch (rule->action) {
3212 case ACT_ACTION_ALLOW:
3213 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3214 goto end;
3215
3216 case ACT_ACTION_DENY:
3217 txn->flags |= TX_SVDENY;
3218 rule_ret = HTTP_RULE_RES_STOP;
3219 goto end;
3220
3221 case ACT_HTTP_SET_NICE:
3222 s->task->nice = rule->arg.nice;
3223 break;
3224
3225 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003226 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003227 break;
3228
3229 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003230 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003231 break;
3232
3233 case ACT_HTTP_SET_LOGL:
3234 s->logs.level = rule->arg.loglevel;
3235 break;
3236
3237 case ACT_HTTP_REPLACE_HDR:
3238 case ACT_HTTP_REPLACE_VAL:
3239 if (htx_transform_header(s, &s->res, htx,
3240 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3241 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003242 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003243 rule_ret = HTTP_RULE_RES_BADREQ;
3244 goto end;
3245 }
3246 break;
3247
3248 case ACT_HTTP_DEL_HDR:
3249 /* remove all occurrences of the header */
3250 ctx.blk = NULL;
3251 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3252 http_remove_header(htx, &ctx);
3253 break;
3254
3255 case ACT_HTTP_SET_HDR:
3256 case ACT_HTTP_ADD_HDR: {
3257 struct buffer *replace;
3258 struct ist n, v;
3259
3260 replace = alloc_trash_chunk();
3261 if (!replace) {
3262 rule_ret = HTTP_RULE_RES_BADREQ;
3263 goto end;
3264 }
3265
3266 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3267 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3268 v = ist2(replace->area, replace->data);
3269
3270 if (rule->action == ACT_HTTP_SET_HDR) {
3271 /* remove all occurrences of the header */
3272 ctx.blk = NULL;
3273 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3274 http_remove_header(htx, &ctx);
3275 }
3276
3277 if (!http_add_header(htx, n, v)) {
3278 static unsigned char rate_limit = 0;
3279
3280 if ((rate_limit++ & 255) == 0) {
3281 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);
3282 }
3283
Olivier Houcharda798bf52019-03-08 18:52:00 +01003284 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003285 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003286 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003287 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003288 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003289 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003290 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003291 }
3292 free_trash_chunk(replace);
3293 break;
3294 }
3295
3296 case ACT_HTTP_DEL_ACL:
3297 case ACT_HTTP_DEL_MAP: {
3298 struct pat_ref *ref;
3299 struct buffer *key;
3300
3301 /* collect reference */
3302 ref = pat_ref_lookup(rule->arg.map.ref);
3303 if (!ref)
3304 continue;
3305
3306 /* allocate key */
3307 key = alloc_trash_chunk();
3308 if (!key) {
3309 rule_ret = HTTP_RULE_RES_BADREQ;
3310 goto end;
3311 }
3312
3313 /* collect key */
3314 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3315 key->area[key->data] = '\0';
3316
3317 /* perform update */
3318 /* returned code: 1=ok, 0=ko */
3319 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3320 pat_ref_delete(ref, key->area);
3321 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3322
3323 free_trash_chunk(key);
3324 break;
3325 }
3326
3327 case ACT_HTTP_ADD_ACL: {
3328 struct pat_ref *ref;
3329 struct buffer *key;
3330
3331 /* collect reference */
3332 ref = pat_ref_lookup(rule->arg.map.ref);
3333 if (!ref)
3334 continue;
3335
3336 /* allocate key */
3337 key = alloc_trash_chunk();
3338 if (!key) {
3339 rule_ret = HTTP_RULE_RES_BADREQ;
3340 goto end;
3341 }
3342
3343 /* collect key */
3344 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3345 key->area[key->data] = '\0';
3346
3347 /* perform update */
3348 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003349 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003350 if (pat_ref_find_elt(ref, key->area) == NULL)
3351 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003352 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003353 free_trash_chunk(key);
3354 break;
3355 }
3356
3357 case ACT_HTTP_SET_MAP: {
3358 struct pat_ref *ref;
3359 struct buffer *key, *value;
3360
3361 /* collect reference */
3362 ref = pat_ref_lookup(rule->arg.map.ref);
3363 if (!ref)
3364 continue;
3365
3366 /* allocate key */
3367 key = alloc_trash_chunk();
3368 if (!key) {
3369 rule_ret = HTTP_RULE_RES_BADREQ;
3370 goto end;
3371 }
3372
3373 /* allocate value */
3374 value = alloc_trash_chunk();
3375 if (!value) {
3376 free_trash_chunk(key);
3377 rule_ret = HTTP_RULE_RES_BADREQ;
3378 goto end;
3379 }
3380
3381 /* collect key */
3382 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3383 key->area[key->data] = '\0';
3384
3385 /* collect value */
3386 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3387 value->area[value->data] = '\0';
3388
3389 /* perform update */
3390 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3391 if (pat_ref_find_elt(ref, key->area) != NULL)
3392 /* update entry if it exists */
3393 pat_ref_set(ref, key->area, value->area, NULL);
3394 else
3395 /* insert a new entry */
3396 pat_ref_add(ref, key->area, value->area, NULL);
3397 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3398 free_trash_chunk(key);
3399 free_trash_chunk(value);
3400 break;
3401 }
3402
3403 case ACT_HTTP_REDIR:
3404 rule_ret = HTTP_RULE_RES_DONE;
3405 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3406 rule_ret = HTTP_RULE_RES_BADREQ;
3407 goto end;
3408
3409 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3410 /* Note: only the first valid tracking parameter of each
3411 * applies.
3412 */
3413 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3414 struct stktable *t;
3415 struct stksess *ts;
3416 struct stktable_key *key;
3417 void *ptr;
3418
3419 t = rule->arg.trk_ctr.table.t;
3420 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3421 rule->arg.trk_ctr.expr, NULL);
3422
3423 if (key && (ts = stktable_get_entry(t, key))) {
3424 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3425
3426 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3427
3428 /* let's count a new HTTP request as it's the first time we do it */
3429 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3430 if (ptr)
3431 stktable_data_cast(ptr, http_req_cnt)++;
3432
3433 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3434 if (ptr)
3435 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3436 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3437
3438 /* When the client triggers a 4xx from the server, it's most often due
3439 * to a missing object or permission. These events should be tracked
3440 * because if they happen often, it may indicate a brute force or a
3441 * vulnerability scan. Normally this is done when receiving the response
3442 * but here we're tracking after this ought to have been done so we have
3443 * to do it on purpose.
3444 */
3445 if ((unsigned)(txn->status - 400) < 100) {
3446 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3447 if (ptr)
3448 stktable_data_cast(ptr, http_err_cnt)++;
3449
3450 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3451 if (ptr)
3452 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3453 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3454 }
3455
3456 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3457
3458 /* If data was modified, we need to touch to re-schedule sync */
3459 stktable_touch_local(t, ts, 0);
3460
3461 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3462 if (sess->fe != s->be)
3463 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3464 }
3465 }
3466 break;
3467
3468 case ACT_CUSTOM:
3469 if ((s->req.flags & CF_READ_ERROR) ||
3470 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003471 (px->options & PR_O_ABRT_CLOSE)))
3472 act_flags |= ACT_FLAG_FINAL;
3473
3474 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3475 case ACT_RET_ERR:
3476 case ACT_RET_CONT:
3477 break;
3478 case ACT_RET_STOP:
3479 rule_ret = HTTP_RULE_RES_STOP;
3480 goto end;
3481 case ACT_RET_YIELD:
3482 s->current_rule = rule;
3483 rule_ret = HTTP_RULE_RES_YIELD;
3484 goto end;
3485 }
3486 break;
3487
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003488 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003489 default:
3490 break;
3491 }
3492 }
3493
3494 end:
3495 /* we reached the end of the rules, nothing to report */
3496 return rule_ret;
3497}
3498
Christopher Faulet33640082018-10-24 11:53:01 +02003499/* Iterate the same filter through all request headers.
3500 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3501 * Since it can manage the switch to another backend, it updates the per-proxy
3502 * DENY stats.
3503 */
3504static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3505{
3506 struct http_txn *txn = s->txn;
3507 struct htx *htx;
3508 struct buffer *hdr = get_trash_chunk();
3509 int32_t pos;
3510
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003511 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003512
Christopher Fauleta3f15502019-05-13 15:27:23 +02003513 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003514 struct htx_blk *blk = htx_get_blk(htx, pos);
3515 enum htx_blk_type type;
3516 struct ist n, v;
3517
3518 next_hdr:
3519 type = htx_get_blk_type(blk);
3520 if (type == HTX_BLK_EOH)
3521 break;
3522 if (type != HTX_BLK_HDR)
3523 continue;
3524
3525 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3526 return 1;
3527 else if (unlikely(txn->flags & TX_CLALLOW) &&
3528 (exp->action == ACT_ALLOW ||
3529 exp->action == ACT_DENY ||
3530 exp->action == ACT_TARPIT))
3531 return 0;
3532
3533 n = htx_get_blk_name(htx, blk);
3534 v = htx_get_blk_value(htx, blk);
3535
Christopher Faulet02e771a2019-02-26 15:36:05 +01003536 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003537 hdr->area[hdr->data++] = ':';
3538 hdr->area[hdr->data++] = ' ';
3539 chunk_memcat(hdr, v.ptr, v.len);
3540
3541 /* Now we have one header in <hdr> */
3542
3543 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3544 struct http_hdr_ctx ctx;
3545 int len;
3546
3547 switch (exp->action) {
3548 case ACT_ALLOW:
3549 txn->flags |= TX_CLALLOW;
3550 goto end;
3551
3552 case ACT_DENY:
3553 txn->flags |= TX_CLDENY;
3554 goto end;
3555
3556 case ACT_TARPIT:
3557 txn->flags |= TX_CLTARPIT;
3558 goto end;
3559
3560 case ACT_REPLACE:
3561 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3562 if (len < 0)
3563 return -1;
3564
3565 http_parse_header(ist2(trash.area, len), &n, &v);
3566 ctx.blk = blk;
3567 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003568 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003569 if (!http_replace_header(htx, &ctx, n, v))
3570 return -1;
3571 if (!ctx.blk)
3572 goto end;
3573 pos = htx_get_blk_pos(htx, blk);
3574 break;
3575
3576 case ACT_REMOVE:
3577 ctx.blk = blk;
3578 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003579 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003580 if (!http_remove_header(htx, &ctx))
3581 return -1;
3582 if (!ctx.blk)
3583 goto end;
3584 pos = htx_get_blk_pos(htx, blk);
3585 goto next_hdr;
3586
3587 }
3588 }
3589 }
3590 end:
3591 return 0;
3592}
3593
3594/* Apply the filter to the request line.
3595 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3596 * or -1 if a replacement resulted in an invalid request line.
3597 * Since it can manage the switch to another backend, it updates the per-proxy
3598 * DENY stats.
3599 */
3600static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3601{
3602 struct http_txn *txn = s->txn;
3603 struct htx *htx;
3604 struct buffer *reqline = get_trash_chunk();
3605 int done;
3606
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003607 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003608
3609 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3610 return 1;
3611 else if (unlikely(txn->flags & TX_CLALLOW) &&
3612 (exp->action == ACT_ALLOW ||
3613 exp->action == ACT_DENY ||
3614 exp->action == ACT_TARPIT))
3615 return 0;
3616 else if (exp->action == ACT_REMOVE)
3617 return 0;
3618
3619 done = 0;
3620
Christopher Faulet297fbb42019-05-13 14:41:27 +02003621 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003622
3623 /* Now we have the request line between cur_ptr and cur_end */
3624 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003625 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003626 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003627 int len;
3628
3629 switch (exp->action) {
3630 case ACT_ALLOW:
3631 txn->flags |= TX_CLALLOW;
3632 done = 1;
3633 break;
3634
3635 case ACT_DENY:
3636 txn->flags |= TX_CLDENY;
3637 done = 1;
3638 break;
3639
3640 case ACT_TARPIT:
3641 txn->flags |= TX_CLTARPIT;
3642 done = 1;
3643 break;
3644
3645 case ACT_REPLACE:
3646 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3647 if (len < 0)
3648 return -1;
3649
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003650 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3651 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3652 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003653 return -1;
3654 done = 1;
3655 break;
3656 }
3657 }
3658 return done;
3659}
3660
3661/*
3662 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3663 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3664 * unparsable request. Since it can manage the switch to another backend, it
3665 * updates the per-proxy DENY stats.
3666 */
3667static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3668{
3669 struct session *sess = s->sess;
3670 struct http_txn *txn = s->txn;
3671 struct hdr_exp *exp;
3672
3673 for (exp = px->req_exp; exp; exp = exp->next) {
3674 int ret;
3675
3676 /*
3677 * The interleaving of transformations and verdicts
3678 * makes it difficult to decide to continue or stop
3679 * the evaluation.
3680 */
3681
3682 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3683 break;
3684
3685 if ((txn->flags & TX_CLALLOW) &&
3686 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3687 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3688 continue;
3689
3690 /* if this filter had a condition, evaluate it now and skip to
3691 * next filter if the condition does not match.
3692 */
3693 if (exp->cond) {
3694 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3695 ret = acl_pass(ret);
3696 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3697 ret = !ret;
3698
3699 if (!ret)
3700 continue;
3701 }
3702
3703 /* Apply the filter to the request line. */
3704 ret = htx_apply_filter_to_req_line(s, req, exp);
3705 if (unlikely(ret < 0))
3706 return -1;
3707
3708 if (likely(ret == 0)) {
3709 /* The filter did not match the request, it can be
3710 * iterated through all headers.
3711 */
3712 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3713 return -1;
3714 }
3715 }
3716 return 0;
3717}
3718
3719/* Iterate the same filter through all response headers contained in <res>.
3720 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3721 */
3722static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3723{
3724 struct http_txn *txn = s->txn;
3725 struct htx *htx;
3726 struct buffer *hdr = get_trash_chunk();
3727 int32_t pos;
3728
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003729 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003730
Christopher Fauleta3f15502019-05-13 15:27:23 +02003731 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003732 struct htx_blk *blk = htx_get_blk(htx, pos);
3733 enum htx_blk_type type;
3734 struct ist n, v;
3735
3736 next_hdr:
3737 type = htx_get_blk_type(blk);
3738 if (type == HTX_BLK_EOH)
3739 break;
3740 if (type != HTX_BLK_HDR)
3741 continue;
3742
3743 if (unlikely(txn->flags & TX_SVDENY))
3744 return 1;
3745 else if (unlikely(txn->flags & TX_SVALLOW) &&
3746 (exp->action == ACT_ALLOW ||
3747 exp->action == ACT_DENY))
3748 return 0;
3749
3750 n = htx_get_blk_name(htx, blk);
3751 v = htx_get_blk_value(htx, blk);
3752
Christopher Faulet02e771a2019-02-26 15:36:05 +01003753 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003754 hdr->area[hdr->data++] = ':';
3755 hdr->area[hdr->data++] = ' ';
3756 chunk_memcat(hdr, v.ptr, v.len);
3757
3758 /* Now we have one header in <hdr> */
3759
3760 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3761 struct http_hdr_ctx ctx;
3762 int len;
3763
3764 switch (exp->action) {
3765 case ACT_ALLOW:
3766 txn->flags |= TX_SVALLOW;
3767 goto end;
3768 break;
3769
3770 case ACT_DENY:
3771 txn->flags |= TX_SVDENY;
3772 goto end;
3773 break;
3774
3775 case ACT_REPLACE:
3776 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3777 if (len < 0)
3778 return -1;
3779
3780 http_parse_header(ist2(trash.area, len), &n, &v);
3781 ctx.blk = blk;
3782 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003783 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003784 if (!http_replace_header(htx, &ctx, n, v))
3785 return -1;
3786 if (!ctx.blk)
3787 goto end;
3788 pos = htx_get_blk_pos(htx, blk);
3789 break;
3790
3791 case ACT_REMOVE:
3792 ctx.blk = blk;
3793 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003794 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003795 if (!http_remove_header(htx, &ctx))
3796 return -1;
3797 if (!ctx.blk)
3798 goto end;
3799 pos = htx_get_blk_pos(htx, blk);
3800 goto next_hdr;
3801 }
3802 }
3803
3804 }
3805 end:
3806 return 0;
3807}
3808
3809/* Apply the filter to the status line in the response buffer <res>.
3810 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3811 * or -1 if a replacement resulted in an invalid status line.
3812 */
3813static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3814{
3815 struct http_txn *txn = s->txn;
3816 struct htx *htx;
3817 struct buffer *resline = get_trash_chunk();
3818 int done;
3819
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003820 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003821
3822 if (unlikely(txn->flags & TX_SVDENY))
3823 return 1;
3824 else if (unlikely(txn->flags & TX_SVALLOW) &&
3825 (exp->action == ACT_ALLOW ||
3826 exp->action == ACT_DENY))
3827 return 0;
3828 else if (exp->action == ACT_REMOVE)
3829 return 0;
3830
3831 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003832 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003833
3834 /* Now we have the status line between cur_ptr and cur_end */
3835 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003836 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003837 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003838 int len;
3839
3840 switch (exp->action) {
3841 case ACT_ALLOW:
3842 txn->flags |= TX_SVALLOW;
3843 done = 1;
3844 break;
3845
3846 case ACT_DENY:
3847 txn->flags |= TX_SVDENY;
3848 done = 1;
3849 break;
3850
3851 case ACT_REPLACE:
3852 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3853 if (len < 0)
3854 return -1;
3855
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003856 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3857 sl->info.res.status = strl2ui(code.ptr, code.len);
3858 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003859 return -1;
3860
3861 done = 1;
3862 return 1;
3863 }
3864 }
3865 return done;
3866}
3867
3868/*
3869 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3870 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3871 * unparsable response.
3872 */
3873static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3874{
3875 struct session *sess = s->sess;
3876 struct http_txn *txn = s->txn;
3877 struct hdr_exp *exp;
3878
3879 for (exp = px->rsp_exp; exp; exp = exp->next) {
3880 int ret;
3881
3882 /*
3883 * The interleaving of transformations and verdicts
3884 * makes it difficult to decide to continue or stop
3885 * the evaluation.
3886 */
3887
3888 if (txn->flags & TX_SVDENY)
3889 break;
3890
3891 if ((txn->flags & TX_SVALLOW) &&
3892 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3893 exp->action == ACT_PASS)) {
3894 exp = exp->next;
3895 continue;
3896 }
3897
3898 /* if this filter had a condition, evaluate it now and skip to
3899 * next filter if the condition does not match.
3900 */
3901 if (exp->cond) {
3902 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3903 ret = acl_pass(ret);
3904 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3905 ret = !ret;
3906 if (!ret)
3907 continue;
3908 }
3909
3910 /* Apply the filter to the status line. */
3911 ret = htx_apply_filter_to_sts_line(s, res, exp);
3912 if (unlikely(ret < 0))
3913 return -1;
3914
3915 if (likely(ret == 0)) {
3916 /* The filter did not match the response, it can be
3917 * iterated through all headers.
3918 */
3919 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3920 return -1;
3921 }
3922 }
3923 return 0;
3924}
3925
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003926/*
3927 * Manage client-side cookie. It can impact performance by about 2% so it is
3928 * desirable to call it only when needed. This code is quite complex because
3929 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3930 * highly recommended not to touch this part without a good reason !
3931 */
3932static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3933{
3934 struct session *sess = s->sess;
3935 struct http_txn *txn = s->txn;
3936 struct htx *htx;
3937 struct http_hdr_ctx ctx;
3938 char *hdr_beg, *hdr_end, *del_from;
3939 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3940 int preserve_hdr;
3941
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003942 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003943 ctx.blk = NULL;
3944 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3945 del_from = NULL; /* nothing to be deleted */
3946 preserve_hdr = 0; /* assume we may kill the whole header */
3947
3948 /* Now look for cookies. Conforming to RFC2109, we have to support
3949 * attributes whose name begin with a '$', and associate them with
3950 * the right cookie, if we want to delete this cookie.
3951 * So there are 3 cases for each cookie read :
3952 * 1) it's a special attribute, beginning with a '$' : ignore it.
3953 * 2) it's a server id cookie that we *MAY* want to delete : save
3954 * some pointers on it (last semi-colon, beginning of cookie...)
3955 * 3) it's an application cookie : we *MAY* have to delete a previous
3956 * "special" cookie.
3957 * At the end of loop, if a "special" cookie remains, we may have to
3958 * remove it. If no application cookie persists in the header, we
3959 * *MUST* delete it.
3960 *
3961 * Note: RFC2965 is unclear about the processing of spaces around
3962 * the equal sign in the ATTR=VALUE form. A careful inspection of
3963 * the RFC explicitly allows spaces before it, and not within the
3964 * tokens (attrs or values). An inspection of RFC2109 allows that
3965 * too but section 10.1.3 lets one think that spaces may be allowed
3966 * after the equal sign too, resulting in some (rare) buggy
3967 * implementations trying to do that. So let's do what servers do.
3968 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3969 * allowed quoted strings in values, with any possible character
3970 * after a backslash, including control chars and delimitors, which
3971 * causes parsing to become ambiguous. Browsers also allow spaces
3972 * within values even without quotes.
3973 *
3974 * We have to keep multiple pointers in order to support cookie
3975 * removal at the beginning, middle or end of header without
3976 * corrupting the header. All of these headers are valid :
3977 *
3978 * hdr_beg hdr_end
3979 * | |
3980 * v |
3981 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3982 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3983 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3984 * | | | | | | |
3985 * | | | | | | |
3986 * | | | | | | +--> next
3987 * | | | | | +----> val_end
3988 * | | | | +-----------> val_beg
3989 * | | | +--------------> equal
3990 * | | +----------------> att_end
3991 * | +---------------------> att_beg
3992 * +--------------------------> prev
3993 *
3994 */
3995 hdr_beg = ctx.value.ptr;
3996 hdr_end = hdr_beg + ctx.value.len;
3997 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3998 /* Iterate through all cookies on this line */
3999
4000 /* find att_beg */
4001 att_beg = prev;
4002 if (prev > hdr_beg)
4003 att_beg++;
4004
4005 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4006 att_beg++;
4007
4008 /* find att_end : this is the first character after the last non
4009 * space before the equal. It may be equal to hdr_end.
4010 */
4011 equal = att_end = att_beg;
4012 while (equal < hdr_end) {
4013 if (*equal == '=' || *equal == ',' || *equal == ';')
4014 break;
4015 if (HTTP_IS_SPHT(*equal++))
4016 continue;
4017 att_end = equal;
4018 }
4019
4020 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4021 * is between <att_beg> and <equal>, both may be identical.
4022 */
4023 /* look for end of cookie if there is an equal sign */
4024 if (equal < hdr_end && *equal == '=') {
4025 /* look for the beginning of the value */
4026 val_beg = equal + 1;
4027 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4028 val_beg++;
4029
4030 /* find the end of the value, respecting quotes */
4031 next = http_find_cookie_value_end(val_beg, hdr_end);
4032
4033 /* make val_end point to the first white space or delimitor after the value */
4034 val_end = next;
4035 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4036 val_end--;
4037 }
4038 else
4039 val_beg = val_end = next = equal;
4040
4041 /* We have nothing to do with attributes beginning with
4042 * '$'. However, they will automatically be removed if a
4043 * header before them is removed, since they're supposed
4044 * to be linked together.
4045 */
4046 if (*att_beg == '$')
4047 continue;
4048
4049 /* Ignore cookies with no equal sign */
4050 if (equal == next) {
4051 /* This is not our cookie, so we must preserve it. But if we already
4052 * scheduled another cookie for removal, we cannot remove the
4053 * complete header, but we can remove the previous block itself.
4054 */
4055 preserve_hdr = 1;
4056 if (del_from != NULL) {
4057 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4058 val_end += delta;
4059 next += delta;
4060 hdr_end += delta;
4061 prev = del_from;
4062 del_from = NULL;
4063 }
4064 continue;
4065 }
4066
4067 /* if there are spaces around the equal sign, we need to
4068 * strip them otherwise we'll get trouble for cookie captures,
4069 * or even for rewrites. Since this happens extremely rarely,
4070 * it does not hurt performance.
4071 */
4072 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4073 int stripped_before = 0;
4074 int stripped_after = 0;
4075
4076 if (att_end != equal) {
4077 memmove(att_end, equal, hdr_end - equal);
4078 stripped_before = (att_end - equal);
4079 equal += stripped_before;
4080 val_beg += stripped_before;
4081 }
4082
4083 if (val_beg > equal + 1) {
4084 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4085 stripped_after = (equal + 1) - val_beg;
4086 val_beg += stripped_after;
4087 stripped_before += stripped_after;
4088 }
4089
4090 val_end += stripped_before;
4091 next += stripped_before;
4092 hdr_end += stripped_before;
4093 }
4094 /* now everything is as on the diagram above */
4095
4096 /* First, let's see if we want to capture this cookie. We check
4097 * that we don't already have a client side cookie, because we
4098 * can only capture one. Also as an optimisation, we ignore
4099 * cookies shorter than the declared name.
4100 */
4101 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4102 (val_end - att_beg >= sess->fe->capture_namelen) &&
4103 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4104 int log_len = val_end - att_beg;
4105
4106 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4107 ha_alert("HTTP logging : out of memory.\n");
4108 } else {
4109 if (log_len > sess->fe->capture_len)
4110 log_len = sess->fe->capture_len;
4111 memcpy(txn->cli_cookie, att_beg, log_len);
4112 txn->cli_cookie[log_len] = 0;
4113 }
4114 }
4115
4116 /* Persistence cookies in passive, rewrite or insert mode have the
4117 * following form :
4118 *
4119 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4120 *
4121 * For cookies in prefix mode, the form is :
4122 *
4123 * Cookie: NAME=SRV~VALUE
4124 */
4125 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4126 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4127 struct server *srv = s->be->srv;
4128 char *delim;
4129
4130 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4131 * have the server ID between val_beg and delim, and the original cookie between
4132 * delim+1 and val_end. Otherwise, delim==val_end :
4133 *
4134 * hdr_beg
4135 * |
4136 * v
4137 * NAME=SRV; # in all but prefix modes
4138 * NAME=SRV~OPAQUE ; # in prefix mode
4139 * || || | |+-> next
4140 * || || | +--> val_end
4141 * || || +---------> delim
4142 * || |+------------> val_beg
4143 * || +-------------> att_end = equal
4144 * |+-----------------> att_beg
4145 * +------------------> prev
4146 *
4147 */
4148 if (s->be->ck_opts & PR_CK_PFX) {
4149 for (delim = val_beg; delim < val_end; delim++)
4150 if (*delim == COOKIE_DELIM)
4151 break;
4152 }
4153 else {
4154 char *vbar1;
4155 delim = val_end;
4156 /* Now check if the cookie contains a date field, which would
4157 * appear after a vertical bar ('|') just after the server name
4158 * and before the delimiter.
4159 */
4160 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4161 if (vbar1) {
4162 /* OK, so left of the bar is the server's cookie and
4163 * right is the last seen date. It is a base64 encoded
4164 * 30-bit value representing the UNIX date since the
4165 * epoch in 4-second quantities.
4166 */
4167 int val;
4168 delim = vbar1++;
4169 if (val_end - vbar1 >= 5) {
4170 val = b64tos30(vbar1);
4171 if (val > 0)
4172 txn->cookie_last_date = val << 2;
4173 }
4174 /* look for a second vertical bar */
4175 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4176 if (vbar1 && (val_end - vbar1 > 5)) {
4177 val = b64tos30(vbar1 + 1);
4178 if (val > 0)
4179 txn->cookie_first_date = val << 2;
4180 }
4181 }
4182 }
4183
4184 /* if the cookie has an expiration date and the proxy wants to check
4185 * it, then we do that now. We first check if the cookie is too old,
4186 * then only if it has expired. We detect strict overflow because the
4187 * time resolution here is not great (4 seconds). Cookies with dates
4188 * in the future are ignored if their offset is beyond one day. This
4189 * allows an admin to fix timezone issues without expiring everyone
4190 * and at the same time avoids keeping unwanted side effects for too
4191 * long.
4192 */
4193 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4194 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4195 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4196 txn->flags &= ~TX_CK_MASK;
4197 txn->flags |= TX_CK_OLD;
4198 delim = val_beg; // let's pretend we have not found the cookie
4199 txn->cookie_first_date = 0;
4200 txn->cookie_last_date = 0;
4201 }
4202 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4203 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4204 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4205 txn->flags &= ~TX_CK_MASK;
4206 txn->flags |= TX_CK_EXPIRED;
4207 delim = val_beg; // let's pretend we have not found the cookie
4208 txn->cookie_first_date = 0;
4209 txn->cookie_last_date = 0;
4210 }
4211
4212 /* Here, we'll look for the first running server which supports the cookie.
4213 * This allows to share a same cookie between several servers, for example
4214 * to dedicate backup servers to specific servers only.
4215 * However, to prevent clients from sticking to cookie-less backup server
4216 * when they have incidentely learned an empty cookie, we simply ignore
4217 * empty cookies and mark them as invalid.
4218 * The same behaviour is applied when persistence must be ignored.
4219 */
4220 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4221 srv = NULL;
4222
4223 while (srv) {
4224 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4225 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4226 if ((srv->cur_state != SRV_ST_STOPPED) ||
4227 (s->be->options & PR_O_PERSIST) ||
4228 (s->flags & SF_FORCE_PRST)) {
4229 /* we found the server and we can use it */
4230 txn->flags &= ~TX_CK_MASK;
4231 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4232 s->flags |= SF_DIRECT | SF_ASSIGNED;
4233 s->target = &srv->obj_type;
4234 break;
4235 } else {
4236 /* we found a server, but it's down,
4237 * mark it as such and go on in case
4238 * another one is available.
4239 */
4240 txn->flags &= ~TX_CK_MASK;
4241 txn->flags |= TX_CK_DOWN;
4242 }
4243 }
4244 srv = srv->next;
4245 }
4246
4247 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4248 /* no server matched this cookie or we deliberately skipped it */
4249 txn->flags &= ~TX_CK_MASK;
4250 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4251 txn->flags |= TX_CK_UNUSED;
4252 else
4253 txn->flags |= TX_CK_INVALID;
4254 }
4255
4256 /* depending on the cookie mode, we may have to either :
4257 * - delete the complete cookie if we're in insert+indirect mode, so that
4258 * the server never sees it ;
4259 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004260 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004261 * if we're in cookie prefix mode
4262 */
4263 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4264 int delta; /* negative */
4265
4266 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4267 delta = val_beg - (delim + 1);
4268 val_end += delta;
4269 next += delta;
4270 hdr_end += delta;
4271 del_from = NULL;
4272 preserve_hdr = 1; /* we want to keep this cookie */
4273 }
4274 else if (del_from == NULL &&
4275 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4276 del_from = prev;
4277 }
4278 }
4279 else {
4280 /* This is not our cookie, so we must preserve it. But if we already
4281 * scheduled another cookie for removal, we cannot remove the
4282 * complete header, but we can remove the previous block itself.
4283 */
4284 preserve_hdr = 1;
4285
4286 if (del_from != NULL) {
4287 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4288 if (att_beg >= del_from)
4289 att_beg += delta;
4290 if (att_end >= del_from)
4291 att_end += delta;
4292 val_beg += delta;
4293 val_end += delta;
4294 next += delta;
4295 hdr_end += delta;
4296 prev = del_from;
4297 del_from = NULL;
4298 }
4299 }
4300
4301 /* continue with next cookie on this header line */
4302 att_beg = next;
4303 } /* for each cookie */
4304
4305
4306 /* There are no more cookies on this line.
4307 * We may still have one (or several) marked for deletion at the
4308 * end of the line. We must do this now in two ways :
4309 * - if some cookies must be preserved, we only delete from the
4310 * mark to the end of line ;
4311 * - if nothing needs to be preserved, simply delete the whole header
4312 */
4313 if (del_from) {
4314 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4315 }
4316 if ((hdr_end - hdr_beg) != ctx.value.len) {
Christopher Faulet41dc8432019-06-18 09:49:16 +02004317 if (hdr_beg != hdr_end)
4318 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004319 else
4320 http_remove_header(htx, &ctx);
4321 }
4322 } /* for each "Cookie header */
4323}
4324
4325/*
4326 * Manage server-side cookies. It can impact performance by about 2% so it is
4327 * desirable to call it only when needed. This function is also used when we
4328 * just need to know if there is a cookie (eg: for check-cache).
4329 */
4330static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4331{
4332 struct session *sess = s->sess;
4333 struct http_txn *txn = s->txn;
4334 struct htx *htx;
4335 struct http_hdr_ctx ctx;
4336 struct server *srv;
4337 char *hdr_beg, *hdr_end;
4338 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004339 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004340
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004341 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004342
4343 ctx.blk = NULL;
4344 while (1) {
4345 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4346 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4347 break;
4348 is_cookie2 = 1;
4349 }
4350
4351 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4352 * <prev> points to the colon.
4353 */
4354 txn->flags |= TX_SCK_PRESENT;
4355
4356 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4357 * check-cache is enabled) and we are not interested in checking
4358 * them. Warning, the cookie capture is declared in the frontend.
4359 */
4360 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4361 break;
4362
4363 /* OK so now we know we have to process this response cookie.
4364 * The format of the Set-Cookie header is slightly different
4365 * from the format of the Cookie header in that it does not
4366 * support the comma as a cookie delimiter (thus the header
4367 * cannot be folded) because the Expires attribute described in
4368 * the original Netscape's spec may contain an unquoted date
4369 * with a comma inside. We have to live with this because
4370 * many browsers don't support Max-Age and some browsers don't
4371 * support quoted strings. However the Set-Cookie2 header is
4372 * clean.
4373 *
4374 * We have to keep multiple pointers in order to support cookie
4375 * removal at the beginning, middle or end of header without
4376 * corrupting the header (in case of set-cookie2). A special
4377 * pointer, <scav> points to the beginning of the set-cookie-av
4378 * fields after the first semi-colon. The <next> pointer points
4379 * either to the end of line (set-cookie) or next unquoted comma
4380 * (set-cookie2). All of these headers are valid :
4381 *
4382 * hdr_beg hdr_end
4383 * | |
4384 * v |
4385 * NAME1 = VALUE 1 ; Secure; Path="/" |
4386 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4387 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4388 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4389 * | | | | | | | |
4390 * | | | | | | | +-> next
4391 * | | | | | | +------------> scav
4392 * | | | | | +--------------> val_end
4393 * | | | | +--------------------> val_beg
4394 * | | | +----------------------> equal
4395 * | | +------------------------> att_end
4396 * | +----------------------------> att_beg
4397 * +------------------------------> prev
4398 * -------------------------------> hdr_beg
4399 */
4400 hdr_beg = ctx.value.ptr;
4401 hdr_end = hdr_beg + ctx.value.len;
4402 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4403
4404 /* Iterate through all cookies on this line */
4405
4406 /* find att_beg */
4407 att_beg = prev;
4408 if (prev > hdr_beg)
4409 att_beg++;
4410
4411 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4412 att_beg++;
4413
4414 /* find att_end : this is the first character after the last non
4415 * space before the equal. It may be equal to hdr_end.
4416 */
4417 equal = att_end = att_beg;
4418
4419 while (equal < hdr_end) {
4420 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4421 break;
4422 if (HTTP_IS_SPHT(*equal++))
4423 continue;
4424 att_end = equal;
4425 }
4426
4427 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4428 * is between <att_beg> and <equal>, both may be identical.
4429 */
4430
4431 /* look for end of cookie if there is an equal sign */
4432 if (equal < hdr_end && *equal == '=') {
4433 /* look for the beginning of the value */
4434 val_beg = equal + 1;
4435 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4436 val_beg++;
4437
4438 /* find the end of the value, respecting quotes */
4439 next = http_find_cookie_value_end(val_beg, hdr_end);
4440
4441 /* make val_end point to the first white space or delimitor after the value */
4442 val_end = next;
4443 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4444 val_end--;
4445 }
4446 else {
4447 /* <equal> points to next comma, semi-colon or EOL */
4448 val_beg = val_end = next = equal;
4449 }
4450
4451 if (next < hdr_end) {
4452 /* Set-Cookie2 supports multiple cookies, and <next> points to
4453 * a colon or semi-colon before the end. So skip all attr-value
4454 * pairs and look for the next comma. For Set-Cookie, since
4455 * commas are permitted in values, skip to the end.
4456 */
4457 if (is_cookie2)
4458 next = http_find_hdr_value_end(next, hdr_end);
4459 else
4460 next = hdr_end;
4461 }
4462
4463 /* Now everything is as on the diagram above */
4464
4465 /* Ignore cookies with no equal sign */
4466 if (equal == val_end)
4467 continue;
4468
4469 /* If there are spaces around the equal sign, we need to
4470 * strip them otherwise we'll get trouble for cookie captures,
4471 * or even for rewrites. Since this happens extremely rarely,
4472 * it does not hurt performance.
4473 */
4474 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4475 int stripped_before = 0;
4476 int stripped_after = 0;
4477
4478 if (att_end != equal) {
4479 memmove(att_end, equal, hdr_end - equal);
4480 stripped_before = (att_end - equal);
4481 equal += stripped_before;
4482 val_beg += stripped_before;
4483 }
4484
4485 if (val_beg > equal + 1) {
4486 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4487 stripped_after = (equal + 1) - val_beg;
4488 val_beg += stripped_after;
4489 stripped_before += stripped_after;
4490 }
4491
4492 val_end += stripped_before;
4493 next += stripped_before;
4494 hdr_end += stripped_before;
4495
Christopher Faulet41dc8432019-06-18 09:49:16 +02004496 htx_change_blk_value_len(htx, ctx.blk, hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004497 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004498 }
4499
4500 /* First, let's see if we want to capture this cookie. We check
4501 * that we don't already have a server side cookie, because we
4502 * can only capture one. Also as an optimisation, we ignore
4503 * cookies shorter than the declared name.
4504 */
4505 if (sess->fe->capture_name != NULL &&
4506 txn->srv_cookie == NULL &&
4507 (val_end - att_beg >= sess->fe->capture_namelen) &&
4508 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4509 int log_len = val_end - att_beg;
4510 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4511 ha_alert("HTTP logging : out of memory.\n");
4512 }
4513 else {
4514 if (log_len > sess->fe->capture_len)
4515 log_len = sess->fe->capture_len;
4516 memcpy(txn->srv_cookie, att_beg, log_len);
4517 txn->srv_cookie[log_len] = 0;
4518 }
4519 }
4520
4521 srv = objt_server(s->target);
4522 /* now check if we need to process it for persistence */
4523 if (!(s->flags & SF_IGNORE_PRST) &&
4524 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4525 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4526 /* assume passive cookie by default */
4527 txn->flags &= ~TX_SCK_MASK;
4528 txn->flags |= TX_SCK_FOUND;
4529
4530 /* If the cookie is in insert mode on a known server, we'll delete
4531 * this occurrence because we'll insert another one later.
4532 * We'll delete it too if the "indirect" option is set and we're in
4533 * a direct access.
4534 */
4535 if (s->be->ck_opts & PR_CK_PSV) {
4536 /* The "preserve" flag was set, we don't want to touch the
4537 * server's cookie.
4538 */
4539 }
4540 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4541 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4542 /* this cookie must be deleted */
4543 if (prev == hdr_beg && next == hdr_end) {
4544 /* whole header */
4545 http_remove_header(htx, &ctx);
4546 /* note: while both invalid now, <next> and <hdr_end>
4547 * are still equal, so the for() will stop as expected.
4548 */
4549 } else {
4550 /* just remove the value */
4551 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4552 next = prev;
4553 hdr_end += delta;
4554 }
4555 txn->flags &= ~TX_SCK_MASK;
4556 txn->flags |= TX_SCK_DELETED;
4557 /* and go on with next cookie */
4558 }
4559 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4560 /* replace bytes val_beg->val_end with the cookie name associated
4561 * with this server since we know it.
4562 */
4563 int sliding, delta;
4564
4565 ctx.value = ist2(val_beg, val_end - val_beg);
4566 ctx.lws_before = ctx.lws_after = 0;
4567 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4568 delta = srv->cklen - (val_end - val_beg);
4569 sliding = (ctx.value.ptr - val_beg);
4570 hdr_beg += sliding;
4571 val_beg += sliding;
4572 next += sliding + delta;
4573 hdr_end += sliding + delta;
4574
4575 txn->flags &= ~TX_SCK_MASK;
4576 txn->flags |= TX_SCK_REPLACED;
4577 }
4578 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4579 /* insert the cookie name associated with this server
4580 * before existing cookie, and insert a delimiter between them..
4581 */
4582 int sliding, delta;
4583 ctx.value = ist2(val_beg, 0);
4584 ctx.lws_before = ctx.lws_after = 0;
4585 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4586 delta = srv->cklen + 1;
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 val_beg[srv->cklen] = COOKIE_DELIM;
4594 txn->flags &= ~TX_SCK_MASK;
4595 txn->flags |= TX_SCK_REPLACED;
4596 }
4597 }
4598 /* that's done for this cookie, check the next one on the same
4599 * line when next != hdr_end (only if is_cookie2).
4600 */
4601 }
4602 }
4603}
4604
Christopher Faulet25a02f62018-10-24 12:00:25 +02004605/*
4606 * Parses the Cache-Control and Pragma request header fields to determine if
4607 * the request may be served from the cache and/or if it is cacheable. Updates
4608 * s->txn->flags.
4609 */
4610void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4611{
4612 struct http_txn *txn = s->txn;
4613 struct htx *htx;
4614 int32_t pos;
4615 int pragma_found, cc_found, i;
4616
4617 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4618 return; /* nothing more to do here */
4619
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004620 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004621 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004622 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004623 struct htx_blk *blk = htx_get_blk(htx, pos);
4624 enum htx_blk_type type = htx_get_blk_type(blk);
4625 struct ist n, v;
4626
4627 if (type == HTX_BLK_EOH)
4628 break;
4629 if (type != HTX_BLK_HDR)
4630 continue;
4631
4632 n = htx_get_blk_name(htx, blk);
4633 v = htx_get_blk_value(htx, blk);
4634
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004635 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004636 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4637 pragma_found = 1;
4638 continue;
4639 }
4640 }
4641
4642 /* Don't use the cache and don't try to store if we found the
4643 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004644 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004645 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4646 txn->flags |= TX_CACHE_IGNORE;
4647 continue;
4648 }
4649
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004650 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004651 continue;
4652
4653 /* OK, right now we know we have a cache-control header */
4654 cc_found = 1;
4655 if (!v.len) /* no info */
4656 continue;
4657
4658 i = 0;
4659 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4660 !isspace((unsigned char)*(v.ptr+i)))
4661 i++;
4662
4663 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4664 * values after max-age, max-stale nor min-fresh, we simply don't
4665 * use the cache when they're specified.
4666 */
4667 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4668 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4669 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4670 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4671 txn->flags |= TX_CACHE_IGNORE;
4672 continue;
4673 }
4674
4675 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4676 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4677 continue;
4678 }
4679 }
4680
4681 /* RFC7234#5.4:
4682 * When the Cache-Control header field is also present and
4683 * understood in a request, Pragma is ignored.
4684 * When the Cache-Control header field is not present in a
4685 * request, caches MUST consider the no-cache request
4686 * pragma-directive as having the same effect as if
4687 * "Cache-Control: no-cache" were present.
4688 */
4689 if (!cc_found && pragma_found)
4690 txn->flags |= TX_CACHE_IGNORE;
4691}
4692
4693/*
4694 * Check if response is cacheable or not. Updates s->txn->flags.
4695 */
4696void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4697{
4698 struct http_txn *txn = s->txn;
4699 struct htx *htx;
4700 int32_t pos;
4701 int i;
4702
4703 if (txn->status < 200) {
4704 /* do not try to cache interim responses! */
4705 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4706 return;
4707 }
4708
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004709 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004710 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004711 struct htx_blk *blk = htx_get_blk(htx, pos);
4712 enum htx_blk_type type = htx_get_blk_type(blk);
4713 struct ist n, v;
4714
4715 if (type == HTX_BLK_EOH)
4716 break;
4717 if (type != HTX_BLK_HDR)
4718 continue;
4719
4720 n = htx_get_blk_name(htx, blk);
4721 v = htx_get_blk_value(htx, blk);
4722
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004723 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004724 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4725 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4726 return;
4727 }
4728 }
4729
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004730 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004731 continue;
4732
4733 /* OK, right now we know we have a cache-control header */
4734 if (!v.len) /* no info */
4735 continue;
4736
4737 i = 0;
4738 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4739 !isspace((unsigned char)*(v.ptr+i)))
4740 i++;
4741
4742 /* we have a complete value between v.ptr and (v.ptr+i) */
4743 if (i < v.len && *(v.ptr + i) == '=') {
4744 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4745 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4746 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4747 continue;
4748 }
4749
4750 /* we have something of the form no-cache="set-cookie" */
4751 if ((v.len >= 21) &&
4752 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4753 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4754 txn->flags &= ~TX_CACHE_COOK;
4755 continue;
4756 }
4757
4758 /* OK, so we know that either p2 points to the end of string or to a comma */
4759 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4760 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4761 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4762 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4763 return;
4764 }
4765
4766 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4767 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4768 continue;
4769 }
4770 }
4771}
4772
Christopher Faulet64159df2018-10-24 21:15:35 +02004773/* send a server's name with an outgoing request over an established connection.
4774 * Note: this function is designed to be called once the request has been
4775 * scheduled for being forwarded. This is the reason why the number of forwarded
4776 * bytes have to be adjusted.
4777 */
4778int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4779{
4780 struct htx *htx;
4781 struct http_hdr_ctx ctx;
4782 struct ist hdr;
4783 uint32_t data;
4784
4785 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004786 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004787 data = htx->data;
4788
4789 ctx.blk = NULL;
4790 while (http_find_header(htx, hdr, &ctx, 1))
4791 http_remove_header(htx, &ctx);
4792 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4793
4794 if (co_data(&s->req)) {
4795 if (data >= htx->data)
4796 c_rew(&s->req, data - htx->data);
4797 else
4798 c_adv(&s->req, htx->data - data);
4799 }
4800 return 0;
4801}
4802
Christopher Faulet377c5a52018-10-24 21:21:30 +02004803/*
4804 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4805 * for the current backend.
4806 *
4807 * It is assumed that the request is either a HEAD, GET, or POST and that the
4808 * uri_auth field is valid.
4809 *
4810 * Returns 1 if stats should be provided, otherwise 0.
4811 */
4812static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4813{
4814 struct uri_auth *uri_auth = backend->uri_auth;
4815 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004816 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004817 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004818
4819 if (!uri_auth)
4820 return 0;
4821
4822 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4823 return 0;
4824
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004825 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004826 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004827 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004828
4829 /* check URI size */
4830 if (uri_auth->uri_len > uri.len)
4831 return 0;
4832
4833 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4834 return 0;
4835
4836 return 1;
4837}
4838
4839/* This function prepares an applet to handle the stats. It can deal with the
4840 * "100-continue" expectation, check that admin rules are met for POST requests,
4841 * and program a response message if something was unexpected. It cannot fail
4842 * and always relies on the stats applet to complete the job. It does not touch
4843 * analysers nor counters, which are left to the caller. It does not touch
4844 * s->target which is supposed to already point to the stats applet. The caller
4845 * is expected to have already assigned an appctx to the stream.
4846 */
4847static int htx_handle_stats(struct stream *s, struct channel *req)
4848{
4849 struct stats_admin_rule *stats_admin_rule;
4850 struct stream_interface *si = &s->si[1];
4851 struct session *sess = s->sess;
4852 struct http_txn *txn = s->txn;
4853 struct http_msg *msg = &txn->req;
4854 struct uri_auth *uri_auth = s->be->uri_auth;
4855 const char *h, *lookup, *end;
4856 struct appctx *appctx;
4857 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004858 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004859
4860 appctx = si_appctx(si);
4861 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4862 appctx->st1 = appctx->st2 = 0;
4863 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4864 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4865 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4866 appctx->ctx.stats.flags |= STAT_CHUNKED;
4867
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004868 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004869 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004870 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4871 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004872
4873 for (h = lookup; h <= end - 3; h++) {
4874 if (memcmp(h, ";up", 3) == 0) {
4875 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4876 break;
4877 }
4878 }
4879
4880 if (uri_auth->refresh) {
4881 for (h = lookup; h <= end - 10; h++) {
4882 if (memcmp(h, ";norefresh", 10) == 0) {
4883 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4884 break;
4885 }
4886 }
4887 }
4888
4889 for (h = lookup; h <= end - 4; h++) {
4890 if (memcmp(h, ";csv", 4) == 0) {
4891 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4892 break;
4893 }
4894 }
4895
4896 for (h = lookup; h <= end - 6; h++) {
4897 if (memcmp(h, ";typed", 6) == 0) {
4898 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4899 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4900 break;
4901 }
4902 }
4903
4904 for (h = lookup; h <= end - 8; h++) {
4905 if (memcmp(h, ";st=", 4) == 0) {
4906 int i;
4907 h += 4;
4908 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4909 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4910 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4911 appctx->ctx.stats.st_code = i;
4912 break;
4913 }
4914 }
4915 break;
4916 }
4917 }
4918
4919 appctx->ctx.stats.scope_str = 0;
4920 appctx->ctx.stats.scope_len = 0;
4921 for (h = lookup; h <= end - 8; h++) {
4922 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4923 int itx = 0;
4924 const char *h2;
4925 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4926 const char *err;
4927
4928 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4929 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004930 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4931 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004932 if (*h == ';' || *h == '&' || *h == ' ')
4933 break;
4934 itx++;
4935 h++;
4936 }
4937
4938 if (itx > STAT_SCOPE_TXT_MAXLEN)
4939 itx = STAT_SCOPE_TXT_MAXLEN;
4940 appctx->ctx.stats.scope_len = itx;
4941
4942 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4943 memcpy(scope_txt, h2, itx);
4944 scope_txt[itx] = '\0';
4945 err = invalid_char(scope_txt);
4946 if (err) {
4947 /* bad char in search text => clear scope */
4948 appctx->ctx.stats.scope_str = 0;
4949 appctx->ctx.stats.scope_len = 0;
4950 }
4951 break;
4952 }
4953 }
4954
4955 /* now check whether we have some admin rules for this request */
4956 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4957 int ret = 1;
4958
4959 if (stats_admin_rule->cond) {
4960 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4961 ret = acl_pass(ret);
4962 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4963 ret = !ret;
4964 }
4965
4966 if (ret) {
4967 /* no rule, or the rule matches */
4968 appctx->ctx.stats.flags |= STAT_ADMIN;
4969 break;
4970 }
4971 }
4972
Christopher Faulet5d45e382019-02-27 15:15:23 +01004973 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4974 appctx->st0 = STAT_HTTP_HEAD;
4975 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004976 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004977 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004978 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004979 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004980 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4981 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4982 appctx->st0 = STAT_HTTP_LAST;
4983 }
4984 }
4985 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004986 /* Unsupported method */
4987 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4988 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4989 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004990 }
4991
4992 s->task->nice = -32; /* small boost for HTTP statistics */
4993 return 1;
4994}
4995
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004996void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4997{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004998 struct channel *req = &s->req;
4999 struct channel *res = &s->res;
5000 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005001 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005002 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 struct ist path, location;
5004 unsigned int flags;
5005 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005006
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005007 /*
5008 * Create the location
5009 */
5010 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005013 /* special prefix "/" means don't change URL */
5014 srv = __objt_server(s->target);
5015 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5016 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5017 return;
5018 }
5019
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005020 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005021 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005022 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005023 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005024 if (!path.ptr)
5025 return;
5026
5027 if (!chunk_memcat(&trash, path.ptr, path.len))
5028 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005030
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005031 /*
5032 * Create the 302 respone
5033 */
5034 htx = htx_from_buf(&res->buf);
5035 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5036 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5037 ist("HTTP/1.1"), ist("302"), ist("Found"));
5038 if (!sl)
5039 goto fail;
5040 sl->info.res.status = 302;
5041 s->txn->status = 302;
5042
5043 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5044 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5045 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5046 !htx_add_header(htx, ist("Location"), location))
5047 goto fail;
5048
5049 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5050 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005052 /*
5053 * Send the message
5054 */
5055 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005056 c_adv(res, data);
5057 res->total += data;
5058
5059 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005060 si_shutr(si);
5061 si_shutw(si);
5062 si->err_type = SI_ET_NONE;
5063 si->state = SI_ST_CLO;
5064
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005065 channel_auto_read(req);
5066 channel_abort(req);
5067 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005068 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005069 channel_auto_read(res);
5070 channel_auto_close(res);
5071
5072 if (!(s->flags & SF_ERR_MASK))
5073 s->flags |= SF_ERR_LOCAL;
5074 if (!(s->flags & SF_FINST_MASK))
5075 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005076
5077 /* FIXME: we should increase a counter of redirects per server and per backend. */
5078 srv_inc_sess_ctr(srv);
5079 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005080 return;
5081
5082 fail:
5083 /* If an error occurred, remove the incomplete HTTP response from the
5084 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005085 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005086}
5087
Christopher Fauletf2824e62018-10-01 12:12:37 +02005088/* This function terminates the request because it was completly analyzed or
5089 * because an error was triggered during the body forwarding.
5090 */
5091static void htx_end_request(struct stream *s)
5092{
5093 struct channel *chn = &s->req;
5094 struct http_txn *txn = s->txn;
5095
5096 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5097 now_ms, __FUNCTION__, s,
5098 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5099 s->req.analysers, s->res.analysers);
5100
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005101 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5102 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005104 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005105 goto end;
5106 }
5107
5108 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5109 return;
5110
5111 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005112 /* No need to read anymore, the request was completely parsed.
5113 * We can shut the read side unless we want to abort_on_close,
5114 * or we have a POST request. The issue with POST requests is
5115 * that some browsers still send a CRLF after the request, and
5116 * this CRLF must be read so that it does not remain in the kernel
5117 * buffers, otherwise a close could cause an RST on some systems
5118 * (eg: Linux).
5119 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005120 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121 channel_dont_read(chn);
5122
5123 /* if the server closes the connection, we want to immediately react
5124 * and close the socket to save packets and syscalls.
5125 */
5126 s->si[1].flags |= SI_FL_NOHALF;
5127
5128 /* In any case we've finished parsing the request so we must
5129 * disable Nagle when sending data because 1) we're not going
5130 * to shut this side, and 2) the server is waiting for us to
5131 * send pending data.
5132 */
5133 chn->flags |= CF_NEVER_WAIT;
5134
Christopher Fauletd01ce402019-01-02 17:44:13 +01005135 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5136 /* The server has not finished to respond, so we
5137 * don't want to move in order not to upset it.
5138 */
5139 return;
5140 }
5141
Christopher Fauletf2824e62018-10-01 12:12:37 +02005142 /* When we get here, it means that both the request and the
5143 * response have finished receiving. Depending on the connection
5144 * mode, we'll have to wait for the last bytes to leave in either
5145 * direction, and sometimes for a close to be effective.
5146 */
5147 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5148 /* Tunnel mode will not have any analyser so it needs to
5149 * poll for reads.
5150 */
5151 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005152 if (b_data(&chn->buf))
5153 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005154 txn->req.msg_state = HTTP_MSG_TUNNEL;
5155 }
5156 else {
5157 /* we're not expecting any new data to come for this
5158 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005159 *
5160 * However, there is an exception if the response
5161 * length is undefined. In this case, we need to wait
5162 * the close from the server. The response will be
5163 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005164 */
5165 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5166 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005167 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168
5169 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5170 channel_shutr_now(chn);
5171 channel_shutw_now(chn);
5172 }
5173 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005174 goto check_channel_flags;
5175 }
5176
5177 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5178 http_msg_closing:
5179 /* nothing else to forward, just waiting for the output buffer
5180 * to be empty and for the shutw_now to take effect.
5181 */
5182 if (channel_is_empty(chn)) {
5183 txn->req.msg_state = HTTP_MSG_CLOSED;
5184 goto http_msg_closed;
5185 }
5186 else if (chn->flags & CF_SHUTW) {
5187 txn->req.err_state = txn->req.msg_state;
5188 txn->req.msg_state = HTTP_MSG_ERROR;
5189 goto end;
5190 }
5191 return;
5192 }
5193
5194 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5195 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005196 /* if we don't know whether the server will close, we need to hard close */
5197 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5198 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005199 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005200 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005201 channel_dont_read(chn);
5202 goto end;
5203 }
5204
5205 check_channel_flags:
5206 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5207 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5208 /* if we've just closed an output, let's switch */
5209 txn->req.msg_state = HTTP_MSG_CLOSING;
5210 goto http_msg_closing;
5211 }
5212
5213 end:
5214 chn->analysers &= AN_REQ_FLT_END;
5215 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5216 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5217 channel_auto_close(chn);
5218 channel_auto_read(chn);
5219}
5220
5221
5222/* This function terminates the response because it was completly analyzed or
5223 * because an error was triggered during the body forwarding.
5224 */
5225static void htx_end_response(struct stream *s)
5226{
5227 struct channel *chn = &s->res;
5228 struct http_txn *txn = s->txn;
5229
5230 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5231 now_ms, __FUNCTION__, s,
5232 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5233 s->req.analysers, s->res.analysers);
5234
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005235 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5236 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005237 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005238 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005239 goto end;
5240 }
5241
5242 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5243 return;
5244
5245 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5246 /* In theory, we don't need to read anymore, but we must
5247 * still monitor the server connection for a possible close
5248 * while the request is being uploaded, so we don't disable
5249 * reading.
5250 */
5251 /* channel_dont_read(chn); */
5252
5253 if (txn->req.msg_state < HTTP_MSG_DONE) {
5254 /* The client seems to still be sending data, probably
5255 * because we got an error response during an upload.
5256 * We have the choice of either breaking the connection
5257 * or letting it pass through. Let's do the later.
5258 */
5259 return;
5260 }
5261
5262 /* When we get here, it means that both the request and the
5263 * response have finished receiving. Depending on the connection
5264 * mode, we'll have to wait for the last bytes to leave in either
5265 * direction, and sometimes for a close to be effective.
5266 */
5267 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5268 channel_auto_read(chn);
5269 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005270 if (b_data(&chn->buf))
5271 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005272 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5273 }
5274 else {
5275 /* we're not expecting any new data to come for this
5276 * transaction, so we can close it.
5277 */
5278 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5279 channel_shutr_now(chn);
5280 channel_shutw_now(chn);
5281 }
5282 }
5283 goto check_channel_flags;
5284 }
5285
5286 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5287 http_msg_closing:
5288 /* nothing else to forward, just waiting for the output buffer
5289 * to be empty and for the shutw_now to take effect.
5290 */
5291 if (channel_is_empty(chn)) {
5292 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5293 goto http_msg_closed;
5294 }
5295 else if (chn->flags & CF_SHUTW) {
5296 txn->rsp.err_state = txn->rsp.msg_state;
5297 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005298 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005299 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005300 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005301 goto end;
5302 }
5303 return;
5304 }
5305
5306 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5307 http_msg_closed:
5308 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005309 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005310 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005311 goto end;
5312 }
5313
5314 check_channel_flags:
5315 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5316 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5317 /* if we've just closed an output, let's switch */
5318 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5319 goto http_msg_closing;
5320 }
5321
5322 end:
5323 chn->analysers &= AN_RES_FLT_END;
5324 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5325 chn->analysers |= AN_RES_FLT_XFER_DATA;
5326 channel_auto_close(chn);
5327 channel_auto_read(chn);
5328}
5329
Christopher Faulet0f226952018-10-22 09:29:56 +02005330void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5331 int finst, const struct buffer *msg)
5332{
5333 channel_auto_read(si_oc(si));
5334 channel_abort(si_oc(si));
5335 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005336 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005337 channel_auto_close(si_ic(si));
5338 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005339
5340 /* <msg> is an HTX structure. So we copy it in the response's
5341 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005342 if (msg) {
5343 struct channel *chn = si_ic(si);
5344 struct htx *htx;
5345
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005346 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005347 chn->buf.data = msg->data;
5348 memcpy(chn->buf.area, msg->area, msg->data);
5349 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005350 c_adv(chn, htx->data);
5351 chn->total += htx->data;
5352 }
5353 if (!(s->flags & SF_ERR_MASK))
5354 s->flags |= err;
5355 if (!(s->flags & SF_FINST_MASK))
5356 s->flags |= finst;
5357}
5358
5359void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5360{
5361 channel_auto_read(&s->req);
5362 channel_abort(&s->req);
5363 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005364 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5365 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005366
5367 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005368
5369 /* <msg> is an HTX structure. So we copy it in the response's
5370 * channel */
5371 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005372 if (msg) {
5373 struct channel *chn = &s->res;
5374 struct htx *htx;
5375
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005376 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005377 chn->buf.data = msg->data;
5378 memcpy(chn->buf.area, msg->area, msg->data);
5379 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005380 c_adv(chn, htx->data);
5381 chn->total += htx->data;
5382 }
5383
5384 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5385 channel_auto_read(&s->res);
5386 channel_auto_close(&s->res);
5387 channel_shutr_now(&s->res);
5388}
5389
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005390struct buffer *htx_error_message(struct stream *s)
5391{
5392 const int msgnum = http_get_status_idx(s->txn->status);
5393
5394 if (s->be->errmsg[msgnum].area)
5395 return &s->be->errmsg[msgnum];
5396 else if (strm_fe(s)->errmsg[msgnum].area)
5397 return &strm_fe(s)->errmsg[msgnum];
5398 else
5399 return &htx_err_chunks[msgnum];
5400}
5401
5402
Christopher Faulet4a28a532019-03-01 11:19:40 +01005403/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5404 * on success and -1 on error.
5405 */
5406static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5407{
5408 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5409 * then we must send an HTTP/1.1 100 Continue intermediate response.
5410 */
5411 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5412 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5413 struct ist hdr = { .ptr = "Expect", .len = 6 };
5414 struct http_hdr_ctx ctx;
5415
5416 ctx.blk = NULL;
5417 /* Expect is allowed in 1.1, look for it */
5418 if (http_find_header(htx, hdr, &ctx, 0) &&
5419 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5420 if (htx_reply_100_continue(s) == -1)
5421 return -1;
5422 http_remove_header(htx, &ctx);
5423 }
5424 }
5425 return 0;
5426}
5427
Christopher Faulet23a3c792018-11-28 10:01:23 +01005428/* Send a 100-Continue response to the client. It returns 0 on success and -1
5429 * on error. The response channel is updated accordingly.
5430 */
5431static int htx_reply_100_continue(struct stream *s)
5432{
5433 struct channel *res = &s->res;
5434 struct htx *htx = htx_from_buf(&res->buf);
5435 struct htx_sl *sl;
5436 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5437 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5438 size_t data;
5439
5440 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5441 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5442 if (!sl)
5443 goto fail;
5444 sl->info.res.status = 100;
5445
Christopher Faulet9869f932019-06-26 14:23:54 +02005446 if (!htx_add_endof(htx, HTX_BLK_EOH))
Christopher Faulet23a3c792018-11-28 10:01:23 +01005447 goto fail;
5448
5449 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005450 c_adv(res, data);
5451 res->total += data;
5452 return 0;
5453
5454 fail:
5455 /* If an error occurred, remove the incomplete HTTP response from the
5456 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005457 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005458 return -1;
5459}
5460
Christopher Faulet12c51e22018-11-28 15:59:42 +01005461
5462/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5463 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5464 * error. The response channel is updated accordingly.
5465 */
5466static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5467{
5468 struct channel *res = &s->res;
5469 struct htx *htx = htx_from_buf(&res->buf);
5470 struct htx_sl *sl;
5471 struct ist code, body;
5472 int status;
5473 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5474 size_t data;
5475
5476 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5477 status = 401;
5478 code = ist("401");
5479 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5480 "You need a valid user and password to access this content.\n"
5481 "</body></html>\n");
5482 }
5483 else {
5484 status = 407;
5485 code = ist("407");
5486 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5487 "You need a valid user and password to access this content.\n"
5488 "</body></html>\n");
5489 }
5490
5491 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5492 ist("HTTP/1.1"), code, ist("Unauthorized"));
5493 if (!sl)
5494 goto fail;
5495 sl->info.res.status = status;
5496 s->txn->status = status;
5497
5498 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5499 goto fail;
5500
Willy Tarreaub5ba2b02019-06-11 16:08:25 +02005501 if (!htx_add_header(htx, ist("Content-length"), ist("112")) ||
5502 !htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
Christopher Faulet12c51e22018-11-28 15:59:42 +01005503 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005504 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5505 goto fail;
5506 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5507 goto fail;
5508 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005509 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005510 if (!htx_add_endof(htx, HTX_BLK_EOH))
5511 goto fail;
5512
5513 while (body.len) {
5514 size_t sent = htx_add_data(htx, body);
5515 if (!sent)
5516 goto fail;
5517 body.ptr += sent;
5518 body.len -= sent;
5519 }
5520
5521 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005522 goto fail;
5523
5524 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005525 c_adv(res, data);
5526 res->total += data;
5527
5528 channel_auto_read(&s->req);
5529 channel_abort(&s->req);
5530 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005531 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005532
5533 res->wex = tick_add_ifset(now_ms, res->wto);
5534 channel_auto_read(res);
5535 channel_auto_close(res);
5536 channel_shutr_now(res);
5537 return 0;
5538
5539 fail:
5540 /* If an error occurred, remove the incomplete HTTP response from the
5541 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005542 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005543 return -1;
5544}
5545
Christopher Faulet0f226952018-10-22 09:29:56 +02005546/*
5547 * Capture headers from message <htx> according to header list <cap_hdr>, and
5548 * fill the <cap> pointers appropriately.
5549 */
5550static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5551{
5552 struct cap_hdr *h;
5553 int32_t pos;
5554
Christopher Fauleta3f15502019-05-13 15:27:23 +02005555 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005556 struct htx_blk *blk = htx_get_blk(htx, pos);
5557 enum htx_blk_type type = htx_get_blk_type(blk);
5558 struct ist n, v;
5559
5560 if (type == HTX_BLK_EOH)
5561 break;
5562 if (type != HTX_BLK_HDR)
5563 continue;
5564
5565 n = htx_get_blk_name(htx, blk);
5566
5567 for (h = cap_hdr; h; h = h->next) {
5568 if (h->namelen && (h->namelen == n.len) &&
5569 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5570 if (cap[h->index] == NULL)
5571 cap[h->index] =
5572 pool_alloc(h->pool);
5573
5574 if (cap[h->index] == NULL) {
5575 ha_alert("HTTP capture : out of memory.\n");
5576 break;
5577 }
5578
5579 v = htx_get_blk_value(htx, blk);
5580 if (v.len > h->len)
5581 v.len = h->len;
5582
5583 memcpy(cap[h->index], v.ptr, v.len);
5584 cap[h->index][v.len]=0;
5585 }
5586 }
5587 }
5588}
5589
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005590/* Delete a value in a header between delimiters <from> and <next>. The header
5591 * itself is delimited by <start> and <end> pointers. The number of characters
5592 * displaced is returned, and the pointer to the first delimiter is updated if
5593 * required. The function tries as much as possible to respect the following
5594 * principles :
5595 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5596 * in which case <next> is simply removed
5597 * - set exactly one space character after the new first delimiter, unless there
5598 * are not enough characters in the block being moved to do so.
5599 * - remove unneeded spaces before the previous delimiter and after the new
5600 * one.
5601 *
5602 * It is the caller's responsibility to ensure that :
5603 * - <from> points to a valid delimiter or <start> ;
5604 * - <next> points to a valid delimiter or <end> ;
5605 * - there are non-space chars before <from>.
5606 */
5607static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5608{
5609 char *prev = *from;
5610
5611 if (prev == start) {
5612 /* We're removing the first value. eat the semicolon, if <next>
5613 * is lower than <end> */
5614 if (next < end)
5615 next++;
5616
5617 while (next < end && HTTP_IS_SPHT(*next))
5618 next++;
5619 }
5620 else {
5621 /* Remove useless spaces before the old delimiter. */
5622 while (HTTP_IS_SPHT(*(prev-1)))
5623 prev--;
5624 *from = prev;
5625
5626 /* copy the delimiter and if possible a space if we're
5627 * not at the end of the line.
5628 */
5629 if (next < end) {
5630 *prev++ = *next++;
5631 if (prev + 1 < next)
5632 *prev++ = ' ';
5633 while (next < end && HTTP_IS_SPHT(*next))
5634 next++;
5635 }
5636 }
5637 memmove(prev, next, end - next);
5638 return (prev - next);
5639}
5640
Christopher Faulet0f226952018-10-22 09:29:56 +02005641
5642/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005643 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005645static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005646{
5647 struct ist dst = ist2(str, 0);
5648
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005649 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005650 goto end;
5651 if (dst.len + 1 > len)
5652 goto end;
5653 dst.ptr[dst.len++] = ' ';
5654
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005655 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005656 goto end;
5657 if (dst.len + 1 > len)
5658 goto end;
5659 dst.ptr[dst.len++] = ' ';
5660
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005661 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005662 end:
5663 return dst.len;
5664}
5665
Christopher Fauletf0523542018-10-24 11:06:58 +02005666/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005667 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005668 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005669static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005670{
5671 struct ist dst = ist2(str, 0);
5672
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005673 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005674 goto end;
5675 if (dst.len + 1 > len)
5676 goto end;
5677 dst.ptr[dst.len++] = ' ';
5678
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005679 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005680 goto end;
5681 if (dst.len + 1 > len)
5682 goto end;
5683 dst.ptr[dst.len++] = ' ';
5684
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005685 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005686 end:
5687 return dst.len;
5688}
5689
5690
Christopher Faulet0f226952018-10-22 09:29:56 +02005691/*
5692 * Print a debug line with a start line.
5693 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005694static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005695{
5696 struct session *sess = strm_sess(s);
5697 int max;
5698
5699 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5700 dir,
5701 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5702 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5703
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005707 trash.area[trash.data++] = ' ';
5708
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005709 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 trash.area[trash.data++] = ' ';
5713
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005714 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005715 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005716 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005717 trash.area[trash.data++] = '\n';
5718
5719 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5720}
5721
5722/*
5723 * Print a debug line with a header.
5724 */
5725static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5726{
5727 struct session *sess = strm_sess(s);
5728 int max;
5729
5730 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5731 dir,
5732 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5733 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5734
5735 max = n.len;
5736 UBOUND(max, trash.size - trash.data - 3);
5737 chunk_memcat(&trash, n.ptr, max);
5738 trash.area[trash.data++] = ':';
5739 trash.area[trash.data++] = ' ';
5740
5741 max = v.len;
5742 UBOUND(max, trash.size - trash.data - 1);
5743 chunk_memcat(&trash, v.ptr, max);
5744 trash.area[trash.data++] = '\n';
5745
5746 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5747}
5748
5749
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005750__attribute__((constructor))
5751static void __htx_protocol_init(void)
5752{
5753}
5754
5755
5756/*
5757 * Local variables:
5758 * c-indent-level: 8
5759 * c-basic-offset: 8
5760 * End:
5761 */