blob: e76d0bffc01a89eed41d8477ab04851b72a5473a [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 Faulet9768c262018-10-22 09:34:31 +020098 htx = htx_from_buf(&req->buf);
99
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 Fauletff2759f2018-10-24 11:13:16 +0200499 htx = htx_from_buf(&req->buf);
500
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 Fauletd7bdfb12018-10-24 11:14:34 +0200774 htx = htx_from_buf(&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
1060 htx = htx_from_buf(&req->buf);
1061
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 Faulet9768c262018-10-22 09:34:31 +02001181 htx = htx_from_buf(&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 */
1248 b_set_data(&req->buf, co_data(req));
1249 if (msg->flags & HTTP_MSGF_XFER_LEN)
1250 htx->extra -= channel_forward(req, htx->extra);
1251 b_set_data(&req->buf, b_size(&req->buf));
1252 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001253
Christopher Faulet9768c262018-10-22 09:34:31 +02001254 /* Check if the end-of-message is reached and if so, switch the message
1255 * in HTTP_MSG_DONE state.
1256 */
1257 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1258 goto missing_data_or_waiting;
1259
1260 msg->msg_state = HTTP_MSG_DONE;
1261
1262 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001263 /* other states, DONE...TUNNEL */
1264 /* we don't want to forward closes on DONE except in tunnel mode. */
1265 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1266 channel_dont_close(req);
1267
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001268 if (HAS_REQ_DATA_FILTERS(s)) {
1269 ret = flt_http_end(s, msg);
1270 if (ret <= 0) {
1271 if (!ret)
1272 goto missing_data_or_waiting;
1273 goto return_bad_req;
1274 }
1275 }
1276
Christopher Fauletf2824e62018-10-01 12:12:37 +02001277 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001279 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1281 if (req->flags & CF_SHUTW) {
1282 /* request errors are most likely due to the
1283 * server aborting the transfer. */
1284 goto aborted_xfer;
1285 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 goto return_bad_req;
1287 }
1288 return 1;
1289 }
1290
1291 /* If "option abortonclose" is set on the backend, we want to monitor
1292 * the client's connection and forward any shutdown notification to the
1293 * server, which will decide whether to close or to go on processing the
1294 * request. We only do that in tunnel mode, and not in other modes since
1295 * it can be abused to exhaust source ports. */
1296 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1297 channel_auto_read(req);
1298 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1299 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1300 s->si[1].flags |= SI_FL_NOLINGER;
1301 channel_auto_close(req);
1302 }
1303 else if (s->txn->meth == HTTP_METH_POST) {
1304 /* POST requests may require to read extra CRLF sent by broken
1305 * browsers and which could cause an RST to be sent upon close
1306 * on some systems (eg: Linux). */
1307 channel_auto_read(req);
1308 }
1309 return 0;
1310
1311 missing_data_or_waiting:
1312 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001313 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001314 if (!(s->flags & SF_ERR_MASK))
1315 s->flags |= SF_ERR_CLICL;
1316 if (!(s->flags & SF_FINST_MASK)) {
1317 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1318 s->flags |= SF_FINST_H;
1319 else
1320 s->flags |= SF_FINST_D;
1321 }
1322
1323 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1324 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1325 if (objt_server(s->target))
1326 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1327
1328 goto return_bad_req_stats_ok;
1329 }
1330
1331 waiting:
1332 /* waiting for the last bits to leave the buffer */
1333 if (req->flags & CF_SHUTW)
1334 goto aborted_xfer;
1335
Christopher Faulet47365272018-10-31 17:40:50 +01001336 if (htx->flags & HTX_FL_PARSING_ERROR)
1337 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001338
Christopher Faulete0768eb2018-10-03 16:38:02 +02001339 /* When TE: chunked is used, we need to get there again to parse remaining
1340 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1341 * And when content-length is used, we never want to let the possible
1342 * shutdown be forwarded to the other side, as the state machine will
1343 * take care of it once the client responds. It's also important to
1344 * prevent TIME_WAITs from accumulating on the backend side, and for
1345 * HTTP/2 where the last frame comes with a shutdown.
1346 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001347 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001348 channel_dont_close(req);
1349
1350 /* We know that more data are expected, but we couldn't send more that
1351 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1352 * system knows it must not set a PUSH on this first part. Interactive
1353 * modes are already handled by the stream sock layer. We must not do
1354 * this in content-length mode because it could present the MSG_MORE
1355 * flag with the last block of forwarded data, which would cause an
1356 * additional delay to be observed by the receiver.
1357 */
1358 if (msg->flags & HTTP_MSGF_TE_CHNK)
1359 req->flags |= CF_EXPECT_MORE;
1360
1361 return 0;
1362
1363 return_bad_req: /* let's centralize all bad requests */
1364 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1365 if (sess->listener->counters)
1366 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1367
1368 return_bad_req_stats_ok:
1369 txn->req.err_state = txn->req.msg_state;
1370 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001371 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001373 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 } else {
1375 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001376 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 }
1378 req->analysers &= AN_REQ_FLT_END;
1379 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1380
1381 if (!(s->flags & SF_ERR_MASK))
1382 s->flags |= SF_ERR_PRXCOND;
1383 if (!(s->flags & SF_FINST_MASK)) {
1384 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1385 s->flags |= SF_FINST_H;
1386 else
1387 s->flags |= SF_FINST_D;
1388 }
1389 return 0;
1390
1391 aborted_xfer:
1392 txn->req.err_state = txn->req.msg_state;
1393 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001394 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001396 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001397 } else {
1398 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001399 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001400 }
1401 req->analysers &= AN_REQ_FLT_END;
1402 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1403
1404 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1405 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1406 if (objt_server(s->target))
1407 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1408
1409 if (!(s->flags & SF_ERR_MASK))
1410 s->flags |= SF_ERR_SRVCL;
1411 if (!(s->flags & SF_FINST_MASK)) {
1412 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1413 s->flags |= SF_FINST_H;
1414 else
1415 s->flags |= SF_FINST_D;
1416 }
1417 return 0;
1418}
1419
1420/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1421 * processing can continue on next analysers, or zero if it either needs more
1422 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1423 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1424 * when it has nothing left to do, and may remove any analyser when it wants to
1425 * abort.
1426 */
1427int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1428{
Christopher Faulet9768c262018-10-22 09:34:31 +02001429 /*
1430 * We will analyze a complete HTTP response to check the its syntax.
1431 *
1432 * Once the start line and all headers are received, we may perform a
1433 * capture of the error (if any), and we will set a few fields. We also
1434 * logging and finally headers capture.
1435 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001436 struct session *sess = s->sess;
1437 struct http_txn *txn = s->txn;
1438 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001439 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001440 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001441 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001442 int n;
1443
1444 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1445 now_ms, __FUNCTION__,
1446 s,
1447 rep,
1448 rep->rex, rep->wex,
1449 rep->flags,
1450 ci_data(rep),
1451 rep->analysers);
1452
Christopher Faulet9768c262018-10-22 09:34:31 +02001453 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454
1455 /*
1456 * Now we quickly check if we have found a full valid response.
1457 * If not so, we check the FD and buffer states before leaving.
1458 * A full response is indicated by the fact that we have seen
1459 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1460 * responses are checked first.
1461 *
1462 * Depending on whether the client is still there or not, we
1463 * may send an error response back or not. Note that normally
1464 * we should only check for HTTP status there, and check I/O
1465 * errors somewhere else.
1466 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001467 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001468 /*
1469 * First catch invalid response
1470 */
1471 if (htx->flags & HTX_FL_PARSING_ERROR)
1472 goto return_bad_res;
1473
Christopher Faulet9768c262018-10-22 09:34:31 +02001474 /* 1: have we encountered a read error ? */
1475 if (rep->flags & CF_READ_ERROR) {
1476 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477 goto abort_keep_alive;
1478
1479 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1480 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001481 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1482 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 }
1484
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485 rep->analysers &= AN_RES_FLT_END;
1486 txn->status = 502;
1487
1488 /* Check to see if the server refused the early data.
1489 * If so, just send a 425
1490 */
1491 if (objt_cs(s->si[1].end)) {
1492 struct connection *conn = objt_cs(s->si[1].end)->conn;
1493
1494 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1495 txn->status = 425;
1496 }
1497
1498 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001499 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500
1501 if (!(s->flags & SF_ERR_MASK))
1502 s->flags |= SF_ERR_SRVCL;
1503 if (!(s->flags & SF_FINST_MASK))
1504 s->flags |= SF_FINST_H;
1505 return 0;
1506 }
1507
Christopher Faulet9768c262018-10-22 09:34:31 +02001508 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1511 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001512 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1513 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 }
1515
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516 rep->analysers &= AN_RES_FLT_END;
1517 txn->status = 504;
1518 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001519 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520
1521 if (!(s->flags & SF_ERR_MASK))
1522 s->flags |= SF_ERR_SRVTO;
1523 if (!(s->flags & SF_FINST_MASK))
1524 s->flags |= SF_FINST_H;
1525 return 0;
1526 }
1527
Christopher Faulet9768c262018-10-22 09:34:31 +02001528 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1530 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1531 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1532 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001533 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534
1535 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_CLICL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543
1544 /* process_stream() will take care of the error */
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001550 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 goto abort_keep_alive;
1552
1553 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1554 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001555 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1556 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 }
1558
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 rep->analysers &= AN_RES_FLT_END;
1560 txn->status = 502;
1561 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001562 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563
1564 if (!(s->flags & SF_ERR_MASK))
1565 s->flags |= SF_ERR_SRVCL;
1566 if (!(s->flags & SF_FINST_MASK))
1567 s->flags |= SF_FINST_H;
1568 return 0;
1569 }
1570
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574 goto abort_keep_alive;
1575
1576 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1577 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578
1579 if (!(s->flags & SF_ERR_MASK))
1580 s->flags |= SF_ERR_CLICL;
1581 if (!(s->flags & SF_FINST_MASK))
1582 s->flags |= SF_FINST_H;
1583
1584 /* process_stream() will take care of the error */
1585 return 0;
1586 }
1587
1588 channel_dont_close(rep);
1589 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1590 return 0;
1591 }
1592
1593 /* More interesting part now : we know that we have a complete
1594 * response which at least looks like HTTP. We have an indicator
1595 * of each header's length, so we can parse them quickly.
1596 */
1597
Christopher Faulet9768c262018-10-22 09:34:31 +02001598 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001599 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 /* 0: we might have to print this header in debug mode */
1602 if (unlikely((global.mode & MODE_DEBUG) &&
1603 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1604 int32_t pos;
1605
Christopher Faulet03599112018-11-27 11:21:21 +01001606 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001607
1608 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1609 struct htx_blk *blk = htx_get_blk(htx, pos);
1610 enum htx_blk_type type = htx_get_blk_type(blk);
1611
1612 if (type == HTX_BLK_EOH)
1613 break;
1614 if (type != HTX_BLK_HDR)
1615 continue;
1616
1617 htx_debug_hdr("srvhdr", s,
1618 htx_get_blk_name(htx, blk),
1619 htx_get_blk_value(htx, blk));
1620 }
1621 }
1622
Christopher Faulet03599112018-11-27 11:21:21 +01001623 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001624 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001625 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001626 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001627 if (sl->flags & HTX_SL_F_XFER_LEN) {
1628 msg->flags |= HTTP_MSGF_XFER_LEN;
1629 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001630 if (sl->flags & HTX_SL_F_BODYLESS)
1631 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001632 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001633
1634 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 if (n < 1 || n > 5)
1636 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001637
Christopher Faulete0768eb2018-10-03 16:38:02 +02001638 /* when the client triggers a 4xx from the server, it's most often due
1639 * to a missing object or permission. These events should be tracked
1640 * because if they happen often, it may indicate a brute force or a
1641 * vulnerability scan.
1642 */
1643 if (n == 4)
1644 stream_inc_http_err_ctr(s);
1645
1646 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001647 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648
Christopher Faulete0768eb2018-10-03 16:38:02 +02001649 /* Adjust server's health based on status code. Note: status codes 501
1650 * and 505 are triggered on demand by client request, so we must not
1651 * count them as server failures.
1652 */
1653 if (objt_server(s->target)) {
1654 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001655 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001656 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001657 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001658 }
1659
1660 /*
1661 * We may be facing a 100-continue response, or any other informational
1662 * 1xx response which is non-final, in which case this is not the right
1663 * response, and we're waiting for the next one. Let's allow this response
1664 * to go to the client and wait for the next one. There's an exception for
1665 * 101 which is used later in the code to switch protocols.
1666 */
1667 if (txn->status < 200 &&
1668 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001669 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001670 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001671 msg->msg_state = HTTP_MSG_RPBEFORE;
1672 txn->status = 0;
1673 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001674 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675 }
1676
1677 /*
1678 * 2: check for cacheability.
1679 */
1680
1681 switch (txn->status) {
1682 case 200:
1683 case 203:
1684 case 204:
1685 case 206:
1686 case 300:
1687 case 301:
1688 case 404:
1689 case 405:
1690 case 410:
1691 case 414:
1692 case 501:
1693 break;
1694 default:
1695 /* RFC7231#6.1:
1696 * Responses with status codes that are defined as
1697 * cacheable by default (e.g., 200, 203, 204, 206,
1698 * 300, 301, 404, 405, 410, 414, and 501 in this
1699 * specification) can be reused by a cache with
1700 * heuristic expiration unless otherwise indicated
1701 * by the method definition or explicit cache
1702 * controls [RFC7234]; all other status codes are
1703 * not cacheable by default.
1704 */
1705 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1706 break;
1707 }
1708
1709 /*
1710 * 3: we may need to capture headers
1711 */
1712 s->logs.logwait &= ~LW_RESP;
1713 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001714 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715
Christopher Faulet9768c262018-10-22 09:34:31 +02001716 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1718 txn->status == 101)) {
1719 /* Either we've established an explicit tunnel, or we're
1720 * switching the protocol. In both cases, we're very unlikely
1721 * to understand the next protocols. We have to switch to tunnel
1722 * mode, so that we transfer the request and responses then let
1723 * this protocol pass unmodified. When we later implement specific
1724 * parsers for such protocols, we'll want to check the Upgrade
1725 * header which contains information about that protocol for
1726 * responses with status 101 (eg: see RFC2817 about TLS).
1727 */
1728 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001729 }
1730
Christopher Faulet61608322018-11-23 16:23:45 +01001731 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1732 * 407 (Proxy-Authenticate) responses and set the connection to private
1733 */
1734 srv_conn = cs_conn(objt_cs(s->si[1].end));
1735 if (srv_conn) {
1736 struct ist hdr;
1737 struct http_hdr_ctx ctx;
1738
1739 if (txn->status == 401)
1740 hdr = ist("WWW-Authenticate");
1741 else if (txn->status == 407)
1742 hdr = ist("Proxy-Authenticate");
1743 else
1744 goto end;
1745
1746 ctx.blk = NULL;
1747 while (http_find_header(htx, hdr, &ctx, 0)) {
1748 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1749 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1750 srv_conn->flags |= CO_FL_PRIVATE;
1751 }
1752 }
1753
1754 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001755 /* we want to have the response time before we start processing it */
1756 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1757
1758 /* end of job, return OK */
1759 rep->analysers &= ~an_bit;
1760 rep->analyse_exp = TICK_ETERNITY;
1761 channel_auto_close(rep);
1762 return 1;
1763
Christopher Faulet47365272018-10-31 17:40:50 +01001764 return_bad_res:
1765 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1766 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001767 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1768 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001769 }
1770 txn->status = 502;
1771 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001772 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001773 rep->analysers &= AN_RES_FLT_END;
1774
1775 if (!(s->flags & SF_ERR_MASK))
1776 s->flags |= SF_ERR_PRXCOND;
1777 if (!(s->flags & SF_FINST_MASK))
1778 s->flags |= SF_FINST_H;
1779 return 0;
1780
Christopher Faulete0768eb2018-10-03 16:38:02 +02001781 abort_keep_alive:
1782 /* A keep-alive request to the server failed on a network error.
1783 * The client is required to retry. We need to close without returning
1784 * any other information so that the client retries.
1785 */
1786 txn->status = 0;
1787 rep->analysers &= AN_RES_FLT_END;
1788 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001789 s->logs.logwait = 0;
1790 s->logs.level = 0;
1791 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001792 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001793 return 0;
1794}
1795
1796/* This function performs all the processing enabled for the current response.
1797 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1798 * and updates s->res.analysers. It might make sense to explode it into several
1799 * other functions. It works like process_request (see indications above).
1800 */
1801int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1802{
1803 struct session *sess = s->sess;
1804 struct http_txn *txn = s->txn;
1805 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001806 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001807 struct proxy *cur_proxy;
1808 struct cond_wordlist *wl;
1809 enum rule_result ret = HTTP_RULE_RES_CONT;
1810
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001811 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1812 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001813
Christopher Faulete0768eb2018-10-03 16:38:02 +02001814 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1815 now_ms, __FUNCTION__,
1816 s,
1817 rep,
1818 rep->rex, rep->wex,
1819 rep->flags,
1820 ci_data(rep),
1821 rep->analysers);
1822
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001823 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001824
1825 /* The stats applet needs to adjust the Connection header but we don't
1826 * apply any filter there.
1827 */
1828 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1829 rep->analysers &= ~an_bit;
1830 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001831 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001832 }
1833
1834 /*
1835 * We will have to evaluate the filters.
1836 * As opposed to version 1.2, now they will be evaluated in the
1837 * filters order and not in the header order. This means that
1838 * each filter has to be validated among all headers.
1839 *
1840 * Filters are tried with ->be first, then with ->fe if it is
1841 * different from ->be.
1842 *
1843 * Maybe we are in resume condiion. In this case I choose the
1844 * "struct proxy" which contains the rule list matching the resume
1845 * pointer. If none of theses "struct proxy" match, I initialise
1846 * the process with the first one.
1847 *
1848 * In fact, I check only correspondance betwwen the current list
1849 * pointer and the ->fe rule list. If it doesn't match, I initialize
1850 * the loop with the ->be.
1851 */
1852 if (s->current_rule_list == &sess->fe->http_res_rules)
1853 cur_proxy = sess->fe;
1854 else
1855 cur_proxy = s->be;
1856 while (1) {
1857 struct proxy *rule_set = cur_proxy;
1858
1859 /* evaluate http-response rules */
1860 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001861 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001862
1863 if (ret == HTTP_RULE_RES_BADREQ)
1864 goto return_srv_prx_502;
1865
1866 if (ret == HTTP_RULE_RES_DONE) {
1867 rep->analysers &= ~an_bit;
1868 rep->analyse_exp = TICK_ETERNITY;
1869 return 1;
1870 }
1871 }
1872
1873 /* we need to be called again. */
1874 if (ret == HTTP_RULE_RES_YIELD) {
1875 channel_dont_close(rep);
1876 return 0;
1877 }
1878
1879 /* try headers filters */
1880 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001881 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1882 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001883 }
1884
1885 /* has the response been denied ? */
1886 if (txn->flags & TX_SVDENY) {
1887 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001888 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001889
1890 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1891 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1892 if (sess->listener->counters)
1893 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001894 goto return_srv_prx_502;
1895 }
1896
1897 /* add response headers from the rule sets in the same order */
1898 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001899 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001900 if (txn->status < 200 && txn->status != 101)
1901 break;
1902 if (wl->cond) {
1903 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1904 ret = acl_pass(ret);
1905 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1906 ret = !ret;
1907 if (!ret)
1908 continue;
1909 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001910
1911 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1912 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001913 goto return_bad_resp;
1914 }
1915
1916 /* check whether we're already working on the frontend */
1917 if (cur_proxy == sess->fe)
1918 break;
1919 cur_proxy = sess->fe;
1920 }
1921
1922 /* After this point, this anayzer can't return yield, so we can
1923 * remove the bit corresponding to this analyzer from the list.
1924 *
1925 * Note that the intermediate returns and goto found previously
1926 * reset the analyzers.
1927 */
1928 rep->analysers &= ~an_bit;
1929 rep->analyse_exp = TICK_ETERNITY;
1930
1931 /* OK that's all we can do for 1xx responses */
1932 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001933 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001934
1935 /*
1936 * Now check for a server cookie.
1937 */
1938 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001939 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001940
1941 /*
1942 * Check for cache-control or pragma headers if required.
1943 */
1944 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1945 check_response_for_cacheability(s, rep);
1946
1947 /*
1948 * Add server cookie in the response if needed
1949 */
1950 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1951 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1952 (!(s->flags & SF_DIRECT) ||
1953 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1954 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1955 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1956 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1957 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1958 !(s->flags & SF_IGNORE_PRST)) {
1959 /* the server is known, it's not the one the client requested, or the
1960 * cookie's last seen date needs to be refreshed. We have to
1961 * insert a set-cookie here, except if we want to insert only on POST
1962 * requests and this one isn't. Note that servers which don't have cookies
1963 * (eg: some backup servers) will return a full cookie removal request.
1964 */
1965 if (!objt_server(s->target)->cookie) {
1966 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001967 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968 s->be->cookie_name);
1969 }
1970 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001971 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001972
1973 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1974 /* emit last_date, which is mandatory */
1975 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1976 s30tob64((date.tv_sec+3) >> 2,
1977 trash.area + trash.data);
1978 trash.data += 5;
1979
1980 if (s->be->cookie_maxlife) {
1981 /* emit first_date, which is either the original one or
1982 * the current date.
1983 */
1984 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1985 s30tob64(txn->cookie_first_date ?
1986 txn->cookie_first_date >> 2 :
1987 (date.tv_sec+3) >> 2,
1988 trash.area + trash.data);
1989 trash.data += 5;
1990 }
1991 }
1992 chunk_appendf(&trash, "; path=/");
1993 }
1994
1995 if (s->be->cookie_domain)
1996 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1997
1998 if (s->be->ck_opts & PR_CK_HTTPONLY)
1999 chunk_appendf(&trash, "; HttpOnly");
2000
2001 if (s->be->ck_opts & PR_CK_SECURE)
2002 chunk_appendf(&trash, "; Secure");
2003
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002004 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002005 goto return_bad_resp;
2006
2007 txn->flags &= ~TX_SCK_MASK;
2008 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2009 /* the server did not change, only the date was updated */
2010 txn->flags |= TX_SCK_UPDATED;
2011 else
2012 txn->flags |= TX_SCK_INSERTED;
2013
2014 /* Here, we will tell an eventual cache on the client side that we don't
2015 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2016 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2017 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2018 */
2019 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2020
2021 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2022
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002023 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024 goto return_bad_resp;
2025 }
2026 }
2027
2028 /*
2029 * Check if result will be cacheable with a cookie.
2030 * We'll block the response if security checks have caught
2031 * nasty things such as a cacheable cookie.
2032 */
2033 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2034 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2035 (s->be->options & PR_O_CHK_CACHE)) {
2036 /* we're in presence of a cacheable response containing
2037 * a set-cookie header. We'll block it as requested by
2038 * the 'checkcache' option, and send an alert.
2039 */
2040 if (objt_server(s->target))
2041 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2042
2043 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2044 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2045 if (sess->listener->counters)
2046 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2047
2048 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2049 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2050 send_log(s->be, LOG_ALERT,
2051 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2052 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2053 goto return_srv_prx_502;
2054 }
2055
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002057 /* Always enter in the body analyzer */
2058 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2059 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2060
2061 /* if the user wants to log as soon as possible, without counting
2062 * bytes from the server, then this is the right moment. We have
2063 * to temporarily assign bytes_out to log what we currently have.
2064 */
2065 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2066 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002067 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002068 s->do_log(s);
2069 s->logs.bytes_out = 0;
2070 }
2071 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002072
2073 return_bad_resp:
2074 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002075 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2076 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002077 }
2078 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2079
2080 return_srv_prx_502:
2081 rep->analysers &= AN_RES_FLT_END;
2082 txn->status = 502;
2083 s->logs.t_data = -1; /* was not a valid response */
2084 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002085 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002086 if (!(s->flags & SF_ERR_MASK))
2087 s->flags |= SF_ERR_PRXCOND;
2088 if (!(s->flags & SF_FINST_MASK))
2089 s->flags |= SF_FINST_H;
2090 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002091}
2092
2093/* This function is an analyser which forwards response body (including chunk
2094 * sizes if any). It is called as soon as we must forward, even if we forward
2095 * zero byte. The only situation where it must not be called is when we're in
2096 * tunnel mode and we want to forward till the close. It's used both to forward
2097 * remaining data and to resync after end of body. It expects the msg_state to
2098 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2099 * read more data, or 1 once we can go on with next request or end the stream.
2100 *
2101 * It is capable of compressing response data both in content-length mode and
2102 * in chunked mode. The state machines follows different flows depending on
2103 * whether content-length and chunked modes are used, since there are no
2104 * trailers in content-length :
2105 *
2106 * chk-mode cl-mode
2107 * ,----- BODY -----.
2108 * / \
2109 * V size > 0 V chk-mode
2110 * .--> SIZE -------------> DATA -------------> CRLF
2111 * | | size == 0 | last byte |
2112 * | v final crlf v inspected |
2113 * | TRAILERS -----------> DONE |
2114 * | |
2115 * `----------------------------------------------'
2116 *
2117 * Compression only happens in the DATA state, and must be flushed in final
2118 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2119 * is performed at once on final states for all bytes parsed, or when leaving
2120 * on missing data.
2121 */
2122int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2123{
2124 struct session *sess = s->sess;
2125 struct http_txn *txn = s->txn;
2126 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002127 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002128 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002129
2130 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2131 now_ms, __FUNCTION__,
2132 s,
2133 res,
2134 res->rex, res->wex,
2135 res->flags,
2136 ci_data(res),
2137 res->analysers);
2138
Christopher Faulet9768c262018-10-22 09:34:31 +02002139 htx = htx_from_buf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002140
2141 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002142 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002143 /* Output closed while we were sending data. We must abort and
2144 * wake the other side up.
2145 */
2146 msg->err_state = msg->msg_state;
2147 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002148 htx_end_response(s);
2149 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002150 return 1;
2151 }
2152
Christopher Faulet9768c262018-10-22 09:34:31 +02002153 if (msg->msg_state == HTTP_MSG_BODY)
2154 msg->msg_state = HTTP_MSG_DATA;
2155
Christopher Faulete0768eb2018-10-03 16:38:02 +02002156 /* in most states, we should abort in case of early close */
2157 channel_auto_close(res);
2158
Christopher Faulete0768eb2018-10-03 16:38:02 +02002159 if (res->to_forward) {
2160 /* We can't process the buffer's contents yet */
2161 res->flags |= CF_WAKE_WRITE;
2162 goto missing_data_or_waiting;
2163 }
2164
Christopher Faulet9768c262018-10-22 09:34:31 +02002165 if (msg->msg_state >= HTTP_MSG_DONE)
2166 goto done;
2167
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 /* Forward input data. We get it by removing all outgoing data not
2169 * forwarded yet from HTX data size. If there are some data filters, we
2170 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002171 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002172 if (HAS_RSP_DATA_FILTERS(s)) {
2173 ret = flt_http_payload(s, msg, htx->data);
2174 if (ret < 0)
2175 goto return_bad_res;
2176 c_adv(res, ret);
2177 if (htx->data != co_data(res) || htx->extra)
2178 goto missing_data_or_waiting;
2179 }
2180 else {
2181 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002182
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002183 /* To let the function channel_forward work as expected we must update
2184 * the channel's buffer to pretend there is no more input data. The
2185 * right length is then restored. We must do that, because when an HTX
2186 * message is stored into a buffer, it appears as full.
2187 */
2188 b_set_data(&res->buf, co_data(res));
2189 if (msg->flags & HTTP_MSGF_XFER_LEN)
2190 htx->extra -= channel_forward(res, htx->extra);
2191 b_set_data(&res->buf, b_size(&res->buf));
2192 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002193
2194 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2195 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002196 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002197 msg->msg_state = HTTP_MSG_TUNNEL;
2198 goto done;
2199 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 }
2201
Christopher Faulet9768c262018-10-22 09:34:31 +02002202 /* Check if the end-of-message is reached and if so, switch the message
2203 * in HTTP_MSG_DONE state.
2204 */
2205 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2206 goto missing_data_or_waiting;
2207
2208 msg->msg_state = HTTP_MSG_DONE;
2209
2210 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002212 channel_dont_close(res);
2213
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 if (HAS_RSP_DATA_FILTERS(s)) {
2215 ret = flt_http_end(s, msg);
2216 if (ret <= 0) {
2217 if (!ret)
2218 goto missing_data_or_waiting;
2219 goto return_bad_res;
2220 }
2221 }
2222
Christopher Fauletf2824e62018-10-01 12:12:37 +02002223 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002225 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2227 if (res->flags & CF_SHUTW) {
2228 /* response errors are most likely due to the
2229 * client aborting the transfer. */
2230 goto aborted_xfer;
2231 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 goto return_bad_res;
2233 }
2234 return 1;
2235 }
2236 return 0;
2237
2238 missing_data_or_waiting:
2239 if (res->flags & CF_SHUTW)
2240 goto aborted_xfer;
2241
Christopher Faulet47365272018-10-31 17:40:50 +01002242 if (htx->flags & HTX_FL_PARSING_ERROR)
2243 goto return_bad_res;
2244
Christopher Faulete0768eb2018-10-03 16:38:02 +02002245 /* stop waiting for data if the input is closed before the end. If the
2246 * client side was already closed, it means that the client has aborted,
2247 * so we don't want to count this as a server abort. Otherwise it's a
2248 * server abort.
2249 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002250 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2252 goto aborted_xfer;
2253 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002254 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002255 if (!(s->flags & SF_ERR_MASK))
2256 s->flags |= SF_ERR_SRVCL;
2257 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2258 if (objt_server(s->target))
2259 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2260 goto return_bad_res_stats_ok;
2261 }
2262 }
2263
Christopher Faulete0768eb2018-10-03 16:38:02 +02002264 /* When TE: chunked is used, we need to get there again to parse
2265 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002266 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2267 * are filters registered on the stream, we don't want to forward a
2268 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002270 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002271 channel_dont_close(res);
2272
2273 /* We know that more data are expected, but we couldn't send more that
2274 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2275 * system knows it must not set a PUSH on this first part. Interactive
2276 * modes are already handled by the stream sock layer. We must not do
2277 * this in content-length mode because it could present the MSG_MORE
2278 * flag with the last block of forwarded data, which would cause an
2279 * additional delay to be observed by the receiver.
2280 */
2281 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2282 res->flags |= CF_EXPECT_MORE;
2283
2284 /* the stream handler will take care of timeouts and errors */
2285 return 0;
2286
2287 return_bad_res: /* let's centralize all bad responses */
2288 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2289 if (objt_server(s->target))
2290 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2291
2292 return_bad_res_stats_ok:
2293 txn->rsp.err_state = txn->rsp.msg_state;
2294 txn->rsp.msg_state = HTTP_MSG_ERROR;
2295 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002296 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 res->analysers &= AN_RES_FLT_END;
2298 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2299 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002300 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301
2302 if (!(s->flags & SF_ERR_MASK))
2303 s->flags |= SF_ERR_PRXCOND;
2304 if (!(s->flags & SF_FINST_MASK))
2305 s->flags |= SF_FINST_D;
2306 return 0;
2307
2308 aborted_xfer:
2309 txn->rsp.err_state = txn->rsp.msg_state;
2310 txn->rsp.msg_state = HTTP_MSG_ERROR;
2311 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002312 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002313 res->analysers &= AN_RES_FLT_END;
2314 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2315
2316 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2317 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2318 if (objt_server(s->target))
2319 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2320
2321 if (!(s->flags & SF_ERR_MASK))
2322 s->flags |= SF_ERR_CLICL;
2323 if (!(s->flags & SF_FINST_MASK))
2324 s->flags |= SF_FINST_D;
2325 return 0;
2326}
2327
Christopher Faulet0f226952018-10-22 09:29:56 +02002328void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002329{
2330 struct proxy *fe = strm_fe(s);
2331 int tmp = TX_CON_WANT_CLO;
2332
2333 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2334 tmp = TX_CON_WANT_TUN;
2335
2336 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002337 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338}
2339
2340/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002341 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002342 * as too large a request to build a valid response.
2343 */
2344int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2345{
Christopher Faulet99daf282018-11-28 22:58:13 +01002346 struct channel *req = &s->req;
2347 struct channel *res = &s->res;
2348 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002349 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002350 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 struct ist status, reason, location;
2352 unsigned int flags;
2353 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354
2355 chunk = alloc_trash_chunk();
2356 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358
Christopher Faulet99daf282018-11-28 22:58:13 +01002359 /*
2360 * Create the location
2361 */
2362 htx = htx_from_buf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002364 case REDIRECT_TYPE_SCHEME: {
2365 struct http_hdr_ctx ctx;
2366 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002367
Christopher Faulet99daf282018-11-28 22:58:13 +01002368 host = ist("");
2369 ctx.blk = NULL;
2370 if (http_find_header(htx, ist("Host"), &ctx, 0))
2371 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 sl = http_find_stline(htx);
2374 path = http_get_path(htx_sl_req_uri(sl));
2375 /* build message using path */
2376 if (path.ptr) {
2377 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2378 int qs = 0;
2379 while (qs < path.len) {
2380 if (*(path.ptr + qs) == '?') {
2381 path.len = qs;
2382 break;
2383 }
2384 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386 }
2387 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 else
2389 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 if (rule->rdr_str) { /* this is an old "redirect" rule */
2392 /* add scheme */
2393 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2394 goto fail;
2395 }
2396 else {
2397 /* add scheme with executing log format */
2398 chunk->data += build_logline(s, chunk->area + chunk->data,
2399 chunk->size - chunk->data,
2400 &rule->rdr_fmt);
2401 }
2402 /* add "://" + host + path */
2403 if (!chunk_memcat(chunk, "://", 3) ||
2404 !chunk_memcat(chunk, host.ptr, host.len) ||
2405 !chunk_memcat(chunk, path.ptr, path.len))
2406 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407
Christopher Faulet99daf282018-11-28 22:58:13 +01002408 /* append a slash at the end of the location if needed and missing */
2409 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2410 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2411 if (chunk->data + 1 >= chunk->size)
2412 goto fail;
2413 chunk->area[chunk->data++] = '/';
2414 }
2415 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417
Christopher Faulet99daf282018-11-28 22:58:13 +01002418 case REDIRECT_TYPE_PREFIX: {
2419 struct ist path;
2420
2421 sl = http_find_stline(htx);
2422 path = http_get_path(htx_sl_req_uri(sl));
2423 /* build message using path */
2424 if (path.ptr) {
2425 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2426 int qs = 0;
2427 while (qs < path.len) {
2428 if (*(path.ptr + qs) == '?') {
2429 path.len = qs;
2430 break;
2431 }
2432 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002433 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434 }
2435 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 else
2437 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438
Christopher Faulet99daf282018-11-28 22:58:13 +01002439 if (rule->rdr_str) { /* this is an old "redirect" rule */
2440 /* add prefix. Note that if prefix == "/", we don't want to
2441 * add anything, otherwise it makes it hard for the user to
2442 * configure a self-redirection.
2443 */
2444 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2445 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2446 goto fail;
2447 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002449 else {
2450 /* add prefix with executing log format */
2451 chunk->data += build_logline(s, chunk->area + chunk->data,
2452 chunk->size - chunk->data,
2453 &rule->rdr_fmt);
2454 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002455
Christopher Faulet99daf282018-11-28 22:58:13 +01002456 /* add path */
2457 if (!chunk_memcat(chunk, path.ptr, path.len))
2458 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459
Christopher Faulet99daf282018-11-28 22:58:13 +01002460 /* append a slash at the end of the location if needed and missing */
2461 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2462 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2463 if (chunk->data + 1 >= chunk->size)
2464 goto fail;
2465 chunk->area[chunk->data++] = '/';
2466 }
2467 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002469 case REDIRECT_TYPE_LOCATION:
2470 default:
2471 if (rule->rdr_str) { /* this is an old "redirect" rule */
2472 /* add location */
2473 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2474 goto fail;
2475 }
2476 else {
2477 /* add location with executing log format */
2478 chunk->data += build_logline(s, chunk->area + chunk->data,
2479 chunk->size - chunk->data,
2480 &rule->rdr_fmt);
2481 }
2482 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002483 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002484 location = ist2(chunk->area, chunk->data);
2485
2486 /*
2487 * Create the 30x response
2488 */
2489 switch (rule->code) {
2490 case 308:
2491 status = ist("308");
2492 reason = ist("Permanent Redirect");
2493 break;
2494 case 307:
2495 status = ist("307");
2496 reason = ist("Temporary Redirect");
2497 break;
2498 case 303:
2499 status = ist("303");
2500 reason = ist("See Other");
2501 break;
2502 case 301:
2503 status = ist("301");
2504 reason = ist("Moved Permanently");
2505 break;
2506 case 302:
2507 default:
2508 status = ist("302");
2509 reason = ist("Found");
2510 break;
2511 }
2512
2513 htx = htx_from_buf(&res->buf);
2514 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2515 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2516 if (!sl)
2517 goto fail;
2518 sl->info.res.status = rule->code;
2519 s->txn->status = rule->code;
2520
2521 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2522 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2523 !htx_add_header(htx, ist("Location"), location))
2524 goto fail;
2525
2526 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2527 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2528 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002529 }
2530
2531 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2533 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002534 }
2535
Christopher Faulet99daf282018-11-28 22:58:13 +01002536 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2537 goto fail;
2538
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539 /* let's log the request time */
2540 s->logs.tv_request = now;
2541
Christopher Faulet99daf282018-11-28 22:58:13 +01002542 data = htx->data - co_data(res);
2543 b_set_data(&res->buf, b_size(&res->buf));
2544 c_adv(res, data);
2545 res->total += data;
2546
2547 channel_auto_read(req);
2548 channel_abort(req);
2549 channel_auto_close(req);
2550 channel_erase(req);
2551
2552 res->wex = tick_add_ifset(now_ms, res->wto);
2553 channel_auto_read(res);
2554 channel_auto_close(res);
2555 channel_shutr_now(res);
2556
2557 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002558
2559 if (!(s->flags & SF_ERR_MASK))
2560 s->flags |= SF_ERR_LOCAL;
2561 if (!(s->flags & SF_FINST_MASK))
2562 s->flags |= SF_FINST_R;
2563
Christopher Faulet99daf282018-11-28 22:58:13 +01002564 free_trash_chunk(chunk);
2565 return 1;
2566
2567 fail:
2568 /* If an error occurred, remove the incomplete HTTP response from the
2569 * buffer */
2570 channel_truncate(res);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002571 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002572 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002573}
2574
Christopher Faulet72333522018-10-24 11:25:02 +02002575int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2576 struct ist name, const char *str, struct my_regex *re, int action)
2577{
2578 struct http_hdr_ctx ctx;
2579 struct buffer *output = get_trash_chunk();
2580
2581 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2582 ctx.blk = NULL;
2583 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2584 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2585 continue;
2586
2587 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2588 if (output->data == -1)
2589 return -1;
2590 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2591 return -1;
2592 }
2593 return 0;
2594}
2595
2596static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2597 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2598{
2599 struct buffer *replace;
2600 int ret = -1;
2601
2602 replace = alloc_trash_chunk();
2603 if (!replace)
2604 goto leave;
2605
2606 replace->data = build_logline(s, replace->area, replace->size, fmt);
2607 if (replace->data >= replace->size - 1)
2608 goto leave;
2609
2610 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2611
2612 leave:
2613 free_trash_chunk(replace);
2614 return ret;
2615}
2616
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002617
2618/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2619 * on success and -1 on error. The response channel is updated accordingly.
2620 */
2621static int htx_reply_103_early_hints(struct channel *res)
2622{
2623 struct htx *htx = htx_from_buf(&res->buf);
2624 size_t data;
2625
2626 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2627 /* If an error occurred during an Early-hint rule,
2628 * remove the incomplete HTTP 103 response from the
2629 * buffer */
2630 channel_truncate(res);
2631 return -1;
2632 }
2633
2634 data = htx->data - co_data(res);
2635 b_set_data(&res->buf, b_size(&res->buf));
2636 c_adv(res, data);
2637 res->total += data;
2638 return 0;
2639}
2640
Christopher Faulet6eb92892018-11-15 16:39:29 +01002641/*
2642 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2643 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002644 * If <early_hints> is 0, it is starts a new response by adding the start
2645 * line. If an error occurred -1 is returned. On success 0 is returned. The
2646 * channel is not updated here. It must be done calling the function
2647 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002648 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002649static 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 +01002650{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 struct channel *res = &s->res;
2652 struct htx *htx = htx_from_buf(&res->buf);
2653 struct buffer *value = alloc_trash_chunk();
2654
Christopher Faulet6eb92892018-11-15 16:39:29 +01002655 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002656 struct htx_sl *sl;
2657 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2658 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2659
2660 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2661 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2662 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002663 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002664 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002665 }
2666
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002667 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2668 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002669 goto fail;
2670
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002671 free_trash_chunk(value);
2672 b_set_data(&res->buf, b_size(&res->buf));
2673 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002674
2675 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002676 /* If an error occurred during an Early-hint rule, remove the incomplete
2677 * HTTP 103 response from the buffer */
2678 channel_truncate(res);
2679 free_trash_chunk(value);
2680 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002681}
2682
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002683/* This function executes one of the set-{method,path,query,uri} actions. It
2684 * takes the string from the variable 'replace' with length 'len', then modifies
2685 * the relevant part of the request line accordingly. Then it updates various
2686 * pointers to the next elements which were moved, and the total buffer length.
2687 * It finds the action to be performed in p[2], previously filled by function
2688 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2689 * error, though this can be revisited when this code is finally exploited.
2690 *
2691 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2692 * query string and 3 to replace uri.
2693 *
2694 * In query string case, the mark question '?' must be set at the start of the
2695 * string by the caller, event if the replacement query string is empty.
2696 */
2697int htx_req_replace_stline(int action, const char *replace, int len,
2698 struct proxy *px, struct stream *s)
2699{
2700 struct htx *htx = htx_from_buf(&s->req.buf);
2701
2702 switch (action) {
2703 case 0: // method
2704 if (!http_replace_req_meth(htx, ist2(replace, len)))
2705 return -1;
2706 break;
2707
2708 case 1: // path
2709 if (!http_replace_req_path(htx, ist2(replace, len)))
2710 return -1;
2711 break;
2712
2713 case 2: // query
2714 if (!http_replace_req_query(htx, ist2(replace, len)))
2715 return -1;
2716 break;
2717
2718 case 3: // uri
2719 if (!http_replace_req_uri(htx, ist2(replace, len)))
2720 return -1;
2721 break;
2722
2723 default:
2724 return -1;
2725 }
2726 return 0;
2727}
2728
2729/* This function replace the HTTP status code and the associated message. The
2730 * variable <status> contains the new status code. This function never fails.
2731 */
2732void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2733{
2734 struct htx *htx = htx_from_buf(&s->res.buf);
2735 char *res;
2736
2737 chunk_reset(&trash);
2738 res = ultoa_o(status, trash.area, trash.size);
2739 trash.data = res - trash.area;
2740
2741 /* Do we have a custom reason format string? */
2742 if (reason == NULL)
2743 reason = http_get_reason(status);
2744
2745 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2746 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2747}
2748
Christopher Faulet3e964192018-10-24 11:39:23 +02002749/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2750 * transaction <txn>. Returns the verdict of the first rule that prevents
2751 * further processing of the request (auth, deny, ...), and defaults to
2752 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2753 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2754 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2755 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2756 * status.
2757 */
2758static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2759 struct stream *s, int *deny_status)
2760{
2761 struct session *sess = strm_sess(s);
2762 struct http_txn *txn = s->txn;
2763 struct htx *htx;
2764 struct connection *cli_conn;
2765 struct act_rule *rule;
2766 struct http_hdr_ctx ctx;
2767 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002768 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2769 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002770 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002771
2772 htx = htx_from_buf(&s->req.buf);
2773
2774 /* If "the current_rule_list" match the executed rule list, we are in
2775 * resume condition. If a resume is needed it is always in the action
2776 * and never in the ACL or converters. In this case, we initialise the
2777 * current rule, and go to the action execution point.
2778 */
2779 if (s->current_rule) {
2780 rule = s->current_rule;
2781 s->current_rule = NULL;
2782 if (s->current_rule_list == rules)
2783 goto resume_execution;
2784 }
2785 s->current_rule_list = rules;
2786
2787 list_for_each_entry(rule, rules, list) {
2788 /* check optional condition */
2789 if (rule->cond) {
2790 int ret;
2791
2792 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2793 ret = acl_pass(ret);
2794
2795 if (rule->cond->pol == ACL_COND_UNLESS)
2796 ret = !ret;
2797
2798 if (!ret) /* condition not matched */
2799 continue;
2800 }
2801
2802 act_flags |= ACT_FLAG_FIRST;
2803 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002804 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2805 early_hints = 0;
2806 if (htx_reply_103_early_hints(&s->res) == -1) {
2807 rule_ret = HTTP_RULE_RES_BADREQ;
2808 goto end;
2809 }
2810 }
2811
Christopher Faulet3e964192018-10-24 11:39:23 +02002812 switch (rule->action) {
2813 case ACT_ACTION_ALLOW:
2814 rule_ret = HTTP_RULE_RES_STOP;
2815 goto end;
2816
2817 case ACT_ACTION_DENY:
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_TARPIT:
2824 txn->flags |= TX_CLTARPIT;
2825 if (deny_status)
2826 *deny_status = rule->deny_status;
2827 rule_ret = HTTP_RULE_RES_DENY;
2828 goto end;
2829
2830 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002831 /* Auth might be performed on regular http-req rules as well as on stats */
2832 auth_realm = rule->arg.auth.realm;
2833 if (!auth_realm) {
2834 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2835 auth_realm = STATS_DEFAULT_REALM;
2836 else
2837 auth_realm = px->id;
2838 }
2839 /* send 401/407 depending on whether we use a proxy or not. We still
2840 * count one error, because normal browsing won't significantly
2841 * increase the counter but brute force attempts will.
2842 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002843 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002844 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2845 rule_ret = HTTP_RULE_RES_BADREQ;
2846 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002847 goto end;
2848
2849 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002850 rule_ret = HTTP_RULE_RES_DONE;
2851 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2852 rule_ret = HTTP_RULE_RES_BADREQ;
2853 goto end;
2854
2855 case ACT_HTTP_SET_NICE:
2856 s->task->nice = rule->arg.nice;
2857 break;
2858
2859 case ACT_HTTP_SET_TOS:
2860 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2861 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2862 break;
2863
2864 case ACT_HTTP_SET_MARK:
2865#ifdef SO_MARK
2866 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2867 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2868#endif
2869 break;
2870
2871 case ACT_HTTP_SET_LOGL:
2872 s->logs.level = rule->arg.loglevel;
2873 break;
2874
2875 case ACT_HTTP_REPLACE_HDR:
2876 case ACT_HTTP_REPLACE_VAL:
2877 if (htx_transform_header(s, &s->req, htx,
2878 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2879 &rule->arg.hdr_add.fmt,
2880 &rule->arg.hdr_add.re, rule->action)) {
2881 rule_ret = HTTP_RULE_RES_BADREQ;
2882 goto end;
2883 }
2884 break;
2885
2886 case ACT_HTTP_DEL_HDR:
2887 /* remove all occurrences of the header */
2888 ctx.blk = NULL;
2889 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2890 http_remove_header(htx, &ctx);
2891 break;
2892
2893 case ACT_HTTP_SET_HDR:
2894 case ACT_HTTP_ADD_HDR: {
2895 /* The scope of the trash buffer must be limited to this function. The
2896 * build_logline() function can execute a lot of other function which
2897 * can use the trash buffer. So for limiting the scope of this global
2898 * buffer, we build first the header value using build_logline, and
2899 * after we store the header name.
2900 */
2901 struct buffer *replace;
2902 struct ist n, v;
2903
2904 replace = alloc_trash_chunk();
2905 if (!replace) {
2906 rule_ret = HTTP_RULE_RES_BADREQ;
2907 goto end;
2908 }
2909
2910 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2911 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2912 v = ist2(replace->area, replace->data);
2913
2914 if (rule->action == ACT_HTTP_SET_HDR) {
2915 /* remove all occurrences of the header */
2916 ctx.blk = NULL;
2917 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2918 http_remove_header(htx, &ctx);
2919 }
2920
2921 if (!http_add_header(htx, n, v)) {
2922 static unsigned char rate_limit = 0;
2923
2924 if ((rate_limit++ & 255) == 0) {
2925 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);
2926 }
2927
2928 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2929 if (sess->fe != s->be)
2930 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2931 if (sess->listener->counters)
2932 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2933 }
2934 free_trash_chunk(replace);
2935 break;
2936 }
2937
2938 case ACT_HTTP_DEL_ACL:
2939 case ACT_HTTP_DEL_MAP: {
2940 struct pat_ref *ref;
2941 struct buffer *key;
2942
2943 /* collect reference */
2944 ref = pat_ref_lookup(rule->arg.map.ref);
2945 if (!ref)
2946 continue;
2947
2948 /* allocate key */
2949 key = alloc_trash_chunk();
2950 if (!key) {
2951 rule_ret = HTTP_RULE_RES_BADREQ;
2952 goto end;
2953 }
2954
2955 /* collect key */
2956 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2957 key->area[key->data] = '\0';
2958
2959 /* perform update */
2960 /* returned code: 1=ok, 0=ko */
2961 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2962 pat_ref_delete(ref, key->area);
2963 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2964
2965 free_trash_chunk(key);
2966 break;
2967 }
2968
2969 case ACT_HTTP_ADD_ACL: {
2970 struct pat_ref *ref;
2971 struct buffer *key;
2972
2973 /* collect reference */
2974 ref = pat_ref_lookup(rule->arg.map.ref);
2975 if (!ref)
2976 continue;
2977
2978 /* allocate key */
2979 key = alloc_trash_chunk();
2980 if (!key) {
2981 rule_ret = HTTP_RULE_RES_BADREQ;
2982 goto end;
2983 }
2984
2985 /* collect key */
2986 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2987 key->area[key->data] = '\0';
2988
2989 /* perform update */
2990 /* add entry only if it does not already exist */
2991 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2992 if (pat_ref_find_elt(ref, key->area) == NULL)
2993 pat_ref_add(ref, key->area, NULL, NULL);
2994 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2995
2996 free_trash_chunk(key);
2997 break;
2998 }
2999
3000 case ACT_HTTP_SET_MAP: {
3001 struct pat_ref *ref;
3002 struct buffer *key, *value;
3003
3004 /* collect reference */
3005 ref = pat_ref_lookup(rule->arg.map.ref);
3006 if (!ref)
3007 continue;
3008
3009 /* allocate key */
3010 key = alloc_trash_chunk();
3011 if (!key) {
3012 rule_ret = HTTP_RULE_RES_BADREQ;
3013 goto end;
3014 }
3015
3016 /* allocate value */
3017 value = alloc_trash_chunk();
3018 if (!value) {
3019 free_trash_chunk(key);
3020 rule_ret = HTTP_RULE_RES_BADREQ;
3021 goto end;
3022 }
3023
3024 /* collect key */
3025 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3026 key->area[key->data] = '\0';
3027
3028 /* collect value */
3029 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3030 value->area[value->data] = '\0';
3031
3032 /* perform update */
3033 if (pat_ref_find_elt(ref, key->area) != NULL)
3034 /* update entry if it exists */
3035 pat_ref_set(ref, key->area, value->area, NULL);
3036 else
3037 /* insert a new entry */
3038 pat_ref_add(ref, key->area, value->area, NULL);
3039
3040 free_trash_chunk(key);
3041 free_trash_chunk(value);
3042 break;
3043 }
3044
3045 case ACT_HTTP_EARLY_HINT:
3046 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3047 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003048 early_hints = htx_add_early_hint_header(s, early_hints,
3049 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003050 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003051 if (early_hints == -1) {
3052 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003053 goto end;
3054 }
3055 break;
3056
3057 case ACT_CUSTOM:
3058 if ((s->req.flags & CF_READ_ERROR) ||
3059 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3060 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3061 (px->options & PR_O_ABRT_CLOSE)))
3062 act_flags |= ACT_FLAG_FINAL;
3063
3064 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3065 case ACT_RET_ERR:
3066 case ACT_RET_CONT:
3067 break;
3068 case ACT_RET_STOP:
3069 rule_ret = HTTP_RULE_RES_DONE;
3070 goto end;
3071 case ACT_RET_YIELD:
3072 s->current_rule = rule;
3073 rule_ret = HTTP_RULE_RES_YIELD;
3074 goto end;
3075 }
3076 break;
3077
3078 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3079 /* Note: only the first valid tracking parameter of each
3080 * applies.
3081 */
3082
3083 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3084 struct stktable *t;
3085 struct stksess *ts;
3086 struct stktable_key *key;
3087 void *ptr1, *ptr2;
3088
3089 t = rule->arg.trk_ctr.table.t;
3090 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3091 rule->arg.trk_ctr.expr, NULL);
3092
3093 if (key && (ts = stktable_get_entry(t, key))) {
3094 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3095
3096 /* let's count a new HTTP request as it's the first time we do it */
3097 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3098 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3099 if (ptr1 || ptr2) {
3100 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3101
3102 if (ptr1)
3103 stktable_data_cast(ptr1, http_req_cnt)++;
3104
3105 if (ptr2)
3106 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3107 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3108
3109 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3110
3111 /* If data was modified, we need to touch to re-schedule sync */
3112 stktable_touch_local(t, ts, 0);
3113 }
3114
3115 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3116 if (sess->fe != s->be)
3117 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3118 }
3119 }
3120 break;
3121
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003122 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003123 default:
3124 break;
3125 }
3126 }
3127
3128 end:
3129 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003130 if (htx_reply_103_early_hints(&s->res) == -1)
3131 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003132 }
3133
3134 /* we reached the end of the rules, nothing to report */
3135 return rule_ret;
3136}
3137
3138/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3139 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3140 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3141 * is returned, the process can continue the evaluation of next rule list. If
3142 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3143 * is returned, it means the operation could not be processed and a server error
3144 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3145 * deny rule. If *YIELD is returned, the caller must call again the function
3146 * with the same context.
3147 */
3148static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3149 struct stream *s)
3150{
3151 struct session *sess = strm_sess(s);
3152 struct http_txn *txn = s->txn;
3153 struct htx *htx;
3154 struct connection *cli_conn;
3155 struct act_rule *rule;
3156 struct http_hdr_ctx ctx;
3157 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3158 int act_flags = 0;
3159
3160 htx = htx_from_buf(&s->res.buf);
3161
3162 /* If "the current_rule_list" match the executed rule list, we are in
3163 * resume condition. If a resume is needed it is always in the action
3164 * and never in the ACL or converters. In this case, we initialise the
3165 * current rule, and go to the action execution point.
3166 */
3167 if (s->current_rule) {
3168 rule = s->current_rule;
3169 s->current_rule = NULL;
3170 if (s->current_rule_list == rules)
3171 goto resume_execution;
3172 }
3173 s->current_rule_list = rules;
3174
3175 list_for_each_entry(rule, rules, list) {
3176 /* check optional condition */
3177 if (rule->cond) {
3178 int ret;
3179
3180 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3181 ret = acl_pass(ret);
3182
3183 if (rule->cond->pol == ACL_COND_UNLESS)
3184 ret = !ret;
3185
3186 if (!ret) /* condition not matched */
3187 continue;
3188 }
3189
3190 act_flags |= ACT_FLAG_FIRST;
3191resume_execution:
3192 switch (rule->action) {
3193 case ACT_ACTION_ALLOW:
3194 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3195 goto end;
3196
3197 case ACT_ACTION_DENY:
3198 txn->flags |= TX_SVDENY;
3199 rule_ret = HTTP_RULE_RES_STOP;
3200 goto end;
3201
3202 case ACT_HTTP_SET_NICE:
3203 s->task->nice = rule->arg.nice;
3204 break;
3205
3206 case ACT_HTTP_SET_TOS:
3207 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3208 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3209 break;
3210
3211 case ACT_HTTP_SET_MARK:
3212#ifdef SO_MARK
3213 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3214 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3215#endif
3216 break;
3217
3218 case ACT_HTTP_SET_LOGL:
3219 s->logs.level = rule->arg.loglevel;
3220 break;
3221
3222 case ACT_HTTP_REPLACE_HDR:
3223 case ACT_HTTP_REPLACE_VAL:
3224 if (htx_transform_header(s, &s->res, htx,
3225 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3226 &rule->arg.hdr_add.fmt,
3227 &rule->arg.hdr_add.re, rule->action)) {
3228 rule_ret = HTTP_RULE_RES_BADREQ;
3229 goto end;
3230 }
3231 break;
3232
3233 case ACT_HTTP_DEL_HDR:
3234 /* remove all occurrences of the header */
3235 ctx.blk = NULL;
3236 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3237 http_remove_header(htx, &ctx);
3238 break;
3239
3240 case ACT_HTTP_SET_HDR:
3241 case ACT_HTTP_ADD_HDR: {
3242 struct buffer *replace;
3243 struct ist n, v;
3244
3245 replace = alloc_trash_chunk();
3246 if (!replace) {
3247 rule_ret = HTTP_RULE_RES_BADREQ;
3248 goto end;
3249 }
3250
3251 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3252 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3253 v = ist2(replace->area, replace->data);
3254
3255 if (rule->action == ACT_HTTP_SET_HDR) {
3256 /* remove all occurrences of the header */
3257 ctx.blk = NULL;
3258 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3259 http_remove_header(htx, &ctx);
3260 }
3261
3262 if (!http_add_header(htx, n, v)) {
3263 static unsigned char rate_limit = 0;
3264
3265 if ((rate_limit++ & 255) == 0) {
3266 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);
3267 }
3268
3269 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3270 if (sess->fe != s->be)
3271 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3272 if (sess->listener->counters)
3273 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3274 if (objt_server(s->target))
3275 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3276 }
3277 free_trash_chunk(replace);
3278 break;
3279 }
3280
3281 case ACT_HTTP_DEL_ACL:
3282 case ACT_HTTP_DEL_MAP: {
3283 struct pat_ref *ref;
3284 struct buffer *key;
3285
3286 /* collect reference */
3287 ref = pat_ref_lookup(rule->arg.map.ref);
3288 if (!ref)
3289 continue;
3290
3291 /* allocate key */
3292 key = alloc_trash_chunk();
3293 if (!key) {
3294 rule_ret = HTTP_RULE_RES_BADREQ;
3295 goto end;
3296 }
3297
3298 /* collect key */
3299 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3300 key->area[key->data] = '\0';
3301
3302 /* perform update */
3303 /* returned code: 1=ok, 0=ko */
3304 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3305 pat_ref_delete(ref, key->area);
3306 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3307
3308 free_trash_chunk(key);
3309 break;
3310 }
3311
3312 case ACT_HTTP_ADD_ACL: {
3313 struct pat_ref *ref;
3314 struct buffer *key;
3315
3316 /* collect reference */
3317 ref = pat_ref_lookup(rule->arg.map.ref);
3318 if (!ref)
3319 continue;
3320
3321 /* allocate key */
3322 key = alloc_trash_chunk();
3323 if (!key) {
3324 rule_ret = HTTP_RULE_RES_BADREQ;
3325 goto end;
3326 }
3327
3328 /* collect key */
3329 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3330 key->area[key->data] = '\0';
3331
3332 /* perform update */
3333 /* check if the entry already exists */
3334 if (pat_ref_find_elt(ref, key->area) == NULL)
3335 pat_ref_add(ref, key->area, NULL, NULL);
3336
3337 free_trash_chunk(key);
3338 break;
3339 }
3340
3341 case ACT_HTTP_SET_MAP: {
3342 struct pat_ref *ref;
3343 struct buffer *key, *value;
3344
3345 /* collect reference */
3346 ref = pat_ref_lookup(rule->arg.map.ref);
3347 if (!ref)
3348 continue;
3349
3350 /* allocate key */
3351 key = alloc_trash_chunk();
3352 if (!key) {
3353 rule_ret = HTTP_RULE_RES_BADREQ;
3354 goto end;
3355 }
3356
3357 /* allocate value */
3358 value = alloc_trash_chunk();
3359 if (!value) {
3360 free_trash_chunk(key);
3361 rule_ret = HTTP_RULE_RES_BADREQ;
3362 goto end;
3363 }
3364
3365 /* collect key */
3366 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3367 key->area[key->data] = '\0';
3368
3369 /* collect value */
3370 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3371 value->area[value->data] = '\0';
3372
3373 /* perform update */
3374 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3375 if (pat_ref_find_elt(ref, key->area) != NULL)
3376 /* update entry if it exists */
3377 pat_ref_set(ref, key->area, value->area, NULL);
3378 else
3379 /* insert a new entry */
3380 pat_ref_add(ref, key->area, value->area, NULL);
3381 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3382 free_trash_chunk(key);
3383 free_trash_chunk(value);
3384 break;
3385 }
3386
3387 case ACT_HTTP_REDIR:
3388 rule_ret = HTTP_RULE_RES_DONE;
3389 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3390 rule_ret = HTTP_RULE_RES_BADREQ;
3391 goto end;
3392
3393 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3394 /* Note: only the first valid tracking parameter of each
3395 * applies.
3396 */
3397 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3398 struct stktable *t;
3399 struct stksess *ts;
3400 struct stktable_key *key;
3401 void *ptr;
3402
3403 t = rule->arg.trk_ctr.table.t;
3404 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3405 rule->arg.trk_ctr.expr, NULL);
3406
3407 if (key && (ts = stktable_get_entry(t, key))) {
3408 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3409
3410 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3411
3412 /* let's count a new HTTP request as it's the first time we do it */
3413 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3414 if (ptr)
3415 stktable_data_cast(ptr, http_req_cnt)++;
3416
3417 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3418 if (ptr)
3419 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3420 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3421
3422 /* When the client triggers a 4xx from the server, it's most often due
3423 * to a missing object or permission. These events should be tracked
3424 * because if they happen often, it may indicate a brute force or a
3425 * vulnerability scan. Normally this is done when receiving the response
3426 * but here we're tracking after this ought to have been done so we have
3427 * to do it on purpose.
3428 */
3429 if ((unsigned)(txn->status - 400) < 100) {
3430 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3431 if (ptr)
3432 stktable_data_cast(ptr, http_err_cnt)++;
3433
3434 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3435 if (ptr)
3436 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3437 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3438 }
3439
3440 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3441
3442 /* If data was modified, we need to touch to re-schedule sync */
3443 stktable_touch_local(t, ts, 0);
3444
3445 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3446 if (sess->fe != s->be)
3447 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3448 }
3449 }
3450 break;
3451
3452 case ACT_CUSTOM:
3453 if ((s->req.flags & CF_READ_ERROR) ||
3454 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3455 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3456 (px->options & PR_O_ABRT_CLOSE)))
3457 act_flags |= ACT_FLAG_FINAL;
3458
3459 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3460 case ACT_RET_ERR:
3461 case ACT_RET_CONT:
3462 break;
3463 case ACT_RET_STOP:
3464 rule_ret = HTTP_RULE_RES_STOP;
3465 goto end;
3466 case ACT_RET_YIELD:
3467 s->current_rule = rule;
3468 rule_ret = HTTP_RULE_RES_YIELD;
3469 goto end;
3470 }
3471 break;
3472
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003473 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003474 default:
3475 break;
3476 }
3477 }
3478
3479 end:
3480 /* we reached the end of the rules, nothing to report */
3481 return rule_ret;
3482}
3483
Christopher Faulet33640082018-10-24 11:53:01 +02003484/* Iterate the same filter through all request headers.
3485 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3486 * Since it can manage the switch to another backend, it updates the per-proxy
3487 * DENY stats.
3488 */
3489static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3490{
3491 struct http_txn *txn = s->txn;
3492 struct htx *htx;
3493 struct buffer *hdr = get_trash_chunk();
3494 int32_t pos;
3495
3496 htx = htx_from_buf(&req->buf);
3497
3498 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3499 struct htx_blk *blk = htx_get_blk(htx, pos);
3500 enum htx_blk_type type;
3501 struct ist n, v;
3502
3503 next_hdr:
3504 type = htx_get_blk_type(blk);
3505 if (type == HTX_BLK_EOH)
3506 break;
3507 if (type != HTX_BLK_HDR)
3508 continue;
3509
3510 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3511 return 1;
3512 else if (unlikely(txn->flags & TX_CLALLOW) &&
3513 (exp->action == ACT_ALLOW ||
3514 exp->action == ACT_DENY ||
3515 exp->action == ACT_TARPIT))
3516 return 0;
3517
3518 n = htx_get_blk_name(htx, blk);
3519 v = htx_get_blk_value(htx, blk);
3520
3521 chunk_memcat(hdr, n.ptr, n.len);
3522 hdr->area[hdr->data++] = ':';
3523 hdr->area[hdr->data++] = ' ';
3524 chunk_memcat(hdr, v.ptr, v.len);
3525
3526 /* Now we have one header in <hdr> */
3527
3528 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3529 struct http_hdr_ctx ctx;
3530 int len;
3531
3532 switch (exp->action) {
3533 case ACT_ALLOW:
3534 txn->flags |= TX_CLALLOW;
3535 goto end;
3536
3537 case ACT_DENY:
3538 txn->flags |= TX_CLDENY;
3539 goto end;
3540
3541 case ACT_TARPIT:
3542 txn->flags |= TX_CLTARPIT;
3543 goto end;
3544
3545 case ACT_REPLACE:
3546 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3547 if (len < 0)
3548 return -1;
3549
3550 http_parse_header(ist2(trash.area, len), &n, &v);
3551 ctx.blk = blk;
3552 ctx.value = v;
3553 if (!http_replace_header(htx, &ctx, n, v))
3554 return -1;
3555 if (!ctx.blk)
3556 goto end;
3557 pos = htx_get_blk_pos(htx, blk);
3558 break;
3559
3560 case ACT_REMOVE:
3561 ctx.blk = blk;
3562 ctx.value = v;
3563 if (!http_remove_header(htx, &ctx))
3564 return -1;
3565 if (!ctx.blk)
3566 goto end;
3567 pos = htx_get_blk_pos(htx, blk);
3568 goto next_hdr;
3569
3570 }
3571 }
3572 }
3573 end:
3574 return 0;
3575}
3576
3577/* Apply the filter to the request line.
3578 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3579 * or -1 if a replacement resulted in an invalid request line.
3580 * Since it can manage the switch to another backend, it updates the per-proxy
3581 * DENY stats.
3582 */
3583static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3584{
3585 struct http_txn *txn = s->txn;
3586 struct htx *htx;
3587 struct buffer *reqline = get_trash_chunk();
3588 int done;
3589
3590 htx = htx_from_buf(&req->buf);
3591
3592 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3593 return 1;
3594 else if (unlikely(txn->flags & TX_CLALLOW) &&
3595 (exp->action == ACT_ALLOW ||
3596 exp->action == ACT_DENY ||
3597 exp->action == ACT_TARPIT))
3598 return 0;
3599 else if (exp->action == ACT_REMOVE)
3600 return 0;
3601
3602 done = 0;
3603
3604 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3605
3606 /* Now we have the request line between cur_ptr and cur_end */
3607 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003608 struct htx_sl *sl = http_find_stline(htx);
3609 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003610 int len;
3611
3612 switch (exp->action) {
3613 case ACT_ALLOW:
3614 txn->flags |= TX_CLALLOW;
3615 done = 1;
3616 break;
3617
3618 case ACT_DENY:
3619 txn->flags |= TX_CLDENY;
3620 done = 1;
3621 break;
3622
3623 case ACT_TARPIT:
3624 txn->flags |= TX_CLTARPIT;
3625 done = 1;
3626 break;
3627
3628 case ACT_REPLACE:
3629 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3630 if (len < 0)
3631 return -1;
3632
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003633 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3634 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3635 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003636 return -1;
3637 done = 1;
3638 break;
3639 }
3640 }
3641 return done;
3642}
3643
3644/*
3645 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3646 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3647 * unparsable request. Since it can manage the switch to another backend, it
3648 * updates the per-proxy DENY stats.
3649 */
3650static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3651{
3652 struct session *sess = s->sess;
3653 struct http_txn *txn = s->txn;
3654 struct hdr_exp *exp;
3655
3656 for (exp = px->req_exp; exp; exp = exp->next) {
3657 int ret;
3658
3659 /*
3660 * The interleaving of transformations and verdicts
3661 * makes it difficult to decide to continue or stop
3662 * the evaluation.
3663 */
3664
3665 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3666 break;
3667
3668 if ((txn->flags & TX_CLALLOW) &&
3669 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3670 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3671 continue;
3672
3673 /* if this filter had a condition, evaluate it now and skip to
3674 * next filter if the condition does not match.
3675 */
3676 if (exp->cond) {
3677 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3678 ret = acl_pass(ret);
3679 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3680 ret = !ret;
3681
3682 if (!ret)
3683 continue;
3684 }
3685
3686 /* Apply the filter to the request line. */
3687 ret = htx_apply_filter_to_req_line(s, req, exp);
3688 if (unlikely(ret < 0))
3689 return -1;
3690
3691 if (likely(ret == 0)) {
3692 /* The filter did not match the request, it can be
3693 * iterated through all headers.
3694 */
3695 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3696 return -1;
3697 }
3698 }
3699 return 0;
3700}
3701
3702/* Iterate the same filter through all response headers contained in <res>.
3703 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3704 */
3705static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3706{
3707 struct http_txn *txn = s->txn;
3708 struct htx *htx;
3709 struct buffer *hdr = get_trash_chunk();
3710 int32_t pos;
3711
3712 htx = htx_from_buf(&res->buf);
3713
3714 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3715 struct htx_blk *blk = htx_get_blk(htx, pos);
3716 enum htx_blk_type type;
3717 struct ist n, v;
3718
3719 next_hdr:
3720 type = htx_get_blk_type(blk);
3721 if (type == HTX_BLK_EOH)
3722 break;
3723 if (type != HTX_BLK_HDR)
3724 continue;
3725
3726 if (unlikely(txn->flags & TX_SVDENY))
3727 return 1;
3728 else if (unlikely(txn->flags & TX_SVALLOW) &&
3729 (exp->action == ACT_ALLOW ||
3730 exp->action == ACT_DENY))
3731 return 0;
3732
3733 n = htx_get_blk_name(htx, blk);
3734 v = htx_get_blk_value(htx, blk);
3735
3736 chunk_memcat(hdr, n.ptr, n.len);
3737 hdr->area[hdr->data++] = ':';
3738 hdr->area[hdr->data++] = ' ';
3739 chunk_memcat(hdr, v.ptr, v.len);
3740
3741 /* Now we have one header in <hdr> */
3742
3743 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3744 struct http_hdr_ctx ctx;
3745 int len;
3746
3747 switch (exp->action) {
3748 case ACT_ALLOW:
3749 txn->flags |= TX_SVALLOW;
3750 goto end;
3751 break;
3752
3753 case ACT_DENY:
3754 txn->flags |= TX_SVDENY;
3755 goto end;
3756 break;
3757
3758 case ACT_REPLACE:
3759 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3760 if (len < 0)
3761 return -1;
3762
3763 http_parse_header(ist2(trash.area, len), &n, &v);
3764 ctx.blk = blk;
3765 ctx.value = v;
3766 if (!http_replace_header(htx, &ctx, n, v))
3767 return -1;
3768 if (!ctx.blk)
3769 goto end;
3770 pos = htx_get_blk_pos(htx, blk);
3771 break;
3772
3773 case ACT_REMOVE:
3774 ctx.blk = blk;
3775 ctx.value = v;
3776 if (!http_remove_header(htx, &ctx))
3777 return -1;
3778 if (!ctx.blk)
3779 goto end;
3780 pos = htx_get_blk_pos(htx, blk);
3781 goto next_hdr;
3782 }
3783 }
3784
3785 }
3786 end:
3787 return 0;
3788}
3789
3790/* Apply the filter to the status line in the response buffer <res>.
3791 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3792 * or -1 if a replacement resulted in an invalid status line.
3793 */
3794static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3795{
3796 struct http_txn *txn = s->txn;
3797 struct htx *htx;
3798 struct buffer *resline = get_trash_chunk();
3799 int done;
3800
3801 htx = htx_from_buf(&res->buf);
3802
3803 if (unlikely(txn->flags & TX_SVDENY))
3804 return 1;
3805 else if (unlikely(txn->flags & TX_SVALLOW) &&
3806 (exp->action == ACT_ALLOW ||
3807 exp->action == ACT_DENY))
3808 return 0;
3809 else if (exp->action == ACT_REMOVE)
3810 return 0;
3811
3812 done = 0;
3813 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3814
3815 /* Now we have the status line between cur_ptr and cur_end */
3816 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003817 struct htx_sl *sl = http_find_stline(htx);
3818 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003819 int len;
3820
3821 switch (exp->action) {
3822 case ACT_ALLOW:
3823 txn->flags |= TX_SVALLOW;
3824 done = 1;
3825 break;
3826
3827 case ACT_DENY:
3828 txn->flags |= TX_SVDENY;
3829 done = 1;
3830 break;
3831
3832 case ACT_REPLACE:
3833 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3834 if (len < 0)
3835 return -1;
3836
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003837 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3838 sl->info.res.status = strl2ui(code.ptr, code.len);
3839 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003840 return -1;
3841
3842 done = 1;
3843 return 1;
3844 }
3845 }
3846 return done;
3847}
3848
3849/*
3850 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3851 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3852 * unparsable response.
3853 */
3854static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3855{
3856 struct session *sess = s->sess;
3857 struct http_txn *txn = s->txn;
3858 struct hdr_exp *exp;
3859
3860 for (exp = px->rsp_exp; exp; exp = exp->next) {
3861 int ret;
3862
3863 /*
3864 * The interleaving of transformations and verdicts
3865 * makes it difficult to decide to continue or stop
3866 * the evaluation.
3867 */
3868
3869 if (txn->flags & TX_SVDENY)
3870 break;
3871
3872 if ((txn->flags & TX_SVALLOW) &&
3873 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3874 exp->action == ACT_PASS)) {
3875 exp = exp->next;
3876 continue;
3877 }
3878
3879 /* if this filter had a condition, evaluate it now and skip to
3880 * next filter if the condition does not match.
3881 */
3882 if (exp->cond) {
3883 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3884 ret = acl_pass(ret);
3885 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3886 ret = !ret;
3887 if (!ret)
3888 continue;
3889 }
3890
3891 /* Apply the filter to the status line. */
3892 ret = htx_apply_filter_to_sts_line(s, res, exp);
3893 if (unlikely(ret < 0))
3894 return -1;
3895
3896 if (likely(ret == 0)) {
3897 /* The filter did not match the response, it can be
3898 * iterated through all headers.
3899 */
3900 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3901 return -1;
3902 }
3903 }
3904 return 0;
3905}
3906
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003907/*
3908 * Manage client-side cookie. It can impact performance by about 2% so it is
3909 * desirable to call it only when needed. This code is quite complex because
3910 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3911 * highly recommended not to touch this part without a good reason !
3912 */
3913static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3914{
3915 struct session *sess = s->sess;
3916 struct http_txn *txn = s->txn;
3917 struct htx *htx;
3918 struct http_hdr_ctx ctx;
3919 char *hdr_beg, *hdr_end, *del_from;
3920 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3921 int preserve_hdr;
3922
3923 htx = htx_from_buf(&req->buf);
3924 ctx.blk = NULL;
3925 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3926 del_from = NULL; /* nothing to be deleted */
3927 preserve_hdr = 0; /* assume we may kill the whole header */
3928
3929 /* Now look for cookies. Conforming to RFC2109, we have to support
3930 * attributes whose name begin with a '$', and associate them with
3931 * the right cookie, if we want to delete this cookie.
3932 * So there are 3 cases for each cookie read :
3933 * 1) it's a special attribute, beginning with a '$' : ignore it.
3934 * 2) it's a server id cookie that we *MAY* want to delete : save
3935 * some pointers on it (last semi-colon, beginning of cookie...)
3936 * 3) it's an application cookie : we *MAY* have to delete a previous
3937 * "special" cookie.
3938 * At the end of loop, if a "special" cookie remains, we may have to
3939 * remove it. If no application cookie persists in the header, we
3940 * *MUST* delete it.
3941 *
3942 * Note: RFC2965 is unclear about the processing of spaces around
3943 * the equal sign in the ATTR=VALUE form. A careful inspection of
3944 * the RFC explicitly allows spaces before it, and not within the
3945 * tokens (attrs or values). An inspection of RFC2109 allows that
3946 * too but section 10.1.3 lets one think that spaces may be allowed
3947 * after the equal sign too, resulting in some (rare) buggy
3948 * implementations trying to do that. So let's do what servers do.
3949 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3950 * allowed quoted strings in values, with any possible character
3951 * after a backslash, including control chars and delimitors, which
3952 * causes parsing to become ambiguous. Browsers also allow spaces
3953 * within values even without quotes.
3954 *
3955 * We have to keep multiple pointers in order to support cookie
3956 * removal at the beginning, middle or end of header without
3957 * corrupting the header. All of these headers are valid :
3958 *
3959 * hdr_beg hdr_end
3960 * | |
3961 * v |
3962 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3963 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3964 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3965 * | | | | | | |
3966 * | | | | | | |
3967 * | | | | | | +--> next
3968 * | | | | | +----> val_end
3969 * | | | | +-----------> val_beg
3970 * | | | +--------------> equal
3971 * | | +----------------> att_end
3972 * | +---------------------> att_beg
3973 * +--------------------------> prev
3974 *
3975 */
3976 hdr_beg = ctx.value.ptr;
3977 hdr_end = hdr_beg + ctx.value.len;
3978 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3979 /* Iterate through all cookies on this line */
3980
3981 /* find att_beg */
3982 att_beg = prev;
3983 if (prev > hdr_beg)
3984 att_beg++;
3985
3986 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3987 att_beg++;
3988
3989 /* find att_end : this is the first character after the last non
3990 * space before the equal. It may be equal to hdr_end.
3991 */
3992 equal = att_end = att_beg;
3993 while (equal < hdr_end) {
3994 if (*equal == '=' || *equal == ',' || *equal == ';')
3995 break;
3996 if (HTTP_IS_SPHT(*equal++))
3997 continue;
3998 att_end = equal;
3999 }
4000
4001 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4002 * is between <att_beg> and <equal>, both may be identical.
4003 */
4004 /* look for end of cookie if there is an equal sign */
4005 if (equal < hdr_end && *equal == '=') {
4006 /* look for the beginning of the value */
4007 val_beg = equal + 1;
4008 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4009 val_beg++;
4010
4011 /* find the end of the value, respecting quotes */
4012 next = http_find_cookie_value_end(val_beg, hdr_end);
4013
4014 /* make val_end point to the first white space or delimitor after the value */
4015 val_end = next;
4016 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4017 val_end--;
4018 }
4019 else
4020 val_beg = val_end = next = equal;
4021
4022 /* We have nothing to do with attributes beginning with
4023 * '$'. However, they will automatically be removed if a
4024 * header before them is removed, since they're supposed
4025 * to be linked together.
4026 */
4027 if (*att_beg == '$')
4028 continue;
4029
4030 /* Ignore cookies with no equal sign */
4031 if (equal == next) {
4032 /* This is not our cookie, so we must preserve it. But if we already
4033 * scheduled another cookie for removal, we cannot remove the
4034 * complete header, but we can remove the previous block itself.
4035 */
4036 preserve_hdr = 1;
4037 if (del_from != NULL) {
4038 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4039 val_end += delta;
4040 next += delta;
4041 hdr_end += delta;
4042 prev = del_from;
4043 del_from = NULL;
4044 }
4045 continue;
4046 }
4047
4048 /* if there are spaces around the equal sign, we need to
4049 * strip them otherwise we'll get trouble for cookie captures,
4050 * or even for rewrites. Since this happens extremely rarely,
4051 * it does not hurt performance.
4052 */
4053 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4054 int stripped_before = 0;
4055 int stripped_after = 0;
4056
4057 if (att_end != equal) {
4058 memmove(att_end, equal, hdr_end - equal);
4059 stripped_before = (att_end - equal);
4060 equal += stripped_before;
4061 val_beg += stripped_before;
4062 }
4063
4064 if (val_beg > equal + 1) {
4065 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4066 stripped_after = (equal + 1) - val_beg;
4067 val_beg += stripped_after;
4068 stripped_before += stripped_after;
4069 }
4070
4071 val_end += stripped_before;
4072 next += stripped_before;
4073 hdr_end += stripped_before;
4074 }
4075 /* now everything is as on the diagram above */
4076
4077 /* First, let's see if we want to capture this cookie. We check
4078 * that we don't already have a client side cookie, because we
4079 * can only capture one. Also as an optimisation, we ignore
4080 * cookies shorter than the declared name.
4081 */
4082 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4083 (val_end - att_beg >= sess->fe->capture_namelen) &&
4084 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4085 int log_len = val_end - att_beg;
4086
4087 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4088 ha_alert("HTTP logging : out of memory.\n");
4089 } else {
4090 if (log_len > sess->fe->capture_len)
4091 log_len = sess->fe->capture_len;
4092 memcpy(txn->cli_cookie, att_beg, log_len);
4093 txn->cli_cookie[log_len] = 0;
4094 }
4095 }
4096
4097 /* Persistence cookies in passive, rewrite or insert mode have the
4098 * following form :
4099 *
4100 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4101 *
4102 * For cookies in prefix mode, the form is :
4103 *
4104 * Cookie: NAME=SRV~VALUE
4105 */
4106 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4107 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4108 struct server *srv = s->be->srv;
4109 char *delim;
4110
4111 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4112 * have the server ID between val_beg and delim, and the original cookie between
4113 * delim+1 and val_end. Otherwise, delim==val_end :
4114 *
4115 * hdr_beg
4116 * |
4117 * v
4118 * NAME=SRV; # in all but prefix modes
4119 * NAME=SRV~OPAQUE ; # in prefix mode
4120 * || || | |+-> next
4121 * || || | +--> val_end
4122 * || || +---------> delim
4123 * || |+------------> val_beg
4124 * || +-------------> att_end = equal
4125 * |+-----------------> att_beg
4126 * +------------------> prev
4127 *
4128 */
4129 if (s->be->ck_opts & PR_CK_PFX) {
4130 for (delim = val_beg; delim < val_end; delim++)
4131 if (*delim == COOKIE_DELIM)
4132 break;
4133 }
4134 else {
4135 char *vbar1;
4136 delim = val_end;
4137 /* Now check if the cookie contains a date field, which would
4138 * appear after a vertical bar ('|') just after the server name
4139 * and before the delimiter.
4140 */
4141 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4142 if (vbar1) {
4143 /* OK, so left of the bar is the server's cookie and
4144 * right is the last seen date. It is a base64 encoded
4145 * 30-bit value representing the UNIX date since the
4146 * epoch in 4-second quantities.
4147 */
4148 int val;
4149 delim = vbar1++;
4150 if (val_end - vbar1 >= 5) {
4151 val = b64tos30(vbar1);
4152 if (val > 0)
4153 txn->cookie_last_date = val << 2;
4154 }
4155 /* look for a second vertical bar */
4156 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4157 if (vbar1 && (val_end - vbar1 > 5)) {
4158 val = b64tos30(vbar1 + 1);
4159 if (val > 0)
4160 txn->cookie_first_date = val << 2;
4161 }
4162 }
4163 }
4164
4165 /* if the cookie has an expiration date and the proxy wants to check
4166 * it, then we do that now. We first check if the cookie is too old,
4167 * then only if it has expired. We detect strict overflow because the
4168 * time resolution here is not great (4 seconds). Cookies with dates
4169 * in the future are ignored if their offset is beyond one day. This
4170 * allows an admin to fix timezone issues without expiring everyone
4171 * and at the same time avoids keeping unwanted side effects for too
4172 * long.
4173 */
4174 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4175 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4176 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4177 txn->flags &= ~TX_CK_MASK;
4178 txn->flags |= TX_CK_OLD;
4179 delim = val_beg; // let's pretend we have not found the cookie
4180 txn->cookie_first_date = 0;
4181 txn->cookie_last_date = 0;
4182 }
4183 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4184 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4185 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4186 txn->flags &= ~TX_CK_MASK;
4187 txn->flags |= TX_CK_EXPIRED;
4188 delim = val_beg; // let's pretend we have not found the cookie
4189 txn->cookie_first_date = 0;
4190 txn->cookie_last_date = 0;
4191 }
4192
4193 /* Here, we'll look for the first running server which supports the cookie.
4194 * This allows to share a same cookie between several servers, for example
4195 * to dedicate backup servers to specific servers only.
4196 * However, to prevent clients from sticking to cookie-less backup server
4197 * when they have incidentely learned an empty cookie, we simply ignore
4198 * empty cookies and mark them as invalid.
4199 * The same behaviour is applied when persistence must be ignored.
4200 */
4201 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4202 srv = NULL;
4203
4204 while (srv) {
4205 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4206 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4207 if ((srv->cur_state != SRV_ST_STOPPED) ||
4208 (s->be->options & PR_O_PERSIST) ||
4209 (s->flags & SF_FORCE_PRST)) {
4210 /* we found the server and we can use it */
4211 txn->flags &= ~TX_CK_MASK;
4212 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4213 s->flags |= SF_DIRECT | SF_ASSIGNED;
4214 s->target = &srv->obj_type;
4215 break;
4216 } else {
4217 /* we found a server, but it's down,
4218 * mark it as such and go on in case
4219 * another one is available.
4220 */
4221 txn->flags &= ~TX_CK_MASK;
4222 txn->flags |= TX_CK_DOWN;
4223 }
4224 }
4225 srv = srv->next;
4226 }
4227
4228 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4229 /* no server matched this cookie or we deliberately skipped it */
4230 txn->flags &= ~TX_CK_MASK;
4231 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4232 txn->flags |= TX_CK_UNUSED;
4233 else
4234 txn->flags |= TX_CK_INVALID;
4235 }
4236
4237 /* depending on the cookie mode, we may have to either :
4238 * - delete the complete cookie if we're in insert+indirect mode, so that
4239 * the server never sees it ;
4240 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004241 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004242 * if we're in cookie prefix mode
4243 */
4244 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4245 int delta; /* negative */
4246
4247 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4248 delta = val_beg - (delim + 1);
4249 val_end += delta;
4250 next += delta;
4251 hdr_end += delta;
4252 del_from = NULL;
4253 preserve_hdr = 1; /* we want to keep this cookie */
4254 }
4255 else if (del_from == NULL &&
4256 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4257 del_from = prev;
4258 }
4259 }
4260 else {
4261 /* This is not our cookie, so we must preserve it. But if we already
4262 * scheduled another cookie for removal, we cannot remove the
4263 * complete header, but we can remove the previous block itself.
4264 */
4265 preserve_hdr = 1;
4266
4267 if (del_from != NULL) {
4268 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4269 if (att_beg >= del_from)
4270 att_beg += delta;
4271 if (att_end >= del_from)
4272 att_end += delta;
4273 val_beg += delta;
4274 val_end += delta;
4275 next += delta;
4276 hdr_end += delta;
4277 prev = del_from;
4278 del_from = NULL;
4279 }
4280 }
4281
4282 /* continue with next cookie on this header line */
4283 att_beg = next;
4284 } /* for each cookie */
4285
4286
4287 /* There are no more cookies on this line.
4288 * We may still have one (or several) marked for deletion at the
4289 * end of the line. We must do this now in two ways :
4290 * - if some cookies must be preserved, we only delete from the
4291 * mark to the end of line ;
4292 * - if nothing needs to be preserved, simply delete the whole header
4293 */
4294 if (del_from) {
4295 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4296 }
4297 if ((hdr_end - hdr_beg) != ctx.value.len) {
4298 if (hdr_beg != hdr_end) {
4299 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4300 htx->data -= (hdr_end - ctx.value.ptr);
4301 }
4302 else
4303 http_remove_header(htx, &ctx);
4304 }
4305 } /* for each "Cookie header */
4306}
4307
4308/*
4309 * Manage server-side cookies. It can impact performance by about 2% so it is
4310 * desirable to call it only when needed. This function is also used when we
4311 * just need to know if there is a cookie (eg: for check-cache).
4312 */
4313static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4314{
4315 struct session *sess = s->sess;
4316 struct http_txn *txn = s->txn;
4317 struct htx *htx;
4318 struct http_hdr_ctx ctx;
4319 struct server *srv;
4320 char *hdr_beg, *hdr_end;
4321 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4322 int is_cookie2;
4323
4324 htx = htx_from_buf(&res->buf);
4325
4326 ctx.blk = NULL;
4327 while (1) {
4328 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4329 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4330 break;
4331 is_cookie2 = 1;
4332 }
4333
4334 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4335 * <prev> points to the colon.
4336 */
4337 txn->flags |= TX_SCK_PRESENT;
4338
4339 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4340 * check-cache is enabled) and we are not interested in checking
4341 * them. Warning, the cookie capture is declared in the frontend.
4342 */
4343 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4344 break;
4345
4346 /* OK so now we know we have to process this response cookie.
4347 * The format of the Set-Cookie header is slightly different
4348 * from the format of the Cookie header in that it does not
4349 * support the comma as a cookie delimiter (thus the header
4350 * cannot be folded) because the Expires attribute described in
4351 * the original Netscape's spec may contain an unquoted date
4352 * with a comma inside. We have to live with this because
4353 * many browsers don't support Max-Age and some browsers don't
4354 * support quoted strings. However the Set-Cookie2 header is
4355 * clean.
4356 *
4357 * We have to keep multiple pointers in order to support cookie
4358 * removal at the beginning, middle or end of header without
4359 * corrupting the header (in case of set-cookie2). A special
4360 * pointer, <scav> points to the beginning of the set-cookie-av
4361 * fields after the first semi-colon. The <next> pointer points
4362 * either to the end of line (set-cookie) or next unquoted comma
4363 * (set-cookie2). All of these headers are valid :
4364 *
4365 * hdr_beg hdr_end
4366 * | |
4367 * v |
4368 * NAME1 = VALUE 1 ; Secure; Path="/" |
4369 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4370 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4371 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4372 * | | | | | | | |
4373 * | | | | | | | +-> next
4374 * | | | | | | +------------> scav
4375 * | | | | | +--------------> val_end
4376 * | | | | +--------------------> val_beg
4377 * | | | +----------------------> equal
4378 * | | +------------------------> att_end
4379 * | +----------------------------> att_beg
4380 * +------------------------------> prev
4381 * -------------------------------> hdr_beg
4382 */
4383 hdr_beg = ctx.value.ptr;
4384 hdr_end = hdr_beg + ctx.value.len;
4385 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4386
4387 /* Iterate through all cookies on this line */
4388
4389 /* find att_beg */
4390 att_beg = prev;
4391 if (prev > hdr_beg)
4392 att_beg++;
4393
4394 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4395 att_beg++;
4396
4397 /* find att_end : this is the first character after the last non
4398 * space before the equal. It may be equal to hdr_end.
4399 */
4400 equal = att_end = att_beg;
4401
4402 while (equal < hdr_end) {
4403 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4404 break;
4405 if (HTTP_IS_SPHT(*equal++))
4406 continue;
4407 att_end = equal;
4408 }
4409
4410 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4411 * is between <att_beg> and <equal>, both may be identical.
4412 */
4413
4414 /* look for end of cookie if there is an equal sign */
4415 if (equal < hdr_end && *equal == '=') {
4416 /* look for the beginning of the value */
4417 val_beg = equal + 1;
4418 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4419 val_beg++;
4420
4421 /* find the end of the value, respecting quotes */
4422 next = http_find_cookie_value_end(val_beg, hdr_end);
4423
4424 /* make val_end point to the first white space or delimitor after the value */
4425 val_end = next;
4426 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4427 val_end--;
4428 }
4429 else {
4430 /* <equal> points to next comma, semi-colon or EOL */
4431 val_beg = val_end = next = equal;
4432 }
4433
4434 if (next < hdr_end) {
4435 /* Set-Cookie2 supports multiple cookies, and <next> points to
4436 * a colon or semi-colon before the end. So skip all attr-value
4437 * pairs and look for the next comma. For Set-Cookie, since
4438 * commas are permitted in values, skip to the end.
4439 */
4440 if (is_cookie2)
4441 next = http_find_hdr_value_end(next, hdr_end);
4442 else
4443 next = hdr_end;
4444 }
4445
4446 /* Now everything is as on the diagram above */
4447
4448 /* Ignore cookies with no equal sign */
4449 if (equal == val_end)
4450 continue;
4451
4452 /* If there are spaces around the equal sign, we need to
4453 * strip them otherwise we'll get trouble for cookie captures,
4454 * or even for rewrites. Since this happens extremely rarely,
4455 * it does not hurt performance.
4456 */
4457 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4458 int stripped_before = 0;
4459 int stripped_after = 0;
4460
4461 if (att_end != equal) {
4462 memmove(att_end, equal, hdr_end - equal);
4463 stripped_before = (att_end - equal);
4464 equal += stripped_before;
4465 val_beg += stripped_before;
4466 }
4467
4468 if (val_beg > equal + 1) {
4469 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4470 stripped_after = (equal + 1) - val_beg;
4471 val_beg += stripped_after;
4472 stripped_before += stripped_after;
4473 }
4474
4475 val_end += stripped_before;
4476 next += stripped_before;
4477 hdr_end += stripped_before;
4478
4479 ctx.value.len = hdr_end - hdr_beg;
4480 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4481 htx->data -= (hdr_end - ctx.value.ptr);
4482 }
4483
4484 /* First, let's see if we want to capture this cookie. We check
4485 * that we don't already have a server side cookie, because we
4486 * can only capture one. Also as an optimisation, we ignore
4487 * cookies shorter than the declared name.
4488 */
4489 if (sess->fe->capture_name != NULL &&
4490 txn->srv_cookie == NULL &&
4491 (val_end - att_beg >= sess->fe->capture_namelen) &&
4492 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4493 int log_len = val_end - att_beg;
4494 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4495 ha_alert("HTTP logging : out of memory.\n");
4496 }
4497 else {
4498 if (log_len > sess->fe->capture_len)
4499 log_len = sess->fe->capture_len;
4500 memcpy(txn->srv_cookie, att_beg, log_len);
4501 txn->srv_cookie[log_len] = 0;
4502 }
4503 }
4504
4505 srv = objt_server(s->target);
4506 /* now check if we need to process it for persistence */
4507 if (!(s->flags & SF_IGNORE_PRST) &&
4508 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4509 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4510 /* assume passive cookie by default */
4511 txn->flags &= ~TX_SCK_MASK;
4512 txn->flags |= TX_SCK_FOUND;
4513
4514 /* If the cookie is in insert mode on a known server, we'll delete
4515 * this occurrence because we'll insert another one later.
4516 * We'll delete it too if the "indirect" option is set and we're in
4517 * a direct access.
4518 */
4519 if (s->be->ck_opts & PR_CK_PSV) {
4520 /* The "preserve" flag was set, we don't want to touch the
4521 * server's cookie.
4522 */
4523 }
4524 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4525 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4526 /* this cookie must be deleted */
4527 if (prev == hdr_beg && next == hdr_end) {
4528 /* whole header */
4529 http_remove_header(htx, &ctx);
4530 /* note: while both invalid now, <next> and <hdr_end>
4531 * are still equal, so the for() will stop as expected.
4532 */
4533 } else {
4534 /* just remove the value */
4535 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4536 next = prev;
4537 hdr_end += delta;
4538 }
4539 txn->flags &= ~TX_SCK_MASK;
4540 txn->flags |= TX_SCK_DELETED;
4541 /* and go on with next cookie */
4542 }
4543 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4544 /* replace bytes val_beg->val_end with the cookie name associated
4545 * with this server since we know it.
4546 */
4547 int sliding, delta;
4548
4549 ctx.value = ist2(val_beg, val_end - val_beg);
4550 ctx.lws_before = ctx.lws_after = 0;
4551 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4552 delta = srv->cklen - (val_end - val_beg);
4553 sliding = (ctx.value.ptr - val_beg);
4554 hdr_beg += sliding;
4555 val_beg += sliding;
4556 next += sliding + delta;
4557 hdr_end += sliding + delta;
4558
4559 txn->flags &= ~TX_SCK_MASK;
4560 txn->flags |= TX_SCK_REPLACED;
4561 }
4562 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4563 /* insert the cookie name associated with this server
4564 * before existing cookie, and insert a delimiter between them..
4565 */
4566 int sliding, delta;
4567 ctx.value = ist2(val_beg, 0);
4568 ctx.lws_before = ctx.lws_after = 0;
4569 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4570 delta = srv->cklen + 1;
4571 sliding = (ctx.value.ptr - val_beg);
4572 hdr_beg += sliding;
4573 val_beg += sliding;
4574 next += sliding + delta;
4575 hdr_end += sliding + delta;
4576
4577 val_beg[srv->cklen] = COOKIE_DELIM;
4578 txn->flags &= ~TX_SCK_MASK;
4579 txn->flags |= TX_SCK_REPLACED;
4580 }
4581 }
4582 /* that's done for this cookie, check the next one on the same
4583 * line when next != hdr_end (only if is_cookie2).
4584 */
4585 }
4586 }
4587}
4588
Christopher Faulet25a02f62018-10-24 12:00:25 +02004589/*
4590 * Parses the Cache-Control and Pragma request header fields to determine if
4591 * the request may be served from the cache and/or if it is cacheable. Updates
4592 * s->txn->flags.
4593 */
4594void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4595{
4596 struct http_txn *txn = s->txn;
4597 struct htx *htx;
4598 int32_t pos;
4599 int pragma_found, cc_found, i;
4600
4601 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4602 return; /* nothing more to do here */
4603
4604 htx = htx_from_buf(&req->buf);
4605 pragma_found = cc_found = 0;
4606 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4607 struct htx_blk *blk = htx_get_blk(htx, pos);
4608 enum htx_blk_type type = htx_get_blk_type(blk);
4609 struct ist n, v;
4610
4611 if (type == HTX_BLK_EOH)
4612 break;
4613 if (type != HTX_BLK_HDR)
4614 continue;
4615
4616 n = htx_get_blk_name(htx, blk);
4617 v = htx_get_blk_value(htx, blk);
4618
4619 if (isteqi(n, ist("Pragma"))) {
4620 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4621 pragma_found = 1;
4622 continue;
4623 }
4624 }
4625
4626 /* Don't use the cache and don't try to store if we found the
4627 * Authorization header */
4628 if (isteqi(n, ist("Authorization"))) {
4629 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4630 txn->flags |= TX_CACHE_IGNORE;
4631 continue;
4632 }
4633
4634 if (!isteqi(n, ist("Cache-control")))
4635 continue;
4636
4637 /* OK, right now we know we have a cache-control header */
4638 cc_found = 1;
4639 if (!v.len) /* no info */
4640 continue;
4641
4642 i = 0;
4643 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4644 !isspace((unsigned char)*(v.ptr+i)))
4645 i++;
4646
4647 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4648 * values after max-age, max-stale nor min-fresh, we simply don't
4649 * use the cache when they're specified.
4650 */
4651 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4652 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4653 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4654 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4655 txn->flags |= TX_CACHE_IGNORE;
4656 continue;
4657 }
4658
4659 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4660 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4661 continue;
4662 }
4663 }
4664
4665 /* RFC7234#5.4:
4666 * When the Cache-Control header field is also present and
4667 * understood in a request, Pragma is ignored.
4668 * When the Cache-Control header field is not present in a
4669 * request, caches MUST consider the no-cache request
4670 * pragma-directive as having the same effect as if
4671 * "Cache-Control: no-cache" were present.
4672 */
4673 if (!cc_found && pragma_found)
4674 txn->flags |= TX_CACHE_IGNORE;
4675}
4676
4677/*
4678 * Check if response is cacheable or not. Updates s->txn->flags.
4679 */
4680void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4681{
4682 struct http_txn *txn = s->txn;
4683 struct htx *htx;
4684 int32_t pos;
4685 int i;
4686
4687 if (txn->status < 200) {
4688 /* do not try to cache interim responses! */
4689 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4690 return;
4691 }
4692
4693 htx = htx_from_buf(&res->buf);
4694 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4695 struct htx_blk *blk = htx_get_blk(htx, pos);
4696 enum htx_blk_type type = htx_get_blk_type(blk);
4697 struct ist n, v;
4698
4699 if (type == HTX_BLK_EOH)
4700 break;
4701 if (type != HTX_BLK_HDR)
4702 continue;
4703
4704 n = htx_get_blk_name(htx, blk);
4705 v = htx_get_blk_value(htx, blk);
4706
4707 if (isteqi(n, ist("Pragma"))) {
4708 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4709 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4710 return;
4711 }
4712 }
4713
4714 if (!isteqi(n, ist("Cache-control")))
4715 continue;
4716
4717 /* OK, right now we know we have a cache-control header */
4718 if (!v.len) /* no info */
4719 continue;
4720
4721 i = 0;
4722 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4723 !isspace((unsigned char)*(v.ptr+i)))
4724 i++;
4725
4726 /* we have a complete value between v.ptr and (v.ptr+i) */
4727 if (i < v.len && *(v.ptr + i) == '=') {
4728 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4729 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4730 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4731 continue;
4732 }
4733
4734 /* we have something of the form no-cache="set-cookie" */
4735 if ((v.len >= 21) &&
4736 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4737 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4738 txn->flags &= ~TX_CACHE_COOK;
4739 continue;
4740 }
4741
4742 /* OK, so we know that either p2 points to the end of string or to a comma */
4743 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4744 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4745 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4746 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4747 return;
4748 }
4749
4750 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4751 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4752 continue;
4753 }
4754 }
4755}
4756
Christopher Faulet64159df2018-10-24 21:15:35 +02004757/* send a server's name with an outgoing request over an established connection.
4758 * Note: this function is designed to be called once the request has been
4759 * scheduled for being forwarded. This is the reason why the number of forwarded
4760 * bytes have to be adjusted.
4761 */
4762int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4763{
4764 struct htx *htx;
4765 struct http_hdr_ctx ctx;
4766 struct ist hdr;
4767 uint32_t data;
4768
4769 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
4770 htx = htx_from_buf(&s->req.buf);
4771 data = htx->data;
4772
4773 ctx.blk = NULL;
4774 while (http_find_header(htx, hdr, &ctx, 1))
4775 http_remove_header(htx, &ctx);
4776 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4777
4778 if (co_data(&s->req)) {
4779 if (data >= htx->data)
4780 c_rew(&s->req, data - htx->data);
4781 else
4782 c_adv(&s->req, htx->data - data);
4783 }
4784 return 0;
4785}
4786
Christopher Faulet377c5a52018-10-24 21:21:30 +02004787/*
4788 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4789 * for the current backend.
4790 *
4791 * It is assumed that the request is either a HEAD, GET, or POST and that the
4792 * uri_auth field is valid.
4793 *
4794 * Returns 1 if stats should be provided, otherwise 0.
4795 */
4796static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4797{
4798 struct uri_auth *uri_auth = backend->uri_auth;
4799 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004800 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004801 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004802
4803 if (!uri_auth)
4804 return 0;
4805
4806 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4807 return 0;
4808
4809 htx = htx_from_buf(&s->req.buf);
4810 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004811 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004812
4813 /* check URI size */
4814 if (uri_auth->uri_len > uri.len)
4815 return 0;
4816
4817 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4818 return 0;
4819
4820 return 1;
4821}
4822
4823/* This function prepares an applet to handle the stats. It can deal with the
4824 * "100-continue" expectation, check that admin rules are met for POST requests,
4825 * and program a response message if something was unexpected. It cannot fail
4826 * and always relies on the stats applet to complete the job. It does not touch
4827 * analysers nor counters, which are left to the caller. It does not touch
4828 * s->target which is supposed to already point to the stats applet. The caller
4829 * is expected to have already assigned an appctx to the stream.
4830 */
4831static int htx_handle_stats(struct stream *s, struct channel *req)
4832{
4833 struct stats_admin_rule *stats_admin_rule;
4834 struct stream_interface *si = &s->si[1];
4835 struct session *sess = s->sess;
4836 struct http_txn *txn = s->txn;
4837 struct http_msg *msg = &txn->req;
4838 struct uri_auth *uri_auth = s->be->uri_auth;
4839 const char *h, *lookup, *end;
4840 struct appctx *appctx;
4841 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004842 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004843
4844 appctx = si_appctx(si);
4845 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4846 appctx->st1 = appctx->st2 = 0;
4847 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4848 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4849 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4850 appctx->ctx.stats.flags |= STAT_CHUNKED;
4851
4852 htx = htx_from_buf(&req->buf);
4853 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004854 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4855 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004856
4857 for (h = lookup; h <= end - 3; h++) {
4858 if (memcmp(h, ";up", 3) == 0) {
4859 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4860 break;
4861 }
4862 }
4863
4864 if (uri_auth->refresh) {
4865 for (h = lookup; h <= end - 10; h++) {
4866 if (memcmp(h, ";norefresh", 10) == 0) {
4867 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4868 break;
4869 }
4870 }
4871 }
4872
4873 for (h = lookup; h <= end - 4; h++) {
4874 if (memcmp(h, ";csv", 4) == 0) {
4875 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4876 break;
4877 }
4878 }
4879
4880 for (h = lookup; h <= end - 6; h++) {
4881 if (memcmp(h, ";typed", 6) == 0) {
4882 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4883 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4884 break;
4885 }
4886 }
4887
4888 for (h = lookup; h <= end - 8; h++) {
4889 if (memcmp(h, ";st=", 4) == 0) {
4890 int i;
4891 h += 4;
4892 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4893 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4894 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4895 appctx->ctx.stats.st_code = i;
4896 break;
4897 }
4898 }
4899 break;
4900 }
4901 }
4902
4903 appctx->ctx.stats.scope_str = 0;
4904 appctx->ctx.stats.scope_len = 0;
4905 for (h = lookup; h <= end - 8; h++) {
4906 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4907 int itx = 0;
4908 const char *h2;
4909 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4910 const char *err;
4911
4912 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4913 h2 = h;
4914 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4915 while (h <= end) {
4916 if (*h == ';' || *h == '&' || *h == ' ')
4917 break;
4918 itx++;
4919 h++;
4920 }
4921
4922 if (itx > STAT_SCOPE_TXT_MAXLEN)
4923 itx = STAT_SCOPE_TXT_MAXLEN;
4924 appctx->ctx.stats.scope_len = itx;
4925
4926 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4927 memcpy(scope_txt, h2, itx);
4928 scope_txt[itx] = '\0';
4929 err = invalid_char(scope_txt);
4930 if (err) {
4931 /* bad char in search text => clear scope */
4932 appctx->ctx.stats.scope_str = 0;
4933 appctx->ctx.stats.scope_len = 0;
4934 }
4935 break;
4936 }
4937 }
4938
4939 /* now check whether we have some admin rules for this request */
4940 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4941 int ret = 1;
4942
4943 if (stats_admin_rule->cond) {
4944 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4945 ret = acl_pass(ret);
4946 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4947 ret = !ret;
4948 }
4949
4950 if (ret) {
4951 /* no rule, or the rule matches */
4952 appctx->ctx.stats.flags |= STAT_ADMIN;
4953 break;
4954 }
4955 }
4956
4957 /* Was the status page requested with a POST ? */
4958 if (unlikely(txn->meth == HTTP_METH_POST)) {
4959 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4960 /* we'll need the request body, possibly after sending 100-continue */
4961 if (msg->msg_state < HTTP_MSG_DATA)
4962 req->analysers |= AN_REQ_HTTP_BODY;
4963 appctx->st0 = STAT_HTTP_POST;
4964 }
4965 else {
4966 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4967 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4968 appctx->st0 = STAT_HTTP_LAST;
4969 }
4970 }
4971 else {
4972 /* So it was another method (GET/HEAD) */
4973 appctx->st0 = STAT_HTTP_HEAD;
4974 }
4975
4976 s->task->nice = -32; /* small boost for HTTP statistics */
4977 return 1;
4978}
4979
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004980void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4981{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004982 struct channel *req = &s->req;
4983 struct channel *res = &s->res;
4984 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004985 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004986 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004987 struct ist path, location;
4988 unsigned int flags;
4989 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004991 /*
4992 * Create the location
4993 */
4994 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004995
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004996 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004997 /* special prefix "/" means don't change URL */
4998 srv = __objt_server(s->target);
4999 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
5000 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
5001 return;
5002 }
5003
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005004 /* 2: add the request Path */
5005 htx = htx_from_buf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005006 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005007 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005008 if (!path.ptr)
5009 return;
5010
5011 if (!chunk_memcat(&trash, path.ptr, path.len))
5012 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005013 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005014
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005015 /*
5016 * Create the 302 respone
5017 */
5018 htx = htx_from_buf(&res->buf);
5019 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5020 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5021 ist("HTTP/1.1"), ist("302"), ist("Found"));
5022 if (!sl)
5023 goto fail;
5024 sl->info.res.status = 302;
5025 s->txn->status = 302;
5026
5027 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5028 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5029 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5030 !htx_add_header(htx, ist("Location"), location))
5031 goto fail;
5032
5033 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5034 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005035
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005036 /*
5037 * Send the message
5038 */
5039 data = htx->data - co_data(res);
5040 b_set_data(&res->buf, b_size(&res->buf));
5041 c_adv(res, data);
5042 res->total += data;
5043
5044 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045 si_shutr(si);
5046 si_shutw(si);
5047 si->err_type = SI_ET_NONE;
5048 si->state = SI_ST_CLO;
5049
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005050 channel_auto_read(req);
5051 channel_abort(req);
5052 channel_auto_close(req);
5053 channel_erase(req);
5054 channel_auto_read(res);
5055 channel_auto_close(res);
5056
5057 if (!(s->flags & SF_ERR_MASK))
5058 s->flags |= SF_ERR_LOCAL;
5059 if (!(s->flags & SF_FINST_MASK))
5060 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005061
5062 /* FIXME: we should increase a counter of redirects per server and per backend. */
5063 srv_inc_sess_ctr(srv);
5064 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005065 return;
5066
5067 fail:
5068 /* If an error occurred, remove the incomplete HTTP response from the
5069 * buffer */
5070 channel_truncate(res);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005071}
5072
Christopher Fauletf2824e62018-10-01 12:12:37 +02005073/* This function terminates the request because it was completly analyzed or
5074 * because an error was triggered during the body forwarding.
5075 */
5076static void htx_end_request(struct stream *s)
5077{
5078 struct channel *chn = &s->req;
5079 struct http_txn *txn = s->txn;
5080
5081 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5082 now_ms, __FUNCTION__, s,
5083 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5084 s->req.analysers, s->res.analysers);
5085
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005086 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5087 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005088 channel_abort(chn);
5089 channel_truncate(chn);
5090 goto end;
5091 }
5092
5093 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5094 return;
5095
5096 if (txn->req.msg_state == HTTP_MSG_DONE) {
5097 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5098 /* The server has not finished to respond, so we
5099 * don't want to move in order not to upset it.
5100 */
5101 return;
5102 }
5103
5104 /* No need to read anymore, the request was completely parsed.
5105 * We can shut the read side unless we want to abort_on_close,
5106 * or we have a POST request. The issue with POST requests is
5107 * that some browsers still send a CRLF after the request, and
5108 * this CRLF must be read so that it does not remain in the kernel
5109 * buffers, otherwise a close could cause an RST on some systems
5110 * (eg: Linux).
5111 */
5112 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5113 txn->meth != HTTP_METH_POST)
5114 channel_dont_read(chn);
5115
5116 /* if the server closes the connection, we want to immediately react
5117 * and close the socket to save packets and syscalls.
5118 */
5119 s->si[1].flags |= SI_FL_NOHALF;
5120
5121 /* In any case we've finished parsing the request so we must
5122 * disable Nagle when sending data because 1) we're not going
5123 * to shut this side, and 2) the server is waiting for us to
5124 * send pending data.
5125 */
5126 chn->flags |= CF_NEVER_WAIT;
5127
5128 /* When we get here, it means that both the request and the
5129 * response have finished receiving. Depending on the connection
5130 * mode, we'll have to wait for the last bytes to leave in either
5131 * direction, and sometimes for a close to be effective.
5132 */
5133 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5134 /* Tunnel mode will not have any analyser so it needs to
5135 * poll for reads.
5136 */
5137 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005138 if (b_data(&chn->buf))
5139 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005140 txn->req.msg_state = HTTP_MSG_TUNNEL;
5141 }
5142 else {
5143 /* we're not expecting any new data to come for this
5144 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005145 *
5146 * However, there is an exception if the response
5147 * length is undefined. In this case, we need to wait
5148 * the close from the server. The response will be
5149 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005150 */
5151 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5152 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005153 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005154
5155 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5156 channel_shutr_now(chn);
5157 channel_shutw_now(chn);
5158 }
5159 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 goto check_channel_flags;
5161 }
5162
5163 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5164 http_msg_closing:
5165 /* nothing else to forward, just waiting for the output buffer
5166 * to be empty and for the shutw_now to take effect.
5167 */
5168 if (channel_is_empty(chn)) {
5169 txn->req.msg_state = HTTP_MSG_CLOSED;
5170 goto http_msg_closed;
5171 }
5172 else if (chn->flags & CF_SHUTW) {
5173 txn->req.err_state = txn->req.msg_state;
5174 txn->req.msg_state = HTTP_MSG_ERROR;
5175 goto end;
5176 }
5177 return;
5178 }
5179
5180 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5181 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005182 /* if we don't know whether the server will close, we need to hard close */
5183 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5184 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005185 /* see above in MSG_DONE why we only do this in these states */
5186 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5187 channel_dont_read(chn);
5188 goto end;
5189 }
5190
5191 check_channel_flags:
5192 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5193 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5194 /* if we've just closed an output, let's switch */
5195 txn->req.msg_state = HTTP_MSG_CLOSING;
5196 goto http_msg_closing;
5197 }
5198
5199 end:
5200 chn->analysers &= AN_REQ_FLT_END;
5201 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5202 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5203 channel_auto_close(chn);
5204 channel_auto_read(chn);
5205}
5206
5207
5208/* This function terminates the response because it was completly analyzed or
5209 * because an error was triggered during the body forwarding.
5210 */
5211static void htx_end_response(struct stream *s)
5212{
5213 struct channel *chn = &s->res;
5214 struct http_txn *txn = s->txn;
5215
5216 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5217 now_ms, __FUNCTION__, s,
5218 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5219 s->req.analysers, s->res.analysers);
5220
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005221 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5222 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf3d48052018-12-04 16:23:54 +01005223 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005224 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005225 goto end;
5226 }
5227
5228 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5229 return;
5230
5231 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5232 /* In theory, we don't need to read anymore, but we must
5233 * still monitor the server connection for a possible close
5234 * while the request is being uploaded, so we don't disable
5235 * reading.
5236 */
5237 /* channel_dont_read(chn); */
5238
5239 if (txn->req.msg_state < HTTP_MSG_DONE) {
5240 /* The client seems to still be sending data, probably
5241 * because we got an error response during an upload.
5242 * We have the choice of either breaking the connection
5243 * or letting it pass through. Let's do the later.
5244 */
5245 return;
5246 }
5247
5248 /* When we get here, it means that both the request and the
5249 * response have finished receiving. Depending on the connection
5250 * mode, we'll have to wait for the last bytes to leave in either
5251 * direction, and sometimes for a close to be effective.
5252 */
5253 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5254 channel_auto_read(chn);
5255 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005256 if (b_data(&chn->buf))
5257 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005258 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5259 }
5260 else {
5261 /* we're not expecting any new data to come for this
5262 * transaction, so we can close it.
5263 */
5264 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5265 channel_shutr_now(chn);
5266 channel_shutw_now(chn);
5267 }
5268 }
5269 goto check_channel_flags;
5270 }
5271
5272 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5273 http_msg_closing:
5274 /* nothing else to forward, just waiting for the output buffer
5275 * to be empty and for the shutw_now to take effect.
5276 */
5277 if (channel_is_empty(chn)) {
5278 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5279 goto http_msg_closed;
5280 }
5281 else if (chn->flags & CF_SHUTW) {
5282 txn->rsp.err_state = txn->rsp.msg_state;
5283 txn->rsp.msg_state = HTTP_MSG_ERROR;
5284 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5285 if (objt_server(s->target))
5286 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5287 goto end;
5288 }
5289 return;
5290 }
5291
5292 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5293 http_msg_closed:
5294 /* drop any pending data */
Christopher Fauletf3d48052018-12-04 16:23:54 +01005295 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005296 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005297 goto end;
5298 }
5299
5300 check_channel_flags:
5301 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5302 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5303 /* if we've just closed an output, let's switch */
5304 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5305 goto http_msg_closing;
5306 }
5307
5308 end:
5309 chn->analysers &= AN_RES_FLT_END;
5310 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5311 chn->analysers |= AN_RES_FLT_XFER_DATA;
5312 channel_auto_close(chn);
5313 channel_auto_read(chn);
5314}
5315
Christopher Faulet0f226952018-10-22 09:29:56 +02005316void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5317 int finst, const struct buffer *msg)
5318{
5319 channel_auto_read(si_oc(si));
5320 channel_abort(si_oc(si));
5321 channel_auto_close(si_oc(si));
5322 channel_erase(si_oc(si));
5323 channel_auto_close(si_ic(si));
5324 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005325
5326 /* <msg> is an HTX structure. So we copy it in the response's
5327 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005328 if (msg) {
5329 struct channel *chn = si_ic(si);
5330 struct htx *htx;
5331
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005332 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005333 chn->buf.data = msg->data;
5334 memcpy(chn->buf.area, msg->area, msg->data);
5335 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005336 b_set_data(&chn->buf, b_size(&chn->buf));
5337 c_adv(chn, htx->data);
5338 chn->total += htx->data;
5339 }
5340 if (!(s->flags & SF_ERR_MASK))
5341 s->flags |= err;
5342 if (!(s->flags & SF_FINST_MASK))
5343 s->flags |= finst;
5344}
5345
5346void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5347{
5348 channel_auto_read(&s->req);
5349 channel_abort(&s->req);
5350 channel_auto_close(&s->req);
5351 channel_erase(&s->req);
5352 channel_truncate(&s->res);
5353
5354 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005355
5356 /* <msg> is an HTX structure. So we copy it in the response's
5357 * channel */
5358 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005359 if (msg) {
5360 struct channel *chn = &s->res;
5361 struct htx *htx;
5362
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005363 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005364 chn->buf.data = msg->data;
5365 memcpy(chn->buf.area, msg->area, msg->data);
5366 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005367 b_set_data(&chn->buf, b_size(&chn->buf));
5368 c_adv(chn, htx->data);
5369 chn->total += htx->data;
5370 }
5371
5372 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5373 channel_auto_read(&s->res);
5374 channel_auto_close(&s->res);
5375 channel_shutr_now(&s->res);
5376}
5377
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005378struct buffer *htx_error_message(struct stream *s)
5379{
5380 const int msgnum = http_get_status_idx(s->txn->status);
5381
5382 if (s->be->errmsg[msgnum].area)
5383 return &s->be->errmsg[msgnum];
5384 else if (strm_fe(s)->errmsg[msgnum].area)
5385 return &strm_fe(s)->errmsg[msgnum];
5386 else
5387 return &htx_err_chunks[msgnum];
5388}
5389
5390
Christopher Faulet23a3c792018-11-28 10:01:23 +01005391/* Send a 100-Continue response to the client. It returns 0 on success and -1
5392 * on error. The response channel is updated accordingly.
5393 */
5394static int htx_reply_100_continue(struct stream *s)
5395{
5396 struct channel *res = &s->res;
5397 struct htx *htx = htx_from_buf(&res->buf);
5398 struct htx_sl *sl;
5399 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5400 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5401 size_t data;
5402
5403 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5404 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5405 if (!sl)
5406 goto fail;
5407 sl->info.res.status = 100;
5408
5409 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5410 goto fail;
5411
5412 data = htx->data - co_data(res);
5413 b_set_data(&res->buf, b_size(&res->buf));
5414 c_adv(res, data);
5415 res->total += data;
5416 return 0;
5417
5418 fail:
5419 /* If an error occurred, remove the incomplete HTTP response from the
5420 * buffer */
5421 channel_truncate(res);
5422 return -1;
5423}
5424
Christopher Faulet12c51e22018-11-28 15:59:42 +01005425
5426/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5427 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5428 * error. The response channel is updated accordingly.
5429 */
5430static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5431{
5432 struct channel *res = &s->res;
5433 struct htx *htx = htx_from_buf(&res->buf);
5434 struct htx_sl *sl;
5435 struct ist code, body;
5436 int status;
5437 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5438 size_t data;
5439
5440 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5441 status = 401;
5442 code = ist("401");
5443 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5444 "You need a valid user and password to access this content.\n"
5445 "</body></html>\n");
5446 }
5447 else {
5448 status = 407;
5449 code = ist("407");
5450 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5451 "You need a valid user and password to access this content.\n"
5452 "</body></html>\n");
5453 }
5454
5455 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5456 ist("HTTP/1.1"), code, ist("Unauthorized"));
5457 if (!sl)
5458 goto fail;
5459 sl->info.res.status = status;
5460 s->txn->status = status;
5461
5462 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5463 goto fail;
5464
5465 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5466 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5467 !htx_add_header(htx, ist("Content-Type"), ist("text/html")) ||
5468 !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
5469 goto fail;
5470
5471 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5472 goto fail;
5473
5474 data = htx->data - co_data(res);
5475 b_set_data(&res->buf, b_size(&res->buf));
5476 c_adv(res, data);
5477 res->total += data;
5478
5479 channel_auto_read(&s->req);
5480 channel_abort(&s->req);
5481 channel_auto_close(&s->req);
5482 channel_erase(&s->req);
5483
5484 res->wex = tick_add_ifset(now_ms, res->wto);
5485 channel_auto_read(res);
5486 channel_auto_close(res);
5487 channel_shutr_now(res);
5488 return 0;
5489
5490 fail:
5491 /* If an error occurred, remove the incomplete HTTP response from the
5492 * buffer */
5493 channel_truncate(res);
5494 return -1;
5495}
5496
Christopher Faulet0f226952018-10-22 09:29:56 +02005497/*
5498 * Capture headers from message <htx> according to header list <cap_hdr>, and
5499 * fill the <cap> pointers appropriately.
5500 */
5501static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5502{
5503 struct cap_hdr *h;
5504 int32_t pos;
5505
5506 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5507 struct htx_blk *blk = htx_get_blk(htx, pos);
5508 enum htx_blk_type type = htx_get_blk_type(blk);
5509 struct ist n, v;
5510
5511 if (type == HTX_BLK_EOH)
5512 break;
5513 if (type != HTX_BLK_HDR)
5514 continue;
5515
5516 n = htx_get_blk_name(htx, blk);
5517
5518 for (h = cap_hdr; h; h = h->next) {
5519 if (h->namelen && (h->namelen == n.len) &&
5520 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5521 if (cap[h->index] == NULL)
5522 cap[h->index] =
5523 pool_alloc(h->pool);
5524
5525 if (cap[h->index] == NULL) {
5526 ha_alert("HTTP capture : out of memory.\n");
5527 break;
5528 }
5529
5530 v = htx_get_blk_value(htx, blk);
5531 if (v.len > h->len)
5532 v.len = h->len;
5533
5534 memcpy(cap[h->index], v.ptr, v.len);
5535 cap[h->index][v.len]=0;
5536 }
5537 }
5538 }
5539}
5540
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005541/* Delete a value in a header between delimiters <from> and <next>. The header
5542 * itself is delimited by <start> and <end> pointers. The number of characters
5543 * displaced is returned, and the pointer to the first delimiter is updated if
5544 * required. The function tries as much as possible to respect the following
5545 * principles :
5546 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5547 * in which case <next> is simply removed
5548 * - set exactly one space character after the new first delimiter, unless there
5549 * are not enough characters in the block being moved to do so.
5550 * - remove unneeded spaces before the previous delimiter and after the new
5551 * one.
5552 *
5553 * It is the caller's responsibility to ensure that :
5554 * - <from> points to a valid delimiter or <start> ;
5555 * - <next> points to a valid delimiter or <end> ;
5556 * - there are non-space chars before <from>.
5557 */
5558static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5559{
5560 char *prev = *from;
5561
5562 if (prev == start) {
5563 /* We're removing the first value. eat the semicolon, if <next>
5564 * is lower than <end> */
5565 if (next < end)
5566 next++;
5567
5568 while (next < end && HTTP_IS_SPHT(*next))
5569 next++;
5570 }
5571 else {
5572 /* Remove useless spaces before the old delimiter. */
5573 while (HTTP_IS_SPHT(*(prev-1)))
5574 prev--;
5575 *from = prev;
5576
5577 /* copy the delimiter and if possible a space if we're
5578 * not at the end of the line.
5579 */
5580 if (next < end) {
5581 *prev++ = *next++;
5582 if (prev + 1 < next)
5583 *prev++ = ' ';
5584 while (next < end && HTTP_IS_SPHT(*next))
5585 next++;
5586 }
5587 }
5588 memmove(prev, next, end - next);
5589 return (prev - next);
5590}
5591
Christopher Faulet0f226952018-10-22 09:29:56 +02005592
5593/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005594 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005595 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005596static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005597{
5598 struct ist dst = ist2(str, 0);
5599
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005600 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005601 goto end;
5602 if (dst.len + 1 > len)
5603 goto end;
5604 dst.ptr[dst.len++] = ' ';
5605
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005606 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005607 goto end;
5608 if (dst.len + 1 > len)
5609 goto end;
5610 dst.ptr[dst.len++] = ' ';
5611
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005612 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005613 end:
5614 return dst.len;
5615}
5616
Christopher Fauletf0523542018-10-24 11:06:58 +02005617/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005618 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005619 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005620static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005621{
5622 struct ist dst = ist2(str, 0);
5623
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005624 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005625 goto end;
5626 if (dst.len + 1 > len)
5627 goto end;
5628 dst.ptr[dst.len++] = ' ';
5629
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005631 goto end;
5632 if (dst.len + 1 > len)
5633 goto end;
5634 dst.ptr[dst.len++] = ' ';
5635
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005636 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005637 end:
5638 return dst.len;
5639}
5640
5641
Christopher Faulet0f226952018-10-22 09:29:56 +02005642/*
5643 * Print a debug line with a start line.
5644 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005645static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005646{
5647 struct session *sess = strm_sess(s);
5648 int max;
5649
5650 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5651 dir,
5652 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5653 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5654
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005655 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005656 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005657 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005658 trash.area[trash.data++] = ' ';
5659
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005660 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005661 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005662 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005663 trash.area[trash.data++] = ' ';
5664
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005665 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005666 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005667 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005668 trash.area[trash.data++] = '\n';
5669
5670 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5671}
5672
5673/*
5674 * Print a debug line with a header.
5675 */
5676static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5677{
5678 struct session *sess = strm_sess(s);
5679 int max;
5680
5681 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5682 dir,
5683 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5684 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5685
5686 max = n.len;
5687 UBOUND(max, trash.size - trash.data - 3);
5688 chunk_memcat(&trash, n.ptr, max);
5689 trash.area[trash.data++] = ':';
5690 trash.area[trash.data++] = ' ';
5691
5692 max = v.len;
5693 UBOUND(max, trash.size - trash.data - 1);
5694 chunk_memcat(&trash, v.ptr, max);
5695 trash.area[trash.data++] = '\n';
5696
5697 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5698}
5699
5700
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005701__attribute__((constructor))
5702static void __htx_protocol_init(void)
5703{
5704}
5705
5706
5707/*
5708 * Local variables:
5709 * c-indent-level: 8
5710 * c-basic-offset: 8
5711 * End:
5712 */