blob: c613e72e2c8e782c1690cb51441de35decf416a4 [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 */
228#ifdef TCP_QUICKACK
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 */
235 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
236 }
237#endif
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;
954#ifdef TCP_QUICKACK
955 /* 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) &&
961 cli_conn && conn_ctrl_ready(cli_conn) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200962 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200963 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
964#endif
965
966 /*************************************************************
967 * OK, that's finished for the headers. We have done what we *
968 * could. Let's switch to the DATA state. *
969 ************************************************************/
970 req->analyse_exp = TICK_ETERNITY;
971 req->analysers &= ~an_bit;
972
973 s->logs.tv_request = now;
974 /* OK let's go on with the BODY now */
975 return 1;
976
977 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978 txn->req.err_state = txn->req.msg_state;
979 txn->req.msg_state = HTTP_MSG_ERROR;
980 txn->status = 400;
981 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100982 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200983
984 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
985 if (sess->listener->counters)
986 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
987
988 if (!(s->flags & SF_ERR_MASK))
989 s->flags |= SF_ERR_PRXCOND;
990 if (!(s->flags & SF_FINST_MASK))
991 s->flags |= SF_FINST_R;
992 return 0;
993}
994
995/* This function is an analyser which processes the HTTP tarpit. It always
996 * returns zero, at the beginning because it prevents any other processing
997 * from occurring, and at the end because it terminates the request.
998 */
999int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1000{
1001 struct http_txn *txn = s->txn;
1002
1003 /* This connection is being tarpitted. The CLIENT side has
1004 * already set the connect expiration date to the right
1005 * timeout. We just have to check that the client is still
1006 * there and that the timeout has not expired.
1007 */
1008 channel_dont_connect(req);
1009 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1010 !tick_is_expired(req->analyse_exp, now_ms))
1011 return 0;
1012
1013 /* We will set the queue timer to the time spent, just for
1014 * logging purposes. We fake a 500 server error, so that the
1015 * attacker will not suspect his connection has been tarpitted.
1016 * It will not cause trouble to the logs because we can exclude
1017 * the tarpitted connections by filtering on the 'PT' status flags.
1018 */
1019 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1020
1021 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001022 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001023
1024 req->analysers &= AN_REQ_FLT_END;
1025 req->analyse_exp = TICK_ETERNITY;
1026
1027 if (!(s->flags & SF_ERR_MASK))
1028 s->flags |= SF_ERR_PRXCOND;
1029 if (!(s->flags & SF_FINST_MASK))
1030 s->flags |= SF_FINST_T;
1031 return 0;
1032}
1033
1034/* This function is an analyser which waits for the HTTP request body. It waits
1035 * for either the buffer to be full, or the full advertised contents to have
1036 * reached the buffer. It must only be called after the standard HTTP request
1037 * processing has occurred, because it expects the request to be parsed and will
1038 * look for the Expect header. It may send a 100-Continue interim response. It
1039 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1040 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1041 * needs to read more data, or 1 once it has completed its analysis.
1042 */
1043int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1044{
1045 struct session *sess = s->sess;
1046 struct http_txn *txn = s->txn;
1047 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001048 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001049
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001050
1051 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1052 now_ms, __FUNCTION__,
1053 s,
1054 req,
1055 req->rex, req->wex,
1056 req->flags,
1057 ci_data(req),
1058 req->analysers);
1059
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001060 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001061
1062 if (msg->msg_state < HTTP_MSG_BODY)
1063 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001064
Christopher Faulete0768eb2018-10-03 16:38:02 +02001065 /* We have to parse the HTTP request body to find any required data.
1066 * "balance url_param check_post" should have been the only way to get
1067 * into this. We were brought here after HTTP header analysis, so all
1068 * related structures are ready.
1069 */
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 if (msg->msg_state < HTTP_MSG_DATA) {
1072 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1073 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001075 if (msg->flags & HTTP_MSGF_VER_11) {
1076 struct ist hdr = { .ptr = "Expect", .len = 6 };
1077 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 ctx.blk = NULL;
1080 /* Expect is allowed in 1.1, look for it */
1081 if (http_find_header(htx, hdr, &ctx, 0) &&
1082 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001083 if (htx_reply_100_continue(s) == -1)
1084 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 http_remove_header(htx, &ctx);
1086 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001088 }
1089
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001090 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001091
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001092 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1093 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001094 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1096 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001097 goto http_end;
1098
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001099 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001100 if (htx->flags & HTX_FL_PARSING_ERROR)
1101 goto return_bad_req;
1102
Christopher Faulete0768eb2018-10-03 16:38:02 +02001103 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1104 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001105 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001106
1107 if (!(s->flags & SF_ERR_MASK))
1108 s->flags |= SF_ERR_CLITO;
1109 if (!(s->flags & SF_FINST_MASK))
1110 s->flags |= SF_FINST_D;
1111 goto return_err_msg;
1112 }
1113
1114 /* we get here if we need to wait for more data */
1115 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1116 /* Not enough data. We'll re-use the http-request
1117 * timeout here. Ideally, we should set the timeout
1118 * relative to the accept() date. We just set the
1119 * request timeout once at the beginning of the
1120 * request.
1121 */
1122 channel_dont_connect(req);
1123 if (!tick_isset(req->analyse_exp))
1124 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1125 return 0;
1126 }
1127
1128 http_end:
1129 /* The situation will not evolve, so let's give up on the analysis. */
1130 s->logs.tv_request = now; /* update the request timer to reflect full request */
1131 req->analysers &= ~an_bit;
1132 req->analyse_exp = TICK_ETERNITY;
1133 return 1;
1134
1135 return_bad_req: /* let's centralize all bad requests */
1136 txn->req.err_state = txn->req.msg_state;
1137 txn->req.msg_state = HTTP_MSG_ERROR;
1138 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001139 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001140
1141 if (!(s->flags & SF_ERR_MASK))
1142 s->flags |= SF_ERR_PRXCOND;
1143 if (!(s->flags & SF_FINST_MASK))
1144 s->flags |= SF_FINST_R;
1145
1146 return_err_msg:
1147 req->analysers &= AN_REQ_FLT_END;
1148 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1149 if (sess->listener->counters)
1150 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1151 return 0;
1152}
1153
1154/* This function is an analyser which forwards request body (including chunk
1155 * sizes if any). It is called as soon as we must forward, even if we forward
1156 * zero byte. The only situation where it must not be called is when we're in
1157 * tunnel mode and we want to forward till the close. It's used both to forward
1158 * remaining data and to resync after end of body. It expects the msg_state to
1159 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1160 * read more data, or 1 once we can go on with next request or end the stream.
1161 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1162 * bytes of pending data + the headers if not already done.
1163 */
1164int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1165{
1166 struct session *sess = s->sess;
1167 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001168 struct http_msg *msg = &txn->req;
1169 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001170 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001171
1172 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1173 now_ms, __FUNCTION__,
1174 s,
1175 req,
1176 req->rex, req->wex,
1177 req->flags,
1178 ci_data(req),
1179 req->analysers);
1180
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001181 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001182
1183 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1184 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1185 /* Output closed while we were sending data. We must abort and
1186 * wake the other side up.
1187 */
1188 msg->err_state = msg->msg_state;
1189 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001190 htx_end_request(s);
1191 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001192 return 1;
1193 }
1194
1195 /* Note that we don't have to send 100-continue back because we don't
1196 * need the data to complete our job, and it's up to the server to
1197 * decide whether to return 100, 417 or anything else in return of
1198 * an "Expect: 100-continue" header.
1199 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001200 if (msg->msg_state == HTTP_MSG_BODY)
1201 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001202
1203 /* Some post-connect processing might want us to refrain from starting to
1204 * forward data. Currently, the only reason for this is "balance url_param"
1205 * whichs need to parse/process the request after we've enabled forwarding.
1206 */
1207 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1208 if (!(s->res.flags & CF_READ_ATTACHED)) {
1209 channel_auto_connect(req);
1210 req->flags |= CF_WAKE_CONNECT;
1211 channel_dont_close(req); /* don't fail on early shutr */
1212 goto waiting;
1213 }
1214 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1215 }
1216
1217 /* in most states, we should abort in case of early close */
1218 channel_auto_close(req);
1219
1220 if (req->to_forward) {
1221 /* We can't process the buffer's contents yet */
1222 req->flags |= CF_WAKE_WRITE;
1223 goto missing_data_or_waiting;
1224 }
1225
Christopher Faulet9768c262018-10-22 09:34:31 +02001226 if (msg->msg_state >= HTTP_MSG_DONE)
1227 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 /* Forward input data. We get it by removing all outgoing data not
1229 * forwarded yet from HTX data size. If there are some data filters, we
1230 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001231 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001232 if (HAS_REQ_DATA_FILTERS(s)) {
1233 ret = flt_http_payload(s, msg, htx->data);
1234 if (ret < 0)
1235 goto return_bad_req;
1236 c_adv(req, ret);
1237 if (htx->data != co_data(req) || htx->extra)
1238 goto missing_data_or_waiting;
1239 }
1240 else {
1241 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001242
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001243 /* To let the function channel_forward work as expected we must update
1244 * the channel's buffer to pretend there is no more input data. The
1245 * right length is then restored. We must do that, because when an HTX
1246 * message is stored into a buffer, it appears as full.
1247 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001248 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1249 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001250 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001251
Christopher Faulet9768c262018-10-22 09:34:31 +02001252 /* Check if the end-of-message is reached and if so, switch the message
1253 * in HTTP_MSG_DONE state.
1254 */
1255 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1256 goto missing_data_or_waiting;
1257
1258 msg->msg_state = HTTP_MSG_DONE;
1259
1260 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001261 /* other states, DONE...TUNNEL */
1262 /* we don't want to forward closes on DONE except in tunnel mode. */
1263 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1264 channel_dont_close(req);
1265
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001266 if (HAS_REQ_DATA_FILTERS(s)) {
1267 ret = flt_http_end(s, msg);
1268 if (ret <= 0) {
1269 if (!ret)
1270 goto missing_data_or_waiting;
1271 goto return_bad_req;
1272 }
1273 }
1274
Christopher Fauletf2824e62018-10-01 12:12:37 +02001275 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001277 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1279 if (req->flags & CF_SHUTW) {
1280 /* request errors are most likely due to the
1281 * server aborting the transfer. */
1282 goto aborted_xfer;
1283 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001284 goto return_bad_req;
1285 }
1286 return 1;
1287 }
1288
1289 /* If "option abortonclose" is set on the backend, we want to monitor
1290 * the client's connection and forward any shutdown notification to the
1291 * server, which will decide whether to close or to go on processing the
1292 * request. We only do that in tunnel mode, and not in other modes since
1293 * it can be abused to exhaust source ports. */
1294 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1295 channel_auto_read(req);
1296 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1297 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1298 s->si[1].flags |= SI_FL_NOLINGER;
1299 channel_auto_close(req);
1300 }
1301 else if (s->txn->meth == HTTP_METH_POST) {
1302 /* POST requests may require to read extra CRLF sent by broken
1303 * browsers and which could cause an RST to be sent upon close
1304 * on some systems (eg: Linux). */
1305 channel_auto_read(req);
1306 }
1307 return 0;
1308
1309 missing_data_or_waiting:
1310 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001311 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001312 if (!(s->flags & SF_ERR_MASK))
1313 s->flags |= SF_ERR_CLICL;
1314 if (!(s->flags & SF_FINST_MASK)) {
1315 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1316 s->flags |= SF_FINST_H;
1317 else
1318 s->flags |= SF_FINST_D;
1319 }
1320
1321 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1322 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1323 if (objt_server(s->target))
1324 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1325
1326 goto return_bad_req_stats_ok;
1327 }
1328
1329 waiting:
1330 /* waiting for the last bits to leave the buffer */
1331 if (req->flags & CF_SHUTW)
1332 goto aborted_xfer;
1333
Christopher Faulet47365272018-10-31 17:40:50 +01001334 if (htx->flags & HTX_FL_PARSING_ERROR)
1335 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001336
Christopher Faulete0768eb2018-10-03 16:38:02 +02001337 /* When TE: chunked is used, we need to get there again to parse remaining
1338 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1339 * And when content-length is used, we never want to let the possible
1340 * shutdown be forwarded to the other side, as the state machine will
1341 * take care of it once the client responds. It's also important to
1342 * prevent TIME_WAITs from accumulating on the backend side, and for
1343 * HTTP/2 where the last frame comes with a shutdown.
1344 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001345 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001346 channel_dont_close(req);
1347
1348 /* We know that more data are expected, but we couldn't send more that
1349 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1350 * system knows it must not set a PUSH on this first part. Interactive
1351 * modes are already handled by the stream sock layer. We must not do
1352 * this in content-length mode because it could present the MSG_MORE
1353 * flag with the last block of forwarded data, which would cause an
1354 * additional delay to be observed by the receiver.
1355 */
1356 if (msg->flags & HTTP_MSGF_TE_CHNK)
1357 req->flags |= CF_EXPECT_MORE;
1358
1359 return 0;
1360
1361 return_bad_req: /* let's centralize all bad requests */
1362 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1363 if (sess->listener->counters)
1364 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1365
1366 return_bad_req_stats_ok:
1367 txn->req.err_state = txn->req.msg_state;
1368 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001369 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001370 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001371 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 } else {
1373 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001374 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 }
1376 req->analysers &= AN_REQ_FLT_END;
1377 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1378
1379 if (!(s->flags & SF_ERR_MASK))
1380 s->flags |= SF_ERR_PRXCOND;
1381 if (!(s->flags & SF_FINST_MASK)) {
1382 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1383 s->flags |= SF_FINST_H;
1384 else
1385 s->flags |= SF_FINST_D;
1386 }
1387 return 0;
1388
1389 aborted_xfer:
1390 txn->req.err_state = txn->req.msg_state;
1391 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001392 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001393 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001394 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 } else {
1396 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001397 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001398 }
1399 req->analysers &= AN_REQ_FLT_END;
1400 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1401
1402 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1403 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1404 if (objt_server(s->target))
1405 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1406
1407 if (!(s->flags & SF_ERR_MASK))
1408 s->flags |= SF_ERR_SRVCL;
1409 if (!(s->flags & SF_FINST_MASK)) {
1410 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1411 s->flags |= SF_FINST_H;
1412 else
1413 s->flags |= SF_FINST_D;
1414 }
1415 return 0;
1416}
1417
1418/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1419 * processing can continue on next analysers, or zero if it either needs more
1420 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1421 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1422 * when it has nothing left to do, and may remove any analyser when it wants to
1423 * abort.
1424 */
1425int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1426{
Christopher Faulet9768c262018-10-22 09:34:31 +02001427 /*
1428 * We will analyze a complete HTTP response to check the its syntax.
1429 *
1430 * Once the start line and all headers are received, we may perform a
1431 * capture of the error (if any), and we will set a few fields. We also
1432 * logging and finally headers capture.
1433 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001434 struct session *sess = s->sess;
1435 struct http_txn *txn = s->txn;
1436 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001437 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001438 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001439 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001440 int n;
1441
1442 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1443 now_ms, __FUNCTION__,
1444 s,
1445 rep,
1446 rep->rex, rep->wex,
1447 rep->flags,
1448 ci_data(rep),
1449 rep->analysers);
1450
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001451 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001452
1453 /*
1454 * Now we quickly check if we have found a full valid response.
1455 * If not so, we check the FD and buffer states before leaving.
1456 * A full response is indicated by the fact that we have seen
1457 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1458 * responses are checked first.
1459 *
1460 * Depending on whether the client is still there or not, we
1461 * may send an error response back or not. Note that normally
1462 * we should only check for HTTP status there, and check I/O
1463 * errors somewhere else.
1464 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001465 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001466 /*
1467 * First catch invalid response
1468 */
1469 if (htx->flags & HTX_FL_PARSING_ERROR)
1470 goto return_bad_res;
1471
Christopher Faulet9768c262018-10-22 09:34:31 +02001472 /* 1: have we encountered a read error ? */
1473 if (rep->flags & CF_READ_ERROR) {
1474 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001475 goto abort_keep_alive;
1476
1477 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1478 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001479 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1480 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001481 }
1482
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 rep->analysers &= AN_RES_FLT_END;
1484 txn->status = 502;
1485
1486 /* Check to see if the server refused the early data.
1487 * If so, just send a 425
1488 */
1489 if (objt_cs(s->si[1].end)) {
1490 struct connection *conn = objt_cs(s->si[1].end)->conn;
1491
1492 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1493 txn->status = 425;
1494 }
1495
1496 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001497 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001498
1499 if (!(s->flags & SF_ERR_MASK))
1500 s->flags |= SF_ERR_SRVCL;
1501 if (!(s->flags & SF_FINST_MASK))
1502 s->flags |= SF_FINST_H;
1503 return 0;
1504 }
1505
Christopher Faulet9768c262018-10-22 09:34:31 +02001506 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1509 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001510 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1511 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512 }
1513
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 rep->analysers &= AN_RES_FLT_END;
1515 txn->status = 504;
1516 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001517 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518
1519 if (!(s->flags & SF_ERR_MASK))
1520 s->flags |= SF_ERR_SRVTO;
1521 if (!(s->flags & SF_FINST_MASK))
1522 s->flags |= SF_FINST_H;
1523 return 0;
1524 }
1525
Christopher Faulet9768c262018-10-22 09:34:31 +02001526 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1528 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1529 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1530 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001531 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532
1533 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001535 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536
1537 if (!(s->flags & SF_ERR_MASK))
1538 s->flags |= SF_ERR_CLICL;
1539 if (!(s->flags & SF_FINST_MASK))
1540 s->flags |= SF_FINST_H;
1541
1542 /* process_stream() will take care of the error */
1543 return 0;
1544 }
1545
Christopher Faulet9768c262018-10-22 09:34:31 +02001546 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 goto abort_keep_alive;
1550
1551 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1552 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001553 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1554 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 }
1556
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 rep->analysers &= AN_RES_FLT_END;
1558 txn->status = 502;
1559 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001560 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561
1562 if (!(s->flags & SF_ERR_MASK))
1563 s->flags |= SF_ERR_SRVCL;
1564 if (!(s->flags & SF_FINST_MASK))
1565 s->flags |= SF_FINST_H;
1566 return 0;
1567 }
1568
Christopher Faulet9768c262018-10-22 09:34:31 +02001569 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001570 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 goto abort_keep_alive;
1573
1574 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1575 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576
1577 if (!(s->flags & SF_ERR_MASK))
1578 s->flags |= SF_ERR_CLICL;
1579 if (!(s->flags & SF_FINST_MASK))
1580 s->flags |= SF_FINST_H;
1581
1582 /* process_stream() will take care of the error */
1583 return 0;
1584 }
1585
1586 channel_dont_close(rep);
1587 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1588 return 0;
1589 }
1590
1591 /* More interesting part now : we know that we have a complete
1592 * response which at least looks like HTTP. We have an indicator
1593 * of each header's length, so we can parse them quickly.
1594 */
1595
Christopher Faulet9768c262018-10-22 09:34:31 +02001596 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001597 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001598
Christopher Faulet9768c262018-10-22 09:34:31 +02001599 /* 0: we might have to print this header in debug mode */
1600 if (unlikely((global.mode & MODE_DEBUG) &&
1601 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1602 int32_t pos;
1603
Christopher Faulet03599112018-11-27 11:21:21 +01001604 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001605
1606 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1607 struct htx_blk *blk = htx_get_blk(htx, pos);
1608 enum htx_blk_type type = htx_get_blk_type(blk);
1609
1610 if (type == HTX_BLK_EOH)
1611 break;
1612 if (type != HTX_BLK_HDR)
1613 continue;
1614
1615 htx_debug_hdr("srvhdr", s,
1616 htx_get_blk_name(htx, blk),
1617 htx_get_blk_value(htx, blk));
1618 }
1619 }
1620
Christopher Faulet03599112018-11-27 11:21:21 +01001621 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001622 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001623 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001624 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001625 if (sl->flags & HTX_SL_F_XFER_LEN) {
1626 msg->flags |= HTTP_MSGF_XFER_LEN;
1627 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001628 if (sl->flags & HTX_SL_F_BODYLESS)
1629 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001630 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001631
1632 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001633 if (n < 1 || n > 5)
1634 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001635
Christopher Faulete0768eb2018-10-03 16:38:02 +02001636 /* when the client triggers a 4xx from the server, it's most often due
1637 * to a missing object or permission. These events should be tracked
1638 * because if they happen often, it may indicate a brute force or a
1639 * vulnerability scan.
1640 */
1641 if (n == 4)
1642 stream_inc_http_err_ctr(s);
1643
1644 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001645 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001646
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647 /* Adjust server's health based on status code. Note: status codes 501
1648 * and 505 are triggered on demand by client request, so we must not
1649 * count them as server failures.
1650 */
1651 if (objt_server(s->target)) {
1652 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001653 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001654 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001655 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001656 }
1657
1658 /*
1659 * We may be facing a 100-continue response, or any other informational
1660 * 1xx response which is non-final, in which case this is not the right
1661 * response, and we're waiting for the next one. Let's allow this response
1662 * to go to the client and wait for the next one. There's an exception for
1663 * 101 which is used later in the code to switch protocols.
1664 */
1665 if (txn->status < 200 &&
1666 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001667 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001668 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001669 msg->msg_state = HTTP_MSG_RPBEFORE;
1670 txn->status = 0;
1671 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001672 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001673 }
1674
1675 /*
1676 * 2: check for cacheability.
1677 */
1678
1679 switch (txn->status) {
1680 case 200:
1681 case 203:
1682 case 204:
1683 case 206:
1684 case 300:
1685 case 301:
1686 case 404:
1687 case 405:
1688 case 410:
1689 case 414:
1690 case 501:
1691 break;
1692 default:
1693 /* RFC7231#6.1:
1694 * Responses with status codes that are defined as
1695 * cacheable by default (e.g., 200, 203, 204, 206,
1696 * 300, 301, 404, 405, 410, 414, and 501 in this
1697 * specification) can be reused by a cache with
1698 * heuristic expiration unless otherwise indicated
1699 * by the method definition or explicit cache
1700 * controls [RFC7234]; all other status codes are
1701 * not cacheable by default.
1702 */
1703 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1704 break;
1705 }
1706
1707 /*
1708 * 3: we may need to capture headers
1709 */
1710 s->logs.logwait &= ~LW_RESP;
1711 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001712 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001713
Christopher Faulet9768c262018-10-22 09:34:31 +02001714 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1716 txn->status == 101)) {
1717 /* Either we've established an explicit tunnel, or we're
1718 * switching the protocol. In both cases, we're very unlikely
1719 * to understand the next protocols. We have to switch to tunnel
1720 * mode, so that we transfer the request and responses then let
1721 * this protocol pass unmodified. When we later implement specific
1722 * parsers for such protocols, we'll want to check the Upgrade
1723 * header which contains information about that protocol for
1724 * responses with status 101 (eg: see RFC2817 about TLS).
1725 */
1726 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001727 }
1728
Christopher Faulet61608322018-11-23 16:23:45 +01001729 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1730 * 407 (Proxy-Authenticate) responses and set the connection to private
1731 */
1732 srv_conn = cs_conn(objt_cs(s->si[1].end));
1733 if (srv_conn) {
1734 struct ist hdr;
1735 struct http_hdr_ctx ctx;
1736
1737 if (txn->status == 401)
1738 hdr = ist("WWW-Authenticate");
1739 else if (txn->status == 407)
1740 hdr = ist("Proxy-Authenticate");
1741 else
1742 goto end;
1743
1744 ctx.blk = NULL;
1745 while (http_find_header(htx, hdr, &ctx, 0)) {
1746 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1747 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1748 srv_conn->flags |= CO_FL_PRIVATE;
1749 }
1750 }
1751
1752 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001753 /* we want to have the response time before we start processing it */
1754 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1755
1756 /* end of job, return OK */
1757 rep->analysers &= ~an_bit;
1758 rep->analyse_exp = TICK_ETERNITY;
1759 channel_auto_close(rep);
1760 return 1;
1761
Christopher Faulet47365272018-10-31 17:40:50 +01001762 return_bad_res:
1763 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1764 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001765 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1766 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001767 }
1768 txn->status = 502;
1769 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001770 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001771 rep->analysers &= AN_RES_FLT_END;
1772
1773 if (!(s->flags & SF_ERR_MASK))
1774 s->flags |= SF_ERR_PRXCOND;
1775 if (!(s->flags & SF_FINST_MASK))
1776 s->flags |= SF_FINST_H;
1777 return 0;
1778
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 abort_keep_alive:
1780 /* A keep-alive request to the server failed on a network error.
1781 * The client is required to retry. We need to close without returning
1782 * any other information so that the client retries.
1783 */
1784 txn->status = 0;
1785 rep->analysers &= AN_RES_FLT_END;
1786 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001787 s->logs.logwait = 0;
1788 s->logs.level = 0;
1789 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001790 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791 return 0;
1792}
1793
1794/* This function performs all the processing enabled for the current response.
1795 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1796 * and updates s->res.analysers. It might make sense to explode it into several
1797 * other functions. It works like process_request (see indications above).
1798 */
1799int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1800{
1801 struct session *sess = s->sess;
1802 struct http_txn *txn = s->txn;
1803 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001804 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 struct proxy *cur_proxy;
1806 struct cond_wordlist *wl;
1807 enum rule_result ret = HTTP_RULE_RES_CONT;
1808
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001809 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1810 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001811
Christopher Faulete0768eb2018-10-03 16:38:02 +02001812 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1813 now_ms, __FUNCTION__,
1814 s,
1815 rep,
1816 rep->rex, rep->wex,
1817 rep->flags,
1818 ci_data(rep),
1819 rep->analysers);
1820
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001821 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001822
1823 /* The stats applet needs to adjust the Connection header but we don't
1824 * apply any filter there.
1825 */
1826 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1827 rep->analysers &= ~an_bit;
1828 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001829 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001830 }
1831
1832 /*
1833 * We will have to evaluate the filters.
1834 * As opposed to version 1.2, now they will be evaluated in the
1835 * filters order and not in the header order. This means that
1836 * each filter has to be validated among all headers.
1837 *
1838 * Filters are tried with ->be first, then with ->fe if it is
1839 * different from ->be.
1840 *
1841 * Maybe we are in resume condiion. In this case I choose the
1842 * "struct proxy" which contains the rule list matching the resume
1843 * pointer. If none of theses "struct proxy" match, I initialise
1844 * the process with the first one.
1845 *
1846 * In fact, I check only correspondance betwwen the current list
1847 * pointer and the ->fe rule list. If it doesn't match, I initialize
1848 * the loop with the ->be.
1849 */
1850 if (s->current_rule_list == &sess->fe->http_res_rules)
1851 cur_proxy = sess->fe;
1852 else
1853 cur_proxy = s->be;
1854 while (1) {
1855 struct proxy *rule_set = cur_proxy;
1856
1857 /* evaluate http-response rules */
1858 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001859 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001860
1861 if (ret == HTTP_RULE_RES_BADREQ)
1862 goto return_srv_prx_502;
1863
1864 if (ret == HTTP_RULE_RES_DONE) {
1865 rep->analysers &= ~an_bit;
1866 rep->analyse_exp = TICK_ETERNITY;
1867 return 1;
1868 }
1869 }
1870
1871 /* we need to be called again. */
1872 if (ret == HTTP_RULE_RES_YIELD) {
1873 channel_dont_close(rep);
1874 return 0;
1875 }
1876
1877 /* try headers filters */
1878 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001879 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1880 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001881 }
1882
1883 /* has the response been denied ? */
1884 if (txn->flags & TX_SVDENY) {
1885 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001886 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001887
1888 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1889 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1890 if (sess->listener->counters)
1891 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001892 goto return_srv_prx_502;
1893 }
1894
1895 /* add response headers from the rule sets in the same order */
1896 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001897 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001898 if (txn->status < 200 && txn->status != 101)
1899 break;
1900 if (wl->cond) {
1901 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1902 ret = acl_pass(ret);
1903 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1904 ret = !ret;
1905 if (!ret)
1906 continue;
1907 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001908
1909 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1910 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001911 goto return_bad_resp;
1912 }
1913
1914 /* check whether we're already working on the frontend */
1915 if (cur_proxy == sess->fe)
1916 break;
1917 cur_proxy = sess->fe;
1918 }
1919
1920 /* After this point, this anayzer can't return yield, so we can
1921 * remove the bit corresponding to this analyzer from the list.
1922 *
1923 * Note that the intermediate returns and goto found previously
1924 * reset the analyzers.
1925 */
1926 rep->analysers &= ~an_bit;
1927 rep->analyse_exp = TICK_ETERNITY;
1928
1929 /* OK that's all we can do for 1xx responses */
1930 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001931 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001932
1933 /*
1934 * Now check for a server cookie.
1935 */
1936 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001937 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001938
1939 /*
1940 * Check for cache-control or pragma headers if required.
1941 */
1942 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1943 check_response_for_cacheability(s, rep);
1944
1945 /*
1946 * Add server cookie in the response if needed
1947 */
1948 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1949 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1950 (!(s->flags & SF_DIRECT) ||
1951 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1952 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1953 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1954 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1955 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1956 !(s->flags & SF_IGNORE_PRST)) {
1957 /* the server is known, it's not the one the client requested, or the
1958 * cookie's last seen date needs to be refreshed. We have to
1959 * insert a set-cookie here, except if we want to insert only on POST
1960 * requests and this one isn't. Note that servers which don't have cookies
1961 * (eg: some backup servers) will return a full cookie removal request.
1962 */
1963 if (!objt_server(s->target)->cookie) {
1964 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001965 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966 s->be->cookie_name);
1967 }
1968 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001969 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001970
1971 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1972 /* emit last_date, which is mandatory */
1973 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1974 s30tob64((date.tv_sec+3) >> 2,
1975 trash.area + trash.data);
1976 trash.data += 5;
1977
1978 if (s->be->cookie_maxlife) {
1979 /* emit first_date, which is either the original one or
1980 * the current date.
1981 */
1982 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1983 s30tob64(txn->cookie_first_date ?
1984 txn->cookie_first_date >> 2 :
1985 (date.tv_sec+3) >> 2,
1986 trash.area + trash.data);
1987 trash.data += 5;
1988 }
1989 }
1990 chunk_appendf(&trash, "; path=/");
1991 }
1992
1993 if (s->be->cookie_domain)
1994 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1995
1996 if (s->be->ck_opts & PR_CK_HTTPONLY)
1997 chunk_appendf(&trash, "; HttpOnly");
1998
1999 if (s->be->ck_opts & PR_CK_SECURE)
2000 chunk_appendf(&trash, "; Secure");
2001
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002002 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002003 goto return_bad_resp;
2004
2005 txn->flags &= ~TX_SCK_MASK;
2006 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2007 /* the server did not change, only the date was updated */
2008 txn->flags |= TX_SCK_UPDATED;
2009 else
2010 txn->flags |= TX_SCK_INSERTED;
2011
2012 /* Here, we will tell an eventual cache on the client side that we don't
2013 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2014 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2015 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2016 */
2017 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2018
2019 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2020
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002021 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002022 goto return_bad_resp;
2023 }
2024 }
2025
2026 /*
2027 * Check if result will be cacheable with a cookie.
2028 * We'll block the response if security checks have caught
2029 * nasty things such as a cacheable cookie.
2030 */
2031 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2032 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2033 (s->be->options & PR_O_CHK_CACHE)) {
2034 /* we're in presence of a cacheable response containing
2035 * a set-cookie header. We'll block it as requested by
2036 * the 'checkcache' option, and send an alert.
2037 */
2038 if (objt_server(s->target))
2039 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2040
2041 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2042 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2043 if (sess->listener->counters)
2044 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2045
2046 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2047 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2048 send_log(s->be, LOG_ALERT,
2049 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2050 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2051 goto return_srv_prx_502;
2052 }
2053
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002054 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002055 /* Always enter in the body analyzer */
2056 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2057 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2058
2059 /* if the user wants to log as soon as possible, without counting
2060 * bytes from the server, then this is the right moment. We have
2061 * to temporarily assign bytes_out to log what we currently have.
2062 */
2063 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2064 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002065 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002066 s->do_log(s);
2067 s->logs.bytes_out = 0;
2068 }
2069 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002070
2071 return_bad_resp:
2072 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002073 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2074 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002075 }
2076 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2077
2078 return_srv_prx_502:
2079 rep->analysers &= AN_RES_FLT_END;
2080 txn->status = 502;
2081 s->logs.t_data = -1; /* was not a valid response */
2082 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002083 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002084 if (!(s->flags & SF_ERR_MASK))
2085 s->flags |= SF_ERR_PRXCOND;
2086 if (!(s->flags & SF_FINST_MASK))
2087 s->flags |= SF_FINST_H;
2088 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002089}
2090
2091/* This function is an analyser which forwards response body (including chunk
2092 * sizes if any). It is called as soon as we must forward, even if we forward
2093 * zero byte. The only situation where it must not be called is when we're in
2094 * tunnel mode and we want to forward till the close. It's used both to forward
2095 * remaining data and to resync after end of body. It expects the msg_state to
2096 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2097 * read more data, or 1 once we can go on with next request or end the stream.
2098 *
2099 * It is capable of compressing response data both in content-length mode and
2100 * in chunked mode. The state machines follows different flows depending on
2101 * whether content-length and chunked modes are used, since there are no
2102 * trailers in content-length :
2103 *
2104 * chk-mode cl-mode
2105 * ,----- BODY -----.
2106 * / \
2107 * V size > 0 V chk-mode
2108 * .--> SIZE -------------> DATA -------------> CRLF
2109 * | | size == 0 | last byte |
2110 * | v final crlf v inspected |
2111 * | TRAILERS -----------> DONE |
2112 * | |
2113 * `----------------------------------------------'
2114 *
2115 * Compression only happens in the DATA state, and must be flushed in final
2116 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2117 * is performed at once on final states for all bytes parsed, or when leaving
2118 * on missing data.
2119 */
2120int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2121{
2122 struct session *sess = s->sess;
2123 struct http_txn *txn = s->txn;
2124 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002125 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002126 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002127
2128 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2129 now_ms, __FUNCTION__,
2130 s,
2131 res,
2132 res->rex, res->wex,
2133 res->flags,
2134 ci_data(res),
2135 res->analysers);
2136
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002137 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002138
2139 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002140 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002141 /* Output closed while we were sending data. We must abort and
2142 * wake the other side up.
2143 */
2144 msg->err_state = msg->msg_state;
2145 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002146 htx_end_response(s);
2147 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002148 return 1;
2149 }
2150
Christopher Faulet9768c262018-10-22 09:34:31 +02002151 if (msg->msg_state == HTTP_MSG_BODY)
2152 msg->msg_state = HTTP_MSG_DATA;
2153
Christopher Faulete0768eb2018-10-03 16:38:02 +02002154 /* in most states, we should abort in case of early close */
2155 channel_auto_close(res);
2156
Christopher Faulete0768eb2018-10-03 16:38:02 +02002157 if (res->to_forward) {
2158 /* We can't process the buffer's contents yet */
2159 res->flags |= CF_WAKE_WRITE;
2160 goto missing_data_or_waiting;
2161 }
2162
Christopher Faulet9768c262018-10-22 09:34:31 +02002163 if (msg->msg_state >= HTTP_MSG_DONE)
2164 goto done;
2165
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002166 /* Forward input data. We get it by removing all outgoing data not
2167 * forwarded yet from HTX data size. If there are some data filters, we
2168 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002169 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002170 if (HAS_RSP_DATA_FILTERS(s)) {
2171 ret = flt_http_payload(s, msg, htx->data);
2172 if (ret < 0)
2173 goto return_bad_res;
2174 c_adv(res, ret);
2175 if (htx->data != co_data(res) || htx->extra)
2176 goto missing_data_or_waiting;
2177 }
2178 else {
2179 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002180
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002181 /* To let the function channel_forward work as expected we must update
2182 * the channel's buffer to pretend there is no more input data. The
2183 * right length is then restored. We must do that, because when an HTX
2184 * message is stored into a buffer, it appears as full.
2185 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002186 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2187 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002188 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002189
2190 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2191 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002192 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002193 msg->msg_state = HTTP_MSG_TUNNEL;
2194 goto done;
2195 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 }
2197
Christopher Faulet9768c262018-10-22 09:34:31 +02002198 /* Check if the end-of-message is reached and if so, switch the message
2199 * in HTTP_MSG_DONE state.
2200 */
2201 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2202 goto missing_data_or_waiting;
2203
2204 msg->msg_state = HTTP_MSG_DONE;
2205
2206 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002208 channel_dont_close(res);
2209
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002210 if (HAS_RSP_DATA_FILTERS(s)) {
2211 ret = flt_http_end(s, msg);
2212 if (ret <= 0) {
2213 if (!ret)
2214 goto missing_data_or_waiting;
2215 goto return_bad_res;
2216 }
2217 }
2218
Christopher Fauletf2824e62018-10-01 12:12:37 +02002219 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002221 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2223 if (res->flags & CF_SHUTW) {
2224 /* response errors are most likely due to the
2225 * client aborting the transfer. */
2226 goto aborted_xfer;
2227 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228 goto return_bad_res;
2229 }
2230 return 1;
2231 }
2232 return 0;
2233
2234 missing_data_or_waiting:
2235 if (res->flags & CF_SHUTW)
2236 goto aborted_xfer;
2237
Christopher Faulet47365272018-10-31 17:40:50 +01002238 if (htx->flags & HTX_FL_PARSING_ERROR)
2239 goto return_bad_res;
2240
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 /* stop waiting for data if the input is closed before the end. If the
2242 * client side was already closed, it means that the client has aborted,
2243 * so we don't want to count this as a server abort. Otherwise it's a
2244 * server abort.
2245 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002246 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002247 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2248 goto aborted_xfer;
2249 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002250 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 if (!(s->flags & SF_ERR_MASK))
2252 s->flags |= SF_ERR_SRVCL;
2253 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2254 if (objt_server(s->target))
2255 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2256 goto return_bad_res_stats_ok;
2257 }
2258 }
2259
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260 /* When TE: chunked is used, we need to get there again to parse
2261 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002262 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2263 * are filters registered on the stream, we don't want to forward a
2264 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002266 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002267 channel_dont_close(res);
2268
2269 /* We know that more data are expected, but we couldn't send more that
2270 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2271 * system knows it must not set a PUSH on this first part. Interactive
2272 * modes are already handled by the stream sock layer. We must not do
2273 * this in content-length mode because it could present the MSG_MORE
2274 * flag with the last block of forwarded data, which would cause an
2275 * additional delay to be observed by the receiver.
2276 */
2277 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2278 res->flags |= CF_EXPECT_MORE;
2279
2280 /* the stream handler will take care of timeouts and errors */
2281 return 0;
2282
2283 return_bad_res: /* let's centralize all bad responses */
2284 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2285 if (objt_server(s->target))
2286 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2287
2288 return_bad_res_stats_ok:
2289 txn->rsp.err_state = txn->rsp.msg_state;
2290 txn->rsp.msg_state = HTTP_MSG_ERROR;
2291 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002292 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002293 res->analysers &= AN_RES_FLT_END;
2294 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2295 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002296 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297
2298 if (!(s->flags & SF_ERR_MASK))
2299 s->flags |= SF_ERR_PRXCOND;
2300 if (!(s->flags & SF_FINST_MASK))
2301 s->flags |= SF_FINST_D;
2302 return 0;
2303
2304 aborted_xfer:
2305 txn->rsp.err_state = txn->rsp.msg_state;
2306 txn->rsp.msg_state = HTTP_MSG_ERROR;
2307 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002308 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002309 res->analysers &= AN_RES_FLT_END;
2310 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2311
2312 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2313 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2314 if (objt_server(s->target))
2315 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2316
2317 if (!(s->flags & SF_ERR_MASK))
2318 s->flags |= SF_ERR_CLICL;
2319 if (!(s->flags & SF_FINST_MASK))
2320 s->flags |= SF_FINST_D;
2321 return 0;
2322}
2323
Christopher Faulet0f226952018-10-22 09:29:56 +02002324void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002325{
2326 struct proxy *fe = strm_fe(s);
2327 int tmp = TX_CON_WANT_CLO;
2328
2329 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2330 tmp = TX_CON_WANT_TUN;
2331
2332 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002333 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002334}
2335
2336/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002337 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338 * as too large a request to build a valid response.
2339 */
2340int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2341{
Christopher Faulet99daf282018-11-28 22:58:13 +01002342 struct channel *req = &s->req;
2343 struct channel *res = &s->res;
2344 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002345 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002346 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002347 struct ist status, reason, location;
2348 unsigned int flags;
2349 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002350
2351 chunk = alloc_trash_chunk();
2352 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002353 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354
Christopher Faulet99daf282018-11-28 22:58:13 +01002355 /*
2356 * Create the location
2357 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002358 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002360 case REDIRECT_TYPE_SCHEME: {
2361 struct http_hdr_ctx ctx;
2362 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363
Christopher Faulet99daf282018-11-28 22:58:13 +01002364 host = ist("");
2365 ctx.blk = NULL;
2366 if (http_find_header(htx, ist("Host"), &ctx, 0))
2367 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368
Christopher Faulet99daf282018-11-28 22:58:13 +01002369 sl = http_find_stline(htx);
2370 path = http_get_path(htx_sl_req_uri(sl));
2371 /* build message using path */
2372 if (path.ptr) {
2373 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2374 int qs = 0;
2375 while (qs < path.len) {
2376 if (*(path.ptr + qs) == '?') {
2377 path.len = qs;
2378 break;
2379 }
2380 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002381 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382 }
2383 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002384 else
2385 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386
Christopher Faulet99daf282018-11-28 22:58:13 +01002387 if (rule->rdr_str) { /* this is an old "redirect" rule */
2388 /* add scheme */
2389 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2390 goto fail;
2391 }
2392 else {
2393 /* add scheme with executing log format */
2394 chunk->data += build_logline(s, chunk->area + chunk->data,
2395 chunk->size - chunk->data,
2396 &rule->rdr_fmt);
2397 }
2398 /* add "://" + host + path */
2399 if (!chunk_memcat(chunk, "://", 3) ||
2400 !chunk_memcat(chunk, host.ptr, host.len) ||
2401 !chunk_memcat(chunk, path.ptr, path.len))
2402 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002403
Christopher Faulet99daf282018-11-28 22:58:13 +01002404 /* append a slash at the end of the location if needed and missing */
2405 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2406 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2407 if (chunk->data + 1 >= chunk->size)
2408 goto fail;
2409 chunk->area[chunk->data++] = '/';
2410 }
2411 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002412 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002413
Christopher Faulet99daf282018-11-28 22:58:13 +01002414 case REDIRECT_TYPE_PREFIX: {
2415 struct ist path;
2416
2417 sl = http_find_stline(htx);
2418 path = http_get_path(htx_sl_req_uri(sl));
2419 /* build message using path */
2420 if (path.ptr) {
2421 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2422 int qs = 0;
2423 while (qs < path.len) {
2424 if (*(path.ptr + qs) == '?') {
2425 path.len = qs;
2426 break;
2427 }
2428 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430 }
2431 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002432 else
2433 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434
Christopher Faulet99daf282018-11-28 22:58:13 +01002435 if (rule->rdr_str) { /* this is an old "redirect" rule */
2436 /* add prefix. Note that if prefix == "/", we don't want to
2437 * add anything, otherwise it makes it hard for the user to
2438 * configure a self-redirection.
2439 */
2440 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2441 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2442 goto fail;
2443 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 else {
2446 /* add prefix with executing log format */
2447 chunk->data += build_logline(s, chunk->area + chunk->data,
2448 chunk->size - chunk->data,
2449 &rule->rdr_fmt);
2450 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451
Christopher Faulet99daf282018-11-28 22:58:13 +01002452 /* add path */
2453 if (!chunk_memcat(chunk, path.ptr, path.len))
2454 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002455
Christopher Faulet99daf282018-11-28 22:58:13 +01002456 /* append a slash at the end of the location if needed and missing */
2457 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2458 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2459 if (chunk->data + 1 >= chunk->size)
2460 goto fail;
2461 chunk->area[chunk->data++] = '/';
2462 }
2463 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002465 case REDIRECT_TYPE_LOCATION:
2466 default:
2467 if (rule->rdr_str) { /* this is an old "redirect" rule */
2468 /* add location */
2469 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2470 goto fail;
2471 }
2472 else {
2473 /* add location with executing log format */
2474 chunk->data += build_logline(s, chunk->area + chunk->data,
2475 chunk->size - chunk->data,
2476 &rule->rdr_fmt);
2477 }
2478 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002479 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002480 location = ist2(chunk->area, chunk->data);
2481
2482 /*
2483 * Create the 30x response
2484 */
2485 switch (rule->code) {
2486 case 308:
2487 status = ist("308");
2488 reason = ist("Permanent Redirect");
2489 break;
2490 case 307:
2491 status = ist("307");
2492 reason = ist("Temporary Redirect");
2493 break;
2494 case 303:
2495 status = ist("303");
2496 reason = ist("See Other");
2497 break;
2498 case 301:
2499 status = ist("301");
2500 reason = ist("Moved Permanently");
2501 break;
2502 case 302:
2503 default:
2504 status = ist("302");
2505 reason = ist("Found");
2506 break;
2507 }
2508
2509 htx = htx_from_buf(&res->buf);
2510 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2511 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2512 if (!sl)
2513 goto fail;
2514 sl->info.res.status = rule->code;
2515 s->txn->status = rule->code;
2516
2517 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2518 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2519 !htx_add_header(htx, ist("Location"), location))
2520 goto fail;
2521
2522 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2523 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2524 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002525 }
2526
2527 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002528 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2529 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002530 }
2531
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2533 goto fail;
2534
Christopher Fauletf2824e62018-10-01 12:12:37 +02002535 /* let's log the request time */
2536 s->logs.tv_request = now;
2537
Christopher Faulet99daf282018-11-28 22:58:13 +01002538 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 c_adv(res, data);
2540 res->total += data;
2541
2542 channel_auto_read(req);
2543 channel_abort(req);
2544 channel_auto_close(req);
2545 channel_erase(req);
2546
2547 res->wex = tick_add_ifset(now_ms, res->wto);
2548 channel_auto_read(res);
2549 channel_auto_close(res);
2550 channel_shutr_now(res);
2551
2552 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002553
2554 if (!(s->flags & SF_ERR_MASK))
2555 s->flags |= SF_ERR_LOCAL;
2556 if (!(s->flags & SF_FINST_MASK))
2557 s->flags |= SF_FINST_R;
2558
Christopher Faulet99daf282018-11-28 22:58:13 +01002559 free_trash_chunk(chunk);
2560 return 1;
2561
2562 fail:
2563 /* If an error occurred, remove the incomplete HTTP response from the
2564 * buffer */
2565 channel_truncate(res);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002566 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002567 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002568}
2569
Christopher Faulet72333522018-10-24 11:25:02 +02002570int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2571 struct ist name, const char *str, struct my_regex *re, int action)
2572{
2573 struct http_hdr_ctx ctx;
2574 struct buffer *output = get_trash_chunk();
2575
2576 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2577 ctx.blk = NULL;
2578 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2579 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2580 continue;
2581
2582 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2583 if (output->data == -1)
2584 return -1;
2585 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2586 return -1;
2587 }
2588 return 0;
2589}
2590
2591static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2592 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2593{
2594 struct buffer *replace;
2595 int ret = -1;
2596
2597 replace = alloc_trash_chunk();
2598 if (!replace)
2599 goto leave;
2600
2601 replace->data = build_logline(s, replace->area, replace->size, fmt);
2602 if (replace->data >= replace->size - 1)
2603 goto leave;
2604
2605 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2606
2607 leave:
2608 free_trash_chunk(replace);
2609 return ret;
2610}
2611
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002612
2613/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2614 * on success and -1 on error. The response channel is updated accordingly.
2615 */
2616static int htx_reply_103_early_hints(struct channel *res)
2617{
2618 struct htx *htx = htx_from_buf(&res->buf);
2619 size_t data;
2620
2621 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2622 /* If an error occurred during an Early-hint rule,
2623 * remove the incomplete HTTP 103 response from the
2624 * buffer */
2625 channel_truncate(res);
2626 return -1;
2627 }
2628
2629 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002630 c_adv(res, data);
2631 res->total += data;
2632 return 0;
2633}
2634
Christopher Faulet6eb92892018-11-15 16:39:29 +01002635/*
2636 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2637 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 * If <early_hints> is 0, it is starts a new response by adding the start
2639 * line. If an error occurred -1 is returned. On success 0 is returned. The
2640 * channel is not updated here. It must be done calling the function
2641 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002642 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643static 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 +01002644{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002645 struct channel *res = &s->res;
2646 struct htx *htx = htx_from_buf(&res->buf);
2647 struct buffer *value = alloc_trash_chunk();
2648
Christopher Faulet6eb92892018-11-15 16:39:29 +01002649 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 struct htx_sl *sl;
2651 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2652 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2653
2654 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2655 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2656 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002657 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002659 }
2660
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2662 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002663 goto fail;
2664
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002666 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667
2668 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002669 /* If an error occurred during an Early-hint rule, remove the incomplete
2670 * HTTP 103 response from the buffer */
2671 channel_truncate(res);
2672 free_trash_chunk(value);
2673 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674}
2675
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002676/* This function executes one of the set-{method,path,query,uri} actions. It
2677 * takes the string from the variable 'replace' with length 'len', then modifies
2678 * the relevant part of the request line accordingly. Then it updates various
2679 * pointers to the next elements which were moved, and the total buffer length.
2680 * It finds the action to be performed in p[2], previously filled by function
2681 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2682 * error, though this can be revisited when this code is finally exploited.
2683 *
2684 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2685 * query string and 3 to replace uri.
2686 *
2687 * In query string case, the mark question '?' must be set at the start of the
2688 * string by the caller, event if the replacement query string is empty.
2689 */
2690int htx_req_replace_stline(int action, const char *replace, int len,
2691 struct proxy *px, struct stream *s)
2692{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002693 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002694
2695 switch (action) {
2696 case 0: // method
2697 if (!http_replace_req_meth(htx, ist2(replace, len)))
2698 return -1;
2699 break;
2700
2701 case 1: // path
2702 if (!http_replace_req_path(htx, ist2(replace, len)))
2703 return -1;
2704 break;
2705
2706 case 2: // query
2707 if (!http_replace_req_query(htx, ist2(replace, len)))
2708 return -1;
2709 break;
2710
2711 case 3: // uri
2712 if (!http_replace_req_uri(htx, ist2(replace, len)))
2713 return -1;
2714 break;
2715
2716 default:
2717 return -1;
2718 }
2719 return 0;
2720}
2721
2722/* This function replace the HTTP status code and the associated message. The
2723 * variable <status> contains the new status code. This function never fails.
2724 */
2725void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2726{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002727 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002728 char *res;
2729
2730 chunk_reset(&trash);
2731 res = ultoa_o(status, trash.area, trash.size);
2732 trash.data = res - trash.area;
2733
2734 /* Do we have a custom reason format string? */
2735 if (reason == NULL)
2736 reason = http_get_reason(status);
2737
2738 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2739 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2740}
2741
Christopher Faulet3e964192018-10-24 11:39:23 +02002742/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2743 * transaction <txn>. Returns the verdict of the first rule that prevents
2744 * further processing of the request (auth, deny, ...), and defaults to
2745 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2746 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2747 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2748 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2749 * status.
2750 */
2751static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2752 struct stream *s, int *deny_status)
2753{
2754 struct session *sess = strm_sess(s);
2755 struct http_txn *txn = s->txn;
2756 struct htx *htx;
2757 struct connection *cli_conn;
2758 struct act_rule *rule;
2759 struct http_hdr_ctx ctx;
2760 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002761 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2762 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002763 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002764
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002765 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002766
2767 /* If "the current_rule_list" match the executed rule list, we are in
2768 * resume condition. If a resume is needed it is always in the action
2769 * and never in the ACL or converters. In this case, we initialise the
2770 * current rule, and go to the action execution point.
2771 */
2772 if (s->current_rule) {
2773 rule = s->current_rule;
2774 s->current_rule = NULL;
2775 if (s->current_rule_list == rules)
2776 goto resume_execution;
2777 }
2778 s->current_rule_list = rules;
2779
2780 list_for_each_entry(rule, rules, list) {
2781 /* check optional condition */
2782 if (rule->cond) {
2783 int ret;
2784
2785 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2786 ret = acl_pass(ret);
2787
2788 if (rule->cond->pol == ACL_COND_UNLESS)
2789 ret = !ret;
2790
2791 if (!ret) /* condition not matched */
2792 continue;
2793 }
2794
2795 act_flags |= ACT_FLAG_FIRST;
2796 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002797 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2798 early_hints = 0;
2799 if (htx_reply_103_early_hints(&s->res) == -1) {
2800 rule_ret = HTTP_RULE_RES_BADREQ;
2801 goto end;
2802 }
2803 }
2804
Christopher Faulet3e964192018-10-24 11:39:23 +02002805 switch (rule->action) {
2806 case ACT_ACTION_ALLOW:
2807 rule_ret = HTTP_RULE_RES_STOP;
2808 goto end;
2809
2810 case ACT_ACTION_DENY:
2811 if (deny_status)
2812 *deny_status = rule->deny_status;
2813 rule_ret = HTTP_RULE_RES_DENY;
2814 goto end;
2815
2816 case ACT_HTTP_REQ_TARPIT:
2817 txn->flags |= TX_CLTARPIT;
2818 if (deny_status)
2819 *deny_status = rule->deny_status;
2820 rule_ret = HTTP_RULE_RES_DENY;
2821 goto end;
2822
2823 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 /* Auth might be performed on regular http-req rules as well as on stats */
2825 auth_realm = rule->arg.auth.realm;
2826 if (!auth_realm) {
2827 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2828 auth_realm = STATS_DEFAULT_REALM;
2829 else
2830 auth_realm = px->id;
2831 }
2832 /* send 401/407 depending on whether we use a proxy or not. We still
2833 * count one error, because normal browsing won't significantly
2834 * increase the counter but brute force attempts will.
2835 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002836 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002837 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2838 rule_ret = HTTP_RULE_RES_BADREQ;
2839 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002840 goto end;
2841
2842 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002843 rule_ret = HTTP_RULE_RES_DONE;
2844 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2845 rule_ret = HTTP_RULE_RES_BADREQ;
2846 goto end;
2847
2848 case ACT_HTTP_SET_NICE:
2849 s->task->nice = rule->arg.nice;
2850 break;
2851
2852 case ACT_HTTP_SET_TOS:
2853 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2854 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2855 break;
2856
2857 case ACT_HTTP_SET_MARK:
2858#ifdef SO_MARK
2859 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2860 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2861#endif
2862 break;
2863
2864 case ACT_HTTP_SET_LOGL:
2865 s->logs.level = rule->arg.loglevel;
2866 break;
2867
2868 case ACT_HTTP_REPLACE_HDR:
2869 case ACT_HTTP_REPLACE_VAL:
2870 if (htx_transform_header(s, &s->req, htx,
2871 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2872 &rule->arg.hdr_add.fmt,
2873 &rule->arg.hdr_add.re, rule->action)) {
2874 rule_ret = HTTP_RULE_RES_BADREQ;
2875 goto end;
2876 }
2877 break;
2878
2879 case ACT_HTTP_DEL_HDR:
2880 /* remove all occurrences of the header */
2881 ctx.blk = NULL;
2882 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2883 http_remove_header(htx, &ctx);
2884 break;
2885
2886 case ACT_HTTP_SET_HDR:
2887 case ACT_HTTP_ADD_HDR: {
2888 /* The scope of the trash buffer must be limited to this function. The
2889 * build_logline() function can execute a lot of other function which
2890 * can use the trash buffer. So for limiting the scope of this global
2891 * buffer, we build first the header value using build_logline, and
2892 * after we store the header name.
2893 */
2894 struct buffer *replace;
2895 struct ist n, v;
2896
2897 replace = alloc_trash_chunk();
2898 if (!replace) {
2899 rule_ret = HTTP_RULE_RES_BADREQ;
2900 goto end;
2901 }
2902
2903 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2904 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2905 v = ist2(replace->area, replace->data);
2906
2907 if (rule->action == ACT_HTTP_SET_HDR) {
2908 /* remove all occurrences of the header */
2909 ctx.blk = NULL;
2910 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2911 http_remove_header(htx, &ctx);
2912 }
2913
2914 if (!http_add_header(htx, n, v)) {
2915 static unsigned char rate_limit = 0;
2916
2917 if ((rate_limit++ & 255) == 0) {
2918 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);
2919 }
2920
2921 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2922 if (sess->fe != s->be)
2923 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2924 if (sess->listener->counters)
2925 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2926 }
2927 free_trash_chunk(replace);
2928 break;
2929 }
2930
2931 case ACT_HTTP_DEL_ACL:
2932 case ACT_HTTP_DEL_MAP: {
2933 struct pat_ref *ref;
2934 struct buffer *key;
2935
2936 /* collect reference */
2937 ref = pat_ref_lookup(rule->arg.map.ref);
2938 if (!ref)
2939 continue;
2940
2941 /* allocate key */
2942 key = alloc_trash_chunk();
2943 if (!key) {
2944 rule_ret = HTTP_RULE_RES_BADREQ;
2945 goto end;
2946 }
2947
2948 /* collect key */
2949 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2950 key->area[key->data] = '\0';
2951
2952 /* perform update */
2953 /* returned code: 1=ok, 0=ko */
2954 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2955 pat_ref_delete(ref, key->area);
2956 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2957
2958 free_trash_chunk(key);
2959 break;
2960 }
2961
2962 case ACT_HTTP_ADD_ACL: {
2963 struct pat_ref *ref;
2964 struct buffer *key;
2965
2966 /* collect reference */
2967 ref = pat_ref_lookup(rule->arg.map.ref);
2968 if (!ref)
2969 continue;
2970
2971 /* allocate key */
2972 key = alloc_trash_chunk();
2973 if (!key) {
2974 rule_ret = HTTP_RULE_RES_BADREQ;
2975 goto end;
2976 }
2977
2978 /* collect key */
2979 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2980 key->area[key->data] = '\0';
2981
2982 /* perform update */
2983 /* add entry only if it does not already exist */
2984 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2985 if (pat_ref_find_elt(ref, key->area) == NULL)
2986 pat_ref_add(ref, key->area, NULL, NULL);
2987 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2988
2989 free_trash_chunk(key);
2990 break;
2991 }
2992
2993 case ACT_HTTP_SET_MAP: {
2994 struct pat_ref *ref;
2995 struct buffer *key, *value;
2996
2997 /* collect reference */
2998 ref = pat_ref_lookup(rule->arg.map.ref);
2999 if (!ref)
3000 continue;
3001
3002 /* allocate key */
3003 key = alloc_trash_chunk();
3004 if (!key) {
3005 rule_ret = HTTP_RULE_RES_BADREQ;
3006 goto end;
3007 }
3008
3009 /* allocate value */
3010 value = alloc_trash_chunk();
3011 if (!value) {
3012 free_trash_chunk(key);
3013 rule_ret = HTTP_RULE_RES_BADREQ;
3014 goto end;
3015 }
3016
3017 /* collect key */
3018 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3019 key->area[key->data] = '\0';
3020
3021 /* collect value */
3022 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3023 value->area[value->data] = '\0';
3024
3025 /* perform update */
3026 if (pat_ref_find_elt(ref, key->area) != NULL)
3027 /* update entry if it exists */
3028 pat_ref_set(ref, key->area, value->area, NULL);
3029 else
3030 /* insert a new entry */
3031 pat_ref_add(ref, key->area, value->area, NULL);
3032
3033 free_trash_chunk(key);
3034 free_trash_chunk(value);
3035 break;
3036 }
3037
3038 case ACT_HTTP_EARLY_HINT:
3039 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3040 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003041 early_hints = htx_add_early_hint_header(s, early_hints,
3042 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003043 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003044 if (early_hints == -1) {
3045 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003046 goto end;
3047 }
3048 break;
3049
3050 case ACT_CUSTOM:
3051 if ((s->req.flags & CF_READ_ERROR) ||
3052 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3053 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3054 (px->options & PR_O_ABRT_CLOSE)))
3055 act_flags |= ACT_FLAG_FINAL;
3056
3057 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3058 case ACT_RET_ERR:
3059 case ACT_RET_CONT:
3060 break;
3061 case ACT_RET_STOP:
3062 rule_ret = HTTP_RULE_RES_DONE;
3063 goto end;
3064 case ACT_RET_YIELD:
3065 s->current_rule = rule;
3066 rule_ret = HTTP_RULE_RES_YIELD;
3067 goto end;
3068 }
3069 break;
3070
3071 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3072 /* Note: only the first valid tracking parameter of each
3073 * applies.
3074 */
3075
3076 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3077 struct stktable *t;
3078 struct stksess *ts;
3079 struct stktable_key *key;
3080 void *ptr1, *ptr2;
3081
3082 t = rule->arg.trk_ctr.table.t;
3083 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3084 rule->arg.trk_ctr.expr, NULL);
3085
3086 if (key && (ts = stktable_get_entry(t, key))) {
3087 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3088
3089 /* let's count a new HTTP request as it's the first time we do it */
3090 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3091 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3092 if (ptr1 || ptr2) {
3093 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3094
3095 if (ptr1)
3096 stktable_data_cast(ptr1, http_req_cnt)++;
3097
3098 if (ptr2)
3099 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3100 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3101
3102 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3103
3104 /* If data was modified, we need to touch to re-schedule sync */
3105 stktable_touch_local(t, ts, 0);
3106 }
3107
3108 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3109 if (sess->fe != s->be)
3110 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3111 }
3112 }
3113 break;
3114
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003115 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003116 default:
3117 break;
3118 }
3119 }
3120
3121 end:
3122 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003123 if (htx_reply_103_early_hints(&s->res) == -1)
3124 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003125 }
3126
3127 /* we reached the end of the rules, nothing to report */
3128 return rule_ret;
3129}
3130
3131/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3132 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3133 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3134 * is returned, the process can continue the evaluation of next rule list. If
3135 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3136 * is returned, it means the operation could not be processed and a server error
3137 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3138 * deny rule. If *YIELD is returned, the caller must call again the function
3139 * with the same context.
3140 */
3141static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3142 struct stream *s)
3143{
3144 struct session *sess = strm_sess(s);
3145 struct http_txn *txn = s->txn;
3146 struct htx *htx;
3147 struct connection *cli_conn;
3148 struct act_rule *rule;
3149 struct http_hdr_ctx ctx;
3150 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3151 int act_flags = 0;
3152
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003153 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003154
3155 /* If "the current_rule_list" match the executed rule list, we are in
3156 * resume condition. If a resume is needed it is always in the action
3157 * and never in the ACL or converters. In this case, we initialise the
3158 * current rule, and go to the action execution point.
3159 */
3160 if (s->current_rule) {
3161 rule = s->current_rule;
3162 s->current_rule = NULL;
3163 if (s->current_rule_list == rules)
3164 goto resume_execution;
3165 }
3166 s->current_rule_list = rules;
3167
3168 list_for_each_entry(rule, rules, list) {
3169 /* check optional condition */
3170 if (rule->cond) {
3171 int ret;
3172
3173 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3174 ret = acl_pass(ret);
3175
3176 if (rule->cond->pol == ACL_COND_UNLESS)
3177 ret = !ret;
3178
3179 if (!ret) /* condition not matched */
3180 continue;
3181 }
3182
3183 act_flags |= ACT_FLAG_FIRST;
3184resume_execution:
3185 switch (rule->action) {
3186 case ACT_ACTION_ALLOW:
3187 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3188 goto end;
3189
3190 case ACT_ACTION_DENY:
3191 txn->flags |= TX_SVDENY;
3192 rule_ret = HTTP_RULE_RES_STOP;
3193 goto end;
3194
3195 case ACT_HTTP_SET_NICE:
3196 s->task->nice = rule->arg.nice;
3197 break;
3198
3199 case ACT_HTTP_SET_TOS:
3200 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3201 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3202 break;
3203
3204 case ACT_HTTP_SET_MARK:
3205#ifdef SO_MARK
3206 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3207 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3208#endif
3209 break;
3210
3211 case ACT_HTTP_SET_LOGL:
3212 s->logs.level = rule->arg.loglevel;
3213 break;
3214
3215 case ACT_HTTP_REPLACE_HDR:
3216 case ACT_HTTP_REPLACE_VAL:
3217 if (htx_transform_header(s, &s->res, htx,
3218 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3219 &rule->arg.hdr_add.fmt,
3220 &rule->arg.hdr_add.re, rule->action)) {
3221 rule_ret = HTTP_RULE_RES_BADREQ;
3222 goto end;
3223 }
3224 break;
3225
3226 case ACT_HTTP_DEL_HDR:
3227 /* remove all occurrences of the header */
3228 ctx.blk = NULL;
3229 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3230 http_remove_header(htx, &ctx);
3231 break;
3232
3233 case ACT_HTTP_SET_HDR:
3234 case ACT_HTTP_ADD_HDR: {
3235 struct buffer *replace;
3236 struct ist n, v;
3237
3238 replace = alloc_trash_chunk();
3239 if (!replace) {
3240 rule_ret = HTTP_RULE_RES_BADREQ;
3241 goto end;
3242 }
3243
3244 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3245 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3246 v = ist2(replace->area, replace->data);
3247
3248 if (rule->action == ACT_HTTP_SET_HDR) {
3249 /* remove all occurrences of the header */
3250 ctx.blk = NULL;
3251 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3252 http_remove_header(htx, &ctx);
3253 }
3254
3255 if (!http_add_header(htx, n, v)) {
3256 static unsigned char rate_limit = 0;
3257
3258 if ((rate_limit++ & 255) == 0) {
3259 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);
3260 }
3261
3262 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3263 if (sess->fe != s->be)
3264 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3265 if (sess->listener->counters)
3266 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3267 if (objt_server(s->target))
3268 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3269 }
3270 free_trash_chunk(replace);
3271 break;
3272 }
3273
3274 case ACT_HTTP_DEL_ACL:
3275 case ACT_HTTP_DEL_MAP: {
3276 struct pat_ref *ref;
3277 struct buffer *key;
3278
3279 /* collect reference */
3280 ref = pat_ref_lookup(rule->arg.map.ref);
3281 if (!ref)
3282 continue;
3283
3284 /* allocate key */
3285 key = alloc_trash_chunk();
3286 if (!key) {
3287 rule_ret = HTTP_RULE_RES_BADREQ;
3288 goto end;
3289 }
3290
3291 /* collect key */
3292 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3293 key->area[key->data] = '\0';
3294
3295 /* perform update */
3296 /* returned code: 1=ok, 0=ko */
3297 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3298 pat_ref_delete(ref, key->area);
3299 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3300
3301 free_trash_chunk(key);
3302 break;
3303 }
3304
3305 case ACT_HTTP_ADD_ACL: {
3306 struct pat_ref *ref;
3307 struct buffer *key;
3308
3309 /* collect reference */
3310 ref = pat_ref_lookup(rule->arg.map.ref);
3311 if (!ref)
3312 continue;
3313
3314 /* allocate key */
3315 key = alloc_trash_chunk();
3316 if (!key) {
3317 rule_ret = HTTP_RULE_RES_BADREQ;
3318 goto end;
3319 }
3320
3321 /* collect key */
3322 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3323 key->area[key->data] = '\0';
3324
3325 /* perform update */
3326 /* check if the entry already exists */
3327 if (pat_ref_find_elt(ref, key->area) == NULL)
3328 pat_ref_add(ref, key->area, NULL, NULL);
3329
3330 free_trash_chunk(key);
3331 break;
3332 }
3333
3334 case ACT_HTTP_SET_MAP: {
3335 struct pat_ref *ref;
3336 struct buffer *key, *value;
3337
3338 /* collect reference */
3339 ref = pat_ref_lookup(rule->arg.map.ref);
3340 if (!ref)
3341 continue;
3342
3343 /* allocate key */
3344 key = alloc_trash_chunk();
3345 if (!key) {
3346 rule_ret = HTTP_RULE_RES_BADREQ;
3347 goto end;
3348 }
3349
3350 /* allocate value */
3351 value = alloc_trash_chunk();
3352 if (!value) {
3353 free_trash_chunk(key);
3354 rule_ret = HTTP_RULE_RES_BADREQ;
3355 goto end;
3356 }
3357
3358 /* collect key */
3359 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3360 key->area[key->data] = '\0';
3361
3362 /* collect value */
3363 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3364 value->area[value->data] = '\0';
3365
3366 /* perform update */
3367 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3368 if (pat_ref_find_elt(ref, key->area) != NULL)
3369 /* update entry if it exists */
3370 pat_ref_set(ref, key->area, value->area, NULL);
3371 else
3372 /* insert a new entry */
3373 pat_ref_add(ref, key->area, value->area, NULL);
3374 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3375 free_trash_chunk(key);
3376 free_trash_chunk(value);
3377 break;
3378 }
3379
3380 case ACT_HTTP_REDIR:
3381 rule_ret = HTTP_RULE_RES_DONE;
3382 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3383 rule_ret = HTTP_RULE_RES_BADREQ;
3384 goto end;
3385
3386 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3387 /* Note: only the first valid tracking parameter of each
3388 * applies.
3389 */
3390 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3391 struct stktable *t;
3392 struct stksess *ts;
3393 struct stktable_key *key;
3394 void *ptr;
3395
3396 t = rule->arg.trk_ctr.table.t;
3397 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3398 rule->arg.trk_ctr.expr, NULL);
3399
3400 if (key && (ts = stktable_get_entry(t, key))) {
3401 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3402
3403 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3404
3405 /* let's count a new HTTP request as it's the first time we do it */
3406 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3407 if (ptr)
3408 stktable_data_cast(ptr, http_req_cnt)++;
3409
3410 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3411 if (ptr)
3412 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3413 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3414
3415 /* When the client triggers a 4xx from the server, it's most often due
3416 * to a missing object or permission. These events should be tracked
3417 * because if they happen often, it may indicate a brute force or a
3418 * vulnerability scan. Normally this is done when receiving the response
3419 * but here we're tracking after this ought to have been done so we have
3420 * to do it on purpose.
3421 */
3422 if ((unsigned)(txn->status - 400) < 100) {
3423 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3424 if (ptr)
3425 stktable_data_cast(ptr, http_err_cnt)++;
3426
3427 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3428 if (ptr)
3429 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3430 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3431 }
3432
3433 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3434
3435 /* If data was modified, we need to touch to re-schedule sync */
3436 stktable_touch_local(t, ts, 0);
3437
3438 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3439 if (sess->fe != s->be)
3440 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3441 }
3442 }
3443 break;
3444
3445 case ACT_CUSTOM:
3446 if ((s->req.flags & CF_READ_ERROR) ||
3447 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3448 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3449 (px->options & PR_O_ABRT_CLOSE)))
3450 act_flags |= ACT_FLAG_FINAL;
3451
3452 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3453 case ACT_RET_ERR:
3454 case ACT_RET_CONT:
3455 break;
3456 case ACT_RET_STOP:
3457 rule_ret = HTTP_RULE_RES_STOP;
3458 goto end;
3459 case ACT_RET_YIELD:
3460 s->current_rule = rule;
3461 rule_ret = HTTP_RULE_RES_YIELD;
3462 goto end;
3463 }
3464 break;
3465
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003466 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003467 default:
3468 break;
3469 }
3470 }
3471
3472 end:
3473 /* we reached the end of the rules, nothing to report */
3474 return rule_ret;
3475}
3476
Christopher Faulet33640082018-10-24 11:53:01 +02003477/* Iterate the same filter through all request headers.
3478 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3479 * Since it can manage the switch to another backend, it updates the per-proxy
3480 * DENY stats.
3481 */
3482static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3483{
3484 struct http_txn *txn = s->txn;
3485 struct htx *htx;
3486 struct buffer *hdr = get_trash_chunk();
3487 int32_t pos;
3488
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003489 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003490
3491 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3492 struct htx_blk *blk = htx_get_blk(htx, pos);
3493 enum htx_blk_type type;
3494 struct ist n, v;
3495
3496 next_hdr:
3497 type = htx_get_blk_type(blk);
3498 if (type == HTX_BLK_EOH)
3499 break;
3500 if (type != HTX_BLK_HDR)
3501 continue;
3502
3503 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3504 return 1;
3505 else if (unlikely(txn->flags & TX_CLALLOW) &&
3506 (exp->action == ACT_ALLOW ||
3507 exp->action == ACT_DENY ||
3508 exp->action == ACT_TARPIT))
3509 return 0;
3510
3511 n = htx_get_blk_name(htx, blk);
3512 v = htx_get_blk_value(htx, blk);
3513
3514 chunk_memcat(hdr, n.ptr, n.len);
3515 hdr->area[hdr->data++] = ':';
3516 hdr->area[hdr->data++] = ' ';
3517 chunk_memcat(hdr, v.ptr, v.len);
3518
3519 /* Now we have one header in <hdr> */
3520
3521 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3522 struct http_hdr_ctx ctx;
3523 int len;
3524
3525 switch (exp->action) {
3526 case ACT_ALLOW:
3527 txn->flags |= TX_CLALLOW;
3528 goto end;
3529
3530 case ACT_DENY:
3531 txn->flags |= TX_CLDENY;
3532 goto end;
3533
3534 case ACT_TARPIT:
3535 txn->flags |= TX_CLTARPIT;
3536 goto end;
3537
3538 case ACT_REPLACE:
3539 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3540 if (len < 0)
3541 return -1;
3542
3543 http_parse_header(ist2(trash.area, len), &n, &v);
3544 ctx.blk = blk;
3545 ctx.value = v;
3546 if (!http_replace_header(htx, &ctx, n, v))
3547 return -1;
3548 if (!ctx.blk)
3549 goto end;
3550 pos = htx_get_blk_pos(htx, blk);
3551 break;
3552
3553 case ACT_REMOVE:
3554 ctx.blk = blk;
3555 ctx.value = v;
3556 if (!http_remove_header(htx, &ctx))
3557 return -1;
3558 if (!ctx.blk)
3559 goto end;
3560 pos = htx_get_blk_pos(htx, blk);
3561 goto next_hdr;
3562
3563 }
3564 }
3565 }
3566 end:
3567 return 0;
3568}
3569
3570/* Apply the filter to the request line.
3571 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3572 * or -1 if a replacement resulted in an invalid request line.
3573 * Since it can manage the switch to another backend, it updates the per-proxy
3574 * DENY stats.
3575 */
3576static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3577{
3578 struct http_txn *txn = s->txn;
3579 struct htx *htx;
3580 struct buffer *reqline = get_trash_chunk();
3581 int done;
3582
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003583 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003584
3585 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3586 return 1;
3587 else if (unlikely(txn->flags & TX_CLALLOW) &&
3588 (exp->action == ACT_ALLOW ||
3589 exp->action == ACT_DENY ||
3590 exp->action == ACT_TARPIT))
3591 return 0;
3592 else if (exp->action == ACT_REMOVE)
3593 return 0;
3594
3595 done = 0;
3596
3597 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3598
3599 /* Now we have the request line between cur_ptr and cur_end */
3600 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003601 struct htx_sl *sl = http_find_stline(htx);
3602 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003603 int len;
3604
3605 switch (exp->action) {
3606 case ACT_ALLOW:
3607 txn->flags |= TX_CLALLOW;
3608 done = 1;
3609 break;
3610
3611 case ACT_DENY:
3612 txn->flags |= TX_CLDENY;
3613 done = 1;
3614 break;
3615
3616 case ACT_TARPIT:
3617 txn->flags |= TX_CLTARPIT;
3618 done = 1;
3619 break;
3620
3621 case ACT_REPLACE:
3622 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3623 if (len < 0)
3624 return -1;
3625
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003626 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3627 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3628 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003629 return -1;
3630 done = 1;
3631 break;
3632 }
3633 }
3634 return done;
3635}
3636
3637/*
3638 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3639 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3640 * unparsable request. Since it can manage the switch to another backend, it
3641 * updates the per-proxy DENY stats.
3642 */
3643static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3644{
3645 struct session *sess = s->sess;
3646 struct http_txn *txn = s->txn;
3647 struct hdr_exp *exp;
3648
3649 for (exp = px->req_exp; exp; exp = exp->next) {
3650 int ret;
3651
3652 /*
3653 * The interleaving of transformations and verdicts
3654 * makes it difficult to decide to continue or stop
3655 * the evaluation.
3656 */
3657
3658 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3659 break;
3660
3661 if ((txn->flags & TX_CLALLOW) &&
3662 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3663 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3664 continue;
3665
3666 /* if this filter had a condition, evaluate it now and skip to
3667 * next filter if the condition does not match.
3668 */
3669 if (exp->cond) {
3670 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3671 ret = acl_pass(ret);
3672 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3673 ret = !ret;
3674
3675 if (!ret)
3676 continue;
3677 }
3678
3679 /* Apply the filter to the request line. */
3680 ret = htx_apply_filter_to_req_line(s, req, exp);
3681 if (unlikely(ret < 0))
3682 return -1;
3683
3684 if (likely(ret == 0)) {
3685 /* The filter did not match the request, it can be
3686 * iterated through all headers.
3687 */
3688 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3689 return -1;
3690 }
3691 }
3692 return 0;
3693}
3694
3695/* Iterate the same filter through all response headers contained in <res>.
3696 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3697 */
3698static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3699{
3700 struct http_txn *txn = s->txn;
3701 struct htx *htx;
3702 struct buffer *hdr = get_trash_chunk();
3703 int32_t pos;
3704
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003705 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003706
3707 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3708 struct htx_blk *blk = htx_get_blk(htx, pos);
3709 enum htx_blk_type type;
3710 struct ist n, v;
3711
3712 next_hdr:
3713 type = htx_get_blk_type(blk);
3714 if (type == HTX_BLK_EOH)
3715 break;
3716 if (type != HTX_BLK_HDR)
3717 continue;
3718
3719 if (unlikely(txn->flags & TX_SVDENY))
3720 return 1;
3721 else if (unlikely(txn->flags & TX_SVALLOW) &&
3722 (exp->action == ACT_ALLOW ||
3723 exp->action == ACT_DENY))
3724 return 0;
3725
3726 n = htx_get_blk_name(htx, blk);
3727 v = htx_get_blk_value(htx, blk);
3728
3729 chunk_memcat(hdr, n.ptr, n.len);
3730 hdr->area[hdr->data++] = ':';
3731 hdr->area[hdr->data++] = ' ';
3732 chunk_memcat(hdr, v.ptr, v.len);
3733
3734 /* Now we have one header in <hdr> */
3735
3736 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3737 struct http_hdr_ctx ctx;
3738 int len;
3739
3740 switch (exp->action) {
3741 case ACT_ALLOW:
3742 txn->flags |= TX_SVALLOW;
3743 goto end;
3744 break;
3745
3746 case ACT_DENY:
3747 txn->flags |= TX_SVDENY;
3748 goto end;
3749 break;
3750
3751 case ACT_REPLACE:
3752 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3753 if (len < 0)
3754 return -1;
3755
3756 http_parse_header(ist2(trash.area, len), &n, &v);
3757 ctx.blk = blk;
3758 ctx.value = v;
3759 if (!http_replace_header(htx, &ctx, n, v))
3760 return -1;
3761 if (!ctx.blk)
3762 goto end;
3763 pos = htx_get_blk_pos(htx, blk);
3764 break;
3765
3766 case ACT_REMOVE:
3767 ctx.blk = blk;
3768 ctx.value = v;
3769 if (!http_remove_header(htx, &ctx))
3770 return -1;
3771 if (!ctx.blk)
3772 goto end;
3773 pos = htx_get_blk_pos(htx, blk);
3774 goto next_hdr;
3775 }
3776 }
3777
3778 }
3779 end:
3780 return 0;
3781}
3782
3783/* Apply the filter to the status line in the response buffer <res>.
3784 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3785 * or -1 if a replacement resulted in an invalid status line.
3786 */
3787static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3788{
3789 struct http_txn *txn = s->txn;
3790 struct htx *htx;
3791 struct buffer *resline = get_trash_chunk();
3792 int done;
3793
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003794 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003795
3796 if (unlikely(txn->flags & TX_SVDENY))
3797 return 1;
3798 else if (unlikely(txn->flags & TX_SVALLOW) &&
3799 (exp->action == ACT_ALLOW ||
3800 exp->action == ACT_DENY))
3801 return 0;
3802 else if (exp->action == ACT_REMOVE)
3803 return 0;
3804
3805 done = 0;
3806 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3807
3808 /* Now we have the status line between cur_ptr and cur_end */
3809 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003810 struct htx_sl *sl = http_find_stline(htx);
3811 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003812 int len;
3813
3814 switch (exp->action) {
3815 case ACT_ALLOW:
3816 txn->flags |= TX_SVALLOW;
3817 done = 1;
3818 break;
3819
3820 case ACT_DENY:
3821 txn->flags |= TX_SVDENY;
3822 done = 1;
3823 break;
3824
3825 case ACT_REPLACE:
3826 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3827 if (len < 0)
3828 return -1;
3829
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003830 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3831 sl->info.res.status = strl2ui(code.ptr, code.len);
3832 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003833 return -1;
3834
3835 done = 1;
3836 return 1;
3837 }
3838 }
3839 return done;
3840}
3841
3842/*
3843 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3844 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3845 * unparsable response.
3846 */
3847static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3848{
3849 struct session *sess = s->sess;
3850 struct http_txn *txn = s->txn;
3851 struct hdr_exp *exp;
3852
3853 for (exp = px->rsp_exp; exp; exp = exp->next) {
3854 int ret;
3855
3856 /*
3857 * The interleaving of transformations and verdicts
3858 * makes it difficult to decide to continue or stop
3859 * the evaluation.
3860 */
3861
3862 if (txn->flags & TX_SVDENY)
3863 break;
3864
3865 if ((txn->flags & TX_SVALLOW) &&
3866 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3867 exp->action == ACT_PASS)) {
3868 exp = exp->next;
3869 continue;
3870 }
3871
3872 /* if this filter had a condition, evaluate it now and skip to
3873 * next filter if the condition does not match.
3874 */
3875 if (exp->cond) {
3876 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3877 ret = acl_pass(ret);
3878 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3879 ret = !ret;
3880 if (!ret)
3881 continue;
3882 }
3883
3884 /* Apply the filter to the status line. */
3885 ret = htx_apply_filter_to_sts_line(s, res, exp);
3886 if (unlikely(ret < 0))
3887 return -1;
3888
3889 if (likely(ret == 0)) {
3890 /* The filter did not match the response, it can be
3891 * iterated through all headers.
3892 */
3893 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3894 return -1;
3895 }
3896 }
3897 return 0;
3898}
3899
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003900/*
3901 * Manage client-side cookie. It can impact performance by about 2% so it is
3902 * desirable to call it only when needed. This code is quite complex because
3903 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3904 * highly recommended not to touch this part without a good reason !
3905 */
3906static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3907{
3908 struct session *sess = s->sess;
3909 struct http_txn *txn = s->txn;
3910 struct htx *htx;
3911 struct http_hdr_ctx ctx;
3912 char *hdr_beg, *hdr_end, *del_from;
3913 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3914 int preserve_hdr;
3915
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003916 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003917 ctx.blk = NULL;
3918 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3919 del_from = NULL; /* nothing to be deleted */
3920 preserve_hdr = 0; /* assume we may kill the whole header */
3921
3922 /* Now look for cookies. Conforming to RFC2109, we have to support
3923 * attributes whose name begin with a '$', and associate them with
3924 * the right cookie, if we want to delete this cookie.
3925 * So there are 3 cases for each cookie read :
3926 * 1) it's a special attribute, beginning with a '$' : ignore it.
3927 * 2) it's a server id cookie that we *MAY* want to delete : save
3928 * some pointers on it (last semi-colon, beginning of cookie...)
3929 * 3) it's an application cookie : we *MAY* have to delete a previous
3930 * "special" cookie.
3931 * At the end of loop, if a "special" cookie remains, we may have to
3932 * remove it. If no application cookie persists in the header, we
3933 * *MUST* delete it.
3934 *
3935 * Note: RFC2965 is unclear about the processing of spaces around
3936 * the equal sign in the ATTR=VALUE form. A careful inspection of
3937 * the RFC explicitly allows spaces before it, and not within the
3938 * tokens (attrs or values). An inspection of RFC2109 allows that
3939 * too but section 10.1.3 lets one think that spaces may be allowed
3940 * after the equal sign too, resulting in some (rare) buggy
3941 * implementations trying to do that. So let's do what servers do.
3942 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3943 * allowed quoted strings in values, with any possible character
3944 * after a backslash, including control chars and delimitors, which
3945 * causes parsing to become ambiguous. Browsers also allow spaces
3946 * within values even without quotes.
3947 *
3948 * We have to keep multiple pointers in order to support cookie
3949 * removal at the beginning, middle or end of header without
3950 * corrupting the header. All of these headers are valid :
3951 *
3952 * hdr_beg hdr_end
3953 * | |
3954 * v |
3955 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3956 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3957 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3958 * | | | | | | |
3959 * | | | | | | |
3960 * | | | | | | +--> next
3961 * | | | | | +----> val_end
3962 * | | | | +-----------> val_beg
3963 * | | | +--------------> equal
3964 * | | +----------------> att_end
3965 * | +---------------------> att_beg
3966 * +--------------------------> prev
3967 *
3968 */
3969 hdr_beg = ctx.value.ptr;
3970 hdr_end = hdr_beg + ctx.value.len;
3971 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3972 /* Iterate through all cookies on this line */
3973
3974 /* find att_beg */
3975 att_beg = prev;
3976 if (prev > hdr_beg)
3977 att_beg++;
3978
3979 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3980 att_beg++;
3981
3982 /* find att_end : this is the first character after the last non
3983 * space before the equal. It may be equal to hdr_end.
3984 */
3985 equal = att_end = att_beg;
3986 while (equal < hdr_end) {
3987 if (*equal == '=' || *equal == ',' || *equal == ';')
3988 break;
3989 if (HTTP_IS_SPHT(*equal++))
3990 continue;
3991 att_end = equal;
3992 }
3993
3994 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3995 * is between <att_beg> and <equal>, both may be identical.
3996 */
3997 /* look for end of cookie if there is an equal sign */
3998 if (equal < hdr_end && *equal == '=') {
3999 /* look for the beginning of the value */
4000 val_beg = equal + 1;
4001 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4002 val_beg++;
4003
4004 /* find the end of the value, respecting quotes */
4005 next = http_find_cookie_value_end(val_beg, hdr_end);
4006
4007 /* make val_end point to the first white space or delimitor after the value */
4008 val_end = next;
4009 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4010 val_end--;
4011 }
4012 else
4013 val_beg = val_end = next = equal;
4014
4015 /* We have nothing to do with attributes beginning with
4016 * '$'. However, they will automatically be removed if a
4017 * header before them is removed, since they're supposed
4018 * to be linked together.
4019 */
4020 if (*att_beg == '$')
4021 continue;
4022
4023 /* Ignore cookies with no equal sign */
4024 if (equal == next) {
4025 /* This is not our cookie, so we must preserve it. But if we already
4026 * scheduled another cookie for removal, we cannot remove the
4027 * complete header, but we can remove the previous block itself.
4028 */
4029 preserve_hdr = 1;
4030 if (del_from != NULL) {
4031 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4032 val_end += delta;
4033 next += delta;
4034 hdr_end += delta;
4035 prev = del_from;
4036 del_from = NULL;
4037 }
4038 continue;
4039 }
4040
4041 /* if there are spaces around the equal sign, we need to
4042 * strip them otherwise we'll get trouble for cookie captures,
4043 * or even for rewrites. Since this happens extremely rarely,
4044 * it does not hurt performance.
4045 */
4046 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4047 int stripped_before = 0;
4048 int stripped_after = 0;
4049
4050 if (att_end != equal) {
4051 memmove(att_end, equal, hdr_end - equal);
4052 stripped_before = (att_end - equal);
4053 equal += stripped_before;
4054 val_beg += stripped_before;
4055 }
4056
4057 if (val_beg > equal + 1) {
4058 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4059 stripped_after = (equal + 1) - val_beg;
4060 val_beg += stripped_after;
4061 stripped_before += stripped_after;
4062 }
4063
4064 val_end += stripped_before;
4065 next += stripped_before;
4066 hdr_end += stripped_before;
4067 }
4068 /* now everything is as on the diagram above */
4069
4070 /* First, let's see if we want to capture this cookie. We check
4071 * that we don't already have a client side cookie, because we
4072 * can only capture one. Also as an optimisation, we ignore
4073 * cookies shorter than the declared name.
4074 */
4075 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4076 (val_end - att_beg >= sess->fe->capture_namelen) &&
4077 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4078 int log_len = val_end - att_beg;
4079
4080 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4081 ha_alert("HTTP logging : out of memory.\n");
4082 } else {
4083 if (log_len > sess->fe->capture_len)
4084 log_len = sess->fe->capture_len;
4085 memcpy(txn->cli_cookie, att_beg, log_len);
4086 txn->cli_cookie[log_len] = 0;
4087 }
4088 }
4089
4090 /* Persistence cookies in passive, rewrite or insert mode have the
4091 * following form :
4092 *
4093 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4094 *
4095 * For cookies in prefix mode, the form is :
4096 *
4097 * Cookie: NAME=SRV~VALUE
4098 */
4099 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4100 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4101 struct server *srv = s->be->srv;
4102 char *delim;
4103
4104 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4105 * have the server ID between val_beg and delim, and the original cookie between
4106 * delim+1 and val_end. Otherwise, delim==val_end :
4107 *
4108 * hdr_beg
4109 * |
4110 * v
4111 * NAME=SRV; # in all but prefix modes
4112 * NAME=SRV~OPAQUE ; # in prefix mode
4113 * || || | |+-> next
4114 * || || | +--> val_end
4115 * || || +---------> delim
4116 * || |+------------> val_beg
4117 * || +-------------> att_end = equal
4118 * |+-----------------> att_beg
4119 * +------------------> prev
4120 *
4121 */
4122 if (s->be->ck_opts & PR_CK_PFX) {
4123 for (delim = val_beg; delim < val_end; delim++)
4124 if (*delim == COOKIE_DELIM)
4125 break;
4126 }
4127 else {
4128 char *vbar1;
4129 delim = val_end;
4130 /* Now check if the cookie contains a date field, which would
4131 * appear after a vertical bar ('|') just after the server name
4132 * and before the delimiter.
4133 */
4134 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4135 if (vbar1) {
4136 /* OK, so left of the bar is the server's cookie and
4137 * right is the last seen date. It is a base64 encoded
4138 * 30-bit value representing the UNIX date since the
4139 * epoch in 4-second quantities.
4140 */
4141 int val;
4142 delim = vbar1++;
4143 if (val_end - vbar1 >= 5) {
4144 val = b64tos30(vbar1);
4145 if (val > 0)
4146 txn->cookie_last_date = val << 2;
4147 }
4148 /* look for a second vertical bar */
4149 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4150 if (vbar1 && (val_end - vbar1 > 5)) {
4151 val = b64tos30(vbar1 + 1);
4152 if (val > 0)
4153 txn->cookie_first_date = val << 2;
4154 }
4155 }
4156 }
4157
4158 /* if the cookie has an expiration date and the proxy wants to check
4159 * it, then we do that now. We first check if the cookie is too old,
4160 * then only if it has expired. We detect strict overflow because the
4161 * time resolution here is not great (4 seconds). Cookies with dates
4162 * in the future are ignored if their offset is beyond one day. This
4163 * allows an admin to fix timezone issues without expiring everyone
4164 * and at the same time avoids keeping unwanted side effects for too
4165 * long.
4166 */
4167 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4168 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4169 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4170 txn->flags &= ~TX_CK_MASK;
4171 txn->flags |= TX_CK_OLD;
4172 delim = val_beg; // let's pretend we have not found the cookie
4173 txn->cookie_first_date = 0;
4174 txn->cookie_last_date = 0;
4175 }
4176 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4177 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4178 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4179 txn->flags &= ~TX_CK_MASK;
4180 txn->flags |= TX_CK_EXPIRED;
4181 delim = val_beg; // let's pretend we have not found the cookie
4182 txn->cookie_first_date = 0;
4183 txn->cookie_last_date = 0;
4184 }
4185
4186 /* Here, we'll look for the first running server which supports the cookie.
4187 * This allows to share a same cookie between several servers, for example
4188 * to dedicate backup servers to specific servers only.
4189 * However, to prevent clients from sticking to cookie-less backup server
4190 * when they have incidentely learned an empty cookie, we simply ignore
4191 * empty cookies and mark them as invalid.
4192 * The same behaviour is applied when persistence must be ignored.
4193 */
4194 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4195 srv = NULL;
4196
4197 while (srv) {
4198 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4199 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4200 if ((srv->cur_state != SRV_ST_STOPPED) ||
4201 (s->be->options & PR_O_PERSIST) ||
4202 (s->flags & SF_FORCE_PRST)) {
4203 /* we found the server and we can use it */
4204 txn->flags &= ~TX_CK_MASK;
4205 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4206 s->flags |= SF_DIRECT | SF_ASSIGNED;
4207 s->target = &srv->obj_type;
4208 break;
4209 } else {
4210 /* we found a server, but it's down,
4211 * mark it as such and go on in case
4212 * another one is available.
4213 */
4214 txn->flags &= ~TX_CK_MASK;
4215 txn->flags |= TX_CK_DOWN;
4216 }
4217 }
4218 srv = srv->next;
4219 }
4220
4221 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4222 /* no server matched this cookie or we deliberately skipped it */
4223 txn->flags &= ~TX_CK_MASK;
4224 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4225 txn->flags |= TX_CK_UNUSED;
4226 else
4227 txn->flags |= TX_CK_INVALID;
4228 }
4229
4230 /* depending on the cookie mode, we may have to either :
4231 * - delete the complete cookie if we're in insert+indirect mode, so that
4232 * the server never sees it ;
4233 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004234 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004235 * if we're in cookie prefix mode
4236 */
4237 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4238 int delta; /* negative */
4239
4240 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4241 delta = val_beg - (delim + 1);
4242 val_end += delta;
4243 next += delta;
4244 hdr_end += delta;
4245 del_from = NULL;
4246 preserve_hdr = 1; /* we want to keep this cookie */
4247 }
4248 else if (del_from == NULL &&
4249 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4250 del_from = prev;
4251 }
4252 }
4253 else {
4254 /* This is not our cookie, so we must preserve it. But if we already
4255 * scheduled another cookie for removal, we cannot remove the
4256 * complete header, but we can remove the previous block itself.
4257 */
4258 preserve_hdr = 1;
4259
4260 if (del_from != NULL) {
4261 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4262 if (att_beg >= del_from)
4263 att_beg += delta;
4264 if (att_end >= del_from)
4265 att_end += delta;
4266 val_beg += delta;
4267 val_end += delta;
4268 next += delta;
4269 hdr_end += delta;
4270 prev = del_from;
4271 del_from = NULL;
4272 }
4273 }
4274
4275 /* continue with next cookie on this header line */
4276 att_beg = next;
4277 } /* for each cookie */
4278
4279
4280 /* There are no more cookies on this line.
4281 * We may still have one (or several) marked for deletion at the
4282 * end of the line. We must do this now in two ways :
4283 * - if some cookies must be preserved, we only delete from the
4284 * mark to the end of line ;
4285 * - if nothing needs to be preserved, simply delete the whole header
4286 */
4287 if (del_from) {
4288 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4289 }
4290 if ((hdr_end - hdr_beg) != ctx.value.len) {
4291 if (hdr_beg != hdr_end) {
4292 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4293 htx->data -= (hdr_end - ctx.value.ptr);
4294 }
4295 else
4296 http_remove_header(htx, &ctx);
4297 }
4298 } /* for each "Cookie header */
4299}
4300
4301/*
4302 * Manage server-side cookies. It can impact performance by about 2% so it is
4303 * desirable to call it only when needed. This function is also used when we
4304 * just need to know if there is a cookie (eg: for check-cache).
4305 */
4306static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4307{
4308 struct session *sess = s->sess;
4309 struct http_txn *txn = s->txn;
4310 struct htx *htx;
4311 struct http_hdr_ctx ctx;
4312 struct server *srv;
4313 char *hdr_beg, *hdr_end;
4314 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4315 int is_cookie2;
4316
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004317 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004318
4319 ctx.blk = NULL;
4320 while (1) {
4321 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4322 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4323 break;
4324 is_cookie2 = 1;
4325 }
4326
4327 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4328 * <prev> points to the colon.
4329 */
4330 txn->flags |= TX_SCK_PRESENT;
4331
4332 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4333 * check-cache is enabled) and we are not interested in checking
4334 * them. Warning, the cookie capture is declared in the frontend.
4335 */
4336 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4337 break;
4338
4339 /* OK so now we know we have to process this response cookie.
4340 * The format of the Set-Cookie header is slightly different
4341 * from the format of the Cookie header in that it does not
4342 * support the comma as a cookie delimiter (thus the header
4343 * cannot be folded) because the Expires attribute described in
4344 * the original Netscape's spec may contain an unquoted date
4345 * with a comma inside. We have to live with this because
4346 * many browsers don't support Max-Age and some browsers don't
4347 * support quoted strings. However the Set-Cookie2 header is
4348 * clean.
4349 *
4350 * We have to keep multiple pointers in order to support cookie
4351 * removal at the beginning, middle or end of header without
4352 * corrupting the header (in case of set-cookie2). A special
4353 * pointer, <scav> points to the beginning of the set-cookie-av
4354 * fields after the first semi-colon. The <next> pointer points
4355 * either to the end of line (set-cookie) or next unquoted comma
4356 * (set-cookie2). All of these headers are valid :
4357 *
4358 * hdr_beg hdr_end
4359 * | |
4360 * v |
4361 * NAME1 = VALUE 1 ; Secure; Path="/" |
4362 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4363 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4364 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4365 * | | | | | | | |
4366 * | | | | | | | +-> next
4367 * | | | | | | +------------> scav
4368 * | | | | | +--------------> val_end
4369 * | | | | +--------------------> val_beg
4370 * | | | +----------------------> equal
4371 * | | +------------------------> att_end
4372 * | +----------------------------> att_beg
4373 * +------------------------------> prev
4374 * -------------------------------> hdr_beg
4375 */
4376 hdr_beg = ctx.value.ptr;
4377 hdr_end = hdr_beg + ctx.value.len;
4378 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4379
4380 /* Iterate through all cookies on this line */
4381
4382 /* find att_beg */
4383 att_beg = prev;
4384 if (prev > hdr_beg)
4385 att_beg++;
4386
4387 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4388 att_beg++;
4389
4390 /* find att_end : this is the first character after the last non
4391 * space before the equal. It may be equal to hdr_end.
4392 */
4393 equal = att_end = att_beg;
4394
4395 while (equal < hdr_end) {
4396 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4397 break;
4398 if (HTTP_IS_SPHT(*equal++))
4399 continue;
4400 att_end = equal;
4401 }
4402
4403 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4404 * is between <att_beg> and <equal>, both may be identical.
4405 */
4406
4407 /* look for end of cookie if there is an equal sign */
4408 if (equal < hdr_end && *equal == '=') {
4409 /* look for the beginning of the value */
4410 val_beg = equal + 1;
4411 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4412 val_beg++;
4413
4414 /* find the end of the value, respecting quotes */
4415 next = http_find_cookie_value_end(val_beg, hdr_end);
4416
4417 /* make val_end point to the first white space or delimitor after the value */
4418 val_end = next;
4419 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4420 val_end--;
4421 }
4422 else {
4423 /* <equal> points to next comma, semi-colon or EOL */
4424 val_beg = val_end = next = equal;
4425 }
4426
4427 if (next < hdr_end) {
4428 /* Set-Cookie2 supports multiple cookies, and <next> points to
4429 * a colon or semi-colon before the end. So skip all attr-value
4430 * pairs and look for the next comma. For Set-Cookie, since
4431 * commas are permitted in values, skip to the end.
4432 */
4433 if (is_cookie2)
4434 next = http_find_hdr_value_end(next, hdr_end);
4435 else
4436 next = hdr_end;
4437 }
4438
4439 /* Now everything is as on the diagram above */
4440
4441 /* Ignore cookies with no equal sign */
4442 if (equal == val_end)
4443 continue;
4444
4445 /* If there are spaces around the equal sign, we need to
4446 * strip them otherwise we'll get trouble for cookie captures,
4447 * or even for rewrites. Since this happens extremely rarely,
4448 * it does not hurt performance.
4449 */
4450 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4451 int stripped_before = 0;
4452 int stripped_after = 0;
4453
4454 if (att_end != equal) {
4455 memmove(att_end, equal, hdr_end - equal);
4456 stripped_before = (att_end - equal);
4457 equal += stripped_before;
4458 val_beg += stripped_before;
4459 }
4460
4461 if (val_beg > equal + 1) {
4462 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4463 stripped_after = (equal + 1) - val_beg;
4464 val_beg += stripped_after;
4465 stripped_before += stripped_after;
4466 }
4467
4468 val_end += stripped_before;
4469 next += stripped_before;
4470 hdr_end += stripped_before;
4471
4472 ctx.value.len = hdr_end - hdr_beg;
4473 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4474 htx->data -= (hdr_end - ctx.value.ptr);
4475 }
4476
4477 /* First, let's see if we want to capture this cookie. We check
4478 * that we don't already have a server side cookie, because we
4479 * can only capture one. Also as an optimisation, we ignore
4480 * cookies shorter than the declared name.
4481 */
4482 if (sess->fe->capture_name != NULL &&
4483 txn->srv_cookie == NULL &&
4484 (val_end - att_beg >= sess->fe->capture_namelen) &&
4485 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4486 int log_len = val_end - att_beg;
4487 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4488 ha_alert("HTTP logging : out of memory.\n");
4489 }
4490 else {
4491 if (log_len > sess->fe->capture_len)
4492 log_len = sess->fe->capture_len;
4493 memcpy(txn->srv_cookie, att_beg, log_len);
4494 txn->srv_cookie[log_len] = 0;
4495 }
4496 }
4497
4498 srv = objt_server(s->target);
4499 /* now check if we need to process it for persistence */
4500 if (!(s->flags & SF_IGNORE_PRST) &&
4501 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4502 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4503 /* assume passive cookie by default */
4504 txn->flags &= ~TX_SCK_MASK;
4505 txn->flags |= TX_SCK_FOUND;
4506
4507 /* If the cookie is in insert mode on a known server, we'll delete
4508 * this occurrence because we'll insert another one later.
4509 * We'll delete it too if the "indirect" option is set and we're in
4510 * a direct access.
4511 */
4512 if (s->be->ck_opts & PR_CK_PSV) {
4513 /* The "preserve" flag was set, we don't want to touch the
4514 * server's cookie.
4515 */
4516 }
4517 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4518 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4519 /* this cookie must be deleted */
4520 if (prev == hdr_beg && next == hdr_end) {
4521 /* whole header */
4522 http_remove_header(htx, &ctx);
4523 /* note: while both invalid now, <next> and <hdr_end>
4524 * are still equal, so the for() will stop as expected.
4525 */
4526 } else {
4527 /* just remove the value */
4528 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4529 next = prev;
4530 hdr_end += delta;
4531 }
4532 txn->flags &= ~TX_SCK_MASK;
4533 txn->flags |= TX_SCK_DELETED;
4534 /* and go on with next cookie */
4535 }
4536 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4537 /* replace bytes val_beg->val_end with the cookie name associated
4538 * with this server since we know it.
4539 */
4540 int sliding, delta;
4541
4542 ctx.value = ist2(val_beg, val_end - val_beg);
4543 ctx.lws_before = ctx.lws_after = 0;
4544 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4545 delta = srv->cklen - (val_end - val_beg);
4546 sliding = (ctx.value.ptr - val_beg);
4547 hdr_beg += sliding;
4548 val_beg += sliding;
4549 next += sliding + delta;
4550 hdr_end += sliding + delta;
4551
4552 txn->flags &= ~TX_SCK_MASK;
4553 txn->flags |= TX_SCK_REPLACED;
4554 }
4555 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4556 /* insert the cookie name associated with this server
4557 * before existing cookie, and insert a delimiter between them..
4558 */
4559 int sliding, delta;
4560 ctx.value = ist2(val_beg, 0);
4561 ctx.lws_before = ctx.lws_after = 0;
4562 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4563 delta = srv->cklen + 1;
4564 sliding = (ctx.value.ptr - val_beg);
4565 hdr_beg += sliding;
4566 val_beg += sliding;
4567 next += sliding + delta;
4568 hdr_end += sliding + delta;
4569
4570 val_beg[srv->cklen] = COOKIE_DELIM;
4571 txn->flags &= ~TX_SCK_MASK;
4572 txn->flags |= TX_SCK_REPLACED;
4573 }
4574 }
4575 /* that's done for this cookie, check the next one on the same
4576 * line when next != hdr_end (only if is_cookie2).
4577 */
4578 }
4579 }
4580}
4581
Christopher Faulet25a02f62018-10-24 12:00:25 +02004582/*
4583 * Parses the Cache-Control and Pragma request header fields to determine if
4584 * the request may be served from the cache and/or if it is cacheable. Updates
4585 * s->txn->flags.
4586 */
4587void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4588{
4589 struct http_txn *txn = s->txn;
4590 struct htx *htx;
4591 int32_t pos;
4592 int pragma_found, cc_found, i;
4593
4594 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4595 return; /* nothing more to do here */
4596
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004597 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004598 pragma_found = cc_found = 0;
4599 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4600 struct htx_blk *blk = htx_get_blk(htx, pos);
4601 enum htx_blk_type type = htx_get_blk_type(blk);
4602 struct ist n, v;
4603
4604 if (type == HTX_BLK_EOH)
4605 break;
4606 if (type != HTX_BLK_HDR)
4607 continue;
4608
4609 n = htx_get_blk_name(htx, blk);
4610 v = htx_get_blk_value(htx, blk);
4611
4612 if (isteqi(n, ist("Pragma"))) {
4613 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4614 pragma_found = 1;
4615 continue;
4616 }
4617 }
4618
4619 /* Don't use the cache and don't try to store if we found the
4620 * Authorization header */
4621 if (isteqi(n, ist("Authorization"))) {
4622 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4623 txn->flags |= TX_CACHE_IGNORE;
4624 continue;
4625 }
4626
4627 if (!isteqi(n, ist("Cache-control")))
4628 continue;
4629
4630 /* OK, right now we know we have a cache-control header */
4631 cc_found = 1;
4632 if (!v.len) /* no info */
4633 continue;
4634
4635 i = 0;
4636 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4637 !isspace((unsigned char)*(v.ptr+i)))
4638 i++;
4639
4640 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4641 * values after max-age, max-stale nor min-fresh, we simply don't
4642 * use the cache when they're specified.
4643 */
4644 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4645 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4646 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4647 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4648 txn->flags |= TX_CACHE_IGNORE;
4649 continue;
4650 }
4651
4652 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4653 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4654 continue;
4655 }
4656 }
4657
4658 /* RFC7234#5.4:
4659 * When the Cache-Control header field is also present and
4660 * understood in a request, Pragma is ignored.
4661 * When the Cache-Control header field is not present in a
4662 * request, caches MUST consider the no-cache request
4663 * pragma-directive as having the same effect as if
4664 * "Cache-Control: no-cache" were present.
4665 */
4666 if (!cc_found && pragma_found)
4667 txn->flags |= TX_CACHE_IGNORE;
4668}
4669
4670/*
4671 * Check if response is cacheable or not. Updates s->txn->flags.
4672 */
4673void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4674{
4675 struct http_txn *txn = s->txn;
4676 struct htx *htx;
4677 int32_t pos;
4678 int i;
4679
4680 if (txn->status < 200) {
4681 /* do not try to cache interim responses! */
4682 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4683 return;
4684 }
4685
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004686 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004687 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4688 struct htx_blk *blk = htx_get_blk(htx, pos);
4689 enum htx_blk_type type = htx_get_blk_type(blk);
4690 struct ist n, v;
4691
4692 if (type == HTX_BLK_EOH)
4693 break;
4694 if (type != HTX_BLK_HDR)
4695 continue;
4696
4697 n = htx_get_blk_name(htx, blk);
4698 v = htx_get_blk_value(htx, blk);
4699
4700 if (isteqi(n, ist("Pragma"))) {
4701 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4702 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4703 return;
4704 }
4705 }
4706
4707 if (!isteqi(n, ist("Cache-control")))
4708 continue;
4709
4710 /* OK, right now we know we have a cache-control header */
4711 if (!v.len) /* no info */
4712 continue;
4713
4714 i = 0;
4715 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4716 !isspace((unsigned char)*(v.ptr+i)))
4717 i++;
4718
4719 /* we have a complete value between v.ptr and (v.ptr+i) */
4720 if (i < v.len && *(v.ptr + i) == '=') {
4721 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4722 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4723 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4724 continue;
4725 }
4726
4727 /* we have something of the form no-cache="set-cookie" */
4728 if ((v.len >= 21) &&
4729 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4730 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4731 txn->flags &= ~TX_CACHE_COOK;
4732 continue;
4733 }
4734
4735 /* OK, so we know that either p2 points to the end of string or to a comma */
4736 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4737 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4738 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4739 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4740 return;
4741 }
4742
4743 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4744 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4745 continue;
4746 }
4747 }
4748}
4749
Christopher Faulet64159df2018-10-24 21:15:35 +02004750/* send a server's name with an outgoing request over an established connection.
4751 * Note: this function is designed to be called once the request has been
4752 * scheduled for being forwarded. This is the reason why the number of forwarded
4753 * bytes have to be adjusted.
4754 */
4755int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4756{
4757 struct htx *htx;
4758 struct http_hdr_ctx ctx;
4759 struct ist hdr;
4760 uint32_t data;
4761
4762 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004763 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004764 data = htx->data;
4765
4766 ctx.blk = NULL;
4767 while (http_find_header(htx, hdr, &ctx, 1))
4768 http_remove_header(htx, &ctx);
4769 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4770
4771 if (co_data(&s->req)) {
4772 if (data >= htx->data)
4773 c_rew(&s->req, data - htx->data);
4774 else
4775 c_adv(&s->req, htx->data - data);
4776 }
4777 return 0;
4778}
4779
Christopher Faulet377c5a52018-10-24 21:21:30 +02004780/*
4781 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4782 * for the current backend.
4783 *
4784 * It is assumed that the request is either a HEAD, GET, or POST and that the
4785 * uri_auth field is valid.
4786 *
4787 * Returns 1 if stats should be provided, otherwise 0.
4788 */
4789static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4790{
4791 struct uri_auth *uri_auth = backend->uri_auth;
4792 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004793 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004794 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004795
4796 if (!uri_auth)
4797 return 0;
4798
4799 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4800 return 0;
4801
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004802 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004803 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004804 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004805
4806 /* check URI size */
4807 if (uri_auth->uri_len > uri.len)
4808 return 0;
4809
4810 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4811 return 0;
4812
4813 return 1;
4814}
4815
4816/* This function prepares an applet to handle the stats. It can deal with the
4817 * "100-continue" expectation, check that admin rules are met for POST requests,
4818 * and program a response message if something was unexpected. It cannot fail
4819 * and always relies on the stats applet to complete the job. It does not touch
4820 * analysers nor counters, which are left to the caller. It does not touch
4821 * s->target which is supposed to already point to the stats applet. The caller
4822 * is expected to have already assigned an appctx to the stream.
4823 */
4824static int htx_handle_stats(struct stream *s, struct channel *req)
4825{
4826 struct stats_admin_rule *stats_admin_rule;
4827 struct stream_interface *si = &s->si[1];
4828 struct session *sess = s->sess;
4829 struct http_txn *txn = s->txn;
4830 struct http_msg *msg = &txn->req;
4831 struct uri_auth *uri_auth = s->be->uri_auth;
4832 const char *h, *lookup, *end;
4833 struct appctx *appctx;
4834 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004835 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004836
4837 appctx = si_appctx(si);
4838 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4839 appctx->st1 = appctx->st2 = 0;
4840 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4841 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4842 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4843 appctx->ctx.stats.flags |= STAT_CHUNKED;
4844
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004845 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004846 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004847 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4848 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004849
4850 for (h = lookup; h <= end - 3; h++) {
4851 if (memcmp(h, ";up", 3) == 0) {
4852 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4853 break;
4854 }
4855 }
4856
4857 if (uri_auth->refresh) {
4858 for (h = lookup; h <= end - 10; h++) {
4859 if (memcmp(h, ";norefresh", 10) == 0) {
4860 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4861 break;
4862 }
4863 }
4864 }
4865
4866 for (h = lookup; h <= end - 4; h++) {
4867 if (memcmp(h, ";csv", 4) == 0) {
4868 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4869 break;
4870 }
4871 }
4872
4873 for (h = lookup; h <= end - 6; h++) {
4874 if (memcmp(h, ";typed", 6) == 0) {
4875 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4876 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4877 break;
4878 }
4879 }
4880
4881 for (h = lookup; h <= end - 8; h++) {
4882 if (memcmp(h, ";st=", 4) == 0) {
4883 int i;
4884 h += 4;
4885 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4886 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4887 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4888 appctx->ctx.stats.st_code = i;
4889 break;
4890 }
4891 }
4892 break;
4893 }
4894 }
4895
4896 appctx->ctx.stats.scope_str = 0;
4897 appctx->ctx.stats.scope_len = 0;
4898 for (h = lookup; h <= end - 8; h++) {
4899 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4900 int itx = 0;
4901 const char *h2;
4902 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4903 const char *err;
4904
4905 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4906 h2 = h;
4907 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4908 while (h <= end) {
4909 if (*h == ';' || *h == '&' || *h == ' ')
4910 break;
4911 itx++;
4912 h++;
4913 }
4914
4915 if (itx > STAT_SCOPE_TXT_MAXLEN)
4916 itx = STAT_SCOPE_TXT_MAXLEN;
4917 appctx->ctx.stats.scope_len = itx;
4918
4919 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4920 memcpy(scope_txt, h2, itx);
4921 scope_txt[itx] = '\0';
4922 err = invalid_char(scope_txt);
4923 if (err) {
4924 /* bad char in search text => clear scope */
4925 appctx->ctx.stats.scope_str = 0;
4926 appctx->ctx.stats.scope_len = 0;
4927 }
4928 break;
4929 }
4930 }
4931
4932 /* now check whether we have some admin rules for this request */
4933 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4934 int ret = 1;
4935
4936 if (stats_admin_rule->cond) {
4937 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4938 ret = acl_pass(ret);
4939 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4940 ret = !ret;
4941 }
4942
4943 if (ret) {
4944 /* no rule, or the rule matches */
4945 appctx->ctx.stats.flags |= STAT_ADMIN;
4946 break;
4947 }
4948 }
4949
4950 /* Was the status page requested with a POST ? */
4951 if (unlikely(txn->meth == HTTP_METH_POST)) {
4952 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4953 /* we'll need the request body, possibly after sending 100-continue */
4954 if (msg->msg_state < HTTP_MSG_DATA)
4955 req->analysers |= AN_REQ_HTTP_BODY;
4956 appctx->st0 = STAT_HTTP_POST;
4957 }
4958 else {
4959 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4960 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4961 appctx->st0 = STAT_HTTP_LAST;
4962 }
4963 }
4964 else {
4965 /* So it was another method (GET/HEAD) */
4966 appctx->st0 = STAT_HTTP_HEAD;
4967 }
4968
4969 s->task->nice = -32; /* small boost for HTTP statistics */
4970 return 1;
4971}
4972
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004973void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4974{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004975 struct channel *req = &s->req;
4976 struct channel *res = &s->res;
4977 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004978 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004979 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004980 struct ist path, location;
4981 unsigned int flags;
4982 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004983
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004984 /*
4985 * Create the location
4986 */
4987 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004988
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004989 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990 /* special prefix "/" means don't change URL */
4991 srv = __objt_server(s->target);
4992 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4993 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4994 return;
4995 }
4996
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004998 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004999 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005000 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005001 if (!path.ptr)
5002 return;
5003
5004 if (!chunk_memcat(&trash, path.ptr, path.len))
5005 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005006 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005007
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005008 /*
5009 * Create the 302 respone
5010 */
5011 htx = htx_from_buf(&res->buf);
5012 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5013 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5014 ist("HTTP/1.1"), ist("302"), ist("Found"));
5015 if (!sl)
5016 goto fail;
5017 sl->info.res.status = 302;
5018 s->txn->status = 302;
5019
5020 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5021 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5022 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5023 !htx_add_header(htx, ist("Location"), location))
5024 goto fail;
5025
5026 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5027 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 /*
5030 * Send the message
5031 */
5032 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005033 c_adv(res, data);
5034 res->total += data;
5035
5036 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005037 si_shutr(si);
5038 si_shutw(si);
5039 si->err_type = SI_ET_NONE;
5040 si->state = SI_ST_CLO;
5041
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005042 channel_auto_read(req);
5043 channel_abort(req);
5044 channel_auto_close(req);
5045 channel_erase(req);
5046 channel_auto_read(res);
5047 channel_auto_close(res);
5048
5049 if (!(s->flags & SF_ERR_MASK))
5050 s->flags |= SF_ERR_LOCAL;
5051 if (!(s->flags & SF_FINST_MASK))
5052 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005053
5054 /* FIXME: we should increase a counter of redirects per server and per backend. */
5055 srv_inc_sess_ctr(srv);
5056 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005057 return;
5058
5059 fail:
5060 /* If an error occurred, remove the incomplete HTTP response from the
5061 * buffer */
5062 channel_truncate(res);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005063}
5064
Christopher Fauletf2824e62018-10-01 12:12:37 +02005065/* This function terminates the request because it was completly analyzed or
5066 * because an error was triggered during the body forwarding.
5067 */
5068static void htx_end_request(struct stream *s)
5069{
5070 struct channel *chn = &s->req;
5071 struct http_txn *txn = s->txn;
5072
5073 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5074 now_ms, __FUNCTION__, s,
5075 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5076 s->req.analysers, s->res.analysers);
5077
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005078 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5079 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005080 channel_abort(chn);
5081 channel_truncate(chn);
5082 goto end;
5083 }
5084
5085 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5086 return;
5087
5088 if (txn->req.msg_state == HTTP_MSG_DONE) {
5089 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5090 /* The server has not finished to respond, so we
5091 * don't want to move in order not to upset it.
5092 */
5093 return;
5094 }
5095
5096 /* No need to read anymore, the request was completely parsed.
5097 * We can shut the read side unless we want to abort_on_close,
5098 * or we have a POST request. The issue with POST requests is
5099 * that some browsers still send a CRLF after the request, and
5100 * this CRLF must be read so that it does not remain in the kernel
5101 * buffers, otherwise a close could cause an RST on some systems
5102 * (eg: Linux).
5103 */
5104 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5105 txn->meth != HTTP_METH_POST)
5106 channel_dont_read(chn);
5107
5108 /* if the server closes the connection, we want to immediately react
5109 * and close the socket to save packets and syscalls.
5110 */
5111 s->si[1].flags |= SI_FL_NOHALF;
5112
5113 /* In any case we've finished parsing the request so we must
5114 * disable Nagle when sending data because 1) we're not going
5115 * to shut this side, and 2) the server is waiting for us to
5116 * send pending data.
5117 */
5118 chn->flags |= CF_NEVER_WAIT;
5119
5120 /* When we get here, it means that both the request and the
5121 * response have finished receiving. Depending on the connection
5122 * mode, we'll have to wait for the last bytes to leave in either
5123 * direction, and sometimes for a close to be effective.
5124 */
5125 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5126 /* Tunnel mode will not have any analyser so it needs to
5127 * poll for reads.
5128 */
5129 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005130 if (b_data(&chn->buf))
5131 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005132 txn->req.msg_state = HTTP_MSG_TUNNEL;
5133 }
5134 else {
5135 /* we're not expecting any new data to come for this
5136 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005137 *
5138 * However, there is an exception if the response
5139 * length is undefined. In this case, we need to wait
5140 * the close from the server. The response will be
5141 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005142 */
5143 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5144 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005145 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005146
5147 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5148 channel_shutr_now(chn);
5149 channel_shutw_now(chn);
5150 }
5151 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005152 goto check_channel_flags;
5153 }
5154
5155 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5156 http_msg_closing:
5157 /* nothing else to forward, just waiting for the output buffer
5158 * to be empty and for the shutw_now to take effect.
5159 */
5160 if (channel_is_empty(chn)) {
5161 txn->req.msg_state = HTTP_MSG_CLOSED;
5162 goto http_msg_closed;
5163 }
5164 else if (chn->flags & CF_SHUTW) {
5165 txn->req.err_state = txn->req.msg_state;
5166 txn->req.msg_state = HTTP_MSG_ERROR;
5167 goto end;
5168 }
5169 return;
5170 }
5171
5172 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5173 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005174 /* if we don't know whether the server will close, we need to hard close */
5175 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5176 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005177 /* see above in MSG_DONE why we only do this in these states */
5178 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5179 channel_dont_read(chn);
5180 goto end;
5181 }
5182
5183 check_channel_flags:
5184 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5185 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5186 /* if we've just closed an output, let's switch */
5187 txn->req.msg_state = HTTP_MSG_CLOSING;
5188 goto http_msg_closing;
5189 }
5190
5191 end:
5192 chn->analysers &= AN_REQ_FLT_END;
5193 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5194 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5195 channel_auto_close(chn);
5196 channel_auto_read(chn);
5197}
5198
5199
5200/* This function terminates the response because it was completly analyzed or
5201 * because an error was triggered during the body forwarding.
5202 */
5203static void htx_end_response(struct stream *s)
5204{
5205 struct channel *chn = &s->res;
5206 struct http_txn *txn = s->txn;
5207
5208 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5209 now_ms, __FUNCTION__, s,
5210 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5211 s->req.analysers, s->res.analysers);
5212
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005213 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5214 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf3d48052018-12-04 16:23:54 +01005215 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005216 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005217 goto end;
5218 }
5219
5220 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5221 return;
5222
5223 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5224 /* In theory, we don't need to read anymore, but we must
5225 * still monitor the server connection for a possible close
5226 * while the request is being uploaded, so we don't disable
5227 * reading.
5228 */
5229 /* channel_dont_read(chn); */
5230
5231 if (txn->req.msg_state < HTTP_MSG_DONE) {
5232 /* The client seems to still be sending data, probably
5233 * because we got an error response during an upload.
5234 * We have the choice of either breaking the connection
5235 * or letting it pass through. Let's do the later.
5236 */
5237 return;
5238 }
5239
5240 /* When we get here, it means that both the request and the
5241 * response have finished receiving. Depending on the connection
5242 * mode, we'll have to wait for the last bytes to leave in either
5243 * direction, and sometimes for a close to be effective.
5244 */
5245 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5246 channel_auto_read(chn);
5247 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005248 if (b_data(&chn->buf))
5249 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005250 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5251 }
5252 else {
5253 /* we're not expecting any new data to come for this
5254 * transaction, so we can close it.
5255 */
5256 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5257 channel_shutr_now(chn);
5258 channel_shutw_now(chn);
5259 }
5260 }
5261 goto check_channel_flags;
5262 }
5263
5264 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5265 http_msg_closing:
5266 /* nothing else to forward, just waiting for the output buffer
5267 * to be empty and for the shutw_now to take effect.
5268 */
5269 if (channel_is_empty(chn)) {
5270 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5271 goto http_msg_closed;
5272 }
5273 else if (chn->flags & CF_SHUTW) {
5274 txn->rsp.err_state = txn->rsp.msg_state;
5275 txn->rsp.msg_state = HTTP_MSG_ERROR;
5276 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5277 if (objt_server(s->target))
5278 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5279 goto end;
5280 }
5281 return;
5282 }
5283
5284 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5285 http_msg_closed:
5286 /* drop any pending data */
Christopher Fauletf3d48052018-12-04 16:23:54 +01005287 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005288 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005289 goto end;
5290 }
5291
5292 check_channel_flags:
5293 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5294 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5295 /* if we've just closed an output, let's switch */
5296 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5297 goto http_msg_closing;
5298 }
5299
5300 end:
5301 chn->analysers &= AN_RES_FLT_END;
5302 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5303 chn->analysers |= AN_RES_FLT_XFER_DATA;
5304 channel_auto_close(chn);
5305 channel_auto_read(chn);
5306}
5307
Christopher Faulet0f226952018-10-22 09:29:56 +02005308void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5309 int finst, const struct buffer *msg)
5310{
5311 channel_auto_read(si_oc(si));
5312 channel_abort(si_oc(si));
5313 channel_auto_close(si_oc(si));
5314 channel_erase(si_oc(si));
5315 channel_auto_close(si_ic(si));
5316 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005317
5318 /* <msg> is an HTX structure. So we copy it in the response's
5319 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005320 if (msg) {
5321 struct channel *chn = si_ic(si);
5322 struct htx *htx;
5323
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005324 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005325 chn->buf.data = msg->data;
5326 memcpy(chn->buf.area, msg->area, msg->data);
5327 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005328 c_adv(chn, htx->data);
5329 chn->total += htx->data;
5330 }
5331 if (!(s->flags & SF_ERR_MASK))
5332 s->flags |= err;
5333 if (!(s->flags & SF_FINST_MASK))
5334 s->flags |= finst;
5335}
5336
5337void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5338{
5339 channel_auto_read(&s->req);
5340 channel_abort(&s->req);
5341 channel_auto_close(&s->req);
5342 channel_erase(&s->req);
5343 channel_truncate(&s->res);
5344
5345 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005346
5347 /* <msg> is an HTX structure. So we copy it in the response's
5348 * channel */
5349 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005350 if (msg) {
5351 struct channel *chn = &s->res;
5352 struct htx *htx;
5353
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005354 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005355 chn->buf.data = msg->data;
5356 memcpy(chn->buf.area, msg->area, msg->data);
5357 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005358 c_adv(chn, htx->data);
5359 chn->total += htx->data;
5360 }
5361
5362 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5363 channel_auto_read(&s->res);
5364 channel_auto_close(&s->res);
5365 channel_shutr_now(&s->res);
5366}
5367
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005368struct buffer *htx_error_message(struct stream *s)
5369{
5370 const int msgnum = http_get_status_idx(s->txn->status);
5371
5372 if (s->be->errmsg[msgnum].area)
5373 return &s->be->errmsg[msgnum];
5374 else if (strm_fe(s)->errmsg[msgnum].area)
5375 return &strm_fe(s)->errmsg[msgnum];
5376 else
5377 return &htx_err_chunks[msgnum];
5378}
5379
5380
Christopher Faulet23a3c792018-11-28 10:01:23 +01005381/* Send a 100-Continue response to the client. It returns 0 on success and -1
5382 * on error. The response channel is updated accordingly.
5383 */
5384static int htx_reply_100_continue(struct stream *s)
5385{
5386 struct channel *res = &s->res;
5387 struct htx *htx = htx_from_buf(&res->buf);
5388 struct htx_sl *sl;
5389 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5390 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5391 size_t data;
5392
5393 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5394 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5395 if (!sl)
5396 goto fail;
5397 sl->info.res.status = 100;
5398
5399 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5400 goto fail;
5401
5402 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005403 c_adv(res, data);
5404 res->total += data;
5405 return 0;
5406
5407 fail:
5408 /* If an error occurred, remove the incomplete HTTP response from the
5409 * buffer */
5410 channel_truncate(res);
5411 return -1;
5412}
5413
Christopher Faulet12c51e22018-11-28 15:59:42 +01005414
5415/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5416 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5417 * error. The response channel is updated accordingly.
5418 */
5419static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5420{
5421 struct channel *res = &s->res;
5422 struct htx *htx = htx_from_buf(&res->buf);
5423 struct htx_sl *sl;
5424 struct ist code, body;
5425 int status;
5426 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5427 size_t data;
5428
5429 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5430 status = 401;
5431 code = ist("401");
5432 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5433 "You need a valid user and password to access this content.\n"
5434 "</body></html>\n");
5435 }
5436 else {
5437 status = 407;
5438 code = ist("407");
5439 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5440 "You need a valid user and password to access this content.\n"
5441 "</body></html>\n");
5442 }
5443
5444 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5445 ist("HTTP/1.1"), code, ist("Unauthorized"));
5446 if (!sl)
5447 goto fail;
5448 sl->info.res.status = status;
5449 s->txn->status = status;
5450
5451 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5452 goto fail;
5453
5454 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5455 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5456 !htx_add_header(htx, ist("Content-Type"), ist("text/html")) ||
5457 !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
5458 goto fail;
5459
5460 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5461 goto fail;
5462
5463 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005464 c_adv(res, data);
5465 res->total += data;
5466
5467 channel_auto_read(&s->req);
5468 channel_abort(&s->req);
5469 channel_auto_close(&s->req);
5470 channel_erase(&s->req);
5471
5472 res->wex = tick_add_ifset(now_ms, res->wto);
5473 channel_auto_read(res);
5474 channel_auto_close(res);
5475 channel_shutr_now(res);
5476 return 0;
5477
5478 fail:
5479 /* If an error occurred, remove the incomplete HTTP response from the
5480 * buffer */
5481 channel_truncate(res);
5482 return -1;
5483}
5484
Christopher Faulet0f226952018-10-22 09:29:56 +02005485/*
5486 * Capture headers from message <htx> according to header list <cap_hdr>, and
5487 * fill the <cap> pointers appropriately.
5488 */
5489static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5490{
5491 struct cap_hdr *h;
5492 int32_t pos;
5493
5494 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5495 struct htx_blk *blk = htx_get_blk(htx, pos);
5496 enum htx_blk_type type = htx_get_blk_type(blk);
5497 struct ist n, v;
5498
5499 if (type == HTX_BLK_EOH)
5500 break;
5501 if (type != HTX_BLK_HDR)
5502 continue;
5503
5504 n = htx_get_blk_name(htx, blk);
5505
5506 for (h = cap_hdr; h; h = h->next) {
5507 if (h->namelen && (h->namelen == n.len) &&
5508 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5509 if (cap[h->index] == NULL)
5510 cap[h->index] =
5511 pool_alloc(h->pool);
5512
5513 if (cap[h->index] == NULL) {
5514 ha_alert("HTTP capture : out of memory.\n");
5515 break;
5516 }
5517
5518 v = htx_get_blk_value(htx, blk);
5519 if (v.len > h->len)
5520 v.len = h->len;
5521
5522 memcpy(cap[h->index], v.ptr, v.len);
5523 cap[h->index][v.len]=0;
5524 }
5525 }
5526 }
5527}
5528
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005529/* Delete a value in a header between delimiters <from> and <next>. The header
5530 * itself is delimited by <start> and <end> pointers. The number of characters
5531 * displaced is returned, and the pointer to the first delimiter is updated if
5532 * required. The function tries as much as possible to respect the following
5533 * principles :
5534 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5535 * in which case <next> is simply removed
5536 * - set exactly one space character after the new first delimiter, unless there
5537 * are not enough characters in the block being moved to do so.
5538 * - remove unneeded spaces before the previous delimiter and after the new
5539 * one.
5540 *
5541 * It is the caller's responsibility to ensure that :
5542 * - <from> points to a valid delimiter or <start> ;
5543 * - <next> points to a valid delimiter or <end> ;
5544 * - there are non-space chars before <from>.
5545 */
5546static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5547{
5548 char *prev = *from;
5549
5550 if (prev == start) {
5551 /* We're removing the first value. eat the semicolon, if <next>
5552 * is lower than <end> */
5553 if (next < end)
5554 next++;
5555
5556 while (next < end && HTTP_IS_SPHT(*next))
5557 next++;
5558 }
5559 else {
5560 /* Remove useless spaces before the old delimiter. */
5561 while (HTTP_IS_SPHT(*(prev-1)))
5562 prev--;
5563 *from = prev;
5564
5565 /* copy the delimiter and if possible a space if we're
5566 * not at the end of the line.
5567 */
5568 if (next < end) {
5569 *prev++ = *next++;
5570 if (prev + 1 < next)
5571 *prev++ = ' ';
5572 while (next < end && HTTP_IS_SPHT(*next))
5573 next++;
5574 }
5575 }
5576 memmove(prev, next, end - next);
5577 return (prev - next);
5578}
5579
Christopher Faulet0f226952018-10-22 09:29:56 +02005580
5581/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005582 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005583 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005584static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005585{
5586 struct ist dst = ist2(str, 0);
5587
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005588 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005589 goto end;
5590 if (dst.len + 1 > len)
5591 goto end;
5592 dst.ptr[dst.len++] = ' ';
5593
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005594 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005595 goto end;
5596 if (dst.len + 1 > len)
5597 goto end;
5598 dst.ptr[dst.len++] = ' ';
5599
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005600 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005601 end:
5602 return dst.len;
5603}
5604
Christopher Fauletf0523542018-10-24 11:06:58 +02005605/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005606 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005607 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005608static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005609{
5610 struct ist dst = ist2(str, 0);
5611
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005612 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005613 goto end;
5614 if (dst.len + 1 > len)
5615 goto end;
5616 dst.ptr[dst.len++] = ' ';
5617
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005618 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005619 goto end;
5620 if (dst.len + 1 > len)
5621 goto end;
5622 dst.ptr[dst.len++] = ' ';
5623
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005624 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005625 end:
5626 return dst.len;
5627}
5628
5629
Christopher Faulet0f226952018-10-22 09:29:56 +02005630/*
5631 * Print a debug line with a start line.
5632 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005634{
5635 struct session *sess = strm_sess(s);
5636 int max;
5637
5638 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5639 dir,
5640 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5641 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5642
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005645 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005646 trash.area[trash.data++] = ' ';
5647
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005648 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005649 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005650 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005651 trash.area[trash.data++] = ' ';
5652
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005653 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005654 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005655 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005656 trash.area[trash.data++] = '\n';
5657
5658 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5659}
5660
5661/*
5662 * Print a debug line with a header.
5663 */
5664static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5665{
5666 struct session *sess = strm_sess(s);
5667 int max;
5668
5669 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5670 dir,
5671 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5672 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5673
5674 max = n.len;
5675 UBOUND(max, trash.size - trash.data - 3);
5676 chunk_memcat(&trash, n.ptr, max);
5677 trash.area[trash.data++] = ':';
5678 trash.area[trash.data++] = ' ';
5679
5680 max = v.len;
5681 UBOUND(max, trash.size - trash.data - 1);
5682 chunk_memcat(&trash, v.ptr, max);
5683 trash.area[trash.data++] = '\n';
5684
5685 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5686}
5687
5688
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005689__attribute__((constructor))
5690static void __htx_protocol_init(void)
5691{
5692}
5693
5694
5695/*
5696 * Local variables:
5697 * c-indent-level: 8
5698 * c-basic-offset: 8
5699 * End:
5700 */