blob: 9088ecb521fe6e85b1e2278d45785ed5813e7df9 [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>
16#include <common/uri_auth.h>
17
18#include <types/cache.h>
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>
29#include <proto/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020030#include <proto/log.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020031#include <proto/pattern.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020032#include <proto/proto_http.h>
33#include <proto/proxy.h>
Christopher Fauletfefc73d2018-10-24 21:18:04 +020034#include <proto/server.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020035#include <proto/stream.h>
36#include <proto/stream_interface.h>
37#include <proto/stats.h>
38
Christopher Faulet377c5a52018-10-24 21:21:30 +020039extern const char *stat_status_codes[];
Christopher Fauletf2824e62018-10-01 12:12:37 +020040
41static void htx_end_request(struct stream *s);
42static void htx_end_response(struct stream *s);
43
Christopher Faulet0f226952018-10-22 09:29:56 +020044static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr);
Christopher Faulet0b6bdc52018-10-24 11:05:36 +020045static int htx_del_hdr_value(char *start, char *end, char **from, char *next);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010046static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
47static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
48static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020049static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v);
50
Christopher Faulet3e964192018-10-24 11:39:23 +020051static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s, int *deny_status);
52static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules, struct stream *s);
53
Christopher Faulet33640082018-10-24 11:53:01 +020054static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px);
55static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px);
56
Christopher Fauletfcda7c62018-10-24 11:56:22 +020057static void htx_manage_client_side_cookies(struct stream *s, struct channel *req);
58static void htx_manage_server_side_cookies(struct stream *s, struct channel *res);
59
Christopher Faulet377c5a52018-10-24 21:21:30 +020060static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend);
61static int htx_handle_stats(struct stream *s, struct channel *req);
62
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
Christopher Faulete0768eb2018-10-03 16:38:02 +0200100 /* we're speaking HTTP here, so let's speak HTTP to the client */
101 s->srv_error = http_return_srv_error;
102
103 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100104 if (c_data(req) && s->logs.t_idle == -1) {
105 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
106
107 s->logs.t_idle = ((csinfo)
108 ? csinfo->t_idle
109 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
110 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200111
Christopher Faulete0768eb2018-10-03 16:38:02 +0200112 /*
113 * Now we quickly check if we have found a full valid request.
114 * If not so, we check the FD and buffer states before leaving.
115 * A full request is indicated by the fact that we have seen
116 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
117 * requests are checked first. When waiting for a second request
118 * on a keep-alive stream, if we encounter and error, close, t/o,
119 * we note the error in the stream flags but don't set any state.
120 * Since the error will be noted there, it will not be counted by
121 * process_stream() as a frontend error.
122 * Last, we may increase some tracked counters' http request errors on
123 * the cases that are deliberately the client's fault. For instance,
124 * a timeout or connection reset is not counted as an error. However
125 * a bad request is.
126 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200127 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100128 /*
129 * First catch invalid request
130 */
131 if (htx->flags & HTX_FL_PARSING_ERROR) {
132 stream_inc_http_req_ctr(s);
133 stream_inc_http_err_ctr(s);
134 proxy_inc_fe_req_ctr(sess->fe);
135 goto return_bad_req;
136 }
137
Christopher Faulet9768c262018-10-22 09:34:31 +0200138 /* 1: have we encountered a read error ? */
139 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200140 if (!(s->flags & SF_ERR_MASK))
141 s->flags |= SF_ERR_CLICL;
142
143 if (txn->flags & TX_WAIT_NEXT_RQ)
144 goto failed_keep_alive;
145
146 if (sess->fe->options & PR_O_IGNORE_PRB)
147 goto failed_keep_alive;
148
Christopher Faulet9768c262018-10-22 09:34:31 +0200149 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 stream_inc_http_req_ctr(s);
151 proxy_inc_fe_req_ctr(sess->fe);
152 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
153 if (sess->listener->counters)
154 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
155
Christopher Faulet9768c262018-10-22 09:34:31 +0200156 txn->status = 400;
157 msg->err_state = msg->msg_state;
158 msg->msg_state = HTTP_MSG_ERROR;
159 htx_reply_and_close(s, txn->status, NULL);
160 req->analysers &= AN_REQ_FLT_END;
161
Christopher Faulete0768eb2018-10-03 16:38:02 +0200162 if (!(s->flags & SF_FINST_MASK))
163 s->flags |= SF_FINST_R;
164 return 0;
165 }
166
Christopher Faulet9768c262018-10-22 09:34:31 +0200167 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
169 if (!(s->flags & SF_ERR_MASK))
170 s->flags |= SF_ERR_CLITO;
171
172 if (txn->flags & TX_WAIT_NEXT_RQ)
173 goto failed_keep_alive;
174
175 if (sess->fe->options & PR_O_IGNORE_PRB)
176 goto failed_keep_alive;
177
Christopher Faulet9768c262018-10-22 09:34:31 +0200178 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200179 stream_inc_http_req_ctr(s);
180 proxy_inc_fe_req_ctr(sess->fe);
181 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
182 if (sess->listener->counters)
183 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
184
Christopher Faulet9768c262018-10-22 09:34:31 +0200185 txn->status = 408;
186 msg->err_state = msg->msg_state;
187 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100188 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200189 req->analysers &= AN_REQ_FLT_END;
190
Christopher Faulete0768eb2018-10-03 16:38:02 +0200191 if (!(s->flags & SF_FINST_MASK))
192 s->flags |= SF_FINST_R;
193 return 0;
194 }
195
Christopher Faulet9768c262018-10-22 09:34:31 +0200196 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197 else if (req->flags & CF_SHUTR) {
198 if (!(s->flags & SF_ERR_MASK))
199 s->flags |= SF_ERR_CLICL;
200
201 if (txn->flags & TX_WAIT_NEXT_RQ)
202 goto failed_keep_alive;
203
204 if (sess->fe->options & PR_O_IGNORE_PRB)
205 goto failed_keep_alive;
206
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 stream_inc_http_err_ctr(s);
208 stream_inc_http_req_ctr(s);
209 proxy_inc_fe_req_ctr(sess->fe);
210 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
211 if (sess->listener->counters)
212 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
213
Christopher Faulet9768c262018-10-22 09:34:31 +0200214 txn->status = 400;
215 msg->err_state = msg->msg_state;
216 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100217 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200218 req->analysers &= AN_REQ_FLT_END;
219
Christopher Faulete0768eb2018-10-03 16:38:02 +0200220 if (!(s->flags & SF_FINST_MASK))
221 s->flags |= SF_FINST_R;
222 return 0;
223 }
224
225 channel_dont_connect(req);
226 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
227 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100228
Christopher Faulet9768c262018-10-22 09:34:31 +0200229 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
231 /* We need more data, we have to re-enable quick-ack in case we
232 * previously disabled it, otherwise we might cause the client
233 * to delay next data.
234 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100235 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200236 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100237
Christopher Faulet47365272018-10-31 17:40:50 +0100238 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200239 /* If the client starts to talk, let's fall back to
240 * request timeout processing.
241 */
242 txn->flags &= ~TX_WAIT_NEXT_RQ;
243 req->analyse_exp = TICK_ETERNITY;
244 }
245
246 /* just set the request timeout once at the beginning of the request */
247 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
250 else
251 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
252 }
253
254 /* we're not ready yet */
255 return 0;
256
257 failed_keep_alive:
258 /* Here we process low-level errors for keep-alive requests. In
259 * short, if the request is not the first one and it experiences
260 * a timeout, read error or shutdown, we just silently close so
261 * that the client can try again.
262 */
263 txn->status = 0;
264 msg->msg_state = HTTP_MSG_RQBEFORE;
265 req->analysers &= AN_REQ_FLT_END;
266 s->logs.logwait = 0;
267 s->logs.level = 0;
268 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200269 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200270 return 0;
271 }
272
Christopher Faulet9768c262018-10-22 09:34:31 +0200273 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200274 stream_inc_http_req_ctr(s);
275 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
276
Christopher Faulet9768c262018-10-22 09:34:31 +0200277 /* kill the pending keep-alive timeout */
278 txn->flags &= ~TX_WAIT_NEXT_RQ;
279 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280
Christopher Faulet03599112018-11-27 11:21:21 +0100281 sl = http_find_stline(htx);
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 /* 0: we might have to print this header in debug mode */
284 if (unlikely((global.mode & MODE_DEBUG) &&
285 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
286 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200287
Christopher Faulet03599112018-11-27 11:21:21 +0100288 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200289
290 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
291 struct htx_blk *blk = htx_get_blk(htx, pos);
292 enum htx_blk_type type = htx_get_blk_type(blk);
293
294 if (type == HTX_BLK_EOH)
295 break;
296 if (type != HTX_BLK_HDR)
297 continue;
298
299 htx_debug_hdr("clihdr", s,
300 htx_get_blk_name(htx, blk),
301 htx_get_blk_value(htx, blk));
302 }
303 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200304
305 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100306 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100308 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100309 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200310 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 msg->flags |= HTTP_MSGF_XFER_LEN;
312 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100313 if (sl->flags & HTX_SL_F_BODYLESS)
314 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200315
316 /* we can make use of server redirect on GET and HEAD */
317 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
318 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100319 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200321 goto return_bad_req;
322 }
323
324 /*
325 * 2: check if the URI matches the monitor_uri.
326 * We have to do this for every request which gets in, because
327 * the monitor-uri is defined by the frontend.
328 */
329 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100330 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 /*
332 * We have found the monitor URI
333 */
334 struct acl_cond *cond;
335
336 s->flags |= SF_MONITOR;
337 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
338
339 /* Check if we want to fail this monitor request or not */
340 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
341 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
342
343 ret = acl_pass(ret);
344 if (cond->pol == ACL_COND_UNLESS)
345 ret = !ret;
346
347 if (ret) {
348 /* we fail this request, let's return 503 service unavail */
349 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100350 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200351 if (!(s->flags & SF_ERR_MASK))
352 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
353 goto return_prx_cond;
354 }
355 }
356
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800357 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200358 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100359 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 if (!(s->flags & SF_ERR_MASK))
361 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
362 goto return_prx_cond;
363 }
364
365 /*
366 * 3: Maybe we have to copy the original REQURI for the logs ?
367 * Note: we cannot log anymore if the request has been
368 * classified as invalid.
369 */
370 if (unlikely(s->logs.logwait & LW_REQ)) {
371 /* we have a complete HTTP request that we must log */
372 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200373 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200374
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
376 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377
378 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
379 s->do_log(s);
380 } else {
381 ha_alert("HTTP logging : out of memory.\n");
382 }
383 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385 /* if the frontend has "option http-use-proxy-header", we'll check if
386 * we have what looks like a proxied connection instead of a connection,
387 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
388 * Note that this is *not* RFC-compliant, however browsers and proxies
389 * happen to do that despite being non-standard :-(
390 * We consider that a request not beginning with either '/' or '*' is
391 * a proxied connection, which covers both "scheme://location" and
392 * CONNECT ip:port.
393 */
394 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100395 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200396 txn->flags |= TX_USE_PX_CONN;
397
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 /* 5: we may need to capture headers */
399 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200400 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200401
402 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
403 * only change if both the request and the config reference something else.
404 * Option httpclose by itself sets tunnel mode where headers are mangled.
405 * However, if another mode is set, it will affect it (eg: server-close/
406 * keep-alive + httpclose = close). Note that we avoid to redo the same work
407 * if FE and BE have the same settings (common). The method consists in
408 * checking if options changed between the two calls (implying that either
409 * one is non-null, or one of them is non-null and we are there for the first
410 * time.
411 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200412 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200413 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
415 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200416 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417 req->analysers |= AN_REQ_HTTP_BODY;
418
419 /*
420 * RFC7234#4:
421 * A cache MUST write through requests with methods
422 * that are unsafe (Section 4.2.1 of [RFC7231]) to
423 * the origin server; i.e., a cache is not allowed
424 * to generate a reply to such a request before
425 * having forwarded the request and having received
426 * a corresponding response.
427 *
428 * RFC7231#4.2.1:
429 * Of the request methods defined by this
430 * specification, the GET, HEAD, OPTIONS, and TRACE
431 * methods are defined to be safe.
432 */
433 if (likely(txn->meth == HTTP_METH_GET ||
434 txn->meth == HTTP_METH_HEAD ||
435 txn->meth == HTTP_METH_OPTIONS ||
436 txn->meth == HTTP_METH_TRACE))
437 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
438
439 /* end of job, return OK */
440 req->analysers &= ~an_bit;
441 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200442
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 return 1;
444
445 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200446 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200447 txn->req.err_state = txn->req.msg_state;
448 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100449 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200450 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
451 if (sess->listener->counters)
452 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
453
454 return_prx_cond:
455 if (!(s->flags & SF_ERR_MASK))
456 s->flags |= SF_ERR_PRXCOND;
457 if (!(s->flags & SF_FINST_MASK))
458 s->flags |= SF_FINST_R;
459
460 req->analysers &= AN_REQ_FLT_END;
461 req->analyse_exp = TICK_ETERNITY;
462 return 0;
463}
464
465
466/* This stream analyser runs all HTTP request processing which is common to
467 * frontends and backends, which means blocking ACLs, filters, connection-close,
468 * reqadd, stats and redirects. This is performed for the designated proxy.
469 * It returns 1 if the processing can continue on next analysers, or zero if it
470 * either needs more data or wants to immediately abort the request (eg: deny,
471 * error, ...).
472 */
473int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
474{
475 struct session *sess = s->sess;
476 struct http_txn *txn = s->txn;
477 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200478 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200479 struct redirect_rule *rule;
480 struct cond_wordlist *wl;
481 enum rule_result verdict;
482 int deny_status = HTTP_ERR_403;
483 struct connection *conn = objt_conn(sess->origin);
484
485 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
486 /* we need more data */
487 goto return_prx_yield;
488 }
489
490 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
491 now_ms, __FUNCTION__,
492 s,
493 req,
494 req->rex, req->wex,
495 req->flags,
496 ci_data(req),
497 req->analysers);
498
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100499 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501 /* just in case we have some per-backend tracking */
502 stream_inc_be_http_req_ctr(s);
503
504 /* evaluate http-request rules */
505 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200506 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200507
508 switch (verdict) {
509 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
510 goto return_prx_yield;
511
512 case HTTP_RULE_RES_CONT:
513 case HTTP_RULE_RES_STOP: /* nothing to do */
514 break;
515
516 case HTTP_RULE_RES_DENY: /* deny or tarpit */
517 if (txn->flags & TX_CLTARPIT)
518 goto tarpit;
519 goto deny;
520
521 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
522 goto return_prx_cond;
523
524 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
525 goto done;
526
527 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
528 goto return_bad_req;
529 }
530 }
531
532 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
533 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200534 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535
Christopher Fauletff2759f2018-10-24 11:13:16 +0200536 ctx.blk = NULL;
537 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
538 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200539 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200541 }
542
543 /* OK at this stage, we know that the request was accepted according to
544 * the http-request rules, we can check for the stats. Note that the
545 * URI is detected *before* the req* rules in order not to be affected
546 * by a possible reqrep, while they are processed *after* so that a
547 * reqdeny can still block them. This clearly needs to change in 1.6!
548 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200549 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 s->target = &http_stats_applet.obj_type;
551 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
552 txn->status = 500;
553 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100554 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555
556 if (!(s->flags & SF_ERR_MASK))
557 s->flags |= SF_ERR_RESOURCE;
558 goto return_prx_cond;
559 }
560
561 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200562 htx_handle_stats(s, req);
563 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200564 /* not all actions implemented: deny, allow, auth */
565
566 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
567 goto deny;
568
569 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
570 goto return_prx_cond;
571 }
572
573 /* evaluate the req* rules except reqadd */
574 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200575 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200576 goto return_bad_req;
577
578 if (txn->flags & TX_CLDENY)
579 goto deny;
580
581 if (txn->flags & TX_CLTARPIT) {
582 deny_status = HTTP_ERR_500;
583 goto tarpit;
584 }
585 }
586
587 /* add request headers from the rule sets in the same order */
588 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200589 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200590 if (wl->cond) {
591 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
592 ret = acl_pass(ret);
593 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
594 ret = !ret;
595 if (!ret)
596 continue;
597 }
598
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
600 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601 goto return_bad_req;
602 }
603
Christopher Faulete0768eb2018-10-03 16:38:02 +0200604 /* Proceed with the stats now. */
605 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
606 unlikely(objt_applet(s->target) == &http_cache_applet)) {
Christopher Fauletef779222018-10-31 08:47:01 +0100607
608 if (unlikely(objt_applet(s->target) == &http_cache_applet)) {
609 // TODO: Disabled for now, waiting to be adapted for HTX implementation
610 goto deny;
611 }
Christopher Fauletff2759f2018-10-24 11:13:16 +0200612
Christopher Faulete0768eb2018-10-03 16:38:02 +0200613 /* process the stats request now */
614 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
615 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
616
617 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
618 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
619 if (!(s->flags & SF_FINST_MASK))
620 s->flags |= SF_FINST_R;
621
622 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
623 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
624 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
625 req->analysers |= AN_REQ_HTTP_XFER_BODY;
626 goto done;
627 }
628
629 /* check whether we have some ACLs set to redirect this request */
630 list_for_each_entry(rule, &px->redirect_rules, list) {
631 if (rule->cond) {
632 int ret;
633
634 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
635 ret = acl_pass(ret);
636 if (rule->cond->pol == ACL_COND_UNLESS)
637 ret = !ret;
638 if (!ret)
639 continue;
640 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200641 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200642 goto return_bad_req;
643 goto done;
644 }
645
646 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
647 * If this happens, then the data will not come immediately, so we must
648 * send all what we have without waiting. Note that due to the small gain
649 * in waiting for the body of the request, it's easier to simply put the
650 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
651 * itself once used.
652 */
653 req->flags |= CF_SEND_DONTWAIT;
654
655 done: /* done with this analyser, continue with next ones that the calling
656 * points will have set, if any.
657 */
658 req->analyse_exp = TICK_ETERNITY;
659 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
660 req->analysers &= ~an_bit;
661 return 1;
662
663 tarpit:
664 /* Allow cookie logging
665 */
666 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200667 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200668
669 /* When a connection is tarpitted, we use the tarpit timeout,
670 * which may be the same as the connect timeout if unspecified.
671 * If unset, then set it to zero because we really want it to
672 * eventually expire. We build the tarpit as an analyser.
673 */
674 channel_erase(&s->req);
675
676 /* wipe the request out so that we can drop the connection early
677 * if the client closes first.
678 */
679 channel_dont_connect(req);
680
681 txn->status = http_err_codes[deny_status];
682
683 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
684 req->analysers |= AN_REQ_HTTP_TARPIT;
685 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
686 if (!req->analyse_exp)
687 req->analyse_exp = tick_add(now_ms, 0);
688 stream_inc_http_err_ctr(s);
689 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
690 if (sess->fe != s->be)
691 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
692 if (sess->listener->counters)
693 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
694 goto done_without_exp;
695
696 deny: /* this request was blocked (denied) */
697
698 /* Allow cookie logging
699 */
700 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200701 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702
703 txn->flags |= TX_CLDENY;
704 txn->status = http_err_codes[deny_status];
705 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100706 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 stream_inc_http_err_ctr(s);
708 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
709 if (sess->fe != s->be)
710 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
711 if (sess->listener->counters)
712 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
713 goto return_prx_cond;
714
715 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716 txn->req.err_state = txn->req.msg_state;
717 txn->req.msg_state = HTTP_MSG_ERROR;
718 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100719 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720
721 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
722 if (sess->listener->counters)
723 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
724
725 return_prx_cond:
726 if (!(s->flags & SF_ERR_MASK))
727 s->flags |= SF_ERR_PRXCOND;
728 if (!(s->flags & SF_FINST_MASK))
729 s->flags |= SF_FINST_R;
730
731 req->analysers &= AN_REQ_FLT_END;
732 req->analyse_exp = TICK_ETERNITY;
733 return 0;
734
735 return_prx_yield:
736 channel_dont_connect(req);
737 return 0;
738}
739
740/* This function performs all the processing enabled for the current request.
741 * It returns 1 if the processing can continue on next analysers, or zero if it
742 * needs more data, encounters an error, or wants to immediately abort the
743 * request. It relies on buffers flags, and updates s->req.analysers.
744 */
745int htx_process_request(struct stream *s, struct channel *req, int an_bit)
746{
747 struct session *sess = s->sess;
748 struct http_txn *txn = s->txn;
749 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200750 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200751 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
752
753 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
754 /* we need more data */
755 channel_dont_connect(req);
756 return 0;
757 }
758
759 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
760 now_ms, __FUNCTION__,
761 s,
762 req,
763 req->rex, req->wex,
764 req->flags,
765 ci_data(req),
766 req->analysers);
767
768 /*
769 * Right now, we know that we have processed the entire headers
770 * and that unwanted requests have been filtered out. We can do
771 * whatever we want with the remaining request. Also, now we
772 * may have separate values for ->fe, ->be.
773 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100774 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200775
776 /*
777 * If HTTP PROXY is set we simply get remote server address parsing
778 * incoming request. Note that this requires that a connection is
779 * allocated on the server side.
780 */
781 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
782 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100783 struct htx_sl *sl;
784 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 /* Note that for now we don't reuse existing proxy connections */
787 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
788 txn->req.err_state = txn->req.msg_state;
789 txn->req.msg_state = HTTP_MSG_ERROR;
790 txn->status = 500;
791 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100792 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793
794 if (!(s->flags & SF_ERR_MASK))
795 s->flags |= SF_ERR_RESOURCE;
796 if (!(s->flags & SF_FINST_MASK))
797 s->flags |= SF_FINST_R;
798
799 return 0;
800 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200801 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100802 uri = htx_sl_req_uri(sl);
803 path = http_get_path(uri);
804 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 goto return_bad_req;
806
807 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200808 * uri.ptr and path.ptr (excluded). If it was not found, we need
809 * to replace from all the uri by a single "/".
810 *
811 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100812 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200813 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200814 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100815 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200816 }
817
818 /*
819 * 7: Now we can work with the cookies.
820 * Note that doing so might move headers in the request, but
821 * the fields will stay coherent and the URI will not move.
822 * This should only be performed in the backend.
823 */
824 if (s->be->cookie_name || sess->fe->capture_name)
825 manage_client_side_cookies(s, req);
826
827 /* add unique-id if "header-unique-id" is specified */
828
829 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
830 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
831 goto return_bad_req;
832 s->unique_id[0] = '\0';
833 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
834 }
835
836 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200837 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
838 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
839
840 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200841 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200842 }
843
844 /*
845 * 9: add X-Forwarded-For if either the frontend or the backend
846 * asks for it.
847 */
848 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200849 struct http_hdr_ctx ctx = { .blk = NULL };
850 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
851 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
852
Christopher Faulete0768eb2018-10-03 16:38:02 +0200853 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200854 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200855 /* The header is set to be added only if none is present
856 * and we found it, so don't do anything.
857 */
858 }
859 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
860 /* Add an X-Forwarded-For header unless the source IP is
861 * in the 'except' network range.
862 */
863 if ((!sess->fe->except_mask.s_addr ||
864 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
865 != sess->fe->except_net.s_addr) &&
866 (!s->be->except_mask.s_addr ||
867 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
868 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200870
871 /* Note: we rely on the backend to get the header name to be used for
872 * x-forwarded-for, because the header is really meant for the backends.
873 * However, if the backend did not specify any option, we have to rely
874 * on the frontend's header name.
875 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200876 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
877 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 goto return_bad_req;
879 }
880 }
881 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
882 /* FIXME: for the sake of completeness, we should also support
883 * 'except' here, although it is mostly useless in this case.
884 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200885 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200886
Christopher Faulete0768eb2018-10-03 16:38:02 +0200887 inet_ntop(AF_INET6,
888 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
889 pn, sizeof(pn));
890
891 /* Note: we rely on the backend to get the header name to be used for
892 * x-forwarded-for, because the header is really meant for the backends.
893 * However, if the backend did not specify any option, we have to rely
894 * on the frontend's header name.
895 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200896 chunk_printf(&trash, "%s", pn);
897 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200898 goto return_bad_req;
899 }
900 }
901
902 /*
903 * 10: add X-Original-To if either the frontend or the backend
904 * asks for it.
905 */
906 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
907
908 /* FIXME: don't know if IPv6 can handle that case too. */
909 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
910 /* Add an X-Original-To header unless the destination IP is
911 * in the 'except' network range.
912 */
913 conn_get_to_addr(cli_conn);
914
915 if (cli_conn->addr.to.ss_family == AF_INET &&
916 ((!sess->fe->except_mask_to.s_addr ||
917 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
918 != sess->fe->except_to.s_addr) &&
919 (!s->be->except_mask_to.s_addr ||
920 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
921 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200922 struct ist hdr;
923 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200924
925 /* Note: we rely on the backend to get the header name to be used for
926 * x-original-to, because the header is really meant for the backends.
927 * However, if the backend did not specify any option, we have to rely
928 * on the frontend's header name.
929 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200930 if (s->be->orgto_hdr_len)
931 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
932 else
933 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200935 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
936 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200937 goto return_bad_req;
938 }
939 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 }
941
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 /* If we have no server assigned yet and we're balancing on url_param
943 * with a POST request, we may be interested in checking the body for
944 * that parameter. This will be done in another analyser.
945 */
946 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200947 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 channel_dont_connect(req);
949 req->analysers |= AN_REQ_HTTP_BODY;
950 }
951
952 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
953 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100954
Christopher Faulete0768eb2018-10-03 16:38:02 +0200955 /* We expect some data from the client. Unless we know for sure
956 * we already have a full request, we have to re-enable quick-ack
957 * in case we previously disabled it, otherwise we might cause
958 * the client to delay further data.
959 */
960 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200961 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100962 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200963
964 /*************************************************************
965 * OK, that's finished for the headers. We have done what we *
966 * could. Let's switch to the DATA state. *
967 ************************************************************/
968 req->analyse_exp = TICK_ETERNITY;
969 req->analysers &= ~an_bit;
970
971 s->logs.tv_request = now;
972 /* OK let's go on with the BODY now */
973 return 1;
974
975 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976 txn->req.err_state = txn->req.msg_state;
977 txn->req.msg_state = HTTP_MSG_ERROR;
978 txn->status = 400;
979 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100980 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200981
982 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
983 if (sess->listener->counters)
984 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
985
986 if (!(s->flags & SF_ERR_MASK))
987 s->flags |= SF_ERR_PRXCOND;
988 if (!(s->flags & SF_FINST_MASK))
989 s->flags |= SF_FINST_R;
990 return 0;
991}
992
993/* This function is an analyser which processes the HTTP tarpit. It always
994 * returns zero, at the beginning because it prevents any other processing
995 * from occurring, and at the end because it terminates the request.
996 */
997int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
998{
999 struct http_txn *txn = s->txn;
1000
1001 /* This connection is being tarpitted. The CLIENT side has
1002 * already set the connect expiration date to the right
1003 * timeout. We just have to check that the client is still
1004 * there and that the timeout has not expired.
1005 */
1006 channel_dont_connect(req);
1007 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1008 !tick_is_expired(req->analyse_exp, now_ms))
1009 return 0;
1010
1011 /* We will set the queue timer to the time spent, just for
1012 * logging purposes. We fake a 500 server error, so that the
1013 * attacker will not suspect his connection has been tarpitted.
1014 * It will not cause trouble to the logs because we can exclude
1015 * the tarpitted connections by filtering on the 'PT' status flags.
1016 */
1017 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1018
1019 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001020 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001021
1022 req->analysers &= AN_REQ_FLT_END;
1023 req->analyse_exp = TICK_ETERNITY;
1024
1025 if (!(s->flags & SF_ERR_MASK))
1026 s->flags |= SF_ERR_PRXCOND;
1027 if (!(s->flags & SF_FINST_MASK))
1028 s->flags |= SF_FINST_T;
1029 return 0;
1030}
1031
1032/* This function is an analyser which waits for the HTTP request body. It waits
1033 * for either the buffer to be full, or the full advertised contents to have
1034 * reached the buffer. It must only be called after the standard HTTP request
1035 * processing has occurred, because it expects the request to be parsed and will
1036 * look for the Expect header. It may send a 100-Continue interim response. It
1037 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1038 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1039 * needs to read more data, or 1 once it has completed its analysis.
1040 */
1041int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1042{
1043 struct session *sess = s->sess;
1044 struct http_txn *txn = s->txn;
1045 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001046 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001047
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001048
1049 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1050 now_ms, __FUNCTION__,
1051 s,
1052 req,
1053 req->rex, req->wex,
1054 req->flags,
1055 ci_data(req),
1056 req->analysers);
1057
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001058 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001059
1060 if (msg->msg_state < HTTP_MSG_BODY)
1061 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001062
Christopher Faulete0768eb2018-10-03 16:38:02 +02001063 /* We have to parse the HTTP request body to find any required data.
1064 * "balance url_param check_post" should have been the only way to get
1065 * into this. We were brought here after HTTP header analysis, so all
1066 * related structures are ready.
1067 */
1068
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 if (msg->msg_state < HTTP_MSG_DATA) {
1070 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1071 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001073 if (msg->flags & HTTP_MSGF_VER_11) {
1074 struct ist hdr = { .ptr = "Expect", .len = 6 };
1075 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001076
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001077 ctx.blk = NULL;
1078 /* Expect is allowed in 1.1, look for it */
1079 if (http_find_header(htx, hdr, &ctx, 0) &&
1080 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001081 if (htx_reply_100_continue(s) == -1)
1082 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001083 http_remove_header(htx, &ctx);
1084 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001085 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 }
1087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001090 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1091 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001092 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001093 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1094 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001095 goto http_end;
1096
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001097 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001098 if (htx->flags & HTX_FL_PARSING_ERROR)
1099 goto return_bad_req;
1100
Christopher Faulete0768eb2018-10-03 16:38:02 +02001101 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1102 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001103 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001104
1105 if (!(s->flags & SF_ERR_MASK))
1106 s->flags |= SF_ERR_CLITO;
1107 if (!(s->flags & SF_FINST_MASK))
1108 s->flags |= SF_FINST_D;
1109 goto return_err_msg;
1110 }
1111
1112 /* we get here if we need to wait for more data */
1113 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1114 /* Not enough data. We'll re-use the http-request
1115 * timeout here. Ideally, we should set the timeout
1116 * relative to the accept() date. We just set the
1117 * request timeout once at the beginning of the
1118 * request.
1119 */
1120 channel_dont_connect(req);
1121 if (!tick_isset(req->analyse_exp))
1122 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1123 return 0;
1124 }
1125
1126 http_end:
1127 /* The situation will not evolve, so let's give up on the analysis. */
1128 s->logs.tv_request = now; /* update the request timer to reflect full request */
1129 req->analysers &= ~an_bit;
1130 req->analyse_exp = TICK_ETERNITY;
1131 return 1;
1132
1133 return_bad_req: /* let's centralize all bad requests */
1134 txn->req.err_state = txn->req.msg_state;
1135 txn->req.msg_state = HTTP_MSG_ERROR;
1136 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001137 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001138
1139 if (!(s->flags & SF_ERR_MASK))
1140 s->flags |= SF_ERR_PRXCOND;
1141 if (!(s->flags & SF_FINST_MASK))
1142 s->flags |= SF_FINST_R;
1143
1144 return_err_msg:
1145 req->analysers &= AN_REQ_FLT_END;
1146 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1147 if (sess->listener->counters)
1148 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1149 return 0;
1150}
1151
1152/* This function is an analyser which forwards request body (including chunk
1153 * sizes if any). It is called as soon as we must forward, even if we forward
1154 * zero byte. The only situation where it must not be called is when we're in
1155 * tunnel mode and we want to forward till the close. It's used both to forward
1156 * remaining data and to resync after end of body. It expects the msg_state to
1157 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1158 * read more data, or 1 once we can go on with next request or end the stream.
1159 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1160 * bytes of pending data + the headers if not already done.
1161 */
1162int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1163{
1164 struct session *sess = s->sess;
1165 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001166 struct http_msg *msg = &txn->req;
1167 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001168 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001169
1170 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1171 now_ms, __FUNCTION__,
1172 s,
1173 req,
1174 req->rex, req->wex,
1175 req->flags,
1176 ci_data(req),
1177 req->analysers);
1178
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001179 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001180
1181 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1182 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1183 /* Output closed while we were sending data. We must abort and
1184 * wake the other side up.
1185 */
1186 msg->err_state = msg->msg_state;
1187 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001188 htx_end_request(s);
1189 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001190 return 1;
1191 }
1192
1193 /* Note that we don't have to send 100-continue back because we don't
1194 * need the data to complete our job, and it's up to the server to
1195 * decide whether to return 100, 417 or anything else in return of
1196 * an "Expect: 100-continue" header.
1197 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001198 if (msg->msg_state == HTTP_MSG_BODY)
1199 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001200
1201 /* Some post-connect processing might want us to refrain from starting to
1202 * forward data. Currently, the only reason for this is "balance url_param"
1203 * whichs need to parse/process the request after we've enabled forwarding.
1204 */
1205 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1206 if (!(s->res.flags & CF_READ_ATTACHED)) {
1207 channel_auto_connect(req);
1208 req->flags |= CF_WAKE_CONNECT;
1209 channel_dont_close(req); /* don't fail on early shutr */
1210 goto waiting;
1211 }
1212 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1213 }
1214
1215 /* in most states, we should abort in case of early close */
1216 channel_auto_close(req);
1217
1218 if (req->to_forward) {
1219 /* We can't process the buffer's contents yet */
1220 req->flags |= CF_WAKE_WRITE;
1221 goto missing_data_or_waiting;
1222 }
1223
Christopher Faulet9768c262018-10-22 09:34:31 +02001224 if (msg->msg_state >= HTTP_MSG_DONE)
1225 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001226 /* Forward input data. We get it by removing all outgoing data not
1227 * forwarded yet from HTX data size. If there are some data filters, we
1228 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001229 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001230 if (HAS_REQ_DATA_FILTERS(s)) {
1231 ret = flt_http_payload(s, msg, htx->data);
1232 if (ret < 0)
1233 goto return_bad_req;
1234 c_adv(req, ret);
1235 if (htx->data != co_data(req) || htx->extra)
1236 goto missing_data_or_waiting;
1237 }
1238 else {
1239 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001240
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001241 /* To let the function channel_forward work as expected we must update
1242 * the channel's buffer to pretend there is no more input data. The
1243 * right length is then restored. We must do that, because when an HTX
1244 * message is stored into a buffer, it appears as full.
1245 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001246 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1247 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001248 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001249
Christopher Faulet9768c262018-10-22 09:34:31 +02001250 /* Check if the end-of-message is reached and if so, switch the message
1251 * in HTTP_MSG_DONE state.
1252 */
1253 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1254 goto missing_data_or_waiting;
1255
1256 msg->msg_state = HTTP_MSG_DONE;
1257
1258 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001259 /* other states, DONE...TUNNEL */
1260 /* we don't want to forward closes on DONE except in tunnel mode. */
1261 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1262 channel_dont_close(req);
1263
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001264 if (HAS_REQ_DATA_FILTERS(s)) {
1265 ret = flt_http_end(s, msg);
1266 if (ret <= 0) {
1267 if (!ret)
1268 goto missing_data_or_waiting;
1269 goto return_bad_req;
1270 }
1271 }
1272
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001275 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1277 if (req->flags & CF_SHUTW) {
1278 /* request errors are most likely due to the
1279 * server aborting the transfer. */
1280 goto aborted_xfer;
1281 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 goto return_bad_req;
1283 }
1284 return 1;
1285 }
1286
1287 /* If "option abortonclose" is set on the backend, we want to monitor
1288 * the client's connection and forward any shutdown notification to the
1289 * server, which will decide whether to close or to go on processing the
1290 * request. We only do that in tunnel mode, and not in other modes since
1291 * it can be abused to exhaust source ports. */
1292 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1293 channel_auto_read(req);
1294 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1295 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1296 s->si[1].flags |= SI_FL_NOLINGER;
1297 channel_auto_close(req);
1298 }
1299 else if (s->txn->meth == HTTP_METH_POST) {
1300 /* POST requests may require to read extra CRLF sent by broken
1301 * browsers and which could cause an RST to be sent upon close
1302 * on some systems (eg: Linux). */
1303 channel_auto_read(req);
1304 }
1305 return 0;
1306
1307 missing_data_or_waiting:
1308 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001309 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001310 if (!(s->flags & SF_ERR_MASK))
1311 s->flags |= SF_ERR_CLICL;
1312 if (!(s->flags & SF_FINST_MASK)) {
1313 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1314 s->flags |= SF_FINST_H;
1315 else
1316 s->flags |= SF_FINST_D;
1317 }
1318
1319 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1320 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1321 if (objt_server(s->target))
1322 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1323
1324 goto return_bad_req_stats_ok;
1325 }
1326
1327 waiting:
1328 /* waiting for the last bits to leave the buffer */
1329 if (req->flags & CF_SHUTW)
1330 goto aborted_xfer;
1331
Christopher Faulet47365272018-10-31 17:40:50 +01001332 if (htx->flags & HTX_FL_PARSING_ERROR)
1333 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001334
Christopher Faulete0768eb2018-10-03 16:38:02 +02001335 /* When TE: chunked is used, we need to get there again to parse remaining
1336 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1337 * And when content-length is used, we never want to let the possible
1338 * shutdown be forwarded to the other side, as the state machine will
1339 * take care of it once the client responds. It's also important to
1340 * prevent TIME_WAITs from accumulating on the backend side, and for
1341 * HTTP/2 where the last frame comes with a shutdown.
1342 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001343 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001344 channel_dont_close(req);
1345
1346 /* We know that more data are expected, but we couldn't send more that
1347 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1348 * system knows it must not set a PUSH on this first part. Interactive
1349 * modes are already handled by the stream sock layer. We must not do
1350 * this in content-length mode because it could present the MSG_MORE
1351 * flag with the last block of forwarded data, which would cause an
1352 * additional delay to be observed by the receiver.
1353 */
1354 if (msg->flags & HTTP_MSGF_TE_CHNK)
1355 req->flags |= CF_EXPECT_MORE;
1356
1357 return 0;
1358
1359 return_bad_req: /* let's centralize all bad requests */
1360 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1361 if (sess->listener->counters)
1362 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1363
1364 return_bad_req_stats_ok:
1365 txn->req.err_state = txn->req.msg_state;
1366 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001367 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001369 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 } else {
1371 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001372 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001373 }
1374 req->analysers &= AN_REQ_FLT_END;
1375 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1376
1377 if (!(s->flags & SF_ERR_MASK))
1378 s->flags |= SF_ERR_PRXCOND;
1379 if (!(s->flags & SF_FINST_MASK)) {
1380 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1381 s->flags |= SF_FINST_H;
1382 else
1383 s->flags |= SF_FINST_D;
1384 }
1385 return 0;
1386
1387 aborted_xfer:
1388 txn->req.err_state = txn->req.msg_state;
1389 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001390 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001392 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001393 } else {
1394 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001395 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001396 }
1397 req->analysers &= AN_REQ_FLT_END;
1398 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1399
1400 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1401 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1402 if (objt_server(s->target))
1403 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1404
1405 if (!(s->flags & SF_ERR_MASK))
1406 s->flags |= SF_ERR_SRVCL;
1407 if (!(s->flags & SF_FINST_MASK)) {
1408 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1409 s->flags |= SF_FINST_H;
1410 else
1411 s->flags |= SF_FINST_D;
1412 }
1413 return 0;
1414}
1415
1416/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1417 * processing can continue on next analysers, or zero if it either needs more
1418 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1419 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1420 * when it has nothing left to do, and may remove any analyser when it wants to
1421 * abort.
1422 */
1423int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1424{
Christopher Faulet9768c262018-10-22 09:34:31 +02001425 /*
1426 * We will analyze a complete HTTP response to check the its syntax.
1427 *
1428 * Once the start line and all headers are received, we may perform a
1429 * capture of the error (if any), and we will set a few fields. We also
1430 * logging and finally headers capture.
1431 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001432 struct session *sess = s->sess;
1433 struct http_txn *txn = s->txn;
1434 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001435 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001436 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001437 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001438 int n;
1439
1440 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1441 now_ms, __FUNCTION__,
1442 s,
1443 rep,
1444 rep->rex, rep->wex,
1445 rep->flags,
1446 ci_data(rep),
1447 rep->analysers);
1448
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001449 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001450
1451 /*
1452 * Now we quickly check if we have found a full valid response.
1453 * If not so, we check the FD and buffer states before leaving.
1454 * A full response is indicated by the fact that we have seen
1455 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1456 * responses are checked first.
1457 *
1458 * Depending on whether the client is still there or not, we
1459 * may send an error response back or not. Note that normally
1460 * we should only check for HTTP status there, and check I/O
1461 * errors somewhere else.
1462 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001463 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001464 /*
1465 * First catch invalid response
1466 */
1467 if (htx->flags & HTX_FL_PARSING_ERROR)
1468 goto return_bad_res;
1469
Christopher Faulet9768c262018-10-22 09:34:31 +02001470 /* 1: have we encountered a read error ? */
1471 if (rep->flags & CF_READ_ERROR) {
1472 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473 goto abort_keep_alive;
1474
1475 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1476 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001477 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1478 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001479 }
1480
Christopher Faulete0768eb2018-10-03 16:38:02 +02001481 rep->analysers &= AN_RES_FLT_END;
1482 txn->status = 502;
1483
1484 /* Check to see if the server refused the early data.
1485 * If so, just send a 425
1486 */
1487 if (objt_cs(s->si[1].end)) {
1488 struct connection *conn = objt_cs(s->si[1].end)->conn;
1489
1490 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1491 txn->status = 425;
1492 }
1493
1494 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001495 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496
1497 if (!(s->flags & SF_ERR_MASK))
1498 s->flags |= SF_ERR_SRVCL;
1499 if (!(s->flags & SF_FINST_MASK))
1500 s->flags |= SF_FINST_H;
1501 return 0;
1502 }
1503
Christopher Faulet9768c262018-10-22 09:34:31 +02001504 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1507 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001508 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1509 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510 }
1511
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512 rep->analysers &= AN_RES_FLT_END;
1513 txn->status = 504;
1514 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001515 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516
1517 if (!(s->flags & SF_ERR_MASK))
1518 s->flags |= SF_ERR_SRVTO;
1519 if (!(s->flags & SF_FINST_MASK))
1520 s->flags |= SF_FINST_H;
1521 return 0;
1522 }
1523
Christopher Faulet9768c262018-10-22 09:34:31 +02001524 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1526 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1527 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1528 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001529 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001530
1531 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001533 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534
1535 if (!(s->flags & SF_ERR_MASK))
1536 s->flags |= SF_ERR_CLICL;
1537 if (!(s->flags & SF_FINST_MASK))
1538 s->flags |= SF_FINST_H;
1539
1540 /* process_stream() will take care of the error */
1541 return 0;
1542 }
1543
Christopher Faulet9768c262018-10-22 09:34:31 +02001544 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 goto abort_keep_alive;
1548
1549 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1550 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001551 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1552 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 }
1554
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 rep->analysers &= AN_RES_FLT_END;
1556 txn->status = 502;
1557 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001558 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559
1560 if (!(s->flags & SF_ERR_MASK))
1561 s->flags |= SF_ERR_SRVCL;
1562 if (!(s->flags & SF_FINST_MASK))
1563 s->flags |= SF_FINST_H;
1564 return 0;
1565 }
1566
Christopher Faulet9768c262018-10-22 09:34:31 +02001567 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001569 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001570 goto abort_keep_alive;
1571
1572 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1573 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574
1575 if (!(s->flags & SF_ERR_MASK))
1576 s->flags |= SF_ERR_CLICL;
1577 if (!(s->flags & SF_FINST_MASK))
1578 s->flags |= SF_FINST_H;
1579
1580 /* process_stream() will take care of the error */
1581 return 0;
1582 }
1583
1584 channel_dont_close(rep);
1585 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1586 return 0;
1587 }
1588
1589 /* More interesting part now : we know that we have a complete
1590 * response which at least looks like HTTP. We have an indicator
1591 * of each header's length, so we can parse them quickly.
1592 */
1593
Christopher Faulet9768c262018-10-22 09:34:31 +02001594 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001595 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596
Christopher Faulet9768c262018-10-22 09:34:31 +02001597 /* 0: we might have to print this header in debug mode */
1598 if (unlikely((global.mode & MODE_DEBUG) &&
1599 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1600 int32_t pos;
1601
Christopher Faulet03599112018-11-27 11:21:21 +01001602 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001603
1604 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1605 struct htx_blk *blk = htx_get_blk(htx, pos);
1606 enum htx_blk_type type = htx_get_blk_type(blk);
1607
1608 if (type == HTX_BLK_EOH)
1609 break;
1610 if (type != HTX_BLK_HDR)
1611 continue;
1612
1613 htx_debug_hdr("srvhdr", s,
1614 htx_get_blk_name(htx, blk),
1615 htx_get_blk_value(htx, blk));
1616 }
1617 }
1618
Christopher Faulet03599112018-11-27 11:21:21 +01001619 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001620 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001621 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001622 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001623 if (sl->flags & HTX_SL_F_XFER_LEN) {
1624 msg->flags |= HTTP_MSGF_XFER_LEN;
1625 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001626 if (sl->flags & HTX_SL_F_BODYLESS)
1627 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001628 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001629
1630 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631 if (n < 1 || n > 5)
1632 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001633
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 /* when the client triggers a 4xx from the server, it's most often due
1635 * to a missing object or permission. These events should be tracked
1636 * because if they happen often, it may indicate a brute force or a
1637 * vulnerability scan.
1638 */
1639 if (n == 4)
1640 stream_inc_http_err_ctr(s);
1641
1642 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001643 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001644
Christopher Faulete0768eb2018-10-03 16:38:02 +02001645 /* Adjust server's health based on status code. Note: status codes 501
1646 * and 505 are triggered on demand by client request, so we must not
1647 * count them as server failures.
1648 */
1649 if (objt_server(s->target)) {
1650 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001651 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001652 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001653 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001654 }
1655
1656 /*
1657 * We may be facing a 100-continue response, or any other informational
1658 * 1xx response which is non-final, in which case this is not the right
1659 * response, and we're waiting for the next one. Let's allow this response
1660 * to go to the client and wait for the next one. There's an exception for
1661 * 101 which is used later in the code to switch protocols.
1662 */
1663 if (txn->status < 200 &&
1664 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001665 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001666 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001667 msg->msg_state = HTTP_MSG_RPBEFORE;
1668 txn->status = 0;
1669 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001670 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001671 }
1672
1673 /*
1674 * 2: check for cacheability.
1675 */
1676
1677 switch (txn->status) {
1678 case 200:
1679 case 203:
1680 case 204:
1681 case 206:
1682 case 300:
1683 case 301:
1684 case 404:
1685 case 405:
1686 case 410:
1687 case 414:
1688 case 501:
1689 break;
1690 default:
1691 /* RFC7231#6.1:
1692 * Responses with status codes that are defined as
1693 * cacheable by default (e.g., 200, 203, 204, 206,
1694 * 300, 301, 404, 405, 410, 414, and 501 in this
1695 * specification) can be reused by a cache with
1696 * heuristic expiration unless otherwise indicated
1697 * by the method definition or explicit cache
1698 * controls [RFC7234]; all other status codes are
1699 * not cacheable by default.
1700 */
1701 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1702 break;
1703 }
1704
1705 /*
1706 * 3: we may need to capture headers
1707 */
1708 s->logs.logwait &= ~LW_RESP;
1709 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001710 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001711
Christopher Faulet9768c262018-10-22 09:34:31 +02001712 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1714 txn->status == 101)) {
1715 /* Either we've established an explicit tunnel, or we're
1716 * switching the protocol. In both cases, we're very unlikely
1717 * to understand the next protocols. We have to switch to tunnel
1718 * mode, so that we transfer the request and responses then let
1719 * this protocol pass unmodified. When we later implement specific
1720 * parsers for such protocols, we'll want to check the Upgrade
1721 * header which contains information about that protocol for
1722 * responses with status 101 (eg: see RFC2817 about TLS).
1723 */
1724 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001725 }
1726
Christopher Faulet61608322018-11-23 16:23:45 +01001727 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1728 * 407 (Proxy-Authenticate) responses and set the connection to private
1729 */
1730 srv_conn = cs_conn(objt_cs(s->si[1].end));
1731 if (srv_conn) {
1732 struct ist hdr;
1733 struct http_hdr_ctx ctx;
1734
1735 if (txn->status == 401)
1736 hdr = ist("WWW-Authenticate");
1737 else if (txn->status == 407)
1738 hdr = ist("Proxy-Authenticate");
1739 else
1740 goto end;
1741
1742 ctx.blk = NULL;
1743 while (http_find_header(htx, hdr, &ctx, 0)) {
1744 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1745 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1746 srv_conn->flags |= CO_FL_PRIVATE;
1747 }
1748 }
1749
1750 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001751 /* we want to have the response time before we start processing it */
1752 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1753
1754 /* end of job, return OK */
1755 rep->analysers &= ~an_bit;
1756 rep->analyse_exp = TICK_ETERNITY;
1757 channel_auto_close(rep);
1758 return 1;
1759
Christopher Faulet47365272018-10-31 17:40:50 +01001760 return_bad_res:
1761 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1762 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001763 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1764 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001765 }
1766 txn->status = 502;
1767 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001768 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001769 rep->analysers &= AN_RES_FLT_END;
1770
1771 if (!(s->flags & SF_ERR_MASK))
1772 s->flags |= SF_ERR_PRXCOND;
1773 if (!(s->flags & SF_FINST_MASK))
1774 s->flags |= SF_FINST_H;
1775 return 0;
1776
Christopher Faulete0768eb2018-10-03 16:38:02 +02001777 abort_keep_alive:
1778 /* A keep-alive request to the server failed on a network error.
1779 * The client is required to retry. We need to close without returning
1780 * any other information so that the client retries.
1781 */
1782 txn->status = 0;
1783 rep->analysers &= AN_RES_FLT_END;
1784 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001785 s->logs.logwait = 0;
1786 s->logs.level = 0;
1787 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001788 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001789 return 0;
1790}
1791
1792/* This function performs all the processing enabled for the current response.
1793 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1794 * and updates s->res.analysers. It might make sense to explode it into several
1795 * other functions. It works like process_request (see indications above).
1796 */
1797int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1798{
1799 struct session *sess = s->sess;
1800 struct http_txn *txn = s->txn;
1801 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001802 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001803 struct proxy *cur_proxy;
1804 struct cond_wordlist *wl;
1805 enum rule_result ret = HTTP_RULE_RES_CONT;
1806
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001807 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1808 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001809
Christopher Faulete0768eb2018-10-03 16:38:02 +02001810 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1811 now_ms, __FUNCTION__,
1812 s,
1813 rep,
1814 rep->rex, rep->wex,
1815 rep->flags,
1816 ci_data(rep),
1817 rep->analysers);
1818
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001819 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001820
1821 /* The stats applet needs to adjust the Connection header but we don't
1822 * apply any filter there.
1823 */
1824 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1825 rep->analysers &= ~an_bit;
1826 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001827 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001828 }
1829
1830 /*
1831 * We will have to evaluate the filters.
1832 * As opposed to version 1.2, now they will be evaluated in the
1833 * filters order and not in the header order. This means that
1834 * each filter has to be validated among all headers.
1835 *
1836 * Filters are tried with ->be first, then with ->fe if it is
1837 * different from ->be.
1838 *
1839 * Maybe we are in resume condiion. In this case I choose the
1840 * "struct proxy" which contains the rule list matching the resume
1841 * pointer. If none of theses "struct proxy" match, I initialise
1842 * the process with the first one.
1843 *
1844 * In fact, I check only correspondance betwwen the current list
1845 * pointer and the ->fe rule list. If it doesn't match, I initialize
1846 * the loop with the ->be.
1847 */
1848 if (s->current_rule_list == &sess->fe->http_res_rules)
1849 cur_proxy = sess->fe;
1850 else
1851 cur_proxy = s->be;
1852 while (1) {
1853 struct proxy *rule_set = cur_proxy;
1854
1855 /* evaluate http-response rules */
1856 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001857 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001858
1859 if (ret == HTTP_RULE_RES_BADREQ)
1860 goto return_srv_prx_502;
1861
1862 if (ret == HTTP_RULE_RES_DONE) {
1863 rep->analysers &= ~an_bit;
1864 rep->analyse_exp = TICK_ETERNITY;
1865 return 1;
1866 }
1867 }
1868
1869 /* we need to be called again. */
1870 if (ret == HTTP_RULE_RES_YIELD) {
1871 channel_dont_close(rep);
1872 return 0;
1873 }
1874
1875 /* try headers filters */
1876 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001877 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1878 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879 }
1880
1881 /* has the response been denied ? */
1882 if (txn->flags & TX_SVDENY) {
1883 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001884 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001885
1886 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1887 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1888 if (sess->listener->counters)
1889 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890 goto return_srv_prx_502;
1891 }
1892
1893 /* add response headers from the rule sets in the same order */
1894 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001895 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001896 if (txn->status < 200 && txn->status != 101)
1897 break;
1898 if (wl->cond) {
1899 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1900 ret = acl_pass(ret);
1901 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1902 ret = !ret;
1903 if (!ret)
1904 continue;
1905 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001906
1907 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1908 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001909 goto return_bad_resp;
1910 }
1911
1912 /* check whether we're already working on the frontend */
1913 if (cur_proxy == sess->fe)
1914 break;
1915 cur_proxy = sess->fe;
1916 }
1917
1918 /* After this point, this anayzer can't return yield, so we can
1919 * remove the bit corresponding to this analyzer from the list.
1920 *
1921 * Note that the intermediate returns and goto found previously
1922 * reset the analyzers.
1923 */
1924 rep->analysers &= ~an_bit;
1925 rep->analyse_exp = TICK_ETERNITY;
1926
1927 /* OK that's all we can do for 1xx responses */
1928 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001929 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001930
1931 /*
1932 * Now check for a server cookie.
1933 */
1934 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001935 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001936
1937 /*
1938 * Check for cache-control or pragma headers if required.
1939 */
1940 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1941 check_response_for_cacheability(s, rep);
1942
1943 /*
1944 * Add server cookie in the response if needed
1945 */
1946 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1947 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1948 (!(s->flags & SF_DIRECT) ||
1949 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1950 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1951 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1952 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1953 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1954 !(s->flags & SF_IGNORE_PRST)) {
1955 /* the server is known, it's not the one the client requested, or the
1956 * cookie's last seen date needs to be refreshed. We have to
1957 * insert a set-cookie here, except if we want to insert only on POST
1958 * requests and this one isn't. Note that servers which don't have cookies
1959 * (eg: some backup servers) will return a full cookie removal request.
1960 */
1961 if (!objt_server(s->target)->cookie) {
1962 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001963 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001964 s->be->cookie_name);
1965 }
1966 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001967 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968
1969 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1970 /* emit last_date, which is mandatory */
1971 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1972 s30tob64((date.tv_sec+3) >> 2,
1973 trash.area + trash.data);
1974 trash.data += 5;
1975
1976 if (s->be->cookie_maxlife) {
1977 /* emit first_date, which is either the original one or
1978 * the current date.
1979 */
1980 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1981 s30tob64(txn->cookie_first_date ?
1982 txn->cookie_first_date >> 2 :
1983 (date.tv_sec+3) >> 2,
1984 trash.area + trash.data);
1985 trash.data += 5;
1986 }
1987 }
1988 chunk_appendf(&trash, "; path=/");
1989 }
1990
1991 if (s->be->cookie_domain)
1992 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1993
1994 if (s->be->ck_opts & PR_CK_HTTPONLY)
1995 chunk_appendf(&trash, "; HttpOnly");
1996
1997 if (s->be->ck_opts & PR_CK_SECURE)
1998 chunk_appendf(&trash, "; Secure");
1999
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002000 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002001 goto return_bad_resp;
2002
2003 txn->flags &= ~TX_SCK_MASK;
2004 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2005 /* the server did not change, only the date was updated */
2006 txn->flags |= TX_SCK_UPDATED;
2007 else
2008 txn->flags |= TX_SCK_INSERTED;
2009
2010 /* Here, we will tell an eventual cache on the client side that we don't
2011 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2012 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2013 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2014 */
2015 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2016
2017 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2018
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002019 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002020 goto return_bad_resp;
2021 }
2022 }
2023
2024 /*
2025 * Check if result will be cacheable with a cookie.
2026 * We'll block the response if security checks have caught
2027 * nasty things such as a cacheable cookie.
2028 */
2029 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2030 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2031 (s->be->options & PR_O_CHK_CACHE)) {
2032 /* we're in presence of a cacheable response containing
2033 * a set-cookie header. We'll block it as requested by
2034 * the 'checkcache' option, and send an alert.
2035 */
2036 if (objt_server(s->target))
2037 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2038
2039 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2040 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2041 if (sess->listener->counters)
2042 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2043
2044 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2045 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2046 send_log(s->be, LOG_ALERT,
2047 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2048 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2049 goto return_srv_prx_502;
2050 }
2051
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002052 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002053 /* Always enter in the body analyzer */
2054 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2055 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2056
2057 /* if the user wants to log as soon as possible, without counting
2058 * bytes from the server, then this is the right moment. We have
2059 * to temporarily assign bytes_out to log what we currently have.
2060 */
2061 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2062 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002063 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002064 s->do_log(s);
2065 s->logs.bytes_out = 0;
2066 }
2067 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002068
2069 return_bad_resp:
2070 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002071 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2072 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002073 }
2074 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2075
2076 return_srv_prx_502:
2077 rep->analysers &= AN_RES_FLT_END;
2078 txn->status = 502;
2079 s->logs.t_data = -1; /* was not a valid response */
2080 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002081 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002082 if (!(s->flags & SF_ERR_MASK))
2083 s->flags |= SF_ERR_PRXCOND;
2084 if (!(s->flags & SF_FINST_MASK))
2085 s->flags |= SF_FINST_H;
2086 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002087}
2088
2089/* This function is an analyser which forwards response body (including chunk
2090 * sizes if any). It is called as soon as we must forward, even if we forward
2091 * zero byte. The only situation where it must not be called is when we're in
2092 * tunnel mode and we want to forward till the close. It's used both to forward
2093 * remaining data and to resync after end of body. It expects the msg_state to
2094 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2095 * read more data, or 1 once we can go on with next request or end the stream.
2096 *
2097 * It is capable of compressing response data both in content-length mode and
2098 * in chunked mode. The state machines follows different flows depending on
2099 * whether content-length and chunked modes are used, since there are no
2100 * trailers in content-length :
2101 *
2102 * chk-mode cl-mode
2103 * ,----- BODY -----.
2104 * / \
2105 * V size > 0 V chk-mode
2106 * .--> SIZE -------------> DATA -------------> CRLF
2107 * | | size == 0 | last byte |
2108 * | v final crlf v inspected |
2109 * | TRAILERS -----------> DONE |
2110 * | |
2111 * `----------------------------------------------'
2112 *
2113 * Compression only happens in the DATA state, and must be flushed in final
2114 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2115 * is performed at once on final states for all bytes parsed, or when leaving
2116 * on missing data.
2117 */
2118int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2119{
2120 struct session *sess = s->sess;
2121 struct http_txn *txn = s->txn;
2122 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002123 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002124 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002125
2126 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2127 now_ms, __FUNCTION__,
2128 s,
2129 res,
2130 res->rex, res->wex,
2131 res->flags,
2132 ci_data(res),
2133 res->analysers);
2134
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002135 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136
2137 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002138 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002139 /* Output closed while we were sending data. We must abort and
2140 * wake the other side up.
2141 */
2142 msg->err_state = msg->msg_state;
2143 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002144 htx_end_response(s);
2145 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002146 return 1;
2147 }
2148
Christopher Faulet9768c262018-10-22 09:34:31 +02002149 if (msg->msg_state == HTTP_MSG_BODY)
2150 msg->msg_state = HTTP_MSG_DATA;
2151
Christopher Faulete0768eb2018-10-03 16:38:02 +02002152 /* in most states, we should abort in case of early close */
2153 channel_auto_close(res);
2154
Christopher Faulete0768eb2018-10-03 16:38:02 +02002155 if (res->to_forward) {
2156 /* We can't process the buffer's contents yet */
2157 res->flags |= CF_WAKE_WRITE;
2158 goto missing_data_or_waiting;
2159 }
2160
Christopher Faulet9768c262018-10-22 09:34:31 +02002161 if (msg->msg_state >= HTTP_MSG_DONE)
2162 goto done;
2163
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002164 /* Forward input data. We get it by removing all outgoing data not
2165 * forwarded yet from HTX data size. If there are some data filters, we
2166 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002167 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 if (HAS_RSP_DATA_FILTERS(s)) {
2169 ret = flt_http_payload(s, msg, htx->data);
2170 if (ret < 0)
2171 goto return_bad_res;
2172 c_adv(res, ret);
2173 if (htx->data != co_data(res) || htx->extra)
2174 goto missing_data_or_waiting;
2175 }
2176 else {
2177 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002178
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002179 /* To let the function channel_forward work as expected we must update
2180 * the channel's buffer to pretend there is no more input data. The
2181 * right length is then restored. We must do that, because when an HTX
2182 * message is stored into a buffer, it appears as full.
2183 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002184 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2185 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002186 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002187
2188 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2189 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002190 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002191 msg->msg_state = HTTP_MSG_TUNNEL;
2192 goto done;
2193 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002194 }
2195
Christopher Faulet9768c262018-10-22 09:34:31 +02002196 /* Check if the end-of-message is reached and if so, switch the message
2197 * in HTTP_MSG_DONE state.
2198 */
2199 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2200 goto missing_data_or_waiting;
2201
2202 msg->msg_state = HTTP_MSG_DONE;
2203
2204 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002206 channel_dont_close(res);
2207
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002208 if (HAS_RSP_DATA_FILTERS(s)) {
2209 ret = flt_http_end(s, msg);
2210 if (ret <= 0) {
2211 if (!ret)
2212 goto missing_data_or_waiting;
2213 goto return_bad_res;
2214 }
2215 }
2216
Christopher Fauletf2824e62018-10-01 12:12:37 +02002217 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002218 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002219 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2221 if (res->flags & CF_SHUTW) {
2222 /* response errors are most likely due to the
2223 * client aborting the transfer. */
2224 goto aborted_xfer;
2225 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 goto return_bad_res;
2227 }
2228 return 1;
2229 }
2230 return 0;
2231
2232 missing_data_or_waiting:
2233 if (res->flags & CF_SHUTW)
2234 goto aborted_xfer;
2235
Christopher Faulet47365272018-10-31 17:40:50 +01002236 if (htx->flags & HTX_FL_PARSING_ERROR)
2237 goto return_bad_res;
2238
Christopher Faulete0768eb2018-10-03 16:38:02 +02002239 /* stop waiting for data if the input is closed before the end. If the
2240 * client side was already closed, it means that the client has aborted,
2241 * so we don't want to count this as a server abort. Otherwise it's a
2242 * server abort.
2243 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002244 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002245 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2246 goto aborted_xfer;
2247 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002248 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002249 if (!(s->flags & SF_ERR_MASK))
2250 s->flags |= SF_ERR_SRVCL;
2251 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2252 if (objt_server(s->target))
2253 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2254 goto return_bad_res_stats_ok;
2255 }
2256 }
2257
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258 /* When TE: chunked is used, we need to get there again to parse
2259 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002260 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2261 * are filters registered on the stream, we don't want to forward a
2262 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002263 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002264 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 channel_dont_close(res);
2266
2267 /* We know that more data are expected, but we couldn't send more that
2268 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2269 * system knows it must not set a PUSH on this first part. Interactive
2270 * modes are already handled by the stream sock layer. We must not do
2271 * this in content-length mode because it could present the MSG_MORE
2272 * flag with the last block of forwarded data, which would cause an
2273 * additional delay to be observed by the receiver.
2274 */
2275 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2276 res->flags |= CF_EXPECT_MORE;
2277
2278 /* the stream handler will take care of timeouts and errors */
2279 return 0;
2280
2281 return_bad_res: /* let's centralize all bad responses */
2282 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2283 if (objt_server(s->target))
2284 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2285
2286 return_bad_res_stats_ok:
2287 txn->rsp.err_state = txn->rsp.msg_state;
2288 txn->rsp.msg_state = HTTP_MSG_ERROR;
2289 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002290 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002291 res->analysers &= AN_RES_FLT_END;
2292 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2293 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002294 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002295
2296 if (!(s->flags & SF_ERR_MASK))
2297 s->flags |= SF_ERR_PRXCOND;
2298 if (!(s->flags & SF_FINST_MASK))
2299 s->flags |= SF_FINST_D;
2300 return 0;
2301
2302 aborted_xfer:
2303 txn->rsp.err_state = txn->rsp.msg_state;
2304 txn->rsp.msg_state = HTTP_MSG_ERROR;
2305 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002306 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002307 res->analysers &= AN_RES_FLT_END;
2308 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2309
2310 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2311 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2312 if (objt_server(s->target))
2313 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2314
2315 if (!(s->flags & SF_ERR_MASK))
2316 s->flags |= SF_ERR_CLICL;
2317 if (!(s->flags & SF_FINST_MASK))
2318 s->flags |= SF_FINST_D;
2319 return 0;
2320}
2321
Christopher Faulet0f226952018-10-22 09:29:56 +02002322void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323{
2324 struct proxy *fe = strm_fe(s);
2325 int tmp = TX_CON_WANT_CLO;
2326
2327 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2328 tmp = TX_CON_WANT_TUN;
2329
2330 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002331 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002332}
2333
2334/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002335 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002336 * as too large a request to build a valid response.
2337 */
2338int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2339{
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 struct channel *req = &s->req;
2341 struct channel *res = &s->res;
2342 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002343 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002344 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002345 struct ist status, reason, location;
2346 unsigned int flags;
2347 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002348
2349 chunk = alloc_trash_chunk();
2350 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002352
Christopher Faulet99daf282018-11-28 22:58:13 +01002353 /*
2354 * Create the location
2355 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002356 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002357 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002358 case REDIRECT_TYPE_SCHEME: {
2359 struct http_hdr_ctx ctx;
2360 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002361
Christopher Faulet99daf282018-11-28 22:58:13 +01002362 host = ist("");
2363 ctx.blk = NULL;
2364 if (http_find_header(htx, ist("Host"), &ctx, 0))
2365 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366
Christopher Faulet99daf282018-11-28 22:58:13 +01002367 sl = http_find_stline(htx);
2368 path = http_get_path(htx_sl_req_uri(sl));
2369 /* build message using path */
2370 if (path.ptr) {
2371 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2372 int qs = 0;
2373 while (qs < path.len) {
2374 if (*(path.ptr + qs) == '?') {
2375 path.len = qs;
2376 break;
2377 }
2378 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002380 }
2381 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002382 else
2383 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002384
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 if (rule->rdr_str) { /* this is an old "redirect" rule */
2386 /* add scheme */
2387 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2388 goto fail;
2389 }
2390 else {
2391 /* add scheme with executing log format */
2392 chunk->data += build_logline(s, chunk->area + chunk->data,
2393 chunk->size - chunk->data,
2394 &rule->rdr_fmt);
2395 }
2396 /* add "://" + host + path */
2397 if (!chunk_memcat(chunk, "://", 3) ||
2398 !chunk_memcat(chunk, host.ptr, host.len) ||
2399 !chunk_memcat(chunk, path.ptr, path.len))
2400 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401
Christopher Faulet99daf282018-11-28 22:58:13 +01002402 /* append a slash at the end of the location if needed and missing */
2403 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2404 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2405 if (chunk->data + 1 >= chunk->size)
2406 goto fail;
2407 chunk->area[chunk->data++] = '/';
2408 }
2409 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 case REDIRECT_TYPE_PREFIX: {
2413 struct ist path;
2414
2415 sl = http_find_stline(htx);
2416 path = http_get_path(htx_sl_req_uri(sl));
2417 /* build message using path */
2418 if (path.ptr) {
2419 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2420 int qs = 0;
2421 while (qs < path.len) {
2422 if (*(path.ptr + qs) == '?') {
2423 path.len = qs;
2424 break;
2425 }
2426 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428 }
2429 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002430 else
2431 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 if (rule->rdr_str) { /* this is an old "redirect" rule */
2434 /* add prefix. Note that if prefix == "/", we don't want to
2435 * add anything, otherwise it makes it hard for the user to
2436 * configure a self-redirection.
2437 */
2438 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2439 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2440 goto fail;
2441 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002443 else {
2444 /* add prefix with executing log format */
2445 chunk->data += build_logline(s, chunk->area + chunk->data,
2446 chunk->size - chunk->data,
2447 &rule->rdr_fmt);
2448 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449
Christopher Faulet99daf282018-11-28 22:58:13 +01002450 /* add path */
2451 if (!chunk_memcat(chunk, path.ptr, path.len))
2452 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453
Christopher Faulet99daf282018-11-28 22:58:13 +01002454 /* append a slash at the end of the location if needed and missing */
2455 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2456 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2457 if (chunk->data + 1 >= chunk->size)
2458 goto fail;
2459 chunk->area[chunk->data++] = '/';
2460 }
2461 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002462 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002463 case REDIRECT_TYPE_LOCATION:
2464 default:
2465 if (rule->rdr_str) { /* this is an old "redirect" rule */
2466 /* add location */
2467 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2468 goto fail;
2469 }
2470 else {
2471 /* add location with executing log format */
2472 chunk->data += build_logline(s, chunk->area + chunk->data,
2473 chunk->size - chunk->data,
2474 &rule->rdr_fmt);
2475 }
2476 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002477 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002478 location = ist2(chunk->area, chunk->data);
2479
2480 /*
2481 * Create the 30x response
2482 */
2483 switch (rule->code) {
2484 case 308:
2485 status = ist("308");
2486 reason = ist("Permanent Redirect");
2487 break;
2488 case 307:
2489 status = ist("307");
2490 reason = ist("Temporary Redirect");
2491 break;
2492 case 303:
2493 status = ist("303");
2494 reason = ist("See Other");
2495 break;
2496 case 301:
2497 status = ist("301");
2498 reason = ist("Moved Permanently");
2499 break;
2500 case 302:
2501 default:
2502 status = ist("302");
2503 reason = ist("Found");
2504 break;
2505 }
2506
2507 htx = htx_from_buf(&res->buf);
2508 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2509 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2510 if (!sl)
2511 goto fail;
2512 sl->info.res.status = rule->code;
2513 s->txn->status = rule->code;
2514
2515 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2516 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2517 !htx_add_header(htx, ist("Location"), location))
2518 goto fail;
2519
2520 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2521 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2522 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002523 }
2524
2525 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002526 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2527 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002528 }
2529
Christopher Faulet99daf282018-11-28 22:58:13 +01002530 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2531 goto fail;
2532
Christopher Fauletf2824e62018-10-01 12:12:37 +02002533 /* let's log the request time */
2534 s->logs.tv_request = now;
2535
Christopher Faulet99daf282018-11-28 22:58:13 +01002536 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002537 c_adv(res, data);
2538 res->total += data;
2539
2540 channel_auto_read(req);
2541 channel_abort(req);
2542 channel_auto_close(req);
2543 channel_erase(req);
2544
2545 res->wex = tick_add_ifset(now_ms, res->wto);
2546 channel_auto_read(res);
2547 channel_auto_close(res);
2548 channel_shutr_now(res);
2549
2550 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002551
2552 if (!(s->flags & SF_ERR_MASK))
2553 s->flags |= SF_ERR_LOCAL;
2554 if (!(s->flags & SF_FINST_MASK))
2555 s->flags |= SF_FINST_R;
2556
Christopher Faulet99daf282018-11-28 22:58:13 +01002557 free_trash_chunk(chunk);
2558 return 1;
2559
2560 fail:
2561 /* If an error occurred, remove the incomplete HTTP response from the
2562 * buffer */
2563 channel_truncate(res);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002564 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002565 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002566}
2567
Christopher Faulet72333522018-10-24 11:25:02 +02002568int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2569 struct ist name, const char *str, struct my_regex *re, int action)
2570{
2571 struct http_hdr_ctx ctx;
2572 struct buffer *output = get_trash_chunk();
2573
2574 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2575 ctx.blk = NULL;
2576 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2577 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2578 continue;
2579
2580 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2581 if (output->data == -1)
2582 return -1;
2583 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2584 return -1;
2585 }
2586 return 0;
2587}
2588
2589static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2590 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2591{
2592 struct buffer *replace;
2593 int ret = -1;
2594
2595 replace = alloc_trash_chunk();
2596 if (!replace)
2597 goto leave;
2598
2599 replace->data = build_logline(s, replace->area, replace->size, fmt);
2600 if (replace->data >= replace->size - 1)
2601 goto leave;
2602
2603 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2604
2605 leave:
2606 free_trash_chunk(replace);
2607 return ret;
2608}
2609
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002610
2611/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2612 * on success and -1 on error. The response channel is updated accordingly.
2613 */
2614static int htx_reply_103_early_hints(struct channel *res)
2615{
2616 struct htx *htx = htx_from_buf(&res->buf);
2617 size_t data;
2618
2619 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2620 /* If an error occurred during an Early-hint rule,
2621 * remove the incomplete HTTP 103 response from the
2622 * buffer */
2623 channel_truncate(res);
2624 return -1;
2625 }
2626
2627 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002628 c_adv(res, data);
2629 res->total += data;
2630 return 0;
2631}
2632
Christopher Faulet6eb92892018-11-15 16:39:29 +01002633/*
2634 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2635 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636 * If <early_hints> is 0, it is starts a new response by adding the start
2637 * line. If an error occurred -1 is returned. On success 0 is returned. The
2638 * channel is not updated here. It must be done calling the function
2639 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002640 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002641static 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 +01002642{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 struct channel *res = &s->res;
2644 struct htx *htx = htx_from_buf(&res->buf);
2645 struct buffer *value = alloc_trash_chunk();
2646
Christopher Faulet6eb92892018-11-15 16:39:29 +01002647 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002648 struct htx_sl *sl;
2649 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2650 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2651
2652 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2653 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2654 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002655 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002656 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002657 }
2658
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002659 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2660 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002661 goto fail;
2662
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002663 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002664 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002665
2666 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002667 /* If an error occurred during an Early-hint rule, remove the incomplete
2668 * HTTP 103 response from the buffer */
2669 channel_truncate(res);
2670 free_trash_chunk(value);
2671 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002672}
2673
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002674/* This function executes one of the set-{method,path,query,uri} actions. It
2675 * takes the string from the variable 'replace' with length 'len', then modifies
2676 * the relevant part of the request line accordingly. Then it updates various
2677 * pointers to the next elements which were moved, and the total buffer length.
2678 * It finds the action to be performed in p[2], previously filled by function
2679 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2680 * error, though this can be revisited when this code is finally exploited.
2681 *
2682 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2683 * query string and 3 to replace uri.
2684 *
2685 * In query string case, the mark question '?' must be set at the start of the
2686 * string by the caller, event if the replacement query string is empty.
2687 */
2688int htx_req_replace_stline(int action, const char *replace, int len,
2689 struct proxy *px, struct stream *s)
2690{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002691 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002692
2693 switch (action) {
2694 case 0: // method
2695 if (!http_replace_req_meth(htx, ist2(replace, len)))
2696 return -1;
2697 break;
2698
2699 case 1: // path
2700 if (!http_replace_req_path(htx, ist2(replace, len)))
2701 return -1;
2702 break;
2703
2704 case 2: // query
2705 if (!http_replace_req_query(htx, ist2(replace, len)))
2706 return -1;
2707 break;
2708
2709 case 3: // uri
2710 if (!http_replace_req_uri(htx, ist2(replace, len)))
2711 return -1;
2712 break;
2713
2714 default:
2715 return -1;
2716 }
2717 return 0;
2718}
2719
2720/* This function replace the HTTP status code and the associated message. The
2721 * variable <status> contains the new status code. This function never fails.
2722 */
2723void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2724{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002725 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002726 char *res;
2727
2728 chunk_reset(&trash);
2729 res = ultoa_o(status, trash.area, trash.size);
2730 trash.data = res - trash.area;
2731
2732 /* Do we have a custom reason format string? */
2733 if (reason == NULL)
2734 reason = http_get_reason(status);
2735
2736 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2737 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2738}
2739
Christopher Faulet3e964192018-10-24 11:39:23 +02002740/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2741 * transaction <txn>. Returns the verdict of the first rule that prevents
2742 * further processing of the request (auth, deny, ...), and defaults to
2743 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2744 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2745 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2746 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2747 * status.
2748 */
2749static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2750 struct stream *s, int *deny_status)
2751{
2752 struct session *sess = strm_sess(s);
2753 struct http_txn *txn = s->txn;
2754 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002755 struct act_rule *rule;
2756 struct http_hdr_ctx ctx;
2757 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002758 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2759 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002760 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002761
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002762 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002763
2764 /* If "the current_rule_list" match the executed rule list, we are in
2765 * resume condition. If a resume is needed it is always in the action
2766 * and never in the ACL or converters. In this case, we initialise the
2767 * current rule, and go to the action execution point.
2768 */
2769 if (s->current_rule) {
2770 rule = s->current_rule;
2771 s->current_rule = NULL;
2772 if (s->current_rule_list == rules)
2773 goto resume_execution;
2774 }
2775 s->current_rule_list = rules;
2776
2777 list_for_each_entry(rule, rules, list) {
2778 /* check optional condition */
2779 if (rule->cond) {
2780 int ret;
2781
2782 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2783 ret = acl_pass(ret);
2784
2785 if (rule->cond->pol == ACL_COND_UNLESS)
2786 ret = !ret;
2787
2788 if (!ret) /* condition not matched */
2789 continue;
2790 }
2791
2792 act_flags |= ACT_FLAG_FIRST;
2793 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002794 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2795 early_hints = 0;
2796 if (htx_reply_103_early_hints(&s->res) == -1) {
2797 rule_ret = HTTP_RULE_RES_BADREQ;
2798 goto end;
2799 }
2800 }
2801
Christopher Faulet3e964192018-10-24 11:39:23 +02002802 switch (rule->action) {
2803 case ACT_ACTION_ALLOW:
2804 rule_ret = HTTP_RULE_RES_STOP;
2805 goto end;
2806
2807 case ACT_ACTION_DENY:
2808 if (deny_status)
2809 *deny_status = rule->deny_status;
2810 rule_ret = HTTP_RULE_RES_DENY;
2811 goto end;
2812
2813 case ACT_HTTP_REQ_TARPIT:
2814 txn->flags |= TX_CLTARPIT;
2815 if (deny_status)
2816 *deny_status = rule->deny_status;
2817 rule_ret = HTTP_RULE_RES_DENY;
2818 goto end;
2819
2820 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002821 /* Auth might be performed on regular http-req rules as well as on stats */
2822 auth_realm = rule->arg.auth.realm;
2823 if (!auth_realm) {
2824 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2825 auth_realm = STATS_DEFAULT_REALM;
2826 else
2827 auth_realm = px->id;
2828 }
2829 /* send 401/407 depending on whether we use a proxy or not. We still
2830 * count one error, because normal browsing won't significantly
2831 * increase the counter but brute force attempts will.
2832 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002833 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002834 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2835 rule_ret = HTTP_RULE_RES_BADREQ;
2836 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002837 goto end;
2838
2839 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002840 rule_ret = HTTP_RULE_RES_DONE;
2841 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2842 rule_ret = HTTP_RULE_RES_BADREQ;
2843 goto end;
2844
2845 case ACT_HTTP_SET_NICE:
2846 s->task->nice = rule->arg.nice;
2847 break;
2848
2849 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002850 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002851 break;
2852
2853 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002854 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002855 break;
2856
2857 case ACT_HTTP_SET_LOGL:
2858 s->logs.level = rule->arg.loglevel;
2859 break;
2860
2861 case ACT_HTTP_REPLACE_HDR:
2862 case ACT_HTTP_REPLACE_VAL:
2863 if (htx_transform_header(s, &s->req, htx,
2864 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2865 &rule->arg.hdr_add.fmt,
2866 &rule->arg.hdr_add.re, rule->action)) {
2867 rule_ret = HTTP_RULE_RES_BADREQ;
2868 goto end;
2869 }
2870 break;
2871
2872 case ACT_HTTP_DEL_HDR:
2873 /* remove all occurrences of the header */
2874 ctx.blk = NULL;
2875 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2876 http_remove_header(htx, &ctx);
2877 break;
2878
2879 case ACT_HTTP_SET_HDR:
2880 case ACT_HTTP_ADD_HDR: {
2881 /* The scope of the trash buffer must be limited to this function. The
2882 * build_logline() function can execute a lot of other function which
2883 * can use the trash buffer. So for limiting the scope of this global
2884 * buffer, we build first the header value using build_logline, and
2885 * after we store the header name.
2886 */
2887 struct buffer *replace;
2888 struct ist n, v;
2889
2890 replace = alloc_trash_chunk();
2891 if (!replace) {
2892 rule_ret = HTTP_RULE_RES_BADREQ;
2893 goto end;
2894 }
2895
2896 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2897 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2898 v = ist2(replace->area, replace->data);
2899
2900 if (rule->action == ACT_HTTP_SET_HDR) {
2901 /* remove all occurrences of the header */
2902 ctx.blk = NULL;
2903 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2904 http_remove_header(htx, &ctx);
2905 }
2906
2907 if (!http_add_header(htx, n, v)) {
2908 static unsigned char rate_limit = 0;
2909
2910 if ((rate_limit++ & 255) == 0) {
2911 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);
2912 }
2913
2914 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2915 if (sess->fe != s->be)
2916 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2917 if (sess->listener->counters)
2918 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2919 }
2920 free_trash_chunk(replace);
2921 break;
2922 }
2923
2924 case ACT_HTTP_DEL_ACL:
2925 case ACT_HTTP_DEL_MAP: {
2926 struct pat_ref *ref;
2927 struct buffer *key;
2928
2929 /* collect reference */
2930 ref = pat_ref_lookup(rule->arg.map.ref);
2931 if (!ref)
2932 continue;
2933
2934 /* allocate key */
2935 key = alloc_trash_chunk();
2936 if (!key) {
2937 rule_ret = HTTP_RULE_RES_BADREQ;
2938 goto end;
2939 }
2940
2941 /* collect key */
2942 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2943 key->area[key->data] = '\0';
2944
2945 /* perform update */
2946 /* returned code: 1=ok, 0=ko */
2947 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2948 pat_ref_delete(ref, key->area);
2949 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2950
2951 free_trash_chunk(key);
2952 break;
2953 }
2954
2955 case ACT_HTTP_ADD_ACL: {
2956 struct pat_ref *ref;
2957 struct buffer *key;
2958
2959 /* collect reference */
2960 ref = pat_ref_lookup(rule->arg.map.ref);
2961 if (!ref)
2962 continue;
2963
2964 /* allocate key */
2965 key = alloc_trash_chunk();
2966 if (!key) {
2967 rule_ret = HTTP_RULE_RES_BADREQ;
2968 goto end;
2969 }
2970
2971 /* collect key */
2972 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2973 key->area[key->data] = '\0';
2974
2975 /* perform update */
2976 /* add entry only if it does not already exist */
2977 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2978 if (pat_ref_find_elt(ref, key->area) == NULL)
2979 pat_ref_add(ref, key->area, NULL, NULL);
2980 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2981
2982 free_trash_chunk(key);
2983 break;
2984 }
2985
2986 case ACT_HTTP_SET_MAP: {
2987 struct pat_ref *ref;
2988 struct buffer *key, *value;
2989
2990 /* collect reference */
2991 ref = pat_ref_lookup(rule->arg.map.ref);
2992 if (!ref)
2993 continue;
2994
2995 /* allocate key */
2996 key = alloc_trash_chunk();
2997 if (!key) {
2998 rule_ret = HTTP_RULE_RES_BADREQ;
2999 goto end;
3000 }
3001
3002 /* allocate value */
3003 value = alloc_trash_chunk();
3004 if (!value) {
3005 free_trash_chunk(key);
3006 rule_ret = HTTP_RULE_RES_BADREQ;
3007 goto end;
3008 }
3009
3010 /* collect key */
3011 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3012 key->area[key->data] = '\0';
3013
3014 /* collect value */
3015 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3016 value->area[value->data] = '\0';
3017
3018 /* perform update */
3019 if (pat_ref_find_elt(ref, key->area) != NULL)
3020 /* update entry if it exists */
3021 pat_ref_set(ref, key->area, value->area, NULL);
3022 else
3023 /* insert a new entry */
3024 pat_ref_add(ref, key->area, value->area, NULL);
3025
3026 free_trash_chunk(key);
3027 free_trash_chunk(value);
3028 break;
3029 }
3030
3031 case ACT_HTTP_EARLY_HINT:
3032 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3033 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003034 early_hints = htx_add_early_hint_header(s, early_hints,
3035 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003036 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003037 if (early_hints == -1) {
3038 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003039 goto end;
3040 }
3041 break;
3042
3043 case ACT_CUSTOM:
3044 if ((s->req.flags & CF_READ_ERROR) ||
3045 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3046 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3047 (px->options & PR_O_ABRT_CLOSE)))
3048 act_flags |= ACT_FLAG_FINAL;
3049
3050 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3051 case ACT_RET_ERR:
3052 case ACT_RET_CONT:
3053 break;
3054 case ACT_RET_STOP:
3055 rule_ret = HTTP_RULE_RES_DONE;
3056 goto end;
3057 case ACT_RET_YIELD:
3058 s->current_rule = rule;
3059 rule_ret = HTTP_RULE_RES_YIELD;
3060 goto end;
3061 }
3062 break;
3063
3064 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3065 /* Note: only the first valid tracking parameter of each
3066 * applies.
3067 */
3068
3069 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3070 struct stktable *t;
3071 struct stksess *ts;
3072 struct stktable_key *key;
3073 void *ptr1, *ptr2;
3074
3075 t = rule->arg.trk_ctr.table.t;
3076 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3077 rule->arg.trk_ctr.expr, NULL);
3078
3079 if (key && (ts = stktable_get_entry(t, key))) {
3080 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3081
3082 /* let's count a new HTTP request as it's the first time we do it */
3083 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3084 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3085 if (ptr1 || ptr2) {
3086 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3087
3088 if (ptr1)
3089 stktable_data_cast(ptr1, http_req_cnt)++;
3090
3091 if (ptr2)
3092 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3093 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3094
3095 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3096
3097 /* If data was modified, we need to touch to re-schedule sync */
3098 stktable_touch_local(t, ts, 0);
3099 }
3100
3101 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3102 if (sess->fe != s->be)
3103 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3104 }
3105 }
3106 break;
3107
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003108 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003109 default:
3110 break;
3111 }
3112 }
3113
3114 end:
3115 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003116 if (htx_reply_103_early_hints(&s->res) == -1)
3117 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003118 }
3119
3120 /* we reached the end of the rules, nothing to report */
3121 return rule_ret;
3122}
3123
3124/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3125 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3126 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3127 * is returned, the process can continue the evaluation of next rule list. If
3128 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3129 * is returned, it means the operation could not be processed and a server error
3130 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3131 * deny rule. If *YIELD is returned, the caller must call again the function
3132 * with the same context.
3133 */
3134static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3135 struct stream *s)
3136{
3137 struct session *sess = strm_sess(s);
3138 struct http_txn *txn = s->txn;
3139 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003140 struct act_rule *rule;
3141 struct http_hdr_ctx ctx;
3142 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3143 int act_flags = 0;
3144
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003145 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003146
3147 /* If "the current_rule_list" match the executed rule list, we are in
3148 * resume condition. If a resume is needed it is always in the action
3149 * and never in the ACL or converters. In this case, we initialise the
3150 * current rule, and go to the action execution point.
3151 */
3152 if (s->current_rule) {
3153 rule = s->current_rule;
3154 s->current_rule = NULL;
3155 if (s->current_rule_list == rules)
3156 goto resume_execution;
3157 }
3158 s->current_rule_list = rules;
3159
3160 list_for_each_entry(rule, rules, list) {
3161 /* check optional condition */
3162 if (rule->cond) {
3163 int ret;
3164
3165 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3166 ret = acl_pass(ret);
3167
3168 if (rule->cond->pol == ACL_COND_UNLESS)
3169 ret = !ret;
3170
3171 if (!ret) /* condition not matched */
3172 continue;
3173 }
3174
3175 act_flags |= ACT_FLAG_FIRST;
3176resume_execution:
3177 switch (rule->action) {
3178 case ACT_ACTION_ALLOW:
3179 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3180 goto end;
3181
3182 case ACT_ACTION_DENY:
3183 txn->flags |= TX_SVDENY;
3184 rule_ret = HTTP_RULE_RES_STOP;
3185 goto end;
3186
3187 case ACT_HTTP_SET_NICE:
3188 s->task->nice = rule->arg.nice;
3189 break;
3190
3191 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003192 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003193 break;
3194
3195 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003196 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003197 break;
3198
3199 case ACT_HTTP_SET_LOGL:
3200 s->logs.level = rule->arg.loglevel;
3201 break;
3202
3203 case ACT_HTTP_REPLACE_HDR:
3204 case ACT_HTTP_REPLACE_VAL:
3205 if (htx_transform_header(s, &s->res, htx,
3206 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3207 &rule->arg.hdr_add.fmt,
3208 &rule->arg.hdr_add.re, rule->action)) {
3209 rule_ret = HTTP_RULE_RES_BADREQ;
3210 goto end;
3211 }
3212 break;
3213
3214 case ACT_HTTP_DEL_HDR:
3215 /* remove all occurrences of the header */
3216 ctx.blk = NULL;
3217 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3218 http_remove_header(htx, &ctx);
3219 break;
3220
3221 case ACT_HTTP_SET_HDR:
3222 case ACT_HTTP_ADD_HDR: {
3223 struct buffer *replace;
3224 struct ist n, v;
3225
3226 replace = alloc_trash_chunk();
3227 if (!replace) {
3228 rule_ret = HTTP_RULE_RES_BADREQ;
3229 goto end;
3230 }
3231
3232 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3233 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3234 v = ist2(replace->area, replace->data);
3235
3236 if (rule->action == ACT_HTTP_SET_HDR) {
3237 /* remove all occurrences of the header */
3238 ctx.blk = NULL;
3239 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3240 http_remove_header(htx, &ctx);
3241 }
3242
3243 if (!http_add_header(htx, n, v)) {
3244 static unsigned char rate_limit = 0;
3245
3246 if ((rate_limit++ & 255) == 0) {
3247 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);
3248 }
3249
3250 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3251 if (sess->fe != s->be)
3252 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3253 if (sess->listener->counters)
3254 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3255 if (objt_server(s->target))
3256 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3257 }
3258 free_trash_chunk(replace);
3259 break;
3260 }
3261
3262 case ACT_HTTP_DEL_ACL:
3263 case ACT_HTTP_DEL_MAP: {
3264 struct pat_ref *ref;
3265 struct buffer *key;
3266
3267 /* collect reference */
3268 ref = pat_ref_lookup(rule->arg.map.ref);
3269 if (!ref)
3270 continue;
3271
3272 /* allocate key */
3273 key = alloc_trash_chunk();
3274 if (!key) {
3275 rule_ret = HTTP_RULE_RES_BADREQ;
3276 goto end;
3277 }
3278
3279 /* collect key */
3280 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3281 key->area[key->data] = '\0';
3282
3283 /* perform update */
3284 /* returned code: 1=ok, 0=ko */
3285 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3286 pat_ref_delete(ref, key->area);
3287 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3288
3289 free_trash_chunk(key);
3290 break;
3291 }
3292
3293 case ACT_HTTP_ADD_ACL: {
3294 struct pat_ref *ref;
3295 struct buffer *key;
3296
3297 /* collect reference */
3298 ref = pat_ref_lookup(rule->arg.map.ref);
3299 if (!ref)
3300 continue;
3301
3302 /* allocate key */
3303 key = alloc_trash_chunk();
3304 if (!key) {
3305 rule_ret = HTTP_RULE_RES_BADREQ;
3306 goto end;
3307 }
3308
3309 /* collect key */
3310 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3311 key->area[key->data] = '\0';
3312
3313 /* perform update */
3314 /* check if the entry already exists */
3315 if (pat_ref_find_elt(ref, key->area) == NULL)
3316 pat_ref_add(ref, key->area, NULL, NULL);
3317
3318 free_trash_chunk(key);
3319 break;
3320 }
3321
3322 case ACT_HTTP_SET_MAP: {
3323 struct pat_ref *ref;
3324 struct buffer *key, *value;
3325
3326 /* collect reference */
3327 ref = pat_ref_lookup(rule->arg.map.ref);
3328 if (!ref)
3329 continue;
3330
3331 /* allocate key */
3332 key = alloc_trash_chunk();
3333 if (!key) {
3334 rule_ret = HTTP_RULE_RES_BADREQ;
3335 goto end;
3336 }
3337
3338 /* allocate value */
3339 value = alloc_trash_chunk();
3340 if (!value) {
3341 free_trash_chunk(key);
3342 rule_ret = HTTP_RULE_RES_BADREQ;
3343 goto end;
3344 }
3345
3346 /* collect key */
3347 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3348 key->area[key->data] = '\0';
3349
3350 /* collect value */
3351 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3352 value->area[value->data] = '\0';
3353
3354 /* perform update */
3355 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3356 if (pat_ref_find_elt(ref, key->area) != NULL)
3357 /* update entry if it exists */
3358 pat_ref_set(ref, key->area, value->area, NULL);
3359 else
3360 /* insert a new entry */
3361 pat_ref_add(ref, key->area, value->area, NULL);
3362 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3363 free_trash_chunk(key);
3364 free_trash_chunk(value);
3365 break;
3366 }
3367
3368 case ACT_HTTP_REDIR:
3369 rule_ret = HTTP_RULE_RES_DONE;
3370 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3371 rule_ret = HTTP_RULE_RES_BADREQ;
3372 goto end;
3373
3374 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3375 /* Note: only the first valid tracking parameter of each
3376 * applies.
3377 */
3378 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3379 struct stktable *t;
3380 struct stksess *ts;
3381 struct stktable_key *key;
3382 void *ptr;
3383
3384 t = rule->arg.trk_ctr.table.t;
3385 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3386 rule->arg.trk_ctr.expr, NULL);
3387
3388 if (key && (ts = stktable_get_entry(t, key))) {
3389 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3390
3391 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3392
3393 /* let's count a new HTTP request as it's the first time we do it */
3394 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3395 if (ptr)
3396 stktable_data_cast(ptr, http_req_cnt)++;
3397
3398 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3399 if (ptr)
3400 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3401 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3402
3403 /* When the client triggers a 4xx from the server, it's most often due
3404 * to a missing object or permission. These events should be tracked
3405 * because if they happen often, it may indicate a brute force or a
3406 * vulnerability scan. Normally this is done when receiving the response
3407 * but here we're tracking after this ought to have been done so we have
3408 * to do it on purpose.
3409 */
3410 if ((unsigned)(txn->status - 400) < 100) {
3411 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3412 if (ptr)
3413 stktable_data_cast(ptr, http_err_cnt)++;
3414
3415 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3416 if (ptr)
3417 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3418 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3419 }
3420
3421 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3422
3423 /* If data was modified, we need to touch to re-schedule sync */
3424 stktable_touch_local(t, ts, 0);
3425
3426 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3427 if (sess->fe != s->be)
3428 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3429 }
3430 }
3431 break;
3432
3433 case ACT_CUSTOM:
3434 if ((s->req.flags & CF_READ_ERROR) ||
3435 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3436 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3437 (px->options & PR_O_ABRT_CLOSE)))
3438 act_flags |= ACT_FLAG_FINAL;
3439
3440 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3441 case ACT_RET_ERR:
3442 case ACT_RET_CONT:
3443 break;
3444 case ACT_RET_STOP:
3445 rule_ret = HTTP_RULE_RES_STOP;
3446 goto end;
3447 case ACT_RET_YIELD:
3448 s->current_rule = rule;
3449 rule_ret = HTTP_RULE_RES_YIELD;
3450 goto end;
3451 }
3452 break;
3453
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003454 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003455 default:
3456 break;
3457 }
3458 }
3459
3460 end:
3461 /* we reached the end of the rules, nothing to report */
3462 return rule_ret;
3463}
3464
Christopher Faulet33640082018-10-24 11:53:01 +02003465/* Iterate the same filter through all request headers.
3466 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3467 * Since it can manage the switch to another backend, it updates the per-proxy
3468 * DENY stats.
3469 */
3470static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3471{
3472 struct http_txn *txn = s->txn;
3473 struct htx *htx;
3474 struct buffer *hdr = get_trash_chunk();
3475 int32_t pos;
3476
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003477 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003478
3479 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3480 struct htx_blk *blk = htx_get_blk(htx, pos);
3481 enum htx_blk_type type;
3482 struct ist n, v;
3483
3484 next_hdr:
3485 type = htx_get_blk_type(blk);
3486 if (type == HTX_BLK_EOH)
3487 break;
3488 if (type != HTX_BLK_HDR)
3489 continue;
3490
3491 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3492 return 1;
3493 else if (unlikely(txn->flags & TX_CLALLOW) &&
3494 (exp->action == ACT_ALLOW ||
3495 exp->action == ACT_DENY ||
3496 exp->action == ACT_TARPIT))
3497 return 0;
3498
3499 n = htx_get_blk_name(htx, blk);
3500 v = htx_get_blk_value(htx, blk);
3501
3502 chunk_memcat(hdr, n.ptr, n.len);
3503 hdr->area[hdr->data++] = ':';
3504 hdr->area[hdr->data++] = ' ';
3505 chunk_memcat(hdr, v.ptr, v.len);
3506
3507 /* Now we have one header in <hdr> */
3508
3509 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3510 struct http_hdr_ctx ctx;
3511 int len;
3512
3513 switch (exp->action) {
3514 case ACT_ALLOW:
3515 txn->flags |= TX_CLALLOW;
3516 goto end;
3517
3518 case ACT_DENY:
3519 txn->flags |= TX_CLDENY;
3520 goto end;
3521
3522 case ACT_TARPIT:
3523 txn->flags |= TX_CLTARPIT;
3524 goto end;
3525
3526 case ACT_REPLACE:
3527 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3528 if (len < 0)
3529 return -1;
3530
3531 http_parse_header(ist2(trash.area, len), &n, &v);
3532 ctx.blk = blk;
3533 ctx.value = v;
3534 if (!http_replace_header(htx, &ctx, n, v))
3535 return -1;
3536 if (!ctx.blk)
3537 goto end;
3538 pos = htx_get_blk_pos(htx, blk);
3539 break;
3540
3541 case ACT_REMOVE:
3542 ctx.blk = blk;
3543 ctx.value = v;
3544 if (!http_remove_header(htx, &ctx))
3545 return -1;
3546 if (!ctx.blk)
3547 goto end;
3548 pos = htx_get_blk_pos(htx, blk);
3549 goto next_hdr;
3550
3551 }
3552 }
3553 }
3554 end:
3555 return 0;
3556}
3557
3558/* Apply the filter to the request line.
3559 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3560 * or -1 if a replacement resulted in an invalid request line.
3561 * Since it can manage the switch to another backend, it updates the per-proxy
3562 * DENY stats.
3563 */
3564static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3565{
3566 struct http_txn *txn = s->txn;
3567 struct htx *htx;
3568 struct buffer *reqline = get_trash_chunk();
3569 int done;
3570
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003571 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003572
3573 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3574 return 1;
3575 else if (unlikely(txn->flags & TX_CLALLOW) &&
3576 (exp->action == ACT_ALLOW ||
3577 exp->action == ACT_DENY ||
3578 exp->action == ACT_TARPIT))
3579 return 0;
3580 else if (exp->action == ACT_REMOVE)
3581 return 0;
3582
3583 done = 0;
3584
3585 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3586
3587 /* Now we have the request line between cur_ptr and cur_end */
3588 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003589 struct htx_sl *sl = http_find_stline(htx);
3590 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003591 int len;
3592
3593 switch (exp->action) {
3594 case ACT_ALLOW:
3595 txn->flags |= TX_CLALLOW;
3596 done = 1;
3597 break;
3598
3599 case ACT_DENY:
3600 txn->flags |= TX_CLDENY;
3601 done = 1;
3602 break;
3603
3604 case ACT_TARPIT:
3605 txn->flags |= TX_CLTARPIT;
3606 done = 1;
3607 break;
3608
3609 case ACT_REPLACE:
3610 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3611 if (len < 0)
3612 return -1;
3613
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003614 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3615 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3616 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003617 return -1;
3618 done = 1;
3619 break;
3620 }
3621 }
3622 return done;
3623}
3624
3625/*
3626 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3627 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3628 * unparsable request. Since it can manage the switch to another backend, it
3629 * updates the per-proxy DENY stats.
3630 */
3631static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3632{
3633 struct session *sess = s->sess;
3634 struct http_txn *txn = s->txn;
3635 struct hdr_exp *exp;
3636
3637 for (exp = px->req_exp; exp; exp = exp->next) {
3638 int ret;
3639
3640 /*
3641 * The interleaving of transformations and verdicts
3642 * makes it difficult to decide to continue or stop
3643 * the evaluation.
3644 */
3645
3646 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3647 break;
3648
3649 if ((txn->flags & TX_CLALLOW) &&
3650 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3651 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3652 continue;
3653
3654 /* if this filter had a condition, evaluate it now and skip to
3655 * next filter if the condition does not match.
3656 */
3657 if (exp->cond) {
3658 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3659 ret = acl_pass(ret);
3660 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3661 ret = !ret;
3662
3663 if (!ret)
3664 continue;
3665 }
3666
3667 /* Apply the filter to the request line. */
3668 ret = htx_apply_filter_to_req_line(s, req, exp);
3669 if (unlikely(ret < 0))
3670 return -1;
3671
3672 if (likely(ret == 0)) {
3673 /* The filter did not match the request, it can be
3674 * iterated through all headers.
3675 */
3676 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3677 return -1;
3678 }
3679 }
3680 return 0;
3681}
3682
3683/* Iterate the same filter through all response headers contained in <res>.
3684 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3685 */
3686static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3687{
3688 struct http_txn *txn = s->txn;
3689 struct htx *htx;
3690 struct buffer *hdr = get_trash_chunk();
3691 int32_t pos;
3692
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003693 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003694
3695 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3696 struct htx_blk *blk = htx_get_blk(htx, pos);
3697 enum htx_blk_type type;
3698 struct ist n, v;
3699
3700 next_hdr:
3701 type = htx_get_blk_type(blk);
3702 if (type == HTX_BLK_EOH)
3703 break;
3704 if (type != HTX_BLK_HDR)
3705 continue;
3706
3707 if (unlikely(txn->flags & TX_SVDENY))
3708 return 1;
3709 else if (unlikely(txn->flags & TX_SVALLOW) &&
3710 (exp->action == ACT_ALLOW ||
3711 exp->action == ACT_DENY))
3712 return 0;
3713
3714 n = htx_get_blk_name(htx, blk);
3715 v = htx_get_blk_value(htx, blk);
3716
3717 chunk_memcat(hdr, n.ptr, n.len);
3718 hdr->area[hdr->data++] = ':';
3719 hdr->area[hdr->data++] = ' ';
3720 chunk_memcat(hdr, v.ptr, v.len);
3721
3722 /* Now we have one header in <hdr> */
3723
3724 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3725 struct http_hdr_ctx ctx;
3726 int len;
3727
3728 switch (exp->action) {
3729 case ACT_ALLOW:
3730 txn->flags |= TX_SVALLOW;
3731 goto end;
3732 break;
3733
3734 case ACT_DENY:
3735 txn->flags |= TX_SVDENY;
3736 goto end;
3737 break;
3738
3739 case ACT_REPLACE:
3740 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3741 if (len < 0)
3742 return -1;
3743
3744 http_parse_header(ist2(trash.area, len), &n, &v);
3745 ctx.blk = blk;
3746 ctx.value = v;
3747 if (!http_replace_header(htx, &ctx, n, v))
3748 return -1;
3749 if (!ctx.blk)
3750 goto end;
3751 pos = htx_get_blk_pos(htx, blk);
3752 break;
3753
3754 case ACT_REMOVE:
3755 ctx.blk = blk;
3756 ctx.value = v;
3757 if (!http_remove_header(htx, &ctx))
3758 return -1;
3759 if (!ctx.blk)
3760 goto end;
3761 pos = htx_get_blk_pos(htx, blk);
3762 goto next_hdr;
3763 }
3764 }
3765
3766 }
3767 end:
3768 return 0;
3769}
3770
3771/* Apply the filter to the status line in the response buffer <res>.
3772 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3773 * or -1 if a replacement resulted in an invalid status line.
3774 */
3775static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3776{
3777 struct http_txn *txn = s->txn;
3778 struct htx *htx;
3779 struct buffer *resline = get_trash_chunk();
3780 int done;
3781
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003782 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003783
3784 if (unlikely(txn->flags & TX_SVDENY))
3785 return 1;
3786 else if (unlikely(txn->flags & TX_SVALLOW) &&
3787 (exp->action == ACT_ALLOW ||
3788 exp->action == ACT_DENY))
3789 return 0;
3790 else if (exp->action == ACT_REMOVE)
3791 return 0;
3792
3793 done = 0;
3794 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3795
3796 /* Now we have the status line between cur_ptr and cur_end */
3797 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003798 struct htx_sl *sl = http_find_stline(htx);
3799 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003800 int len;
3801
3802 switch (exp->action) {
3803 case ACT_ALLOW:
3804 txn->flags |= TX_SVALLOW;
3805 done = 1;
3806 break;
3807
3808 case ACT_DENY:
3809 txn->flags |= TX_SVDENY;
3810 done = 1;
3811 break;
3812
3813 case ACT_REPLACE:
3814 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3815 if (len < 0)
3816 return -1;
3817
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003818 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3819 sl->info.res.status = strl2ui(code.ptr, code.len);
3820 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003821 return -1;
3822
3823 done = 1;
3824 return 1;
3825 }
3826 }
3827 return done;
3828}
3829
3830/*
3831 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3832 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3833 * unparsable response.
3834 */
3835static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3836{
3837 struct session *sess = s->sess;
3838 struct http_txn *txn = s->txn;
3839 struct hdr_exp *exp;
3840
3841 for (exp = px->rsp_exp; exp; exp = exp->next) {
3842 int ret;
3843
3844 /*
3845 * The interleaving of transformations and verdicts
3846 * makes it difficult to decide to continue or stop
3847 * the evaluation.
3848 */
3849
3850 if (txn->flags & TX_SVDENY)
3851 break;
3852
3853 if ((txn->flags & TX_SVALLOW) &&
3854 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3855 exp->action == ACT_PASS)) {
3856 exp = exp->next;
3857 continue;
3858 }
3859
3860 /* if this filter had a condition, evaluate it now and skip to
3861 * next filter if the condition does not match.
3862 */
3863 if (exp->cond) {
3864 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3865 ret = acl_pass(ret);
3866 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3867 ret = !ret;
3868 if (!ret)
3869 continue;
3870 }
3871
3872 /* Apply the filter to the status line. */
3873 ret = htx_apply_filter_to_sts_line(s, res, exp);
3874 if (unlikely(ret < 0))
3875 return -1;
3876
3877 if (likely(ret == 0)) {
3878 /* The filter did not match the response, it can be
3879 * iterated through all headers.
3880 */
3881 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3882 return -1;
3883 }
3884 }
3885 return 0;
3886}
3887
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003888/*
3889 * Manage client-side cookie. It can impact performance by about 2% so it is
3890 * desirable to call it only when needed. This code is quite complex because
3891 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3892 * highly recommended not to touch this part without a good reason !
3893 */
3894static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3895{
3896 struct session *sess = s->sess;
3897 struct http_txn *txn = s->txn;
3898 struct htx *htx;
3899 struct http_hdr_ctx ctx;
3900 char *hdr_beg, *hdr_end, *del_from;
3901 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3902 int preserve_hdr;
3903
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003904 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003905 ctx.blk = NULL;
3906 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3907 del_from = NULL; /* nothing to be deleted */
3908 preserve_hdr = 0; /* assume we may kill the whole header */
3909
3910 /* Now look for cookies. Conforming to RFC2109, we have to support
3911 * attributes whose name begin with a '$', and associate them with
3912 * the right cookie, if we want to delete this cookie.
3913 * So there are 3 cases for each cookie read :
3914 * 1) it's a special attribute, beginning with a '$' : ignore it.
3915 * 2) it's a server id cookie that we *MAY* want to delete : save
3916 * some pointers on it (last semi-colon, beginning of cookie...)
3917 * 3) it's an application cookie : we *MAY* have to delete a previous
3918 * "special" cookie.
3919 * At the end of loop, if a "special" cookie remains, we may have to
3920 * remove it. If no application cookie persists in the header, we
3921 * *MUST* delete it.
3922 *
3923 * Note: RFC2965 is unclear about the processing of spaces around
3924 * the equal sign in the ATTR=VALUE form. A careful inspection of
3925 * the RFC explicitly allows spaces before it, and not within the
3926 * tokens (attrs or values). An inspection of RFC2109 allows that
3927 * too but section 10.1.3 lets one think that spaces may be allowed
3928 * after the equal sign too, resulting in some (rare) buggy
3929 * implementations trying to do that. So let's do what servers do.
3930 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3931 * allowed quoted strings in values, with any possible character
3932 * after a backslash, including control chars and delimitors, which
3933 * causes parsing to become ambiguous. Browsers also allow spaces
3934 * within values even without quotes.
3935 *
3936 * We have to keep multiple pointers in order to support cookie
3937 * removal at the beginning, middle or end of header without
3938 * corrupting the header. All of these headers are valid :
3939 *
3940 * hdr_beg hdr_end
3941 * | |
3942 * v |
3943 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3944 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3945 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3946 * | | | | | | |
3947 * | | | | | | |
3948 * | | | | | | +--> next
3949 * | | | | | +----> val_end
3950 * | | | | +-----------> val_beg
3951 * | | | +--------------> equal
3952 * | | +----------------> att_end
3953 * | +---------------------> att_beg
3954 * +--------------------------> prev
3955 *
3956 */
3957 hdr_beg = ctx.value.ptr;
3958 hdr_end = hdr_beg + ctx.value.len;
3959 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3960 /* Iterate through all cookies on this line */
3961
3962 /* find att_beg */
3963 att_beg = prev;
3964 if (prev > hdr_beg)
3965 att_beg++;
3966
3967 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3968 att_beg++;
3969
3970 /* find att_end : this is the first character after the last non
3971 * space before the equal. It may be equal to hdr_end.
3972 */
3973 equal = att_end = att_beg;
3974 while (equal < hdr_end) {
3975 if (*equal == '=' || *equal == ',' || *equal == ';')
3976 break;
3977 if (HTTP_IS_SPHT(*equal++))
3978 continue;
3979 att_end = equal;
3980 }
3981
3982 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3983 * is between <att_beg> and <equal>, both may be identical.
3984 */
3985 /* look for end of cookie if there is an equal sign */
3986 if (equal < hdr_end && *equal == '=') {
3987 /* look for the beginning of the value */
3988 val_beg = equal + 1;
3989 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3990 val_beg++;
3991
3992 /* find the end of the value, respecting quotes */
3993 next = http_find_cookie_value_end(val_beg, hdr_end);
3994
3995 /* make val_end point to the first white space or delimitor after the value */
3996 val_end = next;
3997 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3998 val_end--;
3999 }
4000 else
4001 val_beg = val_end = next = equal;
4002
4003 /* We have nothing to do with attributes beginning with
4004 * '$'. However, they will automatically be removed if a
4005 * header before them is removed, since they're supposed
4006 * to be linked together.
4007 */
4008 if (*att_beg == '$')
4009 continue;
4010
4011 /* Ignore cookies with no equal sign */
4012 if (equal == next) {
4013 /* This is not our cookie, so we must preserve it. But if we already
4014 * scheduled another cookie for removal, we cannot remove the
4015 * complete header, but we can remove the previous block itself.
4016 */
4017 preserve_hdr = 1;
4018 if (del_from != NULL) {
4019 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4020 val_end += delta;
4021 next += delta;
4022 hdr_end += delta;
4023 prev = del_from;
4024 del_from = NULL;
4025 }
4026 continue;
4027 }
4028
4029 /* if there are spaces around the equal sign, we need to
4030 * strip them otherwise we'll get trouble for cookie captures,
4031 * or even for rewrites. Since this happens extremely rarely,
4032 * it does not hurt performance.
4033 */
4034 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4035 int stripped_before = 0;
4036 int stripped_after = 0;
4037
4038 if (att_end != equal) {
4039 memmove(att_end, equal, hdr_end - equal);
4040 stripped_before = (att_end - equal);
4041 equal += stripped_before;
4042 val_beg += stripped_before;
4043 }
4044
4045 if (val_beg > equal + 1) {
4046 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4047 stripped_after = (equal + 1) - val_beg;
4048 val_beg += stripped_after;
4049 stripped_before += stripped_after;
4050 }
4051
4052 val_end += stripped_before;
4053 next += stripped_before;
4054 hdr_end += stripped_before;
4055 }
4056 /* now everything is as on the diagram above */
4057
4058 /* First, let's see if we want to capture this cookie. We check
4059 * that we don't already have a client side cookie, because we
4060 * can only capture one. Also as an optimisation, we ignore
4061 * cookies shorter than the declared name.
4062 */
4063 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4064 (val_end - att_beg >= sess->fe->capture_namelen) &&
4065 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4066 int log_len = val_end - att_beg;
4067
4068 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4069 ha_alert("HTTP logging : out of memory.\n");
4070 } else {
4071 if (log_len > sess->fe->capture_len)
4072 log_len = sess->fe->capture_len;
4073 memcpy(txn->cli_cookie, att_beg, log_len);
4074 txn->cli_cookie[log_len] = 0;
4075 }
4076 }
4077
4078 /* Persistence cookies in passive, rewrite or insert mode have the
4079 * following form :
4080 *
4081 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4082 *
4083 * For cookies in prefix mode, the form is :
4084 *
4085 * Cookie: NAME=SRV~VALUE
4086 */
4087 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4088 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4089 struct server *srv = s->be->srv;
4090 char *delim;
4091
4092 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4093 * have the server ID between val_beg and delim, and the original cookie between
4094 * delim+1 and val_end. Otherwise, delim==val_end :
4095 *
4096 * hdr_beg
4097 * |
4098 * v
4099 * NAME=SRV; # in all but prefix modes
4100 * NAME=SRV~OPAQUE ; # in prefix mode
4101 * || || | |+-> next
4102 * || || | +--> val_end
4103 * || || +---------> delim
4104 * || |+------------> val_beg
4105 * || +-------------> att_end = equal
4106 * |+-----------------> att_beg
4107 * +------------------> prev
4108 *
4109 */
4110 if (s->be->ck_opts & PR_CK_PFX) {
4111 for (delim = val_beg; delim < val_end; delim++)
4112 if (*delim == COOKIE_DELIM)
4113 break;
4114 }
4115 else {
4116 char *vbar1;
4117 delim = val_end;
4118 /* Now check if the cookie contains a date field, which would
4119 * appear after a vertical bar ('|') just after the server name
4120 * and before the delimiter.
4121 */
4122 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4123 if (vbar1) {
4124 /* OK, so left of the bar is the server's cookie and
4125 * right is the last seen date. It is a base64 encoded
4126 * 30-bit value representing the UNIX date since the
4127 * epoch in 4-second quantities.
4128 */
4129 int val;
4130 delim = vbar1++;
4131 if (val_end - vbar1 >= 5) {
4132 val = b64tos30(vbar1);
4133 if (val > 0)
4134 txn->cookie_last_date = val << 2;
4135 }
4136 /* look for a second vertical bar */
4137 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4138 if (vbar1 && (val_end - vbar1 > 5)) {
4139 val = b64tos30(vbar1 + 1);
4140 if (val > 0)
4141 txn->cookie_first_date = val << 2;
4142 }
4143 }
4144 }
4145
4146 /* if the cookie has an expiration date and the proxy wants to check
4147 * it, then we do that now. We first check if the cookie is too old,
4148 * then only if it has expired. We detect strict overflow because the
4149 * time resolution here is not great (4 seconds). Cookies with dates
4150 * in the future are ignored if their offset is beyond one day. This
4151 * allows an admin to fix timezone issues without expiring everyone
4152 * and at the same time avoids keeping unwanted side effects for too
4153 * long.
4154 */
4155 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4156 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4157 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4158 txn->flags &= ~TX_CK_MASK;
4159 txn->flags |= TX_CK_OLD;
4160 delim = val_beg; // let's pretend we have not found the cookie
4161 txn->cookie_first_date = 0;
4162 txn->cookie_last_date = 0;
4163 }
4164 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4165 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4166 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4167 txn->flags &= ~TX_CK_MASK;
4168 txn->flags |= TX_CK_EXPIRED;
4169 delim = val_beg; // let's pretend we have not found the cookie
4170 txn->cookie_first_date = 0;
4171 txn->cookie_last_date = 0;
4172 }
4173
4174 /* Here, we'll look for the first running server which supports the cookie.
4175 * This allows to share a same cookie between several servers, for example
4176 * to dedicate backup servers to specific servers only.
4177 * However, to prevent clients from sticking to cookie-less backup server
4178 * when they have incidentely learned an empty cookie, we simply ignore
4179 * empty cookies and mark them as invalid.
4180 * The same behaviour is applied when persistence must be ignored.
4181 */
4182 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4183 srv = NULL;
4184
4185 while (srv) {
4186 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4187 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4188 if ((srv->cur_state != SRV_ST_STOPPED) ||
4189 (s->be->options & PR_O_PERSIST) ||
4190 (s->flags & SF_FORCE_PRST)) {
4191 /* we found the server and we can use it */
4192 txn->flags &= ~TX_CK_MASK;
4193 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4194 s->flags |= SF_DIRECT | SF_ASSIGNED;
4195 s->target = &srv->obj_type;
4196 break;
4197 } else {
4198 /* we found a server, but it's down,
4199 * mark it as such and go on in case
4200 * another one is available.
4201 */
4202 txn->flags &= ~TX_CK_MASK;
4203 txn->flags |= TX_CK_DOWN;
4204 }
4205 }
4206 srv = srv->next;
4207 }
4208
4209 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4210 /* no server matched this cookie or we deliberately skipped it */
4211 txn->flags &= ~TX_CK_MASK;
4212 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4213 txn->flags |= TX_CK_UNUSED;
4214 else
4215 txn->flags |= TX_CK_INVALID;
4216 }
4217
4218 /* depending on the cookie mode, we may have to either :
4219 * - delete the complete cookie if we're in insert+indirect mode, so that
4220 * the server never sees it ;
4221 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004222 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004223 * if we're in cookie prefix mode
4224 */
4225 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4226 int delta; /* negative */
4227
4228 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4229 delta = val_beg - (delim + 1);
4230 val_end += delta;
4231 next += delta;
4232 hdr_end += delta;
4233 del_from = NULL;
4234 preserve_hdr = 1; /* we want to keep this cookie */
4235 }
4236 else if (del_from == NULL &&
4237 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4238 del_from = prev;
4239 }
4240 }
4241 else {
4242 /* This is not our cookie, so we must preserve it. But if we already
4243 * scheduled another cookie for removal, we cannot remove the
4244 * complete header, but we can remove the previous block itself.
4245 */
4246 preserve_hdr = 1;
4247
4248 if (del_from != NULL) {
4249 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4250 if (att_beg >= del_from)
4251 att_beg += delta;
4252 if (att_end >= del_from)
4253 att_end += delta;
4254 val_beg += delta;
4255 val_end += delta;
4256 next += delta;
4257 hdr_end += delta;
4258 prev = del_from;
4259 del_from = NULL;
4260 }
4261 }
4262
4263 /* continue with next cookie on this header line */
4264 att_beg = next;
4265 } /* for each cookie */
4266
4267
4268 /* There are no more cookies on this line.
4269 * We may still have one (or several) marked for deletion at the
4270 * end of the line. We must do this now in two ways :
4271 * - if some cookies must be preserved, we only delete from the
4272 * mark to the end of line ;
4273 * - if nothing needs to be preserved, simply delete the whole header
4274 */
4275 if (del_from) {
4276 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4277 }
4278 if ((hdr_end - hdr_beg) != ctx.value.len) {
4279 if (hdr_beg != hdr_end) {
4280 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4281 htx->data -= (hdr_end - ctx.value.ptr);
4282 }
4283 else
4284 http_remove_header(htx, &ctx);
4285 }
4286 } /* for each "Cookie header */
4287}
4288
4289/*
4290 * Manage server-side cookies. It can impact performance by about 2% so it is
4291 * desirable to call it only when needed. This function is also used when we
4292 * just need to know if there is a cookie (eg: for check-cache).
4293 */
4294static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4295{
4296 struct session *sess = s->sess;
4297 struct http_txn *txn = s->txn;
4298 struct htx *htx;
4299 struct http_hdr_ctx ctx;
4300 struct server *srv;
4301 char *hdr_beg, *hdr_end;
4302 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4303 int is_cookie2;
4304
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004305 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004306
4307 ctx.blk = NULL;
4308 while (1) {
4309 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4310 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4311 break;
4312 is_cookie2 = 1;
4313 }
4314
4315 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4316 * <prev> points to the colon.
4317 */
4318 txn->flags |= TX_SCK_PRESENT;
4319
4320 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4321 * check-cache is enabled) and we are not interested in checking
4322 * them. Warning, the cookie capture is declared in the frontend.
4323 */
4324 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4325 break;
4326
4327 /* OK so now we know we have to process this response cookie.
4328 * The format of the Set-Cookie header is slightly different
4329 * from the format of the Cookie header in that it does not
4330 * support the comma as a cookie delimiter (thus the header
4331 * cannot be folded) because the Expires attribute described in
4332 * the original Netscape's spec may contain an unquoted date
4333 * with a comma inside. We have to live with this because
4334 * many browsers don't support Max-Age and some browsers don't
4335 * support quoted strings. However the Set-Cookie2 header is
4336 * clean.
4337 *
4338 * We have to keep multiple pointers in order to support cookie
4339 * removal at the beginning, middle or end of header without
4340 * corrupting the header (in case of set-cookie2). A special
4341 * pointer, <scav> points to the beginning of the set-cookie-av
4342 * fields after the first semi-colon. The <next> pointer points
4343 * either to the end of line (set-cookie) or next unquoted comma
4344 * (set-cookie2). All of these headers are valid :
4345 *
4346 * hdr_beg hdr_end
4347 * | |
4348 * v |
4349 * NAME1 = VALUE 1 ; Secure; Path="/" |
4350 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4351 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4352 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4353 * | | | | | | | |
4354 * | | | | | | | +-> next
4355 * | | | | | | +------------> scav
4356 * | | | | | +--------------> val_end
4357 * | | | | +--------------------> val_beg
4358 * | | | +----------------------> equal
4359 * | | +------------------------> att_end
4360 * | +----------------------------> att_beg
4361 * +------------------------------> prev
4362 * -------------------------------> hdr_beg
4363 */
4364 hdr_beg = ctx.value.ptr;
4365 hdr_end = hdr_beg + ctx.value.len;
4366 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4367
4368 /* Iterate through all cookies on this line */
4369
4370 /* find att_beg */
4371 att_beg = prev;
4372 if (prev > hdr_beg)
4373 att_beg++;
4374
4375 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4376 att_beg++;
4377
4378 /* find att_end : this is the first character after the last non
4379 * space before the equal. It may be equal to hdr_end.
4380 */
4381 equal = att_end = att_beg;
4382
4383 while (equal < hdr_end) {
4384 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4385 break;
4386 if (HTTP_IS_SPHT(*equal++))
4387 continue;
4388 att_end = equal;
4389 }
4390
4391 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4392 * is between <att_beg> and <equal>, both may be identical.
4393 */
4394
4395 /* look for end of cookie if there is an equal sign */
4396 if (equal < hdr_end && *equal == '=') {
4397 /* look for the beginning of the value */
4398 val_beg = equal + 1;
4399 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4400 val_beg++;
4401
4402 /* find the end of the value, respecting quotes */
4403 next = http_find_cookie_value_end(val_beg, hdr_end);
4404
4405 /* make val_end point to the first white space or delimitor after the value */
4406 val_end = next;
4407 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4408 val_end--;
4409 }
4410 else {
4411 /* <equal> points to next comma, semi-colon or EOL */
4412 val_beg = val_end = next = equal;
4413 }
4414
4415 if (next < hdr_end) {
4416 /* Set-Cookie2 supports multiple cookies, and <next> points to
4417 * a colon or semi-colon before the end. So skip all attr-value
4418 * pairs and look for the next comma. For Set-Cookie, since
4419 * commas are permitted in values, skip to the end.
4420 */
4421 if (is_cookie2)
4422 next = http_find_hdr_value_end(next, hdr_end);
4423 else
4424 next = hdr_end;
4425 }
4426
4427 /* Now everything is as on the diagram above */
4428
4429 /* Ignore cookies with no equal sign */
4430 if (equal == val_end)
4431 continue;
4432
4433 /* If there are spaces around the equal sign, we need to
4434 * strip them otherwise we'll get trouble for cookie captures,
4435 * or even for rewrites. Since this happens extremely rarely,
4436 * it does not hurt performance.
4437 */
4438 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4439 int stripped_before = 0;
4440 int stripped_after = 0;
4441
4442 if (att_end != equal) {
4443 memmove(att_end, equal, hdr_end - equal);
4444 stripped_before = (att_end - equal);
4445 equal += stripped_before;
4446 val_beg += stripped_before;
4447 }
4448
4449 if (val_beg > equal + 1) {
4450 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4451 stripped_after = (equal + 1) - val_beg;
4452 val_beg += stripped_after;
4453 stripped_before += stripped_after;
4454 }
4455
4456 val_end += stripped_before;
4457 next += stripped_before;
4458 hdr_end += stripped_before;
4459
4460 ctx.value.len = hdr_end - hdr_beg;
4461 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4462 htx->data -= (hdr_end - ctx.value.ptr);
4463 }
4464
4465 /* First, let's see if we want to capture this cookie. We check
4466 * that we don't already have a server side cookie, because we
4467 * can only capture one. Also as an optimisation, we ignore
4468 * cookies shorter than the declared name.
4469 */
4470 if (sess->fe->capture_name != NULL &&
4471 txn->srv_cookie == NULL &&
4472 (val_end - att_beg >= sess->fe->capture_namelen) &&
4473 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4474 int log_len = val_end - att_beg;
4475 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4476 ha_alert("HTTP logging : out of memory.\n");
4477 }
4478 else {
4479 if (log_len > sess->fe->capture_len)
4480 log_len = sess->fe->capture_len;
4481 memcpy(txn->srv_cookie, att_beg, log_len);
4482 txn->srv_cookie[log_len] = 0;
4483 }
4484 }
4485
4486 srv = objt_server(s->target);
4487 /* now check if we need to process it for persistence */
4488 if (!(s->flags & SF_IGNORE_PRST) &&
4489 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4490 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4491 /* assume passive cookie by default */
4492 txn->flags &= ~TX_SCK_MASK;
4493 txn->flags |= TX_SCK_FOUND;
4494
4495 /* If the cookie is in insert mode on a known server, we'll delete
4496 * this occurrence because we'll insert another one later.
4497 * We'll delete it too if the "indirect" option is set and we're in
4498 * a direct access.
4499 */
4500 if (s->be->ck_opts & PR_CK_PSV) {
4501 /* The "preserve" flag was set, we don't want to touch the
4502 * server's cookie.
4503 */
4504 }
4505 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4506 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4507 /* this cookie must be deleted */
4508 if (prev == hdr_beg && next == hdr_end) {
4509 /* whole header */
4510 http_remove_header(htx, &ctx);
4511 /* note: while both invalid now, <next> and <hdr_end>
4512 * are still equal, so the for() will stop as expected.
4513 */
4514 } else {
4515 /* just remove the value */
4516 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4517 next = prev;
4518 hdr_end += delta;
4519 }
4520 txn->flags &= ~TX_SCK_MASK;
4521 txn->flags |= TX_SCK_DELETED;
4522 /* and go on with next cookie */
4523 }
4524 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4525 /* replace bytes val_beg->val_end with the cookie name associated
4526 * with this server since we know it.
4527 */
4528 int sliding, delta;
4529
4530 ctx.value = ist2(val_beg, val_end - val_beg);
4531 ctx.lws_before = ctx.lws_after = 0;
4532 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4533 delta = srv->cklen - (val_end - val_beg);
4534 sliding = (ctx.value.ptr - val_beg);
4535 hdr_beg += sliding;
4536 val_beg += sliding;
4537 next += sliding + delta;
4538 hdr_end += sliding + delta;
4539
4540 txn->flags &= ~TX_SCK_MASK;
4541 txn->flags |= TX_SCK_REPLACED;
4542 }
4543 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4544 /* insert the cookie name associated with this server
4545 * before existing cookie, and insert a delimiter between them..
4546 */
4547 int sliding, delta;
4548 ctx.value = ist2(val_beg, 0);
4549 ctx.lws_before = ctx.lws_after = 0;
4550 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4551 delta = srv->cklen + 1;
4552 sliding = (ctx.value.ptr - val_beg);
4553 hdr_beg += sliding;
4554 val_beg += sliding;
4555 next += sliding + delta;
4556 hdr_end += sliding + delta;
4557
4558 val_beg[srv->cklen] = COOKIE_DELIM;
4559 txn->flags &= ~TX_SCK_MASK;
4560 txn->flags |= TX_SCK_REPLACED;
4561 }
4562 }
4563 /* that's done for this cookie, check the next one on the same
4564 * line when next != hdr_end (only if is_cookie2).
4565 */
4566 }
4567 }
4568}
4569
Christopher Faulet25a02f62018-10-24 12:00:25 +02004570/*
4571 * Parses the Cache-Control and Pragma request header fields to determine if
4572 * the request may be served from the cache and/or if it is cacheable. Updates
4573 * s->txn->flags.
4574 */
4575void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4576{
4577 struct http_txn *txn = s->txn;
4578 struct htx *htx;
4579 int32_t pos;
4580 int pragma_found, cc_found, i;
4581
4582 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4583 return; /* nothing more to do here */
4584
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004585 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004586 pragma_found = cc_found = 0;
4587 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4588 struct htx_blk *blk = htx_get_blk(htx, pos);
4589 enum htx_blk_type type = htx_get_blk_type(blk);
4590 struct ist n, v;
4591
4592 if (type == HTX_BLK_EOH)
4593 break;
4594 if (type != HTX_BLK_HDR)
4595 continue;
4596
4597 n = htx_get_blk_name(htx, blk);
4598 v = htx_get_blk_value(htx, blk);
4599
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004600 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004601 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4602 pragma_found = 1;
4603 continue;
4604 }
4605 }
4606
4607 /* Don't use the cache and don't try to store if we found the
4608 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004609 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004610 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4611 txn->flags |= TX_CACHE_IGNORE;
4612 continue;
4613 }
4614
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004615 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004616 continue;
4617
4618 /* OK, right now we know we have a cache-control header */
4619 cc_found = 1;
4620 if (!v.len) /* no info */
4621 continue;
4622
4623 i = 0;
4624 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4625 !isspace((unsigned char)*(v.ptr+i)))
4626 i++;
4627
4628 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4629 * values after max-age, max-stale nor min-fresh, we simply don't
4630 * use the cache when they're specified.
4631 */
4632 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4633 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4634 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4635 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4636 txn->flags |= TX_CACHE_IGNORE;
4637 continue;
4638 }
4639
4640 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4641 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4642 continue;
4643 }
4644 }
4645
4646 /* RFC7234#5.4:
4647 * When the Cache-Control header field is also present and
4648 * understood in a request, Pragma is ignored.
4649 * When the Cache-Control header field is not present in a
4650 * request, caches MUST consider the no-cache request
4651 * pragma-directive as having the same effect as if
4652 * "Cache-Control: no-cache" were present.
4653 */
4654 if (!cc_found && pragma_found)
4655 txn->flags |= TX_CACHE_IGNORE;
4656}
4657
4658/*
4659 * Check if response is cacheable or not. Updates s->txn->flags.
4660 */
4661void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4662{
4663 struct http_txn *txn = s->txn;
4664 struct htx *htx;
4665 int32_t pos;
4666 int i;
4667
4668 if (txn->status < 200) {
4669 /* do not try to cache interim responses! */
4670 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4671 return;
4672 }
4673
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004674 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004675 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4676 struct htx_blk *blk = htx_get_blk(htx, pos);
4677 enum htx_blk_type type = htx_get_blk_type(blk);
4678 struct ist n, v;
4679
4680 if (type == HTX_BLK_EOH)
4681 break;
4682 if (type != HTX_BLK_HDR)
4683 continue;
4684
4685 n = htx_get_blk_name(htx, blk);
4686 v = htx_get_blk_value(htx, blk);
4687
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004688 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004689 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4690 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4691 return;
4692 }
4693 }
4694
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004695 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004696 continue;
4697
4698 /* OK, right now we know we have a cache-control header */
4699 if (!v.len) /* no info */
4700 continue;
4701
4702 i = 0;
4703 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4704 !isspace((unsigned char)*(v.ptr+i)))
4705 i++;
4706
4707 /* we have a complete value between v.ptr and (v.ptr+i) */
4708 if (i < v.len && *(v.ptr + i) == '=') {
4709 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4710 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4711 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4712 continue;
4713 }
4714
4715 /* we have something of the form no-cache="set-cookie" */
4716 if ((v.len >= 21) &&
4717 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4718 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4719 txn->flags &= ~TX_CACHE_COOK;
4720 continue;
4721 }
4722
4723 /* OK, so we know that either p2 points to the end of string or to a comma */
4724 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4725 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4726 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4727 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4728 return;
4729 }
4730
4731 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4732 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4733 continue;
4734 }
4735 }
4736}
4737
Christopher Faulet64159df2018-10-24 21:15:35 +02004738/* send a server's name with an outgoing request over an established connection.
4739 * Note: this function is designed to be called once the request has been
4740 * scheduled for being forwarded. This is the reason why the number of forwarded
4741 * bytes have to be adjusted.
4742 */
4743int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4744{
4745 struct htx *htx;
4746 struct http_hdr_ctx ctx;
4747 struct ist hdr;
4748 uint32_t data;
4749
4750 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004751 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004752 data = htx->data;
4753
4754 ctx.blk = NULL;
4755 while (http_find_header(htx, hdr, &ctx, 1))
4756 http_remove_header(htx, &ctx);
4757 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4758
4759 if (co_data(&s->req)) {
4760 if (data >= htx->data)
4761 c_rew(&s->req, data - htx->data);
4762 else
4763 c_adv(&s->req, htx->data - data);
4764 }
4765 return 0;
4766}
4767
Christopher Faulet377c5a52018-10-24 21:21:30 +02004768/*
4769 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4770 * for the current backend.
4771 *
4772 * It is assumed that the request is either a HEAD, GET, or POST and that the
4773 * uri_auth field is valid.
4774 *
4775 * Returns 1 if stats should be provided, otherwise 0.
4776 */
4777static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4778{
4779 struct uri_auth *uri_auth = backend->uri_auth;
4780 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004781 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004782 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004783
4784 if (!uri_auth)
4785 return 0;
4786
4787 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4788 return 0;
4789
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004790 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004791 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004792 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004793
4794 /* check URI size */
4795 if (uri_auth->uri_len > uri.len)
4796 return 0;
4797
4798 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4799 return 0;
4800
4801 return 1;
4802}
4803
4804/* This function prepares an applet to handle the stats. It can deal with the
4805 * "100-continue" expectation, check that admin rules are met for POST requests,
4806 * and program a response message if something was unexpected. It cannot fail
4807 * and always relies on the stats applet to complete the job. It does not touch
4808 * analysers nor counters, which are left to the caller. It does not touch
4809 * s->target which is supposed to already point to the stats applet. The caller
4810 * is expected to have already assigned an appctx to the stream.
4811 */
4812static int htx_handle_stats(struct stream *s, struct channel *req)
4813{
4814 struct stats_admin_rule *stats_admin_rule;
4815 struct stream_interface *si = &s->si[1];
4816 struct session *sess = s->sess;
4817 struct http_txn *txn = s->txn;
4818 struct http_msg *msg = &txn->req;
4819 struct uri_auth *uri_auth = s->be->uri_auth;
4820 const char *h, *lookup, *end;
4821 struct appctx *appctx;
4822 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004823 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004824
4825 appctx = si_appctx(si);
4826 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4827 appctx->st1 = appctx->st2 = 0;
4828 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4829 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4830 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4831 appctx->ctx.stats.flags |= STAT_CHUNKED;
4832
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004833 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004834 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004835 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4836 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004837
4838 for (h = lookup; h <= end - 3; h++) {
4839 if (memcmp(h, ";up", 3) == 0) {
4840 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4841 break;
4842 }
4843 }
4844
4845 if (uri_auth->refresh) {
4846 for (h = lookup; h <= end - 10; h++) {
4847 if (memcmp(h, ";norefresh", 10) == 0) {
4848 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4849 break;
4850 }
4851 }
4852 }
4853
4854 for (h = lookup; h <= end - 4; h++) {
4855 if (memcmp(h, ";csv", 4) == 0) {
4856 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4857 break;
4858 }
4859 }
4860
4861 for (h = lookup; h <= end - 6; h++) {
4862 if (memcmp(h, ";typed", 6) == 0) {
4863 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4864 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4865 break;
4866 }
4867 }
4868
4869 for (h = lookup; h <= end - 8; h++) {
4870 if (memcmp(h, ";st=", 4) == 0) {
4871 int i;
4872 h += 4;
4873 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4874 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4875 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4876 appctx->ctx.stats.st_code = i;
4877 break;
4878 }
4879 }
4880 break;
4881 }
4882 }
4883
4884 appctx->ctx.stats.scope_str = 0;
4885 appctx->ctx.stats.scope_len = 0;
4886 for (h = lookup; h <= end - 8; h++) {
4887 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4888 int itx = 0;
4889 const char *h2;
4890 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4891 const char *err;
4892
4893 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4894 h2 = h;
4895 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4896 while (h <= end) {
4897 if (*h == ';' || *h == '&' || *h == ' ')
4898 break;
4899 itx++;
4900 h++;
4901 }
4902
4903 if (itx > STAT_SCOPE_TXT_MAXLEN)
4904 itx = STAT_SCOPE_TXT_MAXLEN;
4905 appctx->ctx.stats.scope_len = itx;
4906
4907 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4908 memcpy(scope_txt, h2, itx);
4909 scope_txt[itx] = '\0';
4910 err = invalid_char(scope_txt);
4911 if (err) {
4912 /* bad char in search text => clear scope */
4913 appctx->ctx.stats.scope_str = 0;
4914 appctx->ctx.stats.scope_len = 0;
4915 }
4916 break;
4917 }
4918 }
4919
4920 /* now check whether we have some admin rules for this request */
4921 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4922 int ret = 1;
4923
4924 if (stats_admin_rule->cond) {
4925 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4926 ret = acl_pass(ret);
4927 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4928 ret = !ret;
4929 }
4930
4931 if (ret) {
4932 /* no rule, or the rule matches */
4933 appctx->ctx.stats.flags |= STAT_ADMIN;
4934 break;
4935 }
4936 }
4937
4938 /* Was the status page requested with a POST ? */
4939 if (unlikely(txn->meth == HTTP_METH_POST)) {
4940 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4941 /* we'll need the request body, possibly after sending 100-continue */
4942 if (msg->msg_state < HTTP_MSG_DATA)
4943 req->analysers |= AN_REQ_HTTP_BODY;
4944 appctx->st0 = STAT_HTTP_POST;
4945 }
4946 else {
4947 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4948 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4949 appctx->st0 = STAT_HTTP_LAST;
4950 }
4951 }
4952 else {
4953 /* So it was another method (GET/HEAD) */
4954 appctx->st0 = STAT_HTTP_HEAD;
4955 }
4956
4957 s->task->nice = -32; /* small boost for HTTP statistics */
4958 return 1;
4959}
4960
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004961void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4962{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004963 struct channel *req = &s->req;
4964 struct channel *res = &s->res;
4965 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004966 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004967 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004968 struct ist path, location;
4969 unsigned int flags;
4970 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004971
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004972 /*
4973 * Create the location
4974 */
4975 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004976
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004977 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004978 /* special prefix "/" means don't change URL */
4979 srv = __objt_server(s->target);
4980 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4981 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4982 return;
4983 }
4984
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004985 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004986 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004987 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004988 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004989 if (!path.ptr)
4990 return;
4991
4992 if (!chunk_memcat(&trash, path.ptr, path.len))
4993 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004994 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004996 /*
4997 * Create the 302 respone
4998 */
4999 htx = htx_from_buf(&res->buf);
5000 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5001 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5002 ist("HTTP/1.1"), ist("302"), ist("Found"));
5003 if (!sl)
5004 goto fail;
5005 sl->info.res.status = 302;
5006 s->txn->status = 302;
5007
5008 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5009 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5010 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5011 !htx_add_header(htx, ist("Location"), location))
5012 goto fail;
5013
5014 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5015 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005016
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005017 /*
5018 * Send the message
5019 */
5020 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005021 c_adv(res, data);
5022 res->total += data;
5023
5024 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005025 si_shutr(si);
5026 si_shutw(si);
5027 si->err_type = SI_ET_NONE;
5028 si->state = SI_ST_CLO;
5029
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005030 channel_auto_read(req);
5031 channel_abort(req);
5032 channel_auto_close(req);
5033 channel_erase(req);
5034 channel_auto_read(res);
5035 channel_auto_close(res);
5036
5037 if (!(s->flags & SF_ERR_MASK))
5038 s->flags |= SF_ERR_LOCAL;
5039 if (!(s->flags & SF_FINST_MASK))
5040 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005041
5042 /* FIXME: we should increase a counter of redirects per server and per backend. */
5043 srv_inc_sess_ctr(srv);
5044 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005045 return;
5046
5047 fail:
5048 /* If an error occurred, remove the incomplete HTTP response from the
5049 * buffer */
5050 channel_truncate(res);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005051}
5052
Christopher Fauletf2824e62018-10-01 12:12:37 +02005053/* This function terminates the request because it was completly analyzed or
5054 * because an error was triggered during the body forwarding.
5055 */
5056static void htx_end_request(struct stream *s)
5057{
5058 struct channel *chn = &s->req;
5059 struct http_txn *txn = s->txn;
5060
5061 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5062 now_ms, __FUNCTION__, s,
5063 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5064 s->req.analysers, s->res.analysers);
5065
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005066 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5067 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005068 channel_abort(chn);
5069 channel_truncate(chn);
5070 goto end;
5071 }
5072
5073 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5074 return;
5075
5076 if (txn->req.msg_state == HTTP_MSG_DONE) {
5077 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5078 /* The server has not finished to respond, so we
5079 * don't want to move in order not to upset it.
5080 */
5081 return;
5082 }
5083
5084 /* No need to read anymore, the request was completely parsed.
5085 * We can shut the read side unless we want to abort_on_close,
5086 * or we have a POST request. The issue with POST requests is
5087 * that some browsers still send a CRLF after the request, and
5088 * this CRLF must be read so that it does not remain in the kernel
5089 * buffers, otherwise a close could cause an RST on some systems
5090 * (eg: Linux).
5091 */
5092 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5093 txn->meth != HTTP_METH_POST)
5094 channel_dont_read(chn);
5095
5096 /* if the server closes the connection, we want to immediately react
5097 * and close the socket to save packets and syscalls.
5098 */
5099 s->si[1].flags |= SI_FL_NOHALF;
5100
5101 /* In any case we've finished parsing the request so we must
5102 * disable Nagle when sending data because 1) we're not going
5103 * to shut this side, and 2) the server is waiting for us to
5104 * send pending data.
5105 */
5106 chn->flags |= CF_NEVER_WAIT;
5107
5108 /* When we get here, it means that both the request and the
5109 * response have finished receiving. Depending on the connection
5110 * mode, we'll have to wait for the last bytes to leave in either
5111 * direction, and sometimes for a close to be effective.
5112 */
5113 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5114 /* Tunnel mode will not have any analyser so it needs to
5115 * poll for reads.
5116 */
5117 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005118 if (b_data(&chn->buf))
5119 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005120 txn->req.msg_state = HTTP_MSG_TUNNEL;
5121 }
5122 else {
5123 /* we're not expecting any new data to come for this
5124 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005125 *
5126 * However, there is an exception if the response
5127 * length is undefined. In this case, we need to wait
5128 * the close from the server. The response will be
5129 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005130 */
5131 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5132 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005133 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005134
5135 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5136 channel_shutr_now(chn);
5137 channel_shutw_now(chn);
5138 }
5139 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005140 goto check_channel_flags;
5141 }
5142
5143 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5144 http_msg_closing:
5145 /* nothing else to forward, just waiting for the output buffer
5146 * to be empty and for the shutw_now to take effect.
5147 */
5148 if (channel_is_empty(chn)) {
5149 txn->req.msg_state = HTTP_MSG_CLOSED;
5150 goto http_msg_closed;
5151 }
5152 else if (chn->flags & CF_SHUTW) {
5153 txn->req.err_state = txn->req.msg_state;
5154 txn->req.msg_state = HTTP_MSG_ERROR;
5155 goto end;
5156 }
5157 return;
5158 }
5159
5160 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5161 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005162 /* if we don't know whether the server will close, we need to hard close */
5163 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5164 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005165 /* see above in MSG_DONE why we only do this in these states */
5166 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5167 channel_dont_read(chn);
5168 goto end;
5169 }
5170
5171 check_channel_flags:
5172 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5173 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5174 /* if we've just closed an output, let's switch */
5175 txn->req.msg_state = HTTP_MSG_CLOSING;
5176 goto http_msg_closing;
5177 }
5178
5179 end:
5180 chn->analysers &= AN_REQ_FLT_END;
5181 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5182 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5183 channel_auto_close(chn);
5184 channel_auto_read(chn);
5185}
5186
5187
5188/* This function terminates the response because it was completly analyzed or
5189 * because an error was triggered during the body forwarding.
5190 */
5191static void htx_end_response(struct stream *s)
5192{
5193 struct channel *chn = &s->res;
5194 struct http_txn *txn = s->txn;
5195
5196 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5197 now_ms, __FUNCTION__, s,
5198 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5199 s->req.analysers, s->res.analysers);
5200
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005201 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5202 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf3d48052018-12-04 16:23:54 +01005203 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005204 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005205 goto end;
5206 }
5207
5208 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5209 return;
5210
5211 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5212 /* In theory, we don't need to read anymore, but we must
5213 * still monitor the server connection for a possible close
5214 * while the request is being uploaded, so we don't disable
5215 * reading.
5216 */
5217 /* channel_dont_read(chn); */
5218
5219 if (txn->req.msg_state < HTTP_MSG_DONE) {
5220 /* The client seems to still be sending data, probably
5221 * because we got an error response during an upload.
5222 * We have the choice of either breaking the connection
5223 * or letting it pass through. Let's do the later.
5224 */
5225 return;
5226 }
5227
5228 /* When we get here, it means that both the request and the
5229 * response have finished receiving. Depending on the connection
5230 * mode, we'll have to wait for the last bytes to leave in either
5231 * direction, and sometimes for a close to be effective.
5232 */
5233 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5234 channel_auto_read(chn);
5235 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005236 if (b_data(&chn->buf))
5237 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005238 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5239 }
5240 else {
5241 /* we're not expecting any new data to come for this
5242 * transaction, so we can close it.
5243 */
5244 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5245 channel_shutr_now(chn);
5246 channel_shutw_now(chn);
5247 }
5248 }
5249 goto check_channel_flags;
5250 }
5251
5252 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5253 http_msg_closing:
5254 /* nothing else to forward, just waiting for the output buffer
5255 * to be empty and for the shutw_now to take effect.
5256 */
5257 if (channel_is_empty(chn)) {
5258 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5259 goto http_msg_closed;
5260 }
5261 else if (chn->flags & CF_SHUTW) {
5262 txn->rsp.err_state = txn->rsp.msg_state;
5263 txn->rsp.msg_state = HTTP_MSG_ERROR;
5264 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5265 if (objt_server(s->target))
5266 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5267 goto end;
5268 }
5269 return;
5270 }
5271
5272 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5273 http_msg_closed:
5274 /* drop any pending data */
Christopher Fauletf3d48052018-12-04 16:23:54 +01005275 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005276 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005277 goto end;
5278 }
5279
5280 check_channel_flags:
5281 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5282 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5283 /* if we've just closed an output, let's switch */
5284 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5285 goto http_msg_closing;
5286 }
5287
5288 end:
5289 chn->analysers &= AN_RES_FLT_END;
5290 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5291 chn->analysers |= AN_RES_FLT_XFER_DATA;
5292 channel_auto_close(chn);
5293 channel_auto_read(chn);
5294}
5295
Christopher Faulet0f226952018-10-22 09:29:56 +02005296void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5297 int finst, const struct buffer *msg)
5298{
5299 channel_auto_read(si_oc(si));
5300 channel_abort(si_oc(si));
5301 channel_auto_close(si_oc(si));
5302 channel_erase(si_oc(si));
5303 channel_auto_close(si_ic(si));
5304 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005305
5306 /* <msg> is an HTX structure. So we copy it in the response's
5307 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005308 if (msg) {
5309 struct channel *chn = si_ic(si);
5310 struct htx *htx;
5311
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005312 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005313 chn->buf.data = msg->data;
5314 memcpy(chn->buf.area, msg->area, msg->data);
5315 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005316 c_adv(chn, htx->data);
5317 chn->total += htx->data;
5318 }
5319 if (!(s->flags & SF_ERR_MASK))
5320 s->flags |= err;
5321 if (!(s->flags & SF_FINST_MASK))
5322 s->flags |= finst;
5323}
5324
5325void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5326{
5327 channel_auto_read(&s->req);
5328 channel_abort(&s->req);
5329 channel_auto_close(&s->req);
5330 channel_erase(&s->req);
5331 channel_truncate(&s->res);
5332
5333 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005334
5335 /* <msg> is an HTX structure. So we copy it in the response's
5336 * channel */
5337 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005338 if (msg) {
5339 struct channel *chn = &s->res;
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
5350 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5351 channel_auto_read(&s->res);
5352 channel_auto_close(&s->res);
5353 channel_shutr_now(&s->res);
5354}
5355
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005356struct buffer *htx_error_message(struct stream *s)
5357{
5358 const int msgnum = http_get_status_idx(s->txn->status);
5359
5360 if (s->be->errmsg[msgnum].area)
5361 return &s->be->errmsg[msgnum];
5362 else if (strm_fe(s)->errmsg[msgnum].area)
5363 return &strm_fe(s)->errmsg[msgnum];
5364 else
5365 return &htx_err_chunks[msgnum];
5366}
5367
5368
Christopher Faulet23a3c792018-11-28 10:01:23 +01005369/* Send a 100-Continue response to the client. It returns 0 on success and -1
5370 * on error. The response channel is updated accordingly.
5371 */
5372static int htx_reply_100_continue(struct stream *s)
5373{
5374 struct channel *res = &s->res;
5375 struct htx *htx = htx_from_buf(&res->buf);
5376 struct htx_sl *sl;
5377 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5378 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5379 size_t data;
5380
5381 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5382 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5383 if (!sl)
5384 goto fail;
5385 sl->info.res.status = 100;
5386
5387 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5388 goto fail;
5389
5390 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005391 c_adv(res, data);
5392 res->total += data;
5393 return 0;
5394
5395 fail:
5396 /* If an error occurred, remove the incomplete HTTP response from the
5397 * buffer */
5398 channel_truncate(res);
5399 return -1;
5400}
5401
Christopher Faulet12c51e22018-11-28 15:59:42 +01005402
5403/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5404 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5405 * error. The response channel is updated accordingly.
5406 */
5407static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5408{
5409 struct channel *res = &s->res;
5410 struct htx *htx = htx_from_buf(&res->buf);
5411 struct htx_sl *sl;
5412 struct ist code, body;
5413 int status;
5414 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5415 size_t data;
5416
5417 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5418 status = 401;
5419 code = ist("401");
5420 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5421 "You need a valid user and password to access this content.\n"
5422 "</body></html>\n");
5423 }
5424 else {
5425 status = 407;
5426 code = ist("407");
5427 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5428 "You need a valid user and password to access this content.\n"
5429 "</body></html>\n");
5430 }
5431
5432 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5433 ist("HTTP/1.1"), code, ist("Unauthorized"));
5434 if (!sl)
5435 goto fail;
5436 sl->info.res.status = status;
5437 s->txn->status = status;
5438
5439 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5440 goto fail;
5441
5442 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5443 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5444 !htx_add_header(htx, ist("Content-Type"), ist("text/html")) ||
5445 !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
5446 goto fail;
5447
5448 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5449 goto fail;
5450
5451 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005452 c_adv(res, data);
5453 res->total += data;
5454
5455 channel_auto_read(&s->req);
5456 channel_abort(&s->req);
5457 channel_auto_close(&s->req);
5458 channel_erase(&s->req);
5459
5460 res->wex = tick_add_ifset(now_ms, res->wto);
5461 channel_auto_read(res);
5462 channel_auto_close(res);
5463 channel_shutr_now(res);
5464 return 0;
5465
5466 fail:
5467 /* If an error occurred, remove the incomplete HTTP response from the
5468 * buffer */
5469 channel_truncate(res);
5470 return -1;
5471}
5472
Christopher Faulet0f226952018-10-22 09:29:56 +02005473/*
5474 * Capture headers from message <htx> according to header list <cap_hdr>, and
5475 * fill the <cap> pointers appropriately.
5476 */
5477static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5478{
5479 struct cap_hdr *h;
5480 int32_t pos;
5481
5482 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5483 struct htx_blk *blk = htx_get_blk(htx, pos);
5484 enum htx_blk_type type = htx_get_blk_type(blk);
5485 struct ist n, v;
5486
5487 if (type == HTX_BLK_EOH)
5488 break;
5489 if (type != HTX_BLK_HDR)
5490 continue;
5491
5492 n = htx_get_blk_name(htx, blk);
5493
5494 for (h = cap_hdr; h; h = h->next) {
5495 if (h->namelen && (h->namelen == n.len) &&
5496 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5497 if (cap[h->index] == NULL)
5498 cap[h->index] =
5499 pool_alloc(h->pool);
5500
5501 if (cap[h->index] == NULL) {
5502 ha_alert("HTTP capture : out of memory.\n");
5503 break;
5504 }
5505
5506 v = htx_get_blk_value(htx, blk);
5507 if (v.len > h->len)
5508 v.len = h->len;
5509
5510 memcpy(cap[h->index], v.ptr, v.len);
5511 cap[h->index][v.len]=0;
5512 }
5513 }
5514 }
5515}
5516
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005517/* Delete a value in a header between delimiters <from> and <next>. The header
5518 * itself is delimited by <start> and <end> pointers. The number of characters
5519 * displaced is returned, and the pointer to the first delimiter is updated if
5520 * required. The function tries as much as possible to respect the following
5521 * principles :
5522 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5523 * in which case <next> is simply removed
5524 * - set exactly one space character after the new first delimiter, unless there
5525 * are not enough characters in the block being moved to do so.
5526 * - remove unneeded spaces before the previous delimiter and after the new
5527 * one.
5528 *
5529 * It is the caller's responsibility to ensure that :
5530 * - <from> points to a valid delimiter or <start> ;
5531 * - <next> points to a valid delimiter or <end> ;
5532 * - there are non-space chars before <from>.
5533 */
5534static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5535{
5536 char *prev = *from;
5537
5538 if (prev == start) {
5539 /* We're removing the first value. eat the semicolon, if <next>
5540 * is lower than <end> */
5541 if (next < end)
5542 next++;
5543
5544 while (next < end && HTTP_IS_SPHT(*next))
5545 next++;
5546 }
5547 else {
5548 /* Remove useless spaces before the old delimiter. */
5549 while (HTTP_IS_SPHT(*(prev-1)))
5550 prev--;
5551 *from = prev;
5552
5553 /* copy the delimiter and if possible a space if we're
5554 * not at the end of the line.
5555 */
5556 if (next < end) {
5557 *prev++ = *next++;
5558 if (prev + 1 < next)
5559 *prev++ = ' ';
5560 while (next < end && HTTP_IS_SPHT(*next))
5561 next++;
5562 }
5563 }
5564 memmove(prev, next, end - next);
5565 return (prev - next);
5566}
5567
Christopher Faulet0f226952018-10-22 09:29:56 +02005568
5569/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005570 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005571 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005572static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005573{
5574 struct ist dst = ist2(str, 0);
5575
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005576 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005577 goto end;
5578 if (dst.len + 1 > len)
5579 goto end;
5580 dst.ptr[dst.len++] = ' ';
5581
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005582 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005583 goto end;
5584 if (dst.len + 1 > len)
5585 goto end;
5586 dst.ptr[dst.len++] = ' ';
5587
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005588 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005589 end:
5590 return dst.len;
5591}
5592
Christopher Fauletf0523542018-10-24 11:06:58 +02005593/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005594 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005595 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005596static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005597{
5598 struct ist dst = ist2(str, 0);
5599
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005600 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005601 goto end;
5602 if (dst.len + 1 > len)
5603 goto end;
5604 dst.ptr[dst.len++] = ' ';
5605
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005606 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005607 goto end;
5608 if (dst.len + 1 > len)
5609 goto end;
5610 dst.ptr[dst.len++] = ' ';
5611
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005612 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005613 end:
5614 return dst.len;
5615}
5616
5617
Christopher Faulet0f226952018-10-22 09:29:56 +02005618/*
5619 * Print a debug line with a start line.
5620 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005621static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005622{
5623 struct session *sess = strm_sess(s);
5624 int max;
5625
5626 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5627 dir,
5628 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5629 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5630
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005631 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005632 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005634 trash.area[trash.data++] = ' ';
5635
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005636 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005637 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 trash.area[trash.data++] = ' ';
5640
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005641 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005642 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 trash.area[trash.data++] = '\n';
5645
5646 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5647}
5648
5649/*
5650 * Print a debug line with a header.
5651 */
5652static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5653{
5654 struct session *sess = strm_sess(s);
5655 int max;
5656
5657 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5658 dir,
5659 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5660 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5661
5662 max = n.len;
5663 UBOUND(max, trash.size - trash.data - 3);
5664 chunk_memcat(&trash, n.ptr, max);
5665 trash.area[trash.data++] = ':';
5666 trash.area[trash.data++] = ' ';
5667
5668 max = v.len;
5669 UBOUND(max, trash.size - trash.data - 1);
5670 chunk_memcat(&trash, v.ptr, max);
5671 trash.area[trash.data++] = '\n';
5672
5673 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5674}
5675
5676
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005677__attribute__((constructor))
5678static void __htx_protocol_init(void)
5679{
5680}
5681
5682
5683/*
5684 * Local variables:
5685 * c-indent-level: 8
5686 * c-basic-offset: 8
5687 * End:
5688 */