blob: 27150a8ed5cd1e7d7634365505b903b3dbe2cd2f [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 Fauletf76ebe82018-10-24 11:16:22 +02001075 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
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 Fauletee847d42019-05-23 11:55:33 +02001223 channel_htx_fwd_payload(req, htx, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 if (htx->data != co_data(req) || htx->extra)
1225 goto missing_data_or_waiting;
1226 }
1227 else {
Christopher Faulet16af60e2019-05-23 11:53:17 +02001228 channel_htx_fwd_all(req, htx);
Christopher Faulet66af0b22019-03-22 14:54:52 +01001229 if (msg->flags & HTTP_MSGF_XFER_LEN)
1230 channel_htx_forward_forever(req, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001231 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001232
Christopher Fauletc62c2b92019-03-28 11:41:39 +01001233 if (txn->meth == HTTP_METH_CONNECT) {
1234 msg->msg_state = HTTP_MSG_TUNNEL;
1235 goto done;
1236 }
1237
Christopher Faulet9768c262018-10-22 09:34:31 +02001238 /* Check if the end-of-message is reached and if so, switch the message
1239 * in HTTP_MSG_DONE state.
1240 */
1241 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1242 goto missing_data_or_waiting;
1243
1244 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01001245 req->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001246
1247 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001248 /* other states, DONE...TUNNEL */
1249 /* we don't want to forward closes on DONE except in tunnel mode. */
1250 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1251 channel_dont_close(req);
1252
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001253 if (HAS_REQ_DATA_FILTERS(s)) {
1254 ret = flt_http_end(s, msg);
1255 if (ret <= 0) {
1256 if (!ret)
1257 goto missing_data_or_waiting;
1258 goto return_bad_req;
1259 }
1260 }
1261
Christopher Fauletf2824e62018-10-01 12:12:37 +02001262 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001263 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001264 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001265 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1266 if (req->flags & CF_SHUTW) {
1267 /* request errors are most likely due to the
1268 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001269 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001270 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 goto return_bad_req;
1272 }
1273 return 1;
1274 }
1275
1276 /* If "option abortonclose" is set on the backend, we want to monitor
1277 * the client's connection and forward any shutdown notification to the
1278 * server, which will decide whether to close or to go on processing the
1279 * request. We only do that in tunnel mode, and not in other modes since
1280 * it can be abused to exhaust source ports. */
Christopher Faulet769d0e92019-03-22 14:23:18 +01001281 if (s->be->options & PR_O_ABRT_CLOSE) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 channel_auto_read(req);
1283 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1284 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1285 s->si[1].flags |= SI_FL_NOLINGER;
1286 channel_auto_close(req);
1287 }
1288 else if (s->txn->meth == HTTP_METH_POST) {
1289 /* POST requests may require to read extra CRLF sent by broken
1290 * browsers and which could cause an RST to be sent upon close
1291 * on some systems (eg: Linux). */
1292 channel_auto_read(req);
1293 }
1294 return 0;
1295
1296 missing_data_or_waiting:
1297 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001298 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1299 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001300
1301 waiting:
1302 /* waiting for the last bits to leave the buffer */
1303 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001304 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001305
Christopher Faulet47365272018-10-31 17:40:50 +01001306 if (htx->flags & HTX_FL_PARSING_ERROR)
1307 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001308
Christopher Faulete0768eb2018-10-03 16:38:02 +02001309 /* When TE: chunked is used, we need to get there again to parse remaining
1310 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1311 * And when content-length is used, we never want to let the possible
1312 * shutdown be forwarded to the other side, as the state machine will
1313 * take care of it once the client responds. It's also important to
1314 * prevent TIME_WAITs from accumulating on the backend side, and for
1315 * HTTP/2 where the last frame comes with a shutdown.
1316 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001317 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001318 channel_dont_close(req);
1319
1320 /* We know that more data are expected, but we couldn't send more that
1321 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1322 * system knows it must not set a PUSH on this first part. Interactive
1323 * modes are already handled by the stream sock layer. We must not do
1324 * this in content-length mode because it could present the MSG_MORE
1325 * flag with the last block of forwarded data, which would cause an
1326 * additional delay to be observed by the receiver.
1327 */
1328 if (msg->flags & HTTP_MSGF_TE_CHNK)
1329 req->flags |= CF_EXPECT_MORE;
1330
1331 return 0;
1332
Christopher Faulet93e02d82019-03-08 14:18:50 +01001333 return_cli_abort:
1334 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1335 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1336 if (objt_server(s->target))
1337 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1338 if (!(s->flags & SF_ERR_MASK))
1339 s->flags |= SF_ERR_CLICL;
1340 status = 400;
1341 goto return_error;
1342
1343 return_srv_abort:
1344 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1345 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1346 if (objt_server(s->target))
1347 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1348 if (!(s->flags & SF_ERR_MASK))
1349 s->flags |= SF_ERR_SRVCL;
1350 status = 502;
1351 goto return_error;
1352
1353 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001354 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001355 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001356 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001357 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001358 s->flags |= SF_ERR_CLICL;
1359 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360
Christopher Faulet93e02d82019-03-08 14:18:50 +01001361 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001362 txn->req.err_state = txn->req.msg_state;
1363 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001364 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001366 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001368 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 }
1371 req->analysers &= AN_REQ_FLT_END;
1372 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 +01001373 if (!(s->flags & SF_FINST_MASK))
1374 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 return 0;
1376}
1377
Olivier Houcharda254a372019-04-05 15:30:12 +02001378/* Reset the stream and the backend stream_interface to a situation suitable for attemption connection */
1379/* Returns 0 if we can attempt to retry, -1 otherwise */
1380static __inline int do_l7_retry(struct stream *s, struct stream_interface *si)
1381{
1382 struct channel *req, *res;
1383 int co_data;
1384
1385 si->conn_retries--;
1386 if (si->conn_retries < 0)
1387 return -1;
1388
Willy Tarreau223995e2019-05-04 10:38:31 +02001389 if (objt_server(s->target))
1390 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.retries, 1);
1391 _HA_ATOMIC_ADD(&s->be->be_counters.retries, 1);
1392
Olivier Houcharda254a372019-04-05 15:30:12 +02001393 req = &s->req;
1394 res = &s->res;
1395 /* Remove any write error from the request, and read error from the response */
1396 req->flags &= ~(CF_WRITE_ERROR | CF_WRITE_TIMEOUT | CF_SHUTW | CF_SHUTW_NOW);
1397 res->flags &= ~(CF_READ_ERROR | CF_READ_TIMEOUT | CF_SHUTR | CF_EOI | CF_READ_NULL | CF_SHUTR_NOW);
1398 res->analysers = 0;
1399 si->flags &= ~(SI_FL_ERR | SI_FL_EXP | SI_FL_RXBLK_SHUT);
1400 si->state = SI_ST_REQ;
1401 si->exp = TICK_ETERNITY;
1402 res->rex = TICK_ETERNITY;
1403 res->to_forward = 0;
1404 res->analyse_exp = TICK_ETERNITY;
1405 res->total = 0;
1406 s->flags &= ~(SF_ASSIGNED | SF_ADDR_SET | SF_ERR_SRVTO | SF_ERR_SRVCL);
1407 si_release_endpoint(&s->si[1]);
1408 b_free(&req->buf);
1409 /* Swap the L7 buffer with the channel buffer */
1410 /* We know we stored the co_data as b_data, so get it there */
1411 co_data = b_data(&si->l7_buffer);
1412 b_set_data(&si->l7_buffer, b_size(&si->l7_buffer));
1413 b_xfer(&req->buf, &si->l7_buffer, b_data(&si->l7_buffer));
1414
1415 co_set_data(req, co_data);
1416 b_reset(&res->buf);
1417 co_set_data(res, 0);
1418 return 0;
1419}
1420
Christopher Faulete0768eb2018-10-03 16:38:02 +02001421/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1422 * processing can continue on next analysers, or zero if it either needs more
1423 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1424 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1425 * when it has nothing left to do, and may remove any analyser when it wants to
1426 * abort.
1427 */
1428int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1429{
Christopher Faulet9768c262018-10-22 09:34:31 +02001430 /*
1431 * We will analyze a complete HTTP response to check the its syntax.
1432 *
1433 * Once the start line and all headers are received, we may perform a
1434 * capture of the error (if any), and we will set a few fields. We also
1435 * logging and finally headers capture.
1436 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001437 struct session *sess = s->sess;
1438 struct http_txn *txn = s->txn;
1439 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001440 struct htx *htx;
Olivier Houcharda254a372019-04-05 15:30:12 +02001441 struct stream_interface *si_b = &s->si[1];
Christopher Faulet61608322018-11-23 16:23:45 +01001442 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001443 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001444 int n;
1445
1446 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1447 now_ms, __FUNCTION__,
1448 s,
1449 rep,
1450 rep->rex, rep->wex,
1451 rep->flags,
1452 ci_data(rep),
1453 rep->analysers);
1454
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001455 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001456
Willy Tarreau4236f032019-03-05 10:43:32 +01001457 /* Parsing errors are caught here */
1458 if (htx->flags & HTX_FL_PARSING_ERROR)
1459 goto return_bad_res;
1460
Christopher Faulete0768eb2018-10-03 16:38:02 +02001461 /*
1462 * Now we quickly check if we have found a full valid response.
1463 * If not so, we check the FD and buffer states before leaving.
1464 * A full response is indicated by the fact that we have seen
1465 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1466 * responses are checked first.
1467 *
1468 * Depending on whether the client is still there or not, we
1469 * may send an error response back or not. Note that normally
1470 * we should only check for HTTP status there, and check I/O
1471 * errors somewhere else.
1472 */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001473 next_one:
Christopher Faulet29f17582019-05-23 11:03:26 +02001474 if (unlikely(htx_is_empty(htx) || htx->first == -1)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001475 /* 1: have we encountered a read error ? */
1476 if (rep->flags & CF_READ_ERROR) {
Olivier Houchard865d8392019-05-03 22:46:27 +02001477 struct connection *conn = NULL;
1478
Olivier Houchard865d8392019-05-03 22:46:27 +02001479 if (objt_cs(s->si[1].end))
1480 conn = objt_cs(s->si[1].end)->conn;
1481
1482 if (si_b->flags & SI_FL_L7_RETRY &&
1483 (!conn || conn->err_code != CO_ER_SSL_EARLY_FAILED)) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001484 /* If we arrive here, then CF_READ_ERROR was
1485 * set by si_cs_recv() because we matched a
1486 * status, overwise it would have removed
1487 * the SI_FL_L7_RETRY flag, so it's ok not
1488 * to check s->be->retry_type.
1489 */
1490 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1491 return 0;
1492 }
1493
Olivier Houchard6db16992019-05-17 15:40:49 +02001494 if (txn->flags & TX_NOT_FIRST)
1495 goto abort_keep_alive;
1496
Olivier Houcharda798bf52019-03-08 18:52:00 +01001497 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001498 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001499 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001500 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 }
1502
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503 rep->analysers &= AN_RES_FLT_END;
1504 txn->status = 502;
1505
1506 /* Check to see if the server refused the early data.
1507 * If so, just send a 425
1508 */
Olivier Houchard865d8392019-05-03 22:46:27 +02001509 if (conn->err_code == CO_ER_SSL_EARLY_FAILED) {
1510 if ((s->be->retry_type & PR_RE_EARLY_ERROR) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001511 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houchard865d8392019-05-03 22:46:27 +02001512 do_l7_retry(s, si_b) == 0)
1513 return 0;
1514 txn->status = 425;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 }
1516
1517 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001518 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519
1520 if (!(s->flags & SF_ERR_MASK))
1521 s->flags |= SF_ERR_SRVCL;
1522 if (!(s->flags & SF_FINST_MASK))
1523 s->flags |= SF_FINST_H;
1524 return 0;
1525 }
1526
Christopher Faulet9768c262018-10-22 09:34:31 +02001527 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001529 if ((si_b->flags & SI_FL_L7_RETRY) &&
1530 (s->be->retry_type & PR_RE_TIMEOUT)) {
1531 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1532 return 0;
1533 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01001534 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001536 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001537 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538 }
1539
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540 rep->analysers &= AN_RES_FLT_END;
1541 txn->status = 504;
1542 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001543 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544
1545 if (!(s->flags & SF_ERR_MASK))
1546 s->flags |= SF_ERR_SRVTO;
1547 if (!(s->flags & SF_FINST_MASK))
1548 s->flags |= SF_FINST_H;
1549 return 0;
1550 }
1551
Christopher Faulet9768c262018-10-22 09:34:31 +02001552 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001554 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1555 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001557 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558
1559 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001561 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562
1563 if (!(s->flags & SF_ERR_MASK))
1564 s->flags |= SF_ERR_CLICL;
1565 if (!(s->flags & SF_FINST_MASK))
1566 s->flags |= SF_FINST_H;
1567
1568 /* process_stream() will take care of the error */
1569 return 0;
1570 }
1571
Christopher Faulet9768c262018-10-22 09:34:31 +02001572 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573 else if (rep->flags & CF_SHUTR) {
Olivier Houcharda254a372019-04-05 15:30:12 +02001574 if ((si_b->flags & SI_FL_L7_RETRY) &&
1575 (s->be->retry_type & PR_RE_DISCONNECTED)) {
1576 if (co_data(rep) || do_l7_retry(s, si_b) == 0)
1577 return 0;
1578 }
1579
Olivier Houchard6db16992019-05-17 15:40:49 +02001580 if (txn->flags & TX_NOT_FIRST)
1581 goto abort_keep_alive;
1582
Olivier Houcharda798bf52019-03-08 18:52:00 +01001583 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001585 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001586 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001587 }
1588
Christopher Faulete0768eb2018-10-03 16:38:02 +02001589 rep->analysers &= AN_RES_FLT_END;
1590 txn->status = 502;
1591 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001592 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001593
1594 if (!(s->flags & SF_ERR_MASK))
1595 s->flags |= SF_ERR_SRVCL;
1596 if (!(s->flags & SF_FINST_MASK))
1597 s->flags |= SF_FINST_H;
1598 return 0;
1599 }
1600
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001602 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001603 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001604 goto abort_keep_alive;
1605
Olivier Houcharda798bf52019-03-08 18:52:00 +01001606 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001607 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001608
1609 if (!(s->flags & SF_ERR_MASK))
1610 s->flags |= SF_ERR_CLICL;
1611 if (!(s->flags & SF_FINST_MASK))
1612 s->flags |= SF_FINST_H;
1613
1614 /* process_stream() will take care of the error */
1615 return 0;
1616 }
1617
1618 channel_dont_close(rep);
1619 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1620 return 0;
1621 }
1622
1623 /* More interesting part now : we know that we have a complete
1624 * response which at least looks like HTTP. We have an indicator
1625 * of each header's length, so we can parse them quickly.
1626 */
1627
Christopher Faulet9768c262018-10-22 09:34:31 +02001628 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet29f17582019-05-23 11:03:26 +02001629 BUG_ON(htx_get_first_type(htx) != HTX_BLK_RES_SL);
Christopher Faulet297fbb42019-05-13 14:41:27 +02001630 sl = http_get_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631
Christopher Faulet9768c262018-10-22 09:34:31 +02001632 /* 0: we might have to print this header in debug mode */
1633 if (unlikely((global.mode & MODE_DEBUG) &&
1634 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1635 int32_t pos;
1636
Christopher Faulet03599112018-11-27 11:21:21 +01001637 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001638
Christopher Fauleta3f15502019-05-13 15:27:23 +02001639 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001640 struct htx_blk *blk = htx_get_blk(htx, pos);
1641 enum htx_blk_type type = htx_get_blk_type(blk);
1642
1643 if (type == HTX_BLK_EOH)
1644 break;
1645 if (type != HTX_BLK_HDR)
1646 continue;
1647
1648 htx_debug_hdr("srvhdr", s,
1649 htx_get_blk_name(htx, blk),
1650 htx_get_blk_value(htx, blk));
1651 }
1652 }
1653
Christopher Faulet03599112018-11-27 11:21:21 +01001654 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001655 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001656 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001657 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001658 if (sl->flags & HTX_SL_F_XFER_LEN) {
1659 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001660 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001661 if (sl->flags & HTX_SL_F_BODYLESS)
1662 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001663 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001664
1665 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001666 if (n < 1 || n > 5)
1667 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001668
Christopher Faulete0768eb2018-10-03 16:38:02 +02001669 /* when the client triggers a 4xx from the server, it's most often due
1670 * to a missing object or permission. These events should be tracked
1671 * because if they happen often, it may indicate a brute force or a
1672 * vulnerability scan.
1673 */
1674 if (n == 4)
1675 stream_inc_http_err_ctr(s);
1676
1677 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001678 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001679
Christopher Faulete0768eb2018-10-03 16:38:02 +02001680 /* Adjust server's health based on status code. Note: status codes 501
1681 * and 505 are triggered on demand by client request, so we must not
1682 * count them as server failures.
1683 */
1684 if (objt_server(s->target)) {
1685 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001686 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001687 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001688 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001689 }
1690
1691 /*
1692 * We may be facing a 100-continue response, or any other informational
1693 * 1xx response which is non-final, in which case this is not the right
1694 * response, and we're waiting for the next one. Let's allow this response
1695 * to go to the client and wait for the next one. There's an exception for
1696 * 101 which is used later in the code to switch protocols.
1697 */
1698 if (txn->status < 200 &&
1699 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001700 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Fauletee1bd4b2019-05-23 10:33:12 +02001701 channel_htx_fwd_headers(rep, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 msg->msg_state = HTTP_MSG_RPBEFORE;
1703 txn->status = 0;
1704 s->logs.t_data = -1; /* was not a response yet */
Christopher Fauletb75b5ea2019-05-17 08:37:28 +02001705 goto next_one;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706 }
1707
1708 /*
1709 * 2: check for cacheability.
1710 */
1711
1712 switch (txn->status) {
1713 case 200:
1714 case 203:
1715 case 204:
1716 case 206:
1717 case 300:
1718 case 301:
1719 case 404:
1720 case 405:
1721 case 410:
1722 case 414:
1723 case 501:
1724 break;
1725 default:
1726 /* RFC7231#6.1:
1727 * Responses with status codes that are defined as
1728 * cacheable by default (e.g., 200, 203, 204, 206,
1729 * 300, 301, 404, 405, 410, 414, and 501 in this
1730 * specification) can be reused by a cache with
1731 * heuristic expiration unless otherwise indicated
1732 * by the method definition or explicit cache
1733 * controls [RFC7234]; all other status codes are
1734 * not cacheable by default.
1735 */
1736 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1737 break;
1738 }
1739
1740 /*
1741 * 3: we may need to capture headers
1742 */
1743 s->logs.logwait &= ~LW_RESP;
1744 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001745 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001746
Christopher Faulet9768c262018-10-22 09:34:31 +02001747 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001748 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1749 txn->status == 101)) {
1750 /* Either we've established an explicit tunnel, or we're
1751 * switching the protocol. In both cases, we're very unlikely
1752 * to understand the next protocols. We have to switch to tunnel
1753 * mode, so that we transfer the request and responses then let
1754 * this protocol pass unmodified. When we later implement specific
1755 * parsers for such protocols, we'll want to check the Upgrade
1756 * header which contains information about that protocol for
1757 * responses with status 101 (eg: see RFC2817 about TLS).
1758 */
1759 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001760 }
1761
Christopher Faulet61608322018-11-23 16:23:45 +01001762 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1763 * 407 (Proxy-Authenticate) responses and set the connection to private
1764 */
1765 srv_conn = cs_conn(objt_cs(s->si[1].end));
1766 if (srv_conn) {
1767 struct ist hdr;
1768 struct http_hdr_ctx ctx;
1769
1770 if (txn->status == 401)
1771 hdr = ist("WWW-Authenticate");
1772 else if (txn->status == 407)
1773 hdr = ist("Proxy-Authenticate");
1774 else
1775 goto end;
1776
1777 ctx.blk = NULL;
1778 while (http_find_header(htx, hdr, &ctx, 0)) {
1779 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1780 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1781 srv_conn->flags |= CO_FL_PRIVATE;
1782 }
1783 }
1784
1785 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001786 /* we want to have the response time before we start processing it */
1787 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1788
1789 /* end of job, return OK */
1790 rep->analysers &= ~an_bit;
1791 rep->analyse_exp = TICK_ETERNITY;
1792 channel_auto_close(rep);
1793 return 1;
1794
Christopher Faulet47365272018-10-31 17:40:50 +01001795 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001796 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001797 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001798 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001799 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001800 }
Olivier Houcharde3249a92019-05-03 23:01:47 +02001801 if ((s->be->retry_type & PR_RE_JUNK_REQUEST) &&
Olivier Houchardad26d8d2019-05-10 17:48:28 +02001802 (si_b->flags & SI_FL_L7_RETRY) &&
Olivier Houcharde3249a92019-05-03 23:01:47 +02001803 do_l7_retry(s, si_b) == 0)
1804 return 0;
Christopher Faulet47365272018-10-31 17:40:50 +01001805 txn->status = 502;
1806 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001807 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001808 rep->analysers &= AN_RES_FLT_END;
1809
1810 if (!(s->flags & SF_ERR_MASK))
1811 s->flags |= SF_ERR_PRXCOND;
1812 if (!(s->flags & SF_FINST_MASK))
1813 s->flags |= SF_FINST_H;
1814 return 0;
1815
Christopher Faulete0768eb2018-10-03 16:38:02 +02001816 abort_keep_alive:
1817 /* A keep-alive request to the server failed on a network error.
1818 * The client is required to retry. We need to close without returning
1819 * any other information so that the client retries.
1820 */
1821 txn->status = 0;
1822 rep->analysers &= AN_RES_FLT_END;
1823 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001824 s->logs.logwait = 0;
1825 s->logs.level = 0;
1826 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001827 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001828 return 0;
1829}
1830
1831/* This function performs all the processing enabled for the current response.
1832 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1833 * and updates s->res.analysers. It might make sense to explode it into several
1834 * other functions. It works like process_request (see indications above).
1835 */
1836int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1837{
1838 struct session *sess = s->sess;
1839 struct http_txn *txn = s->txn;
1840 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001841 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001842 struct proxy *cur_proxy;
1843 struct cond_wordlist *wl;
1844 enum rule_result ret = HTTP_RULE_RES_CONT;
1845
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001846 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1847 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001848
Christopher Faulete0768eb2018-10-03 16:38:02 +02001849 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1850 now_ms, __FUNCTION__,
1851 s,
1852 rep,
1853 rep->rex, rep->wex,
1854 rep->flags,
1855 ci_data(rep),
1856 rep->analysers);
1857
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001858 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001859
1860 /* The stats applet needs to adjust the Connection header but we don't
1861 * apply any filter there.
1862 */
1863 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1864 rep->analysers &= ~an_bit;
1865 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001866 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001867 }
1868
1869 /*
1870 * We will have to evaluate the filters.
1871 * As opposed to version 1.2, now they will be evaluated in the
1872 * filters order and not in the header order. This means that
1873 * each filter has to be validated among all headers.
1874 *
1875 * Filters are tried with ->be first, then with ->fe if it is
1876 * different from ->be.
1877 *
1878 * Maybe we are in resume condiion. In this case I choose the
1879 * "struct proxy" which contains the rule list matching the resume
1880 * pointer. If none of theses "struct proxy" match, I initialise
1881 * the process with the first one.
1882 *
1883 * In fact, I check only correspondance betwwen the current list
1884 * pointer and the ->fe rule list. If it doesn't match, I initialize
1885 * the loop with the ->be.
1886 */
1887 if (s->current_rule_list == &sess->fe->http_res_rules)
1888 cur_proxy = sess->fe;
1889 else
1890 cur_proxy = s->be;
1891 while (1) {
1892 struct proxy *rule_set = cur_proxy;
1893
1894 /* evaluate http-response rules */
1895 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001896 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001897
1898 if (ret == HTTP_RULE_RES_BADREQ)
1899 goto return_srv_prx_502;
1900
1901 if (ret == HTTP_RULE_RES_DONE) {
1902 rep->analysers &= ~an_bit;
1903 rep->analyse_exp = TICK_ETERNITY;
1904 return 1;
1905 }
1906 }
1907
1908 /* we need to be called again. */
1909 if (ret == HTTP_RULE_RES_YIELD) {
1910 channel_dont_close(rep);
1911 return 0;
1912 }
1913
1914 /* try headers filters */
1915 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001916 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1917 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001918 }
1919
1920 /* has the response been denied ? */
1921 if (txn->flags & TX_SVDENY) {
1922 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001923 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001924
Olivier Houcharda798bf52019-03-08 18:52:00 +01001925 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1926 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001927 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001928 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001929 goto return_srv_prx_502;
1930 }
1931
1932 /* add response headers from the rule sets in the same order */
1933 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001934 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001935 if (txn->status < 200 && txn->status != 101)
1936 break;
1937 if (wl->cond) {
1938 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1939 ret = acl_pass(ret);
1940 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1941 ret = !ret;
1942 if (!ret)
1943 continue;
1944 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001945
1946 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1947 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001948 goto return_bad_resp;
1949 }
1950
1951 /* check whether we're already working on the frontend */
1952 if (cur_proxy == sess->fe)
1953 break;
1954 cur_proxy = sess->fe;
1955 }
1956
1957 /* After this point, this anayzer can't return yield, so we can
1958 * remove the bit corresponding to this analyzer from the list.
1959 *
1960 * Note that the intermediate returns and goto found previously
1961 * reset the analyzers.
1962 */
1963 rep->analysers &= ~an_bit;
1964 rep->analyse_exp = TICK_ETERNITY;
1965
1966 /* OK that's all we can do for 1xx responses */
1967 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001968 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001969
1970 /*
1971 * Now check for a server cookie.
1972 */
1973 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001974 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001975
1976 /*
1977 * Check for cache-control or pragma headers if required.
1978 */
1979 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1980 check_response_for_cacheability(s, rep);
1981
1982 /*
1983 * Add server cookie in the response if needed
1984 */
1985 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1986 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1987 (!(s->flags & SF_DIRECT) ||
1988 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1989 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1990 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1991 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1992 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1993 !(s->flags & SF_IGNORE_PRST)) {
1994 /* the server is known, it's not the one the client requested, or the
1995 * cookie's last seen date needs to be refreshed. We have to
1996 * insert a set-cookie here, except if we want to insert only on POST
1997 * requests and this one isn't. Note that servers which don't have cookies
1998 * (eg: some backup servers) will return a full cookie removal request.
1999 */
2000 if (!objt_server(s->target)->cookie) {
2001 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002002 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02002003 s->be->cookie_name);
2004 }
2005 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002006 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002007
2008 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2009 /* emit last_date, which is mandatory */
2010 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2011 s30tob64((date.tv_sec+3) >> 2,
2012 trash.area + trash.data);
2013 trash.data += 5;
2014
2015 if (s->be->cookie_maxlife) {
2016 /* emit first_date, which is either the original one or
2017 * the current date.
2018 */
2019 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2020 s30tob64(txn->cookie_first_date ?
2021 txn->cookie_first_date >> 2 :
2022 (date.tv_sec+3) >> 2,
2023 trash.area + trash.data);
2024 trash.data += 5;
2025 }
2026 }
2027 chunk_appendf(&trash, "; path=/");
2028 }
2029
2030 if (s->be->cookie_domain)
2031 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2032
2033 if (s->be->ck_opts & PR_CK_HTTPONLY)
2034 chunk_appendf(&trash, "; HttpOnly");
2035
2036 if (s->be->ck_opts & PR_CK_SECURE)
2037 chunk_appendf(&trash, "; Secure");
2038
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002039 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002040 goto return_bad_resp;
2041
2042 txn->flags &= ~TX_SCK_MASK;
2043 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2044 /* the server did not change, only the date was updated */
2045 txn->flags |= TX_SCK_UPDATED;
2046 else
2047 txn->flags |= TX_SCK_INSERTED;
2048
2049 /* Here, we will tell an eventual cache on the client side that we don't
2050 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2051 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2052 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2053 */
2054 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2055
2056 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2057
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002058 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002059 goto return_bad_resp;
2060 }
2061 }
2062
2063 /*
2064 * Check if result will be cacheable with a cookie.
2065 * We'll block the response if security checks have caught
2066 * nasty things such as a cacheable cookie.
2067 */
2068 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2069 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2070 (s->be->options & PR_O_CHK_CACHE)) {
2071 /* we're in presence of a cacheable response containing
2072 * a set-cookie header. We'll block it as requested by
2073 * the 'checkcache' option, and send an alert.
2074 */
2075 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002076 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002077
Olivier Houcharda798bf52019-03-08 18:52:00 +01002078 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2079 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002080 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002081 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082
2083 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2084 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2085 send_log(s->be, LOG_ALERT,
2086 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2087 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2088 goto return_srv_prx_502;
2089 }
2090
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002091 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002092 /* Always enter in the body analyzer */
2093 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2094 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2095
2096 /* if the user wants to log as soon as possible, without counting
2097 * bytes from the server, then this is the right moment. We have
2098 * to temporarily assign bytes_out to log what we currently have.
2099 */
2100 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2101 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002102 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002103 s->do_log(s);
2104 s->logs.bytes_out = 0;
2105 }
2106 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002107
2108 return_bad_resp:
2109 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002110 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002111 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002112 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002113 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002114
2115 return_srv_prx_502:
2116 rep->analysers &= AN_RES_FLT_END;
2117 txn->status = 502;
2118 s->logs.t_data = -1; /* was not a valid response */
2119 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002120 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002121 if (!(s->flags & SF_ERR_MASK))
2122 s->flags |= SF_ERR_PRXCOND;
2123 if (!(s->flags & SF_FINST_MASK))
2124 s->flags |= SF_FINST_H;
2125 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126}
2127
2128/* This function is an analyser which forwards response body (including chunk
2129 * sizes if any). It is called as soon as we must forward, even if we forward
2130 * zero byte. The only situation where it must not be called is when we're in
2131 * tunnel mode and we want to forward till the close. It's used both to forward
2132 * remaining data and to resync after end of body. It expects the msg_state to
2133 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2134 * read more data, or 1 once we can go on with next request or end the stream.
2135 *
2136 * It is capable of compressing response data both in content-length mode and
2137 * in chunked mode. The state machines follows different flows depending on
2138 * whether content-length and chunked modes are used, since there are no
2139 * trailers in content-length :
2140 *
2141 * chk-mode cl-mode
2142 * ,----- BODY -----.
2143 * / \
2144 * V size > 0 V chk-mode
2145 * .--> SIZE -------------> DATA -------------> CRLF
2146 * | | size == 0 | last byte |
2147 * | v final crlf v inspected |
2148 * | TRAILERS -----------> DONE |
2149 * | |
2150 * `----------------------------------------------'
2151 *
2152 * Compression only happens in the DATA state, and must be flushed in final
2153 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2154 * is performed at once on final states for all bytes parsed, or when leaving
2155 * on missing data.
2156 */
2157int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2158{
2159 struct session *sess = s->sess;
2160 struct http_txn *txn = s->txn;
2161 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002162 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002163 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002164
2165 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2166 now_ms, __FUNCTION__,
2167 s,
2168 res,
2169 res->rex, res->wex,
2170 res->flags,
2171 ci_data(res),
2172 res->analysers);
2173
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002174 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002175
2176 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002177 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002178 /* Output closed while we were sending data. We must abort and
2179 * wake the other side up.
2180 */
2181 msg->err_state = msg->msg_state;
2182 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002183 htx_end_response(s);
2184 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002185 return 1;
2186 }
2187
Christopher Faulet9768c262018-10-22 09:34:31 +02002188 if (msg->msg_state == HTTP_MSG_BODY)
2189 msg->msg_state = HTTP_MSG_DATA;
2190
Christopher Faulete0768eb2018-10-03 16:38:02 +02002191 /* in most states, we should abort in case of early close */
2192 channel_auto_close(res);
2193
Christopher Faulete0768eb2018-10-03 16:38:02 +02002194 if (res->to_forward) {
Christopher Faulet66af0b22019-03-22 14:54:52 +01002195 if (res->to_forward == CHN_INFINITE_FORWARD) {
2196 if (res->flags & (CF_SHUTR|CF_EOI)) {
2197 msg->msg_state = HTTP_MSG_DONE;
2198 res->to_forward = 0;
2199 goto done;
2200 }
2201 }
2202 else {
2203 /* We can't process the buffer's contents yet */
2204 res->flags |= CF_WAKE_WRITE;
2205 goto missing_data_or_waiting;
2206 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 }
2208
Christopher Faulet9768c262018-10-22 09:34:31 +02002209 if (msg->msg_state >= HTTP_MSG_DONE)
2210 goto done;
2211
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002212 /* Forward input data. We get it by removing all outgoing data not
2213 * forwarded yet from HTX data size. If there are some data filters, we
2214 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002215 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002216 if (HAS_RSP_DATA_FILTERS(s)) {
2217 ret = flt_http_payload(s, msg, htx->data);
2218 if (ret < 0)
2219 goto return_bad_res;
Christopher Fauletee847d42019-05-23 11:55:33 +02002220 channel_htx_fwd_payload(res, htx, ret);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002221 if (htx->data != co_data(res) || htx->extra)
2222 goto missing_data_or_waiting;
2223 }
2224 else {
Christopher Faulet16af60e2019-05-23 11:53:17 +02002225 channel_htx_fwd_all(res, htx);
Christopher Faulet66af0b22019-03-22 14:54:52 +01002226 if (msg->flags & HTTP_MSGF_XFER_LEN)
2227 channel_htx_forward_forever(res, htx);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002228 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002229
Christopher Fauletc62c2b92019-03-28 11:41:39 +01002230 if ((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101 ||
2231 (!(msg->flags & HTTP_MSGF_XFER_LEN) && (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)))) {
2232 msg->msg_state = HTTP_MSG_TUNNEL;
2233 goto done;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 }
2235
Christopher Faulet9768c262018-10-22 09:34:31 +02002236 /* Check if the end-of-message is reached and if so, switch the message
2237 * in HTTP_MSG_DONE state.
2238 */
2239 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2240 goto missing_data_or_waiting;
2241
2242 msg->msg_state = HTTP_MSG_DONE;
Christopher Fauletaed68d42019-03-28 18:12:46 +01002243 res->to_forward = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02002244
2245 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002246 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002247 channel_dont_close(res);
2248
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002249 if (HAS_RSP_DATA_FILTERS(s)) {
2250 ret = flt_http_end(s, msg);
2251 if (ret <= 0) {
2252 if (!ret)
2253 goto missing_data_or_waiting;
2254 goto return_bad_res;
2255 }
2256 }
2257
Christopher Fauletf2824e62018-10-01 12:12:37 +02002258 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002260 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2262 if (res->flags & CF_SHUTW) {
2263 /* response errors are most likely due to the
2264 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002265 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002267 goto return_bad_res;
2268 }
2269 return 1;
2270 }
2271 return 0;
2272
2273 missing_data_or_waiting:
2274 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002276
Christopher Faulet47365272018-10-31 17:40:50 +01002277 if (htx->flags & HTX_FL_PARSING_ERROR)
2278 goto return_bad_res;
2279
Christopher Faulete0768eb2018-10-03 16:38:02 +02002280 /* stop waiting for data if the input is closed before the end. If the
2281 * client side was already closed, it means that the client has aborted,
2282 * so we don't want to count this as a server abort. Otherwise it's a
2283 * server abort.
2284 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002285 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002289 if (htx_is_empty(htx))
2290 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002291 }
2292
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 /* When TE: chunked is used, we need to get there again to parse
2294 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002295 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2296 * are filters registered on the stream, we don't want to forward a
2297 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002299 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002300 channel_dont_close(res);
2301
2302 /* We know that more data are expected, but we couldn't send more that
2303 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2304 * system knows it must not set a PUSH on this first part. Interactive
2305 * modes are already handled by the stream sock layer. We must not do
2306 * this in content-length mode because it could present the MSG_MORE
2307 * flag with the last block of forwarded data, which would cause an
2308 * additional delay to be observed by the receiver.
2309 */
2310 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2311 res->flags |= CF_EXPECT_MORE;
2312
2313 /* the stream handler will take care of timeouts and errors */
2314 return 0;
2315
Christopher Faulet93e02d82019-03-08 14:18:50 +01002316 return_srv_abort:
2317 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2318 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002319 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002320 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2321 if (!(s->flags & SF_ERR_MASK))
2322 s->flags |= SF_ERR_SRVCL;
2323 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002324
Christopher Faulet93e02d82019-03-08 14:18:50 +01002325 return_cli_abort:
2326 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2327 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002328 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002329 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2330 if (!(s->flags & SF_ERR_MASK))
2331 s->flags |= SF_ERR_CLICL;
2332 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002333
Christopher Faulet93e02d82019-03-08 14:18:50 +01002334 return_bad_res:
2335 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2336 if (objt_server(s->target)) {
2337 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2338 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2339 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002340 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002341 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002342
Christopher Faulet93e02d82019-03-08 14:18:50 +01002343 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002344 txn->rsp.err_state = txn->rsp.msg_state;
2345 txn->rsp.msg_state = HTTP_MSG_ERROR;
2346 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002347 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002348 res->analysers &= AN_RES_FLT_END;
2349 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 +02002350 if (!(s->flags & SF_FINST_MASK))
2351 s->flags |= SF_FINST_D;
2352 return 0;
2353}
2354
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357 * as too large a request to build a valid response.
2358 */
2359int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2360{
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 struct channel *req = &s->req;
2362 struct channel *res = &s->res;
2363 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002364 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002365 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002366 struct ist status, reason, location;
2367 unsigned int flags;
2368 size_t data;
Christopher Faulet08e66462019-05-23 16:44:59 +02002369 int close = 0; /* Try to keep the connection alive byt default */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002370
2371 chunk = alloc_trash_chunk();
2372 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374
Christopher Faulet99daf282018-11-28 22:58:13 +01002375 /*
2376 * Create the location
2377 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002378 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 case REDIRECT_TYPE_SCHEME: {
2381 struct http_hdr_ctx ctx;
2382 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
Christopher Faulet99daf282018-11-28 22:58:13 +01002384 host = ist("");
2385 ctx.blk = NULL;
2386 if (http_find_header(htx, ist("Host"), &ctx, 0))
2387 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388
Christopher Faulet297fbb42019-05-13 14:41:27 +02002389 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002390 path = http_get_path(htx_sl_req_uri(sl));
2391 /* build message using path */
2392 if (path.ptr) {
2393 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2394 int qs = 0;
2395 while (qs < path.len) {
2396 if (*(path.ptr + qs) == '?') {
2397 path.len = qs;
2398 break;
2399 }
2400 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002402 }
2403 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 else
2405 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 if (rule->rdr_str) { /* this is an old "redirect" rule */
2408 /* add scheme */
2409 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2410 goto fail;
2411 }
2412 else {
2413 /* add scheme with executing log format */
2414 chunk->data += build_logline(s, chunk->area + chunk->data,
2415 chunk->size - chunk->data,
2416 &rule->rdr_fmt);
2417 }
2418 /* add "://" + host + path */
2419 if (!chunk_memcat(chunk, "://", 3) ||
2420 !chunk_memcat(chunk, host.ptr, host.len) ||
2421 !chunk_memcat(chunk, path.ptr, path.len))
2422 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 /* append a slash at the end of the location if needed and missing */
2425 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2426 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2427 if (chunk->data + 1 >= chunk->size)
2428 goto fail;
2429 chunk->area[chunk->data++] = '/';
2430 }
2431 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002433
Christopher Faulet99daf282018-11-28 22:58:13 +01002434 case REDIRECT_TYPE_PREFIX: {
2435 struct ist path;
2436
Christopher Faulet297fbb42019-05-13 14:41:27 +02002437 sl = http_get_stline(htx);
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 path = http_get_path(htx_sl_req_uri(sl));
2439 /* build message using path */
2440 if (path.ptr) {
2441 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2442 int qs = 0;
2443 while (qs < path.len) {
2444 if (*(path.ptr + qs) == '?') {
2445 path.len = qs;
2446 break;
2447 }
2448 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 }
2451 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 else
2453 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002454
Christopher Faulet99daf282018-11-28 22:58:13 +01002455 if (rule->rdr_str) { /* this is an old "redirect" rule */
2456 /* add prefix. Note that if prefix == "/", we don't want to
2457 * add anything, otherwise it makes it hard for the user to
2458 * configure a self-redirection.
2459 */
2460 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2461 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2462 goto fail;
2463 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002465 else {
2466 /* add prefix with executing log format */
2467 chunk->data += build_logline(s, chunk->area + chunk->data,
2468 chunk->size - chunk->data,
2469 &rule->rdr_fmt);
2470 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471
Christopher Faulet99daf282018-11-28 22:58:13 +01002472 /* add path */
2473 if (!chunk_memcat(chunk, path.ptr, path.len))
2474 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002475
Christopher Faulet99daf282018-11-28 22:58:13 +01002476 /* append a slash at the end of the location if needed and missing */
2477 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2478 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2479 if (chunk->data + 1 >= chunk->size)
2480 goto fail;
2481 chunk->area[chunk->data++] = '/';
2482 }
2483 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002484 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002485 case REDIRECT_TYPE_LOCATION:
2486 default:
2487 if (rule->rdr_str) { /* this is an old "redirect" rule */
2488 /* add location */
2489 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2490 goto fail;
2491 }
2492 else {
2493 /* add location with executing log format */
2494 chunk->data += build_logline(s, chunk->area + chunk->data,
2495 chunk->size - chunk->data,
2496 &rule->rdr_fmt);
2497 }
2498 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002499 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002500 location = ist2(chunk->area, chunk->data);
2501
2502 /*
2503 * Create the 30x response
2504 */
2505 switch (rule->code) {
2506 case 308:
2507 status = ist("308");
2508 reason = ist("Permanent Redirect");
2509 break;
2510 case 307:
2511 status = ist("307");
2512 reason = ist("Temporary Redirect");
2513 break;
2514 case 303:
2515 status = ist("303");
2516 reason = ist("See Other");
2517 break;
2518 case 301:
2519 status = ist("301");
2520 reason = ist("Moved Permanently");
2521 break;
2522 case 302:
2523 default:
2524 status = ist("302");
2525 reason = ist("Found");
2526 break;
2527 }
2528
Christopher Faulet08e66462019-05-23 16:44:59 +02002529 if (!(txn->req.flags & HTTP_MSGF_BODYLESS) && txn->req.msg_state != HTTP_MSG_DONE)
2530 close = 1;
2531
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 htx = htx_from_buf(&res->buf);
2533 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2534 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2535 if (!sl)
2536 goto fail;
2537 sl->info.res.status = rule->code;
2538 s->txn->status = rule->code;
2539
Christopher Faulet08e66462019-05-23 16:44:59 +02002540 if (close && !htx_add_header(htx, ist("Connection"), ist("close")))
2541 goto fail;
2542
2543 if (!htx_add_header(htx, ist("Content-length"), ist("0")) ||
Christopher Faulet99daf282018-11-28 22:58:13 +01002544 !htx_add_header(htx, ist("Location"), location))
2545 goto fail;
2546
2547 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2548 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2549 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002550 }
2551
2552 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002553 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2554 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002555 }
2556
Christopher Faulet99daf282018-11-28 22:58:13 +01002557 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2558 goto fail;
2559
Christopher Fauletf2824e62018-10-01 12:12:37 +02002560 /* let's log the request time */
2561 s->logs.tv_request = now;
2562
Christopher Faulet99daf282018-11-28 22:58:13 +01002563 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002564 c_adv(res, data);
2565 res->total += data;
2566
2567 channel_auto_read(req);
2568 channel_abort(req);
2569 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002570 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002571
2572 res->wex = tick_add_ifset(now_ms, res->wto);
2573 channel_auto_read(res);
2574 channel_auto_close(res);
2575 channel_shutr_now(res);
2576
2577 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002578
2579 if (!(s->flags & SF_ERR_MASK))
2580 s->flags |= SF_ERR_LOCAL;
2581 if (!(s->flags & SF_FINST_MASK))
2582 s->flags |= SF_FINST_R;
2583
Christopher Faulet99daf282018-11-28 22:58:13 +01002584 free_trash_chunk(chunk);
2585 return 1;
2586
2587 fail:
2588 /* If an error occurred, remove the incomplete HTTP response from the
2589 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002590 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002591 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002592 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002593}
2594
Christopher Faulet72333522018-10-24 11:25:02 +02002595int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2596 struct ist name, const char *str, struct my_regex *re, int action)
2597{
2598 struct http_hdr_ctx ctx;
2599 struct buffer *output = get_trash_chunk();
2600
2601 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2602 ctx.blk = NULL;
2603 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2604 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2605 continue;
2606
2607 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2608 if (output->data == -1)
2609 return -1;
2610 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2611 return -1;
2612 }
2613 return 0;
2614}
2615
2616static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2617 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2618{
2619 struct buffer *replace;
2620 int ret = -1;
2621
2622 replace = alloc_trash_chunk();
2623 if (!replace)
2624 goto leave;
2625
2626 replace->data = build_logline(s, replace->area, replace->size, fmt);
2627 if (replace->data >= replace->size - 1)
2628 goto leave;
2629
2630 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2631
2632 leave:
2633 free_trash_chunk(replace);
2634 return ret;
2635}
2636
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637
2638/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2639 * on success and -1 on error. The response channel is updated accordingly.
2640 */
2641static int htx_reply_103_early_hints(struct channel *res)
2642{
2643 struct htx *htx = htx_from_buf(&res->buf);
2644 size_t data;
2645
2646 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2647 /* If an error occurred during an Early-hint rule,
2648 * remove the incomplete HTTP 103 response from the
2649 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002650 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 return -1;
2652 }
2653
2654 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002655 c_adv(res, data);
2656 res->total += data;
2657 return 0;
2658}
2659
Christopher Faulet6eb92892018-11-15 16:39:29 +01002660/*
2661 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2662 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002663 * If <early_hints> is 0, it is starts a new response by adding the start
2664 * line. If an error occurred -1 is returned. On success 0 is returned. The
2665 * channel is not updated here. It must be done calling the function
2666 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002668static 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 +01002669{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 struct channel *res = &s->res;
2671 struct htx *htx = htx_from_buf(&res->buf);
2672 struct buffer *value = alloc_trash_chunk();
2673
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002675 struct htx_sl *sl;
2676 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2677 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2678
2679 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2680 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2681 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002682 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002683 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002684 }
2685
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002686 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2687 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002688 goto fail;
2689
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002690 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002691 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002692
2693 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002694 /* If an error occurred during an Early-hint rule, remove the incomplete
2695 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002696 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002697 free_trash_chunk(value);
2698 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002699}
2700
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002701/* This function executes one of the set-{method,path,query,uri} actions. It
2702 * takes the string from the variable 'replace' with length 'len', then modifies
2703 * the relevant part of the request line accordingly. Then it updates various
2704 * pointers to the next elements which were moved, and the total buffer length.
2705 * It finds the action to be performed in p[2], previously filled by function
2706 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2707 * error, though this can be revisited when this code is finally exploited.
2708 *
2709 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2710 * query string and 3 to replace uri.
2711 *
2712 * In query string case, the mark question '?' must be set at the start of the
2713 * string by the caller, event if the replacement query string is empty.
2714 */
2715int htx_req_replace_stline(int action, const char *replace, int len,
2716 struct proxy *px, struct stream *s)
2717{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002718 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002719
2720 switch (action) {
2721 case 0: // method
2722 if (!http_replace_req_meth(htx, ist2(replace, len)))
2723 return -1;
2724 break;
2725
2726 case 1: // path
2727 if (!http_replace_req_path(htx, ist2(replace, len)))
2728 return -1;
2729 break;
2730
2731 case 2: // query
2732 if (!http_replace_req_query(htx, ist2(replace, len)))
2733 return -1;
2734 break;
2735
2736 case 3: // uri
2737 if (!http_replace_req_uri(htx, ist2(replace, len)))
2738 return -1;
2739 break;
2740
2741 default:
2742 return -1;
2743 }
2744 return 0;
2745}
2746
2747/* This function replace the HTTP status code and the associated message. The
2748 * variable <status> contains the new status code. This function never fails.
2749 */
2750void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2751{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002752 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002753 char *res;
2754
2755 chunk_reset(&trash);
2756 res = ultoa_o(status, trash.area, trash.size);
2757 trash.data = res - trash.area;
2758
2759 /* Do we have a custom reason format string? */
2760 if (reason == NULL)
2761 reason = http_get_reason(status);
2762
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002763 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002764 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2765}
2766
Christopher Faulet3e964192018-10-24 11:39:23 +02002767/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2768 * transaction <txn>. Returns the verdict of the first rule that prevents
2769 * further processing of the request (auth, deny, ...), and defaults to
2770 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2771 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2772 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2773 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2774 * status.
2775 */
2776static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2777 struct stream *s, int *deny_status)
2778{
2779 struct session *sess = strm_sess(s);
2780 struct http_txn *txn = s->txn;
2781 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002782 struct act_rule *rule;
2783 struct http_hdr_ctx ctx;
2784 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002785 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2786 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002787 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002788
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002789 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002790
2791 /* If "the current_rule_list" match the executed rule list, we are in
2792 * resume condition. If a resume is needed it is always in the action
2793 * and never in the ACL or converters. In this case, we initialise the
2794 * current rule, and go to the action execution point.
2795 */
2796 if (s->current_rule) {
2797 rule = s->current_rule;
2798 s->current_rule = NULL;
2799 if (s->current_rule_list == rules)
2800 goto resume_execution;
2801 }
2802 s->current_rule_list = rules;
2803
2804 list_for_each_entry(rule, rules, list) {
2805 /* check optional condition */
2806 if (rule->cond) {
2807 int ret;
2808
2809 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2810 ret = acl_pass(ret);
2811
2812 if (rule->cond->pol == ACL_COND_UNLESS)
2813 ret = !ret;
2814
2815 if (!ret) /* condition not matched */
2816 continue;
2817 }
2818
2819 act_flags |= ACT_FLAG_FIRST;
2820 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002821 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2822 early_hints = 0;
2823 if (htx_reply_103_early_hints(&s->res) == -1) {
2824 rule_ret = HTTP_RULE_RES_BADREQ;
2825 goto end;
2826 }
2827 }
2828
Christopher Faulet3e964192018-10-24 11:39:23 +02002829 switch (rule->action) {
2830 case ACT_ACTION_ALLOW:
2831 rule_ret = HTTP_RULE_RES_STOP;
2832 goto end;
2833
2834 case ACT_ACTION_DENY:
2835 if (deny_status)
2836 *deny_status = rule->deny_status;
2837 rule_ret = HTTP_RULE_RES_DENY;
2838 goto end;
2839
2840 case ACT_HTTP_REQ_TARPIT:
2841 txn->flags |= TX_CLTARPIT;
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_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002848 /* Auth might be performed on regular http-req rules as well as on stats */
2849 auth_realm = rule->arg.auth.realm;
2850 if (!auth_realm) {
2851 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2852 auth_realm = STATS_DEFAULT_REALM;
2853 else
2854 auth_realm = px->id;
2855 }
2856 /* send 401/407 depending on whether we use a proxy or not. We still
2857 * count one error, because normal browsing won't significantly
2858 * increase the counter but brute force attempts will.
2859 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002860 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002861 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2862 rule_ret = HTTP_RULE_RES_BADREQ;
2863 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002864 goto end;
2865
2866 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002867 rule_ret = HTTP_RULE_RES_DONE;
2868 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2869 rule_ret = HTTP_RULE_RES_BADREQ;
2870 goto end;
2871
2872 case ACT_HTTP_SET_NICE:
2873 s->task->nice = rule->arg.nice;
2874 break;
2875
2876 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002877 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002878 break;
2879
2880 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002881 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002882 break;
2883
2884 case ACT_HTTP_SET_LOGL:
2885 s->logs.level = rule->arg.loglevel;
2886 break;
2887
2888 case ACT_HTTP_REPLACE_HDR:
2889 case ACT_HTTP_REPLACE_VAL:
2890 if (htx_transform_header(s, &s->req, htx,
2891 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2892 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02002893 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02002894 rule_ret = HTTP_RULE_RES_BADREQ;
2895 goto end;
2896 }
2897 break;
2898
2899 case ACT_HTTP_DEL_HDR:
2900 /* remove all occurrences of the header */
2901 ctx.blk = NULL;
2902 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2903 http_remove_header(htx, &ctx);
2904 break;
2905
2906 case ACT_HTTP_SET_HDR:
2907 case ACT_HTTP_ADD_HDR: {
2908 /* The scope of the trash buffer must be limited to this function. The
2909 * build_logline() function can execute a lot of other function which
2910 * can use the trash buffer. So for limiting the scope of this global
2911 * buffer, we build first the header value using build_logline, and
2912 * after we store the header name.
2913 */
2914 struct buffer *replace;
2915 struct ist n, v;
2916
2917 replace = alloc_trash_chunk();
2918 if (!replace) {
2919 rule_ret = HTTP_RULE_RES_BADREQ;
2920 goto end;
2921 }
2922
2923 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2924 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2925 v = ist2(replace->area, replace->data);
2926
2927 if (rule->action == ACT_HTTP_SET_HDR) {
2928 /* remove all occurrences of the header */
2929 ctx.blk = NULL;
2930 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2931 http_remove_header(htx, &ctx);
2932 }
2933
2934 if (!http_add_header(htx, n, v)) {
2935 static unsigned char rate_limit = 0;
2936
2937 if ((rate_limit++ & 255) == 0) {
2938 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);
2939 }
2940
Olivier Houcharda798bf52019-03-08 18:52:00 +01002941 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002942 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002943 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002944 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002945 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002946 }
2947 free_trash_chunk(replace);
2948 break;
2949 }
2950
2951 case ACT_HTTP_DEL_ACL:
2952 case ACT_HTTP_DEL_MAP: {
2953 struct pat_ref *ref;
2954 struct buffer *key;
2955
2956 /* collect reference */
2957 ref = pat_ref_lookup(rule->arg.map.ref);
2958 if (!ref)
2959 continue;
2960
2961 /* allocate key */
2962 key = alloc_trash_chunk();
2963 if (!key) {
2964 rule_ret = HTTP_RULE_RES_BADREQ;
2965 goto end;
2966 }
2967
2968 /* collect key */
2969 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2970 key->area[key->data] = '\0';
2971
2972 /* perform update */
2973 /* returned code: 1=ok, 0=ko */
2974 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2975 pat_ref_delete(ref, key->area);
2976 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2977
2978 free_trash_chunk(key);
2979 break;
2980 }
2981
2982 case ACT_HTTP_ADD_ACL: {
2983 struct pat_ref *ref;
2984 struct buffer *key;
2985
2986 /* collect reference */
2987 ref = pat_ref_lookup(rule->arg.map.ref);
2988 if (!ref)
2989 continue;
2990
2991 /* allocate key */
2992 key = alloc_trash_chunk();
2993 if (!key) {
2994 rule_ret = HTTP_RULE_RES_BADREQ;
2995 goto end;
2996 }
2997
2998 /* collect key */
2999 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3000 key->area[key->data] = '\0';
3001
3002 /* perform update */
3003 /* add entry only if it does not already exist */
3004 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3005 if (pat_ref_find_elt(ref, key->area) == NULL)
3006 pat_ref_add(ref, key->area, NULL, NULL);
3007 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3008
3009 free_trash_chunk(key);
3010 break;
3011 }
3012
3013 case ACT_HTTP_SET_MAP: {
3014 struct pat_ref *ref;
3015 struct buffer *key, *value;
3016
3017 /* collect reference */
3018 ref = pat_ref_lookup(rule->arg.map.ref);
3019 if (!ref)
3020 continue;
3021
3022 /* allocate key */
3023 key = alloc_trash_chunk();
3024 if (!key) {
3025 rule_ret = HTTP_RULE_RES_BADREQ;
3026 goto end;
3027 }
3028
3029 /* allocate value */
3030 value = alloc_trash_chunk();
3031 if (!value) {
3032 free_trash_chunk(key);
3033 rule_ret = HTTP_RULE_RES_BADREQ;
3034 goto end;
3035 }
3036
3037 /* collect key */
3038 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3039 key->area[key->data] = '\0';
3040
3041 /* collect value */
3042 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3043 value->area[value->data] = '\0';
3044
3045 /* perform update */
Christopher Faulete84289e2019-04-19 14:50:55 +02003046 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003047 if (pat_ref_find_elt(ref, key->area) != NULL)
3048 /* update entry if it exists */
3049 pat_ref_set(ref, key->area, value->area, NULL);
3050 else
3051 /* insert a new entry */
3052 pat_ref_add(ref, key->area, value->area, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003053 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003054 free_trash_chunk(key);
3055 free_trash_chunk(value);
3056 break;
3057 }
3058
3059 case ACT_HTTP_EARLY_HINT:
3060 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3061 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003062 early_hints = htx_add_early_hint_header(s, early_hints,
3063 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003064 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003065 if (early_hints == -1) {
3066 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003067 goto end;
3068 }
3069 break;
3070
3071 case ACT_CUSTOM:
3072 if ((s->req.flags & CF_READ_ERROR) ||
3073 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003074 (px->options & PR_O_ABRT_CLOSE)))
3075 act_flags |= ACT_FLAG_FINAL;
3076
3077 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3078 case ACT_RET_ERR:
3079 case ACT_RET_CONT:
3080 break;
3081 case ACT_RET_STOP:
3082 rule_ret = HTTP_RULE_RES_DONE;
3083 goto end;
3084 case ACT_RET_YIELD:
3085 s->current_rule = rule;
3086 rule_ret = HTTP_RULE_RES_YIELD;
3087 goto end;
3088 }
3089 break;
3090
3091 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3092 /* Note: only the first valid tracking parameter of each
3093 * applies.
3094 */
3095
3096 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3097 struct stktable *t;
3098 struct stksess *ts;
3099 struct stktable_key *key;
3100 void *ptr1, *ptr2;
3101
3102 t = rule->arg.trk_ctr.table.t;
3103 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3104 rule->arg.trk_ctr.expr, NULL);
3105
3106 if (key && (ts = stktable_get_entry(t, key))) {
3107 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3108
3109 /* let's count a new HTTP request as it's the first time we do it */
3110 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3111 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3112 if (ptr1 || ptr2) {
3113 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3114
3115 if (ptr1)
3116 stktable_data_cast(ptr1, http_req_cnt)++;
3117
3118 if (ptr2)
3119 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3120 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3121
3122 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3123
3124 /* If data was modified, we need to touch to re-schedule sync */
3125 stktable_touch_local(t, ts, 0);
3126 }
3127
3128 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3129 if (sess->fe != s->be)
3130 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3131 }
3132 }
3133 break;
3134
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003135 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003136 default:
3137 break;
3138 }
3139 }
3140
3141 end:
3142 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003143 if (htx_reply_103_early_hints(&s->res) == -1)
3144 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003145 }
3146
3147 /* we reached the end of the rules, nothing to report */
3148 return rule_ret;
3149}
3150
3151/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3152 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3153 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3154 * is returned, the process can continue the evaluation of next rule list. If
3155 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3156 * is returned, it means the operation could not be processed and a server error
3157 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3158 * deny rule. If *YIELD is returned, the caller must call again the function
3159 * with the same context.
3160 */
3161static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3162 struct stream *s)
3163{
3164 struct session *sess = strm_sess(s);
3165 struct http_txn *txn = s->txn;
3166 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003167 struct act_rule *rule;
3168 struct http_hdr_ctx ctx;
3169 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3170 int act_flags = 0;
3171
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003172 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003173
3174 /* If "the current_rule_list" match the executed rule list, we are in
3175 * resume condition. If a resume is needed it is always in the action
3176 * and never in the ACL or converters. In this case, we initialise the
3177 * current rule, and go to the action execution point.
3178 */
3179 if (s->current_rule) {
3180 rule = s->current_rule;
3181 s->current_rule = NULL;
3182 if (s->current_rule_list == rules)
3183 goto resume_execution;
3184 }
3185 s->current_rule_list = rules;
3186
3187 list_for_each_entry(rule, rules, list) {
3188 /* check optional condition */
3189 if (rule->cond) {
3190 int ret;
3191
3192 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3193 ret = acl_pass(ret);
3194
3195 if (rule->cond->pol == ACL_COND_UNLESS)
3196 ret = !ret;
3197
3198 if (!ret) /* condition not matched */
3199 continue;
3200 }
3201
3202 act_flags |= ACT_FLAG_FIRST;
3203resume_execution:
3204 switch (rule->action) {
3205 case ACT_ACTION_ALLOW:
3206 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3207 goto end;
3208
3209 case ACT_ACTION_DENY:
3210 txn->flags |= TX_SVDENY;
3211 rule_ret = HTTP_RULE_RES_STOP;
3212 goto end;
3213
3214 case ACT_HTTP_SET_NICE:
3215 s->task->nice = rule->arg.nice;
3216 break;
3217
3218 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003219 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003220 break;
3221
3222 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003223 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003224 break;
3225
3226 case ACT_HTTP_SET_LOGL:
3227 s->logs.level = rule->arg.loglevel;
3228 break;
3229
3230 case ACT_HTTP_REPLACE_HDR:
3231 case ACT_HTTP_REPLACE_VAL:
3232 if (htx_transform_header(s, &s->res, htx,
3233 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3234 &rule->arg.hdr_add.fmt,
Dragan Dosen26743032019-04-30 15:54:36 +02003235 rule->arg.hdr_add.re, rule->action)) {
Christopher Faulet3e964192018-10-24 11:39:23 +02003236 rule_ret = HTTP_RULE_RES_BADREQ;
3237 goto end;
3238 }
3239 break;
3240
3241 case ACT_HTTP_DEL_HDR:
3242 /* remove all occurrences of the header */
3243 ctx.blk = NULL;
3244 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3245 http_remove_header(htx, &ctx);
3246 break;
3247
3248 case ACT_HTTP_SET_HDR:
3249 case ACT_HTTP_ADD_HDR: {
3250 struct buffer *replace;
3251 struct ist n, v;
3252
3253 replace = alloc_trash_chunk();
3254 if (!replace) {
3255 rule_ret = HTTP_RULE_RES_BADREQ;
3256 goto end;
3257 }
3258
3259 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3260 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3261 v = ist2(replace->area, replace->data);
3262
3263 if (rule->action == ACT_HTTP_SET_HDR) {
3264 /* remove all occurrences of the header */
3265 ctx.blk = NULL;
3266 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3267 http_remove_header(htx, &ctx);
3268 }
3269
3270 if (!http_add_header(htx, n, v)) {
3271 static unsigned char rate_limit = 0;
3272
3273 if ((rate_limit++ & 255) == 0) {
3274 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);
3275 }
3276
Olivier Houcharda798bf52019-03-08 18:52:00 +01003277 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003278 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003279 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003280 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003281 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003282 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003283 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003284 }
3285 free_trash_chunk(replace);
3286 break;
3287 }
3288
3289 case ACT_HTTP_DEL_ACL:
3290 case ACT_HTTP_DEL_MAP: {
3291 struct pat_ref *ref;
3292 struct buffer *key;
3293
3294 /* collect reference */
3295 ref = pat_ref_lookup(rule->arg.map.ref);
3296 if (!ref)
3297 continue;
3298
3299 /* allocate key */
3300 key = alloc_trash_chunk();
3301 if (!key) {
3302 rule_ret = HTTP_RULE_RES_BADREQ;
3303 goto end;
3304 }
3305
3306 /* collect key */
3307 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3308 key->area[key->data] = '\0';
3309
3310 /* perform update */
3311 /* returned code: 1=ok, 0=ko */
3312 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3313 pat_ref_delete(ref, key->area);
3314 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3315
3316 free_trash_chunk(key);
3317 break;
3318 }
3319
3320 case ACT_HTTP_ADD_ACL: {
3321 struct pat_ref *ref;
3322 struct buffer *key;
3323
3324 /* collect reference */
3325 ref = pat_ref_lookup(rule->arg.map.ref);
3326 if (!ref)
3327 continue;
3328
3329 /* allocate key */
3330 key = alloc_trash_chunk();
3331 if (!key) {
3332 rule_ret = HTTP_RULE_RES_BADREQ;
3333 goto end;
3334 }
3335
3336 /* collect key */
3337 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3338 key->area[key->data] = '\0';
3339
3340 /* perform update */
3341 /* check if the entry already exists */
Christopher Faulete84289e2019-04-19 14:50:55 +02003342 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003343 if (pat_ref_find_elt(ref, key->area) == NULL)
3344 pat_ref_add(ref, key->area, NULL, NULL);
Christopher Faulete84289e2019-04-19 14:50:55 +02003345 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Christopher Faulet3e964192018-10-24 11:39:23 +02003346 free_trash_chunk(key);
3347 break;
3348 }
3349
3350 case ACT_HTTP_SET_MAP: {
3351 struct pat_ref *ref;
3352 struct buffer *key, *value;
3353
3354 /* collect reference */
3355 ref = pat_ref_lookup(rule->arg.map.ref);
3356 if (!ref)
3357 continue;
3358
3359 /* allocate key */
3360 key = alloc_trash_chunk();
3361 if (!key) {
3362 rule_ret = HTTP_RULE_RES_BADREQ;
3363 goto end;
3364 }
3365
3366 /* allocate value */
3367 value = alloc_trash_chunk();
3368 if (!value) {
3369 free_trash_chunk(key);
3370 rule_ret = HTTP_RULE_RES_BADREQ;
3371 goto end;
3372 }
3373
3374 /* collect key */
3375 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3376 key->area[key->data] = '\0';
3377
3378 /* collect value */
3379 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3380 value->area[value->data] = '\0';
3381
3382 /* perform update */
3383 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3384 if (pat_ref_find_elt(ref, key->area) != NULL)
3385 /* update entry if it exists */
3386 pat_ref_set(ref, key->area, value->area, NULL);
3387 else
3388 /* insert a new entry */
3389 pat_ref_add(ref, key->area, value->area, NULL);
3390 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3391 free_trash_chunk(key);
3392 free_trash_chunk(value);
3393 break;
3394 }
3395
3396 case ACT_HTTP_REDIR:
3397 rule_ret = HTTP_RULE_RES_DONE;
3398 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3399 rule_ret = HTTP_RULE_RES_BADREQ;
3400 goto end;
3401
3402 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3403 /* Note: only the first valid tracking parameter of each
3404 * applies.
3405 */
3406 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3407 struct stktable *t;
3408 struct stksess *ts;
3409 struct stktable_key *key;
3410 void *ptr;
3411
3412 t = rule->arg.trk_ctr.table.t;
3413 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3414 rule->arg.trk_ctr.expr, NULL);
3415
3416 if (key && (ts = stktable_get_entry(t, key))) {
3417 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3418
3419 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3420
3421 /* let's count a new HTTP request as it's the first time we do it */
3422 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3423 if (ptr)
3424 stktable_data_cast(ptr, http_req_cnt)++;
3425
3426 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3427 if (ptr)
3428 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3429 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3430
3431 /* When the client triggers a 4xx from the server, it's most often due
3432 * to a missing object or permission. These events should be tracked
3433 * because if they happen often, it may indicate a brute force or a
3434 * vulnerability scan. Normally this is done when receiving the response
3435 * but here we're tracking after this ought to have been done so we have
3436 * to do it on purpose.
3437 */
3438 if ((unsigned)(txn->status - 400) < 100) {
3439 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3440 if (ptr)
3441 stktable_data_cast(ptr, http_err_cnt)++;
3442
3443 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3444 if (ptr)
3445 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3446 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3447 }
3448
3449 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3450
3451 /* If data was modified, we need to touch to re-schedule sync */
3452 stktable_touch_local(t, ts, 0);
3453
3454 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3455 if (sess->fe != s->be)
3456 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3457 }
3458 }
3459 break;
3460
3461 case ACT_CUSTOM:
3462 if ((s->req.flags & CF_READ_ERROR) ||
3463 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
Christopher Faulet3e964192018-10-24 11:39:23 +02003464 (px->options & PR_O_ABRT_CLOSE)))
3465 act_flags |= ACT_FLAG_FINAL;
3466
3467 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3468 case ACT_RET_ERR:
3469 case ACT_RET_CONT:
3470 break;
3471 case ACT_RET_STOP:
3472 rule_ret = HTTP_RULE_RES_STOP;
3473 goto end;
3474 case ACT_RET_YIELD:
3475 s->current_rule = rule;
3476 rule_ret = HTTP_RULE_RES_YIELD;
3477 goto end;
3478 }
3479 break;
3480
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003481 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003482 default:
3483 break;
3484 }
3485 }
3486
3487 end:
3488 /* we reached the end of the rules, nothing to report */
3489 return rule_ret;
3490}
3491
Christopher Faulet33640082018-10-24 11:53:01 +02003492/* Iterate the same filter through all request headers.
3493 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3494 * Since it can manage the switch to another backend, it updates the per-proxy
3495 * DENY stats.
3496 */
3497static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3498{
3499 struct http_txn *txn = s->txn;
3500 struct htx *htx;
3501 struct buffer *hdr = get_trash_chunk();
3502 int32_t pos;
3503
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003504 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003505
Christopher Fauleta3f15502019-05-13 15:27:23 +02003506 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003507 struct htx_blk *blk = htx_get_blk(htx, pos);
3508 enum htx_blk_type type;
3509 struct ist n, v;
3510
3511 next_hdr:
3512 type = htx_get_blk_type(blk);
3513 if (type == HTX_BLK_EOH)
3514 break;
3515 if (type != HTX_BLK_HDR)
3516 continue;
3517
3518 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3519 return 1;
3520 else if (unlikely(txn->flags & TX_CLALLOW) &&
3521 (exp->action == ACT_ALLOW ||
3522 exp->action == ACT_DENY ||
3523 exp->action == ACT_TARPIT))
3524 return 0;
3525
3526 n = htx_get_blk_name(htx, blk);
3527 v = htx_get_blk_value(htx, blk);
3528
Christopher Faulet02e771a2019-02-26 15:36:05 +01003529 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003530 hdr->area[hdr->data++] = ':';
3531 hdr->area[hdr->data++] = ' ';
3532 chunk_memcat(hdr, v.ptr, v.len);
3533
3534 /* Now we have one header in <hdr> */
3535
3536 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3537 struct http_hdr_ctx ctx;
3538 int len;
3539
3540 switch (exp->action) {
3541 case ACT_ALLOW:
3542 txn->flags |= TX_CLALLOW;
3543 goto end;
3544
3545 case ACT_DENY:
3546 txn->flags |= TX_CLDENY;
3547 goto end;
3548
3549 case ACT_TARPIT:
3550 txn->flags |= TX_CLTARPIT;
3551 goto end;
3552
3553 case ACT_REPLACE:
3554 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3555 if (len < 0)
3556 return -1;
3557
3558 http_parse_header(ist2(trash.area, len), &n, &v);
3559 ctx.blk = blk;
3560 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003561 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003562 if (!http_replace_header(htx, &ctx, n, v))
3563 return -1;
3564 if (!ctx.blk)
3565 goto end;
3566 pos = htx_get_blk_pos(htx, blk);
3567 break;
3568
3569 case ACT_REMOVE:
3570 ctx.blk = blk;
3571 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003572 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003573 if (!http_remove_header(htx, &ctx))
3574 return -1;
3575 if (!ctx.blk)
3576 goto end;
3577 pos = htx_get_blk_pos(htx, blk);
3578 goto next_hdr;
3579
3580 }
3581 }
3582 }
3583 end:
3584 return 0;
3585}
3586
3587/* Apply the filter to the request line.
3588 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3589 * or -1 if a replacement resulted in an invalid request line.
3590 * Since it can manage the switch to another backend, it updates the per-proxy
3591 * DENY stats.
3592 */
3593static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3594{
3595 struct http_txn *txn = s->txn;
3596 struct htx *htx;
3597 struct buffer *reqline = get_trash_chunk();
3598 int done;
3599
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003600 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003601
3602 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3603 return 1;
3604 else if (unlikely(txn->flags & TX_CLALLOW) &&
3605 (exp->action == ACT_ALLOW ||
3606 exp->action == ACT_DENY ||
3607 exp->action == ACT_TARPIT))
3608 return 0;
3609 else if (exp->action == ACT_REMOVE)
3610 return 0;
3611
3612 done = 0;
3613
Christopher Faulet297fbb42019-05-13 14:41:27 +02003614 reqline->data = htx_fmt_req_line(http_get_stline(htx), reqline->area, reqline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003615
3616 /* Now we have the request line between cur_ptr and cur_end */
3617 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003618 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003619 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003620 int len;
3621
3622 switch (exp->action) {
3623 case ACT_ALLOW:
3624 txn->flags |= TX_CLALLOW;
3625 done = 1;
3626 break;
3627
3628 case ACT_DENY:
3629 txn->flags |= TX_CLDENY;
3630 done = 1;
3631 break;
3632
3633 case ACT_TARPIT:
3634 txn->flags |= TX_CLTARPIT;
3635 done = 1;
3636 break;
3637
3638 case ACT_REPLACE:
3639 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3640 if (len < 0)
3641 return -1;
3642
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003643 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3644 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3645 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003646 return -1;
3647 done = 1;
3648 break;
3649 }
3650 }
3651 return done;
3652}
3653
3654/*
3655 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3656 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3657 * unparsable request. Since it can manage the switch to another backend, it
3658 * updates the per-proxy DENY stats.
3659 */
3660static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3661{
3662 struct session *sess = s->sess;
3663 struct http_txn *txn = s->txn;
3664 struct hdr_exp *exp;
3665
3666 for (exp = px->req_exp; exp; exp = exp->next) {
3667 int ret;
3668
3669 /*
3670 * The interleaving of transformations and verdicts
3671 * makes it difficult to decide to continue or stop
3672 * the evaluation.
3673 */
3674
3675 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3676 break;
3677
3678 if ((txn->flags & TX_CLALLOW) &&
3679 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3680 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3681 continue;
3682
3683 /* if this filter had a condition, evaluate it now and skip to
3684 * next filter if the condition does not match.
3685 */
3686 if (exp->cond) {
3687 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3688 ret = acl_pass(ret);
3689 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3690 ret = !ret;
3691
3692 if (!ret)
3693 continue;
3694 }
3695
3696 /* Apply the filter to the request line. */
3697 ret = htx_apply_filter_to_req_line(s, req, exp);
3698 if (unlikely(ret < 0))
3699 return -1;
3700
3701 if (likely(ret == 0)) {
3702 /* The filter did not match the request, it can be
3703 * iterated through all headers.
3704 */
3705 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3706 return -1;
3707 }
3708 }
3709 return 0;
3710}
3711
3712/* Iterate the same filter through all response headers contained in <res>.
3713 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3714 */
3715static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3716{
3717 struct http_txn *txn = s->txn;
3718 struct htx *htx;
3719 struct buffer *hdr = get_trash_chunk();
3720 int32_t pos;
3721
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003722 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003723
Christopher Fauleta3f15502019-05-13 15:27:23 +02003724 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet33640082018-10-24 11:53:01 +02003725 struct htx_blk *blk = htx_get_blk(htx, pos);
3726 enum htx_blk_type type;
3727 struct ist n, v;
3728
3729 next_hdr:
3730 type = htx_get_blk_type(blk);
3731 if (type == HTX_BLK_EOH)
3732 break;
3733 if (type != HTX_BLK_HDR)
3734 continue;
3735
3736 if (unlikely(txn->flags & TX_SVDENY))
3737 return 1;
3738 else if (unlikely(txn->flags & TX_SVALLOW) &&
3739 (exp->action == ACT_ALLOW ||
3740 exp->action == ACT_DENY))
3741 return 0;
3742
3743 n = htx_get_blk_name(htx, blk);
3744 v = htx_get_blk_value(htx, blk);
3745
Christopher Faulet02e771a2019-02-26 15:36:05 +01003746 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003747 hdr->area[hdr->data++] = ':';
3748 hdr->area[hdr->data++] = ' ';
3749 chunk_memcat(hdr, v.ptr, v.len);
3750
3751 /* Now we have one header in <hdr> */
3752
3753 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3754 struct http_hdr_ctx ctx;
3755 int len;
3756
3757 switch (exp->action) {
3758 case ACT_ALLOW:
3759 txn->flags |= TX_SVALLOW;
3760 goto end;
3761 break;
3762
3763 case ACT_DENY:
3764 txn->flags |= TX_SVDENY;
3765 goto end;
3766 break;
3767
3768 case ACT_REPLACE:
3769 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3770 if (len < 0)
3771 return -1;
3772
3773 http_parse_header(ist2(trash.area, len), &n, &v);
3774 ctx.blk = blk;
3775 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003776 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003777 if (!http_replace_header(htx, &ctx, n, v))
3778 return -1;
3779 if (!ctx.blk)
3780 goto end;
3781 pos = htx_get_blk_pos(htx, blk);
3782 break;
3783
3784 case ACT_REMOVE:
3785 ctx.blk = blk;
3786 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003787 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003788 if (!http_remove_header(htx, &ctx))
3789 return -1;
3790 if (!ctx.blk)
3791 goto end;
3792 pos = htx_get_blk_pos(htx, blk);
3793 goto next_hdr;
3794 }
3795 }
3796
3797 }
3798 end:
3799 return 0;
3800}
3801
3802/* Apply the filter to the status line in the response buffer <res>.
3803 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3804 * or -1 if a replacement resulted in an invalid status line.
3805 */
3806static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3807{
3808 struct http_txn *txn = s->txn;
3809 struct htx *htx;
3810 struct buffer *resline = get_trash_chunk();
3811 int done;
3812
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003813 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003814
3815 if (unlikely(txn->flags & TX_SVDENY))
3816 return 1;
3817 else if (unlikely(txn->flags & TX_SVALLOW) &&
3818 (exp->action == ACT_ALLOW ||
3819 exp->action == ACT_DENY))
3820 return 0;
3821 else if (exp->action == ACT_REMOVE)
3822 return 0;
3823
3824 done = 0;
Christopher Faulet297fbb42019-05-13 14:41:27 +02003825 resline->data = htx_fmt_res_line(http_get_stline(htx), resline->area, resline->size);
Christopher Faulet33640082018-10-24 11:53:01 +02003826
3827 /* Now we have the status line between cur_ptr and cur_end */
3828 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Faulet297fbb42019-05-13 14:41:27 +02003829 struct htx_sl *sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003830 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003831 int len;
3832
3833 switch (exp->action) {
3834 case ACT_ALLOW:
3835 txn->flags |= TX_SVALLOW;
3836 done = 1;
3837 break;
3838
3839 case ACT_DENY:
3840 txn->flags |= TX_SVDENY;
3841 done = 1;
3842 break;
3843
3844 case ACT_REPLACE:
3845 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3846 if (len < 0)
3847 return -1;
3848
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003849 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3850 sl->info.res.status = strl2ui(code.ptr, code.len);
3851 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003852 return -1;
3853
3854 done = 1;
3855 return 1;
3856 }
3857 }
3858 return done;
3859}
3860
3861/*
3862 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3863 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3864 * unparsable response.
3865 */
3866static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3867{
3868 struct session *sess = s->sess;
3869 struct http_txn *txn = s->txn;
3870 struct hdr_exp *exp;
3871
3872 for (exp = px->rsp_exp; exp; exp = exp->next) {
3873 int ret;
3874
3875 /*
3876 * The interleaving of transformations and verdicts
3877 * makes it difficult to decide to continue or stop
3878 * the evaluation.
3879 */
3880
3881 if (txn->flags & TX_SVDENY)
3882 break;
3883
3884 if ((txn->flags & TX_SVALLOW) &&
3885 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3886 exp->action == ACT_PASS)) {
3887 exp = exp->next;
3888 continue;
3889 }
3890
3891 /* if this filter had a condition, evaluate it now and skip to
3892 * next filter if the condition does not match.
3893 */
3894 if (exp->cond) {
3895 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3896 ret = acl_pass(ret);
3897 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3898 ret = !ret;
3899 if (!ret)
3900 continue;
3901 }
3902
3903 /* Apply the filter to the status line. */
3904 ret = htx_apply_filter_to_sts_line(s, res, exp);
3905 if (unlikely(ret < 0))
3906 return -1;
3907
3908 if (likely(ret == 0)) {
3909 /* The filter did not match the response, it can be
3910 * iterated through all headers.
3911 */
3912 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3913 return -1;
3914 }
3915 }
3916 return 0;
3917}
3918
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003919/*
3920 * Manage client-side cookie. It can impact performance by about 2% so it is
3921 * desirable to call it only when needed. This code is quite complex because
3922 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3923 * highly recommended not to touch this part without a good reason !
3924 */
3925static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3926{
3927 struct session *sess = s->sess;
3928 struct http_txn *txn = s->txn;
3929 struct htx *htx;
3930 struct http_hdr_ctx ctx;
3931 char *hdr_beg, *hdr_end, *del_from;
3932 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3933 int preserve_hdr;
3934
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003935 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003936 ctx.blk = NULL;
3937 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3938 del_from = NULL; /* nothing to be deleted */
3939 preserve_hdr = 0; /* assume we may kill the whole header */
3940
3941 /* Now look for cookies. Conforming to RFC2109, we have to support
3942 * attributes whose name begin with a '$', and associate them with
3943 * the right cookie, if we want to delete this cookie.
3944 * So there are 3 cases for each cookie read :
3945 * 1) it's a special attribute, beginning with a '$' : ignore it.
3946 * 2) it's a server id cookie that we *MAY* want to delete : save
3947 * some pointers on it (last semi-colon, beginning of cookie...)
3948 * 3) it's an application cookie : we *MAY* have to delete a previous
3949 * "special" cookie.
3950 * At the end of loop, if a "special" cookie remains, we may have to
3951 * remove it. If no application cookie persists in the header, we
3952 * *MUST* delete it.
3953 *
3954 * Note: RFC2965 is unclear about the processing of spaces around
3955 * the equal sign in the ATTR=VALUE form. A careful inspection of
3956 * the RFC explicitly allows spaces before it, and not within the
3957 * tokens (attrs or values). An inspection of RFC2109 allows that
3958 * too but section 10.1.3 lets one think that spaces may be allowed
3959 * after the equal sign too, resulting in some (rare) buggy
3960 * implementations trying to do that. So let's do what servers do.
3961 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3962 * allowed quoted strings in values, with any possible character
3963 * after a backslash, including control chars and delimitors, which
3964 * causes parsing to become ambiguous. Browsers also allow spaces
3965 * within values even without quotes.
3966 *
3967 * We have to keep multiple pointers in order to support cookie
3968 * removal at the beginning, middle or end of header without
3969 * corrupting the header. All of these headers are valid :
3970 *
3971 * hdr_beg hdr_end
3972 * | |
3973 * v |
3974 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3975 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3976 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3977 * | | | | | | |
3978 * | | | | | | |
3979 * | | | | | | +--> next
3980 * | | | | | +----> val_end
3981 * | | | | +-----------> val_beg
3982 * | | | +--------------> equal
3983 * | | +----------------> att_end
3984 * | +---------------------> att_beg
3985 * +--------------------------> prev
3986 *
3987 */
3988 hdr_beg = ctx.value.ptr;
3989 hdr_end = hdr_beg + ctx.value.len;
3990 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3991 /* Iterate through all cookies on this line */
3992
3993 /* find att_beg */
3994 att_beg = prev;
3995 if (prev > hdr_beg)
3996 att_beg++;
3997
3998 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3999 att_beg++;
4000
4001 /* find att_end : this is the first character after the last non
4002 * space before the equal. It may be equal to hdr_end.
4003 */
4004 equal = att_end = att_beg;
4005 while (equal < hdr_end) {
4006 if (*equal == '=' || *equal == ',' || *equal == ';')
4007 break;
4008 if (HTTP_IS_SPHT(*equal++))
4009 continue;
4010 att_end = equal;
4011 }
4012
4013 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4014 * is between <att_beg> and <equal>, both may be identical.
4015 */
4016 /* look for end of cookie if there is an equal sign */
4017 if (equal < hdr_end && *equal == '=') {
4018 /* look for the beginning of the value */
4019 val_beg = equal + 1;
4020 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4021 val_beg++;
4022
4023 /* find the end of the value, respecting quotes */
4024 next = http_find_cookie_value_end(val_beg, hdr_end);
4025
4026 /* make val_end point to the first white space or delimitor after the value */
4027 val_end = next;
4028 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4029 val_end--;
4030 }
4031 else
4032 val_beg = val_end = next = equal;
4033
4034 /* We have nothing to do with attributes beginning with
4035 * '$'. However, they will automatically be removed if a
4036 * header before them is removed, since they're supposed
4037 * to be linked together.
4038 */
4039 if (*att_beg == '$')
4040 continue;
4041
4042 /* Ignore cookies with no equal sign */
4043 if (equal == next) {
4044 /* This is not our cookie, so we must preserve it. But if we already
4045 * scheduled another cookie for removal, we cannot remove the
4046 * complete header, but we can remove the previous block itself.
4047 */
4048 preserve_hdr = 1;
4049 if (del_from != NULL) {
4050 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4051 val_end += delta;
4052 next += delta;
4053 hdr_end += delta;
4054 prev = del_from;
4055 del_from = NULL;
4056 }
4057 continue;
4058 }
4059
4060 /* if there are spaces around the equal sign, we need to
4061 * strip them otherwise we'll get trouble for cookie captures,
4062 * or even for rewrites. Since this happens extremely rarely,
4063 * it does not hurt performance.
4064 */
4065 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4066 int stripped_before = 0;
4067 int stripped_after = 0;
4068
4069 if (att_end != equal) {
4070 memmove(att_end, equal, hdr_end - equal);
4071 stripped_before = (att_end - equal);
4072 equal += stripped_before;
4073 val_beg += stripped_before;
4074 }
4075
4076 if (val_beg > equal + 1) {
4077 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4078 stripped_after = (equal + 1) - val_beg;
4079 val_beg += stripped_after;
4080 stripped_before += stripped_after;
4081 }
4082
4083 val_end += stripped_before;
4084 next += stripped_before;
4085 hdr_end += stripped_before;
4086 }
4087 /* now everything is as on the diagram above */
4088
4089 /* First, let's see if we want to capture this cookie. We check
4090 * that we don't already have a client side cookie, because we
4091 * can only capture one. Also as an optimisation, we ignore
4092 * cookies shorter than the declared name.
4093 */
4094 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4095 (val_end - att_beg >= sess->fe->capture_namelen) &&
4096 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4097 int log_len = val_end - att_beg;
4098
4099 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4100 ha_alert("HTTP logging : out of memory.\n");
4101 } else {
4102 if (log_len > sess->fe->capture_len)
4103 log_len = sess->fe->capture_len;
4104 memcpy(txn->cli_cookie, att_beg, log_len);
4105 txn->cli_cookie[log_len] = 0;
4106 }
4107 }
4108
4109 /* Persistence cookies in passive, rewrite or insert mode have the
4110 * following form :
4111 *
4112 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4113 *
4114 * For cookies in prefix mode, the form is :
4115 *
4116 * Cookie: NAME=SRV~VALUE
4117 */
4118 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4119 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4120 struct server *srv = s->be->srv;
4121 char *delim;
4122
4123 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4124 * have the server ID between val_beg and delim, and the original cookie between
4125 * delim+1 and val_end. Otherwise, delim==val_end :
4126 *
4127 * hdr_beg
4128 * |
4129 * v
4130 * NAME=SRV; # in all but prefix modes
4131 * NAME=SRV~OPAQUE ; # in prefix mode
4132 * || || | |+-> next
4133 * || || | +--> val_end
4134 * || || +---------> delim
4135 * || |+------------> val_beg
4136 * || +-------------> att_end = equal
4137 * |+-----------------> att_beg
4138 * +------------------> prev
4139 *
4140 */
4141 if (s->be->ck_opts & PR_CK_PFX) {
4142 for (delim = val_beg; delim < val_end; delim++)
4143 if (*delim == COOKIE_DELIM)
4144 break;
4145 }
4146 else {
4147 char *vbar1;
4148 delim = val_end;
4149 /* Now check if the cookie contains a date field, which would
4150 * appear after a vertical bar ('|') just after the server name
4151 * and before the delimiter.
4152 */
4153 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4154 if (vbar1) {
4155 /* OK, so left of the bar is the server's cookie and
4156 * right is the last seen date. It is a base64 encoded
4157 * 30-bit value representing the UNIX date since the
4158 * epoch in 4-second quantities.
4159 */
4160 int val;
4161 delim = vbar1++;
4162 if (val_end - vbar1 >= 5) {
4163 val = b64tos30(vbar1);
4164 if (val > 0)
4165 txn->cookie_last_date = val << 2;
4166 }
4167 /* look for a second vertical bar */
4168 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4169 if (vbar1 && (val_end - vbar1 > 5)) {
4170 val = b64tos30(vbar1 + 1);
4171 if (val > 0)
4172 txn->cookie_first_date = val << 2;
4173 }
4174 }
4175 }
4176
4177 /* if the cookie has an expiration date and the proxy wants to check
4178 * it, then we do that now. We first check if the cookie is too old,
4179 * then only if it has expired. We detect strict overflow because the
4180 * time resolution here is not great (4 seconds). Cookies with dates
4181 * in the future are ignored if their offset is beyond one day. This
4182 * allows an admin to fix timezone issues without expiring everyone
4183 * and at the same time avoids keeping unwanted side effects for too
4184 * long.
4185 */
4186 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4187 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4188 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4189 txn->flags &= ~TX_CK_MASK;
4190 txn->flags |= TX_CK_OLD;
4191 delim = val_beg; // let's pretend we have not found the cookie
4192 txn->cookie_first_date = 0;
4193 txn->cookie_last_date = 0;
4194 }
4195 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4196 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4197 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4198 txn->flags &= ~TX_CK_MASK;
4199 txn->flags |= TX_CK_EXPIRED;
4200 delim = val_beg; // let's pretend we have not found the cookie
4201 txn->cookie_first_date = 0;
4202 txn->cookie_last_date = 0;
4203 }
4204
4205 /* Here, we'll look for the first running server which supports the cookie.
4206 * This allows to share a same cookie between several servers, for example
4207 * to dedicate backup servers to specific servers only.
4208 * However, to prevent clients from sticking to cookie-less backup server
4209 * when they have incidentely learned an empty cookie, we simply ignore
4210 * empty cookies and mark them as invalid.
4211 * The same behaviour is applied when persistence must be ignored.
4212 */
4213 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4214 srv = NULL;
4215
4216 while (srv) {
4217 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4218 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4219 if ((srv->cur_state != SRV_ST_STOPPED) ||
4220 (s->be->options & PR_O_PERSIST) ||
4221 (s->flags & SF_FORCE_PRST)) {
4222 /* we found the server and we can use it */
4223 txn->flags &= ~TX_CK_MASK;
4224 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4225 s->flags |= SF_DIRECT | SF_ASSIGNED;
4226 s->target = &srv->obj_type;
4227 break;
4228 } else {
4229 /* we found a server, but it's down,
4230 * mark it as such and go on in case
4231 * another one is available.
4232 */
4233 txn->flags &= ~TX_CK_MASK;
4234 txn->flags |= TX_CK_DOWN;
4235 }
4236 }
4237 srv = srv->next;
4238 }
4239
4240 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4241 /* no server matched this cookie or we deliberately skipped it */
4242 txn->flags &= ~TX_CK_MASK;
4243 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4244 txn->flags |= TX_CK_UNUSED;
4245 else
4246 txn->flags |= TX_CK_INVALID;
4247 }
4248
4249 /* depending on the cookie mode, we may have to either :
4250 * - delete the complete cookie if we're in insert+indirect mode, so that
4251 * the server never sees it ;
4252 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004253 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004254 * if we're in cookie prefix mode
4255 */
4256 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4257 int delta; /* negative */
4258
4259 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4260 delta = val_beg - (delim + 1);
4261 val_end += delta;
4262 next += delta;
4263 hdr_end += delta;
4264 del_from = NULL;
4265 preserve_hdr = 1; /* we want to keep this cookie */
4266 }
4267 else if (del_from == NULL &&
4268 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4269 del_from = prev;
4270 }
4271 }
4272 else {
4273 /* This is not our cookie, so we must preserve it. But if we already
4274 * scheduled another cookie for removal, we cannot remove the
4275 * complete header, but we can remove the previous block itself.
4276 */
4277 preserve_hdr = 1;
4278
4279 if (del_from != NULL) {
4280 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4281 if (att_beg >= del_from)
4282 att_beg += delta;
4283 if (att_end >= del_from)
4284 att_end += delta;
4285 val_beg += delta;
4286 val_end += delta;
4287 next += delta;
4288 hdr_end += delta;
4289 prev = del_from;
4290 del_from = NULL;
4291 }
4292 }
4293
4294 /* continue with next cookie on this header line */
4295 att_beg = next;
4296 } /* for each cookie */
4297
4298
4299 /* There are no more cookies on this line.
4300 * We may still have one (or several) marked for deletion at the
4301 * end of the line. We must do this now in two ways :
4302 * - if some cookies must be preserved, we only delete from the
4303 * mark to the end of line ;
4304 * - if nothing needs to be preserved, simply delete the whole header
4305 */
4306 if (del_from) {
4307 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4308 }
4309 if ((hdr_end - hdr_beg) != ctx.value.len) {
4310 if (hdr_beg != hdr_end) {
4311 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004312 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004313 }
4314 else
4315 http_remove_header(htx, &ctx);
4316 }
4317 } /* for each "Cookie header */
4318}
4319
4320/*
4321 * Manage server-side cookies. It can impact performance by about 2% so it is
4322 * desirable to call it only when needed. This function is also used when we
4323 * just need to know if there is a cookie (eg: for check-cache).
4324 */
4325static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4326{
4327 struct session *sess = s->sess;
4328 struct http_txn *txn = s->txn;
4329 struct htx *htx;
4330 struct http_hdr_ctx ctx;
4331 struct server *srv;
4332 char *hdr_beg, *hdr_end;
4333 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
Willy Tarreau6f7a02a2019-04-15 21:49:49 +02004334 int is_cookie2 = 0;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004335
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004336 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004337
4338 ctx.blk = NULL;
4339 while (1) {
4340 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4341 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4342 break;
4343 is_cookie2 = 1;
4344 }
4345
4346 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4347 * <prev> points to the colon.
4348 */
4349 txn->flags |= TX_SCK_PRESENT;
4350
4351 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4352 * check-cache is enabled) and we are not interested in checking
4353 * them. Warning, the cookie capture is declared in the frontend.
4354 */
4355 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4356 break;
4357
4358 /* OK so now we know we have to process this response cookie.
4359 * The format of the Set-Cookie header is slightly different
4360 * from the format of the Cookie header in that it does not
4361 * support the comma as a cookie delimiter (thus the header
4362 * cannot be folded) because the Expires attribute described in
4363 * the original Netscape's spec may contain an unquoted date
4364 * with a comma inside. We have to live with this because
4365 * many browsers don't support Max-Age and some browsers don't
4366 * support quoted strings. However the Set-Cookie2 header is
4367 * clean.
4368 *
4369 * We have to keep multiple pointers in order to support cookie
4370 * removal at the beginning, middle or end of header without
4371 * corrupting the header (in case of set-cookie2). A special
4372 * pointer, <scav> points to the beginning of the set-cookie-av
4373 * fields after the first semi-colon. The <next> pointer points
4374 * either to the end of line (set-cookie) or next unquoted comma
4375 * (set-cookie2). All of these headers are valid :
4376 *
4377 * hdr_beg hdr_end
4378 * | |
4379 * v |
4380 * NAME1 = VALUE 1 ; Secure; Path="/" |
4381 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4382 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4383 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4384 * | | | | | | | |
4385 * | | | | | | | +-> next
4386 * | | | | | | +------------> scav
4387 * | | | | | +--------------> val_end
4388 * | | | | +--------------------> val_beg
4389 * | | | +----------------------> equal
4390 * | | +------------------------> att_end
4391 * | +----------------------------> att_beg
4392 * +------------------------------> prev
4393 * -------------------------------> hdr_beg
4394 */
4395 hdr_beg = ctx.value.ptr;
4396 hdr_end = hdr_beg + ctx.value.len;
4397 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4398
4399 /* Iterate through all cookies on this line */
4400
4401 /* find att_beg */
4402 att_beg = prev;
4403 if (prev > hdr_beg)
4404 att_beg++;
4405
4406 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4407 att_beg++;
4408
4409 /* find att_end : this is the first character after the last non
4410 * space before the equal. It may be equal to hdr_end.
4411 */
4412 equal = att_end = att_beg;
4413
4414 while (equal < hdr_end) {
4415 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4416 break;
4417 if (HTTP_IS_SPHT(*equal++))
4418 continue;
4419 att_end = equal;
4420 }
4421
4422 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4423 * is between <att_beg> and <equal>, both may be identical.
4424 */
4425
4426 /* look for end of cookie if there is an equal sign */
4427 if (equal < hdr_end && *equal == '=') {
4428 /* look for the beginning of the value */
4429 val_beg = equal + 1;
4430 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4431 val_beg++;
4432
4433 /* find the end of the value, respecting quotes */
4434 next = http_find_cookie_value_end(val_beg, hdr_end);
4435
4436 /* make val_end point to the first white space or delimitor after the value */
4437 val_end = next;
4438 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4439 val_end--;
4440 }
4441 else {
4442 /* <equal> points to next comma, semi-colon or EOL */
4443 val_beg = val_end = next = equal;
4444 }
4445
4446 if (next < hdr_end) {
4447 /* Set-Cookie2 supports multiple cookies, and <next> points to
4448 * a colon or semi-colon before the end. So skip all attr-value
4449 * pairs and look for the next comma. For Set-Cookie, since
4450 * commas are permitted in values, skip to the end.
4451 */
4452 if (is_cookie2)
4453 next = http_find_hdr_value_end(next, hdr_end);
4454 else
4455 next = hdr_end;
4456 }
4457
4458 /* Now everything is as on the diagram above */
4459
4460 /* Ignore cookies with no equal sign */
4461 if (equal == val_end)
4462 continue;
4463
4464 /* If there are spaces around the equal sign, we need to
4465 * strip them otherwise we'll get trouble for cookie captures,
4466 * or even for rewrites. Since this happens extremely rarely,
4467 * it does not hurt performance.
4468 */
4469 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4470 int stripped_before = 0;
4471 int stripped_after = 0;
4472
4473 if (att_end != equal) {
4474 memmove(att_end, equal, hdr_end - equal);
4475 stripped_before = (att_end - equal);
4476 equal += stripped_before;
4477 val_beg += stripped_before;
4478 }
4479
4480 if (val_beg > equal + 1) {
4481 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4482 stripped_after = (equal + 1) - val_beg;
4483 val_beg += stripped_after;
4484 stripped_before += stripped_after;
4485 }
4486
4487 val_end += stripped_before;
4488 next += stripped_before;
4489 hdr_end += stripped_before;
4490
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004491 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4492 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004493 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004494 }
4495
4496 /* First, let's see if we want to capture this cookie. We check
4497 * that we don't already have a server side cookie, because we
4498 * can only capture one. Also as an optimisation, we ignore
4499 * cookies shorter than the declared name.
4500 */
4501 if (sess->fe->capture_name != NULL &&
4502 txn->srv_cookie == NULL &&
4503 (val_end - att_beg >= sess->fe->capture_namelen) &&
4504 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4505 int log_len = val_end - att_beg;
4506 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4507 ha_alert("HTTP logging : out of memory.\n");
4508 }
4509 else {
4510 if (log_len > sess->fe->capture_len)
4511 log_len = sess->fe->capture_len;
4512 memcpy(txn->srv_cookie, att_beg, log_len);
4513 txn->srv_cookie[log_len] = 0;
4514 }
4515 }
4516
4517 srv = objt_server(s->target);
4518 /* now check if we need to process it for persistence */
4519 if (!(s->flags & SF_IGNORE_PRST) &&
4520 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4521 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4522 /* assume passive cookie by default */
4523 txn->flags &= ~TX_SCK_MASK;
4524 txn->flags |= TX_SCK_FOUND;
4525
4526 /* If the cookie is in insert mode on a known server, we'll delete
4527 * this occurrence because we'll insert another one later.
4528 * We'll delete it too if the "indirect" option is set and we're in
4529 * a direct access.
4530 */
4531 if (s->be->ck_opts & PR_CK_PSV) {
4532 /* The "preserve" flag was set, we don't want to touch the
4533 * server's cookie.
4534 */
4535 }
4536 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4537 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4538 /* this cookie must be deleted */
4539 if (prev == hdr_beg && next == hdr_end) {
4540 /* whole header */
4541 http_remove_header(htx, &ctx);
4542 /* note: while both invalid now, <next> and <hdr_end>
4543 * are still equal, so the for() will stop as expected.
4544 */
4545 } else {
4546 /* just remove the value */
4547 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4548 next = prev;
4549 hdr_end += delta;
4550 }
4551 txn->flags &= ~TX_SCK_MASK;
4552 txn->flags |= TX_SCK_DELETED;
4553 /* and go on with next cookie */
4554 }
4555 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4556 /* replace bytes val_beg->val_end with the cookie name associated
4557 * with this server since we know it.
4558 */
4559 int sliding, delta;
4560
4561 ctx.value = ist2(val_beg, val_end - val_beg);
4562 ctx.lws_before = ctx.lws_after = 0;
4563 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4564 delta = srv->cklen - (val_end - val_beg);
4565 sliding = (ctx.value.ptr - val_beg);
4566 hdr_beg += sliding;
4567 val_beg += sliding;
4568 next += sliding + delta;
4569 hdr_end += sliding + delta;
4570
4571 txn->flags &= ~TX_SCK_MASK;
4572 txn->flags |= TX_SCK_REPLACED;
4573 }
4574 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4575 /* insert the cookie name associated with this server
4576 * before existing cookie, and insert a delimiter between them..
4577 */
4578 int sliding, delta;
4579 ctx.value = ist2(val_beg, 0);
4580 ctx.lws_before = ctx.lws_after = 0;
4581 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4582 delta = srv->cklen + 1;
4583 sliding = (ctx.value.ptr - val_beg);
4584 hdr_beg += sliding;
4585 val_beg += sliding;
4586 next += sliding + delta;
4587 hdr_end += sliding + delta;
4588
4589 val_beg[srv->cklen] = COOKIE_DELIM;
4590 txn->flags &= ~TX_SCK_MASK;
4591 txn->flags |= TX_SCK_REPLACED;
4592 }
4593 }
4594 /* that's done for this cookie, check the next one on the same
4595 * line when next != hdr_end (only if is_cookie2).
4596 */
4597 }
4598 }
4599}
4600
Christopher Faulet25a02f62018-10-24 12:00:25 +02004601/*
4602 * Parses the Cache-Control and Pragma request header fields to determine if
4603 * the request may be served from the cache and/or if it is cacheable. Updates
4604 * s->txn->flags.
4605 */
4606void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4607{
4608 struct http_txn *txn = s->txn;
4609 struct htx *htx;
4610 int32_t pos;
4611 int pragma_found, cc_found, i;
4612
4613 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4614 return; /* nothing more to do here */
4615
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004616 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004617 pragma_found = cc_found = 0;
Christopher Fauleta3f15502019-05-13 15:27:23 +02004618 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004619 struct htx_blk *blk = htx_get_blk(htx, pos);
4620 enum htx_blk_type type = htx_get_blk_type(blk);
4621 struct ist n, v;
4622
4623 if (type == HTX_BLK_EOH)
4624 break;
4625 if (type != HTX_BLK_HDR)
4626 continue;
4627
4628 n = htx_get_blk_name(htx, blk);
4629 v = htx_get_blk_value(htx, blk);
4630
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004631 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004632 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4633 pragma_found = 1;
4634 continue;
4635 }
4636 }
4637
4638 /* Don't use the cache and don't try to store if we found the
4639 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004640 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004641 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4642 txn->flags |= TX_CACHE_IGNORE;
4643 continue;
4644 }
4645
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004646 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004647 continue;
4648
4649 /* OK, right now we know we have a cache-control header */
4650 cc_found = 1;
4651 if (!v.len) /* no info */
4652 continue;
4653
4654 i = 0;
4655 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4656 !isspace((unsigned char)*(v.ptr+i)))
4657 i++;
4658
4659 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4660 * values after max-age, max-stale nor min-fresh, we simply don't
4661 * use the cache when they're specified.
4662 */
4663 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4664 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4665 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4666 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4667 txn->flags |= TX_CACHE_IGNORE;
4668 continue;
4669 }
4670
4671 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4672 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4673 continue;
4674 }
4675 }
4676
4677 /* RFC7234#5.4:
4678 * When the Cache-Control header field is also present and
4679 * understood in a request, Pragma is ignored.
4680 * When the Cache-Control header field is not present in a
4681 * request, caches MUST consider the no-cache request
4682 * pragma-directive as having the same effect as if
4683 * "Cache-Control: no-cache" were present.
4684 */
4685 if (!cc_found && pragma_found)
4686 txn->flags |= TX_CACHE_IGNORE;
4687}
4688
4689/*
4690 * Check if response is cacheable or not. Updates s->txn->flags.
4691 */
4692void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4693{
4694 struct http_txn *txn = s->txn;
4695 struct htx *htx;
4696 int32_t pos;
4697 int i;
4698
4699 if (txn->status < 200) {
4700 /* do not try to cache interim responses! */
4701 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4702 return;
4703 }
4704
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004705 htx = htxbuf(&res->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004706 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004707 struct htx_blk *blk = htx_get_blk(htx, pos);
4708 enum htx_blk_type type = htx_get_blk_type(blk);
4709 struct ist n, v;
4710
4711 if (type == HTX_BLK_EOH)
4712 break;
4713 if (type != HTX_BLK_HDR)
4714 continue;
4715
4716 n = htx_get_blk_name(htx, blk);
4717 v = htx_get_blk_value(htx, blk);
4718
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004719 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004720 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4721 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4722 return;
4723 }
4724 }
4725
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004726 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004727 continue;
4728
4729 /* OK, right now we know we have a cache-control header */
4730 if (!v.len) /* no info */
4731 continue;
4732
4733 i = 0;
4734 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4735 !isspace((unsigned char)*(v.ptr+i)))
4736 i++;
4737
4738 /* we have a complete value between v.ptr and (v.ptr+i) */
4739 if (i < v.len && *(v.ptr + i) == '=') {
4740 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4741 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4742 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4743 continue;
4744 }
4745
4746 /* we have something of the form no-cache="set-cookie" */
4747 if ((v.len >= 21) &&
4748 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4749 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4750 txn->flags &= ~TX_CACHE_COOK;
4751 continue;
4752 }
4753
4754 /* OK, so we know that either p2 points to the end of string or to a comma */
4755 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4756 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4757 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4758 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4759 return;
4760 }
4761
4762 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4763 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4764 continue;
4765 }
4766 }
4767}
4768
Christopher Faulet64159df2018-10-24 21:15:35 +02004769/* send a server's name with an outgoing request over an established connection.
4770 * Note: this function is designed to be called once the request has been
4771 * scheduled for being forwarded. This is the reason why the number of forwarded
4772 * bytes have to be adjusted.
4773 */
4774int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4775{
4776 struct htx *htx;
4777 struct http_hdr_ctx ctx;
4778 struct ist hdr;
4779 uint32_t data;
4780
4781 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004782 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004783 data = htx->data;
4784
4785 ctx.blk = NULL;
4786 while (http_find_header(htx, hdr, &ctx, 1))
4787 http_remove_header(htx, &ctx);
4788 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4789
4790 if (co_data(&s->req)) {
4791 if (data >= htx->data)
4792 c_rew(&s->req, data - htx->data);
4793 else
4794 c_adv(&s->req, htx->data - data);
4795 }
4796 return 0;
4797}
4798
Christopher Faulet377c5a52018-10-24 21:21:30 +02004799/*
4800 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4801 * for the current backend.
4802 *
4803 * It is assumed that the request is either a HEAD, GET, or POST and that the
4804 * uri_auth field is valid.
4805 *
4806 * Returns 1 if stats should be provided, otherwise 0.
4807 */
4808static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4809{
4810 struct uri_auth *uri_auth = backend->uri_auth;
4811 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004812 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004813 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004814
4815 if (!uri_auth)
4816 return 0;
4817
4818 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4819 return 0;
4820
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004821 htx = htxbuf(&s->req.buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004822 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004823 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004824
4825 /* check URI size */
4826 if (uri_auth->uri_len > uri.len)
4827 return 0;
4828
4829 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4830 return 0;
4831
4832 return 1;
4833}
4834
4835/* This function prepares an applet to handle the stats. It can deal with the
4836 * "100-continue" expectation, check that admin rules are met for POST requests,
4837 * and program a response message if something was unexpected. It cannot fail
4838 * and always relies on the stats applet to complete the job. It does not touch
4839 * analysers nor counters, which are left to the caller. It does not touch
4840 * s->target which is supposed to already point to the stats applet. The caller
4841 * is expected to have already assigned an appctx to the stream.
4842 */
4843static int htx_handle_stats(struct stream *s, struct channel *req)
4844{
4845 struct stats_admin_rule *stats_admin_rule;
4846 struct stream_interface *si = &s->si[1];
4847 struct session *sess = s->sess;
4848 struct http_txn *txn = s->txn;
4849 struct http_msg *msg = &txn->req;
4850 struct uri_auth *uri_auth = s->be->uri_auth;
4851 const char *h, *lookup, *end;
4852 struct appctx *appctx;
4853 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004854 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004855
4856 appctx = si_appctx(si);
4857 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4858 appctx->st1 = appctx->st2 = 0;
4859 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4860 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4861 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4862 appctx->ctx.stats.flags |= STAT_CHUNKED;
4863
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004864 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02004865 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004866 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4867 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004868
4869 for (h = lookup; h <= end - 3; h++) {
4870 if (memcmp(h, ";up", 3) == 0) {
4871 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4872 break;
4873 }
4874 }
4875
4876 if (uri_auth->refresh) {
4877 for (h = lookup; h <= end - 10; h++) {
4878 if (memcmp(h, ";norefresh", 10) == 0) {
4879 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4880 break;
4881 }
4882 }
4883 }
4884
4885 for (h = lookup; h <= end - 4; h++) {
4886 if (memcmp(h, ";csv", 4) == 0) {
4887 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4888 break;
4889 }
4890 }
4891
4892 for (h = lookup; h <= end - 6; h++) {
4893 if (memcmp(h, ";typed", 6) == 0) {
4894 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4895 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4896 break;
4897 }
4898 }
4899
4900 for (h = lookup; h <= end - 8; h++) {
4901 if (memcmp(h, ";st=", 4) == 0) {
4902 int i;
4903 h += 4;
4904 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4905 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4906 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4907 appctx->ctx.stats.st_code = i;
4908 break;
4909 }
4910 }
4911 break;
4912 }
4913 }
4914
4915 appctx->ctx.stats.scope_str = 0;
4916 appctx->ctx.stats.scope_len = 0;
4917 for (h = lookup; h <= end - 8; h++) {
4918 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4919 int itx = 0;
4920 const char *h2;
4921 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4922 const char *err;
4923
4924 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4925 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004926 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4927 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004928 if (*h == ';' || *h == '&' || *h == ' ')
4929 break;
4930 itx++;
4931 h++;
4932 }
4933
4934 if (itx > STAT_SCOPE_TXT_MAXLEN)
4935 itx = STAT_SCOPE_TXT_MAXLEN;
4936 appctx->ctx.stats.scope_len = itx;
4937
4938 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4939 memcpy(scope_txt, h2, itx);
4940 scope_txt[itx] = '\0';
4941 err = invalid_char(scope_txt);
4942 if (err) {
4943 /* bad char in search text => clear scope */
4944 appctx->ctx.stats.scope_str = 0;
4945 appctx->ctx.stats.scope_len = 0;
4946 }
4947 break;
4948 }
4949 }
4950
4951 /* now check whether we have some admin rules for this request */
4952 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4953 int ret = 1;
4954
4955 if (stats_admin_rule->cond) {
4956 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4957 ret = acl_pass(ret);
4958 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4959 ret = !ret;
4960 }
4961
4962 if (ret) {
4963 /* no rule, or the rule matches */
4964 appctx->ctx.stats.flags |= STAT_ADMIN;
4965 break;
4966 }
4967 }
4968
Christopher Faulet5d45e382019-02-27 15:15:23 +01004969 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4970 appctx->st0 = STAT_HTTP_HEAD;
4971 else if (txn->meth == HTTP_METH_POST) {
Christopher Fauletbcf242a2019-03-01 11:36:26 +01004972 if (appctx->ctx.stats.flags & STAT_ADMIN)
Christopher Faulet377c5a52018-10-24 21:21:30 +02004973 appctx->st0 = STAT_HTTP_POST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004974 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004975 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004976 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4977 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4978 appctx->st0 = STAT_HTTP_LAST;
4979 }
4980 }
4981 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004982 /* Unsupported method */
4983 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4984 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4985 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004986 }
4987
4988 s->task->nice = -32; /* small boost for HTTP statistics */
4989 return 1;
4990}
4991
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004992void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4993{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004994 struct channel *req = &s->req;
4995 struct channel *res = &s->res;
4996 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004997 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004998 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004999 struct ist path, location;
5000 unsigned int flags;
5001 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005002
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 /*
5004 * Create the location
5005 */
5006 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005008 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005009 /* special prefix "/" means don't change URL */
5010 srv = __objt_server(s->target);
5011 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5012 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5013 return;
5014 }
5015
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005016 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005017 htx = htxbuf(&req->buf);
Christopher Faulet297fbb42019-05-13 14:41:27 +02005018 sl = http_get_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005019 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005020 if (!path.ptr)
5021 return;
5022
5023 if (!chunk_memcat(&trash, path.ptr, path.len))
5024 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005026
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005027 /*
5028 * Create the 302 respone
5029 */
5030 htx = htx_from_buf(&res->buf);
5031 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5032 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5033 ist("HTTP/1.1"), ist("302"), ist("Found"));
5034 if (!sl)
5035 goto fail;
5036 sl->info.res.status = 302;
5037 s->txn->status = 302;
5038
5039 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5040 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5041 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5042 !htx_add_header(htx, ist("Location"), location))
5043 goto fail;
5044
5045 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5046 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005047
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005048 /*
5049 * Send the message
5050 */
5051 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005052 c_adv(res, data);
5053 res->total += data;
5054
5055 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005056 si_shutr(si);
5057 si_shutw(si);
5058 si->err_type = SI_ET_NONE;
5059 si->state = SI_ST_CLO;
5060
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005061 channel_auto_read(req);
5062 channel_abort(req);
5063 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005064 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005065 channel_auto_read(res);
5066 channel_auto_close(res);
5067
5068 if (!(s->flags & SF_ERR_MASK))
5069 s->flags |= SF_ERR_LOCAL;
5070 if (!(s->flags & SF_FINST_MASK))
5071 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005072
5073 /* FIXME: we should increase a counter of redirects per server and per backend. */
5074 srv_inc_sess_ctr(srv);
5075 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005076 return;
5077
5078 fail:
5079 /* If an error occurred, remove the incomplete HTTP response from the
5080 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005081 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005082}
5083
Christopher Fauletf2824e62018-10-01 12:12:37 +02005084/* This function terminates the request because it was completly analyzed or
5085 * because an error was triggered during the body forwarding.
5086 */
5087static void htx_end_request(struct stream *s)
5088{
5089 struct channel *chn = &s->req;
5090 struct http_txn *txn = s->txn;
5091
5092 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5093 now_ms, __FUNCTION__, s,
5094 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5095 s->req.analysers, s->res.analysers);
5096
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005097 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5098 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005100 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005101 goto end;
5102 }
5103
5104 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5105 return;
5106
5107 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005108 /* No need to read anymore, the request was completely parsed.
5109 * We can shut the read side unless we want to abort_on_close,
5110 * or we have a POST request. The issue with POST requests is
5111 * that some browsers still send a CRLF after the request, and
5112 * this CRLF must be read so that it does not remain in the kernel
5113 * buffers, otherwise a close could cause an RST on some systems
5114 * (eg: Linux).
5115 */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005116 if (!(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST)
Christopher Fauletf2824e62018-10-01 12:12:37 +02005117 channel_dont_read(chn);
5118
5119 /* if the server closes the connection, we want to immediately react
5120 * and close the socket to save packets and syscalls.
5121 */
5122 s->si[1].flags |= SI_FL_NOHALF;
5123
5124 /* In any case we've finished parsing the request so we must
5125 * disable Nagle when sending data because 1) we're not going
5126 * to shut this side, and 2) the server is waiting for us to
5127 * send pending data.
5128 */
5129 chn->flags |= CF_NEVER_WAIT;
5130
Christopher Fauletd01ce402019-01-02 17:44:13 +01005131 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5132 /* The server has not finished to respond, so we
5133 * don't want to move in order not to upset it.
5134 */
5135 return;
5136 }
5137
Christopher Fauletf2824e62018-10-01 12:12:37 +02005138 /* When we get here, it means that both the request and the
5139 * response have finished receiving. Depending on the connection
5140 * mode, we'll have to wait for the last bytes to leave in either
5141 * direction, and sometimes for a close to be effective.
5142 */
5143 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5144 /* Tunnel mode will not have any analyser so it needs to
5145 * poll for reads.
5146 */
5147 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005148 if (b_data(&chn->buf))
5149 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005150 txn->req.msg_state = HTTP_MSG_TUNNEL;
5151 }
5152 else {
5153 /* we're not expecting any new data to come for this
5154 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005155 *
5156 * However, there is an exception if the response
5157 * length is undefined. In this case, we need to wait
5158 * the close from the server. The response will be
5159 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 */
5161 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5162 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005163 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005164
5165 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5166 channel_shutr_now(chn);
5167 channel_shutw_now(chn);
5168 }
5169 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005170 goto check_channel_flags;
5171 }
5172
5173 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5174 http_msg_closing:
5175 /* nothing else to forward, just waiting for the output buffer
5176 * to be empty and for the shutw_now to take effect.
5177 */
5178 if (channel_is_empty(chn)) {
5179 txn->req.msg_state = HTTP_MSG_CLOSED;
5180 goto http_msg_closed;
5181 }
5182 else if (chn->flags & CF_SHUTW) {
5183 txn->req.err_state = txn->req.msg_state;
5184 txn->req.msg_state = HTTP_MSG_ERROR;
5185 goto end;
5186 }
5187 return;
5188 }
5189
5190 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5191 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005192 /* if we don't know whether the server will close, we need to hard close */
5193 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5194 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005195 /* see above in MSG_DONE why we only do this in these states */
Christopher Faulet769d0e92019-03-22 14:23:18 +01005196 if (!(s->be->options & PR_O_ABRT_CLOSE))
Christopher Fauletf2824e62018-10-01 12:12:37 +02005197 channel_dont_read(chn);
5198 goto end;
5199 }
5200
5201 check_channel_flags:
5202 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5203 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5204 /* if we've just closed an output, let's switch */
5205 txn->req.msg_state = HTTP_MSG_CLOSING;
5206 goto http_msg_closing;
5207 }
5208
5209 end:
5210 chn->analysers &= AN_REQ_FLT_END;
5211 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5212 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5213 channel_auto_close(chn);
5214 channel_auto_read(chn);
5215}
5216
5217
5218/* This function terminates the response because it was completly analyzed or
5219 * because an error was triggered during the body forwarding.
5220 */
5221static void htx_end_response(struct stream *s)
5222{
5223 struct channel *chn = &s->res;
5224 struct http_txn *txn = s->txn;
5225
5226 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5227 now_ms, __FUNCTION__, s,
5228 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5229 s->req.analysers, s->res.analysers);
5230
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005231 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5232 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005233 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005234 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005235 goto end;
5236 }
5237
5238 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5239 return;
5240
5241 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5242 /* In theory, we don't need to read anymore, but we must
5243 * still monitor the server connection for a possible close
5244 * while the request is being uploaded, so we don't disable
5245 * reading.
5246 */
5247 /* channel_dont_read(chn); */
5248
5249 if (txn->req.msg_state < HTTP_MSG_DONE) {
5250 /* The client seems to still be sending data, probably
5251 * because we got an error response during an upload.
5252 * We have the choice of either breaking the connection
5253 * or letting it pass through. Let's do the later.
5254 */
5255 return;
5256 }
5257
5258 /* When we get here, it means that both the request and the
5259 * response have finished receiving. Depending on the connection
5260 * mode, we'll have to wait for the last bytes to leave in either
5261 * direction, and sometimes for a close to be effective.
5262 */
5263 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5264 channel_auto_read(chn);
5265 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005266 if (b_data(&chn->buf))
5267 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005268 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5269 }
5270 else {
5271 /* we're not expecting any new data to come for this
5272 * transaction, so we can close it.
5273 */
5274 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5275 channel_shutr_now(chn);
5276 channel_shutw_now(chn);
5277 }
5278 }
5279 goto check_channel_flags;
5280 }
5281
5282 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5283 http_msg_closing:
5284 /* nothing else to forward, just waiting for the output buffer
5285 * to be empty and for the shutw_now to take effect.
5286 */
5287 if (channel_is_empty(chn)) {
5288 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5289 goto http_msg_closed;
5290 }
5291 else if (chn->flags & CF_SHUTW) {
5292 txn->rsp.err_state = txn->rsp.msg_state;
5293 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005294 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005295 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005296 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005297 goto end;
5298 }
5299 return;
5300 }
5301
5302 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5303 http_msg_closed:
5304 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005305 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005306 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005307 goto end;
5308 }
5309
5310 check_channel_flags:
5311 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5312 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5313 /* if we've just closed an output, let's switch */
5314 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5315 goto http_msg_closing;
5316 }
5317
5318 end:
5319 chn->analysers &= AN_RES_FLT_END;
5320 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5321 chn->analysers |= AN_RES_FLT_XFER_DATA;
5322 channel_auto_close(chn);
5323 channel_auto_read(chn);
5324}
5325
Christopher Faulet0f226952018-10-22 09:29:56 +02005326void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5327 int finst, const struct buffer *msg)
5328{
5329 channel_auto_read(si_oc(si));
5330 channel_abort(si_oc(si));
5331 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005332 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005333 channel_auto_close(si_ic(si));
5334 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005335
5336 /* <msg> is an HTX structure. So we copy it in the response's
5337 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005338 if (msg) {
5339 struct channel *chn = si_ic(si);
5340 struct htx *htx;
5341
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005342 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005343 chn->buf.data = msg->data;
5344 memcpy(chn->buf.area, msg->area, msg->data);
5345 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005346 c_adv(chn, htx->data);
5347 chn->total += htx->data;
5348 }
5349 if (!(s->flags & SF_ERR_MASK))
5350 s->flags |= err;
5351 if (!(s->flags & SF_FINST_MASK))
5352 s->flags |= finst;
5353}
5354
5355void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5356{
5357 channel_auto_read(&s->req);
5358 channel_abort(&s->req);
5359 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005360 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5361 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005362
5363 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005364
5365 /* <msg> is an HTX structure. So we copy it in the response's
5366 * channel */
5367 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005368 if (msg) {
5369 struct channel *chn = &s->res;
5370 struct htx *htx;
5371
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005372 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005373 chn->buf.data = msg->data;
5374 memcpy(chn->buf.area, msg->area, msg->data);
5375 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005376 c_adv(chn, htx->data);
5377 chn->total += htx->data;
5378 }
5379
5380 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5381 channel_auto_read(&s->res);
5382 channel_auto_close(&s->res);
5383 channel_shutr_now(&s->res);
5384}
5385
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005386struct buffer *htx_error_message(struct stream *s)
5387{
5388 const int msgnum = http_get_status_idx(s->txn->status);
5389
5390 if (s->be->errmsg[msgnum].area)
5391 return &s->be->errmsg[msgnum];
5392 else if (strm_fe(s)->errmsg[msgnum].area)
5393 return &strm_fe(s)->errmsg[msgnum];
5394 else
5395 return &htx_err_chunks[msgnum];
5396}
5397
5398
Christopher Faulet4a28a532019-03-01 11:19:40 +01005399/* Handle Expect: 100-continue for HTTP/1.1 messages if necessary. It returns 0
5400 * on success and -1 on error.
5401 */
5402static int htx_handle_expect_hdr(struct stream *s, struct htx *htx, struct http_msg *msg)
5403{
5404 /* If we have HTTP/1.1 message with a body and Expect: 100-continue,
5405 * then we must send an HTTP/1.1 100 Continue intermediate response.
5406 */
5407 if (msg->msg_state == HTTP_MSG_BODY && (msg->flags & HTTP_MSGF_VER_11) &&
5408 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
5409 struct ist hdr = { .ptr = "Expect", .len = 6 };
5410 struct http_hdr_ctx ctx;
5411
5412 ctx.blk = NULL;
5413 /* Expect is allowed in 1.1, look for it */
5414 if (http_find_header(htx, hdr, &ctx, 0) &&
5415 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
5416 if (htx_reply_100_continue(s) == -1)
5417 return -1;
5418 http_remove_header(htx, &ctx);
5419 }
5420 }
5421 return 0;
5422}
5423
Christopher Faulet23a3c792018-11-28 10:01:23 +01005424/* Send a 100-Continue response to the client. It returns 0 on success and -1
5425 * on error. The response channel is updated accordingly.
5426 */
5427static int htx_reply_100_continue(struct stream *s)
5428{
5429 struct channel *res = &s->res;
5430 struct htx *htx = htx_from_buf(&res->buf);
5431 struct htx_sl *sl;
5432 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5433 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5434 size_t data;
5435
5436 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5437 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5438 if (!sl)
5439 goto fail;
5440 sl->info.res.status = 100;
5441
5442 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5443 goto fail;
5444
5445 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005446 c_adv(res, data);
5447 res->total += data;
5448 return 0;
5449
5450 fail:
5451 /* If an error occurred, remove the incomplete HTTP response from the
5452 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005453 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005454 return -1;
5455}
5456
Christopher Faulet12c51e22018-11-28 15:59:42 +01005457
5458/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5459 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5460 * error. The response channel is updated accordingly.
5461 */
5462static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5463{
5464 struct channel *res = &s->res;
5465 struct htx *htx = htx_from_buf(&res->buf);
5466 struct htx_sl *sl;
5467 struct ist code, body;
5468 int status;
5469 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5470 size_t data;
5471
5472 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5473 status = 401;
5474 code = ist("401");
5475 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5476 "You need a valid user and password to access this content.\n"
5477 "</body></html>\n");
5478 }
5479 else {
5480 status = 407;
5481 code = ist("407");
5482 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5483 "You need a valid user and password to access this content.\n"
5484 "</body></html>\n");
5485 }
5486
5487 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5488 ist("HTTP/1.1"), code, ist("Unauthorized"));
5489 if (!sl)
5490 goto fail;
5491 sl->info.res.status = status;
5492 s->txn->status = status;
5493
5494 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5495 goto fail;
5496
5497 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5498 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005499 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5500 goto fail;
5501 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5502 goto fail;
5503 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005504 goto fail;
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005505 if (!htx_add_endof(htx, HTX_BLK_EOH))
5506 goto fail;
5507
5508 while (body.len) {
5509 size_t sent = htx_add_data(htx, body);
5510 if (!sent)
5511 goto fail;
5512 body.ptr += sent;
5513 body.len -= sent;
5514 }
5515
5516 if (!htx_add_endof(htx, HTX_BLK_EOM))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005517 goto fail;
5518
5519 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005520 c_adv(res, data);
5521 res->total += data;
5522
5523 channel_auto_read(&s->req);
5524 channel_abort(&s->req);
5525 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005526 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005527
5528 res->wex = tick_add_ifset(now_ms, res->wto);
5529 channel_auto_read(res);
5530 channel_auto_close(res);
5531 channel_shutr_now(res);
5532 return 0;
5533
5534 fail:
5535 /* If an error occurred, remove the incomplete HTTP response from the
5536 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005537 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005538 return -1;
5539}
5540
Christopher Faulet0f226952018-10-22 09:29:56 +02005541/*
5542 * Capture headers from message <htx> according to header list <cap_hdr>, and
5543 * fill the <cap> pointers appropriately.
5544 */
5545static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5546{
5547 struct cap_hdr *h;
5548 int32_t pos;
5549
Christopher Fauleta3f15502019-05-13 15:27:23 +02005550 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet0f226952018-10-22 09:29:56 +02005551 struct htx_blk *blk = htx_get_blk(htx, pos);
5552 enum htx_blk_type type = htx_get_blk_type(blk);
5553 struct ist n, v;
5554
5555 if (type == HTX_BLK_EOH)
5556 break;
5557 if (type != HTX_BLK_HDR)
5558 continue;
5559
5560 n = htx_get_blk_name(htx, blk);
5561
5562 for (h = cap_hdr; h; h = h->next) {
5563 if (h->namelen && (h->namelen == n.len) &&
5564 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5565 if (cap[h->index] == NULL)
5566 cap[h->index] =
5567 pool_alloc(h->pool);
5568
5569 if (cap[h->index] == NULL) {
5570 ha_alert("HTTP capture : out of memory.\n");
5571 break;
5572 }
5573
5574 v = htx_get_blk_value(htx, blk);
5575 if (v.len > h->len)
5576 v.len = h->len;
5577
5578 memcpy(cap[h->index], v.ptr, v.len);
5579 cap[h->index][v.len]=0;
5580 }
5581 }
5582 }
5583}
5584
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005585/* Delete a value in a header between delimiters <from> and <next>. The header
5586 * itself is delimited by <start> and <end> pointers. The number of characters
5587 * displaced is returned, and the pointer to the first delimiter is updated if
5588 * required. The function tries as much as possible to respect the following
5589 * principles :
5590 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5591 * in which case <next> is simply removed
5592 * - set exactly one space character after the new first delimiter, unless there
5593 * are not enough characters in the block being moved to do so.
5594 * - remove unneeded spaces before the previous delimiter and after the new
5595 * one.
5596 *
5597 * It is the caller's responsibility to ensure that :
5598 * - <from> points to a valid delimiter or <start> ;
5599 * - <next> points to a valid delimiter or <end> ;
5600 * - there are non-space chars before <from>.
5601 */
5602static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5603{
5604 char *prev = *from;
5605
5606 if (prev == start) {
5607 /* We're removing the first value. eat the semicolon, if <next>
5608 * is lower than <end> */
5609 if (next < end)
5610 next++;
5611
5612 while (next < end && HTTP_IS_SPHT(*next))
5613 next++;
5614 }
5615 else {
5616 /* Remove useless spaces before the old delimiter. */
5617 while (HTTP_IS_SPHT(*(prev-1)))
5618 prev--;
5619 *from = prev;
5620
5621 /* copy the delimiter and if possible a space if we're
5622 * not at the end of the line.
5623 */
5624 if (next < end) {
5625 *prev++ = *next++;
5626 if (prev + 1 < next)
5627 *prev++ = ' ';
5628 while (next < end && HTTP_IS_SPHT(*next))
5629 next++;
5630 }
5631 }
5632 memmove(prev, next, end - next);
5633 return (prev - next);
5634}
5635
Christopher Faulet0f226952018-10-22 09:29:56 +02005636
5637/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005638 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005641{
5642 struct ist dst = ist2(str, 0);
5643
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005644 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005645 goto end;
5646 if (dst.len + 1 > len)
5647 goto end;
5648 dst.ptr[dst.len++] = ' ';
5649
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005650 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005651 goto end;
5652 if (dst.len + 1 > len)
5653 goto end;
5654 dst.ptr[dst.len++] = ' ';
5655
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005656 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005657 end:
5658 return dst.len;
5659}
5660
Christopher Fauletf0523542018-10-24 11:06:58 +02005661/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005662 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005663 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005664static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005665{
5666 struct ist dst = ist2(str, 0);
5667
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005668 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005669 goto end;
5670 if (dst.len + 1 > len)
5671 goto end;
5672 dst.ptr[dst.len++] = ' ';
5673
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005674 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005675 goto end;
5676 if (dst.len + 1 > len)
5677 goto end;
5678 dst.ptr[dst.len++] = ' ';
5679
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005680 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005681 end:
5682 return dst.len;
5683}
5684
5685
Christopher Faulet0f226952018-10-22 09:29:56 +02005686/*
5687 * Print a debug line with a start line.
5688 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005689static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005690{
5691 struct session *sess = strm_sess(s);
5692 int max;
5693
5694 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5695 dir,
5696 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5697 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5698
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005699 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005700 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005701 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005702 trash.area[trash.data++] = ' ';
5703
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005704 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005705 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005706 chunk_memcat(&trash, HTX_SL_P2_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_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005710 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005711 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005712 trash.area[trash.data++] = '\n';
5713
5714 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5715}
5716
5717/*
5718 * Print a debug line with a header.
5719 */
5720static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5721{
5722 struct session *sess = strm_sess(s);
5723 int max;
5724
5725 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5726 dir,
5727 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5728 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5729
5730 max = n.len;
5731 UBOUND(max, trash.size - trash.data - 3);
5732 chunk_memcat(&trash, n.ptr, max);
5733 trash.area[trash.data++] = ':';
5734 trash.area[trash.data++] = ' ';
5735
5736 max = v.len;
5737 UBOUND(max, trash.size - trash.data - 1);
5738 chunk_memcat(&trash, v.ptr, max);
5739 trash.area[trash.data++] = '\n';
5740
5741 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5742}
5743
5744
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005745__attribute__((constructor))
5746static void __htx_protocol_init(void)
5747{
5748}
5749
5750
5751/*
5752 * Local variables:
5753 * c-indent-level: 8
5754 * c-basic-offset: 8
5755 * End:
5756 */