blob: c16fc1e29406e1af5d944f2351f433a3f527082d [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 Faulet0f226952018-10-22 09:29:56 +020046static size_t htx_fmt_req_line(const union h1_sl sl, char *str, size_t len);
Christopher Fauletf0523542018-10-24 11:06:58 +020047static size_t htx_fmt_res_line(const union h1_sl sl, char *str, size_t len);
Christopher Faulet0f226952018-10-22 09:29:56 +020048static void htx_debug_stline(const char *dir, struct stream *s, const union h1_sl sl);
49static 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 Faulete0768eb2018-10-03 16:38:02 +020063/* This stream analyser waits for a complete HTTP request. It returns 1 if the
64 * processing can continue on next analysers, or zero if it either needs more
65 * data or wants to immediately abort the request (eg: timeout, error, ...). It
66 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
67 * when it has nothing left to do, and may remove any analyser when it wants to
68 * abort.
69 */
70int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
71{
Christopher Faulet9768c262018-10-22 09:34:31 +020072
Christopher Faulete0768eb2018-10-03 16:38:02 +020073 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020074 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020075 *
Christopher Faulet9768c262018-10-22 09:34:31 +020076 * Once the start line and all headers are received, we may perform a
77 * capture of the error (if any), and we will set a few fields. We also
78 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020079 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020080 struct session *sess = s->sess;
81 struct http_txn *txn = s->txn;
82 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020083 struct htx *htx;
84 union h1_sl sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020085
86 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
87 now_ms, __FUNCTION__,
88 s,
89 req,
90 req->rex, req->wex,
91 req->flags,
92 ci_data(req),
93 req->analysers);
94
Christopher Faulet9768c262018-10-22 09:34:31 +020095 htx = htx_from_buf(&req->buf);
96
Christopher Faulete0768eb2018-10-03 16:38:02 +020097 /* we're speaking HTTP here, so let's speak HTTP to the client */
98 s->srv_error = http_return_srv_error;
99
100 /* If there is data available for analysis, log the end of the idle time. */
101 if (c_data(req) && s->logs.t_idle == -1)
102 s->logs.t_idle = tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake;
103
Christopher Faulete0768eb2018-10-03 16:38:02 +0200104 /*
105 * Now we quickly check if we have found a full valid request.
106 * If not so, we check the FD and buffer states before leaving.
107 * A full request is indicated by the fact that we have seen
108 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
109 * requests are checked first. When waiting for a second request
110 * on a keep-alive stream, if we encounter and error, close, t/o,
111 * we note the error in the stream flags but don't set any state.
112 * Since the error will be noted there, it will not be counted by
113 * process_stream() as a frontend error.
114 * Last, we may increase some tracked counters' http request errors on
115 * the cases that are deliberately the client's fault. For instance,
116 * a timeout or connection reset is not counted as an error. However
117 * a bad request is.
118 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200119 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100120 /*
121 * First catch invalid request
122 */
123 if (htx->flags & HTX_FL_PARSING_ERROR) {
124 stream_inc_http_req_ctr(s);
125 stream_inc_http_err_ctr(s);
126 proxy_inc_fe_req_ctr(sess->fe);
127 goto return_bad_req;
128 }
129
Christopher Faulet9768c262018-10-22 09:34:31 +0200130 /* 1: have we encountered a read error ? */
131 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200132 if (!(s->flags & SF_ERR_MASK))
133 s->flags |= SF_ERR_CLICL;
134
135 if (txn->flags & TX_WAIT_NEXT_RQ)
136 goto failed_keep_alive;
137
138 if (sess->fe->options & PR_O_IGNORE_PRB)
139 goto failed_keep_alive;
140
Christopher Faulet9768c262018-10-22 09:34:31 +0200141 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200142 stream_inc_http_req_ctr(s);
143 proxy_inc_fe_req_ctr(sess->fe);
144 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
145 if (sess->listener->counters)
146 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 txn->status = 400;
149 msg->err_state = msg->msg_state;
150 msg->msg_state = HTTP_MSG_ERROR;
151 htx_reply_and_close(s, txn->status, NULL);
152 req->analysers &= AN_REQ_FLT_END;
153
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (!(s->flags & SF_FINST_MASK))
155 s->flags |= SF_FINST_R;
156 return 0;
157 }
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
161 if (!(s->flags & SF_ERR_MASK))
162 s->flags |= SF_ERR_CLITO;
163
164 if (txn->flags & TX_WAIT_NEXT_RQ)
165 goto failed_keep_alive;
166
167 if (sess->fe->options & PR_O_IGNORE_PRB)
168 goto failed_keep_alive;
169
Christopher Faulet9768c262018-10-22 09:34:31 +0200170 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200171 stream_inc_http_req_ctr(s);
172 proxy_inc_fe_req_ctr(sess->fe);
173 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
174 if (sess->listener->counters)
175 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 txn->status = 408;
178 msg->err_state = msg->msg_state;
179 msg->msg_state = HTTP_MSG_ERROR;
180 htx_reply_and_close(s, txn->status, http_error_message(s));
181 req->analysers &= AN_REQ_FLT_END;
182
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (!(s->flags & SF_FINST_MASK))
184 s->flags |= SF_FINST_R;
185 return 0;
186 }
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 else if (req->flags & CF_SHUTR) {
190 if (!(s->flags & SF_ERR_MASK))
191 s->flags |= SF_ERR_CLICL;
192
193 if (txn->flags & TX_WAIT_NEXT_RQ)
194 goto failed_keep_alive;
195
196 if (sess->fe->options & PR_O_IGNORE_PRB)
197 goto failed_keep_alive;
198
Christopher Faulete0768eb2018-10-03 16:38:02 +0200199 stream_inc_http_err_ctr(s);
200 stream_inc_http_req_ctr(s);
201 proxy_inc_fe_req_ctr(sess->fe);
202 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
203 if (sess->listener->counters)
204 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 txn->status = 400;
207 msg->err_state = msg->msg_state;
208 msg->msg_state = HTTP_MSG_ERROR;
209 htx_reply_and_close(s, txn->status, http_error_message(s));
210 req->analysers &= AN_REQ_FLT_END;
211
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (!(s->flags & SF_FINST_MASK))
213 s->flags |= SF_FINST_R;
214 return 0;
215 }
216
217 channel_dont_connect(req);
218 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
219 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
220#ifdef TCP_QUICKACK
Christopher Faulet9768c262018-10-22 09:34:31 +0200221 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200222 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
223 /* We need more data, we have to re-enable quick-ack in case we
224 * previously disabled it, otherwise we might cause the client
225 * to delay next data.
226 */
227 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
228 }
229#endif
Christopher Faulet47365272018-10-31 17:40:50 +0100230 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 /* If the client starts to talk, let's fall back to
232 * request timeout processing.
233 */
234 txn->flags &= ~TX_WAIT_NEXT_RQ;
235 req->analyse_exp = TICK_ETERNITY;
236 }
237
238 /* just set the request timeout once at the beginning of the request */
239 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100240 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200241 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
242 else
243 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
244 }
245
246 /* we're not ready yet */
247 return 0;
248
249 failed_keep_alive:
250 /* Here we process low-level errors for keep-alive requests. In
251 * short, if the request is not the first one and it experiences
252 * a timeout, read error or shutdown, we just silently close so
253 * that the client can try again.
254 */
255 txn->status = 0;
256 msg->msg_state = HTTP_MSG_RQBEFORE;
257 req->analysers &= AN_REQ_FLT_END;
258 s->logs.logwait = 0;
259 s->logs.level = 0;
260 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200261 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200262 return 0;
263 }
264
Christopher Faulet9768c262018-10-22 09:34:31 +0200265 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200266 stream_inc_http_req_ctr(s);
267 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
268
Christopher Faulet9768c262018-10-22 09:34:31 +0200269 /* kill the pending keep-alive timeout */
270 txn->flags &= ~TX_WAIT_NEXT_RQ;
271 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200272
Christopher Faulet9768c262018-10-22 09:34:31 +0200273 /* 0: we might have to print this header in debug mode */
274 if (unlikely((global.mode & MODE_DEBUG) &&
275 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
276 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 htx_debug_stline("clireq", s, http_find_stline(htx));
279
280 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
281 struct htx_blk *blk = htx_get_blk(htx, pos);
282 enum htx_blk_type type = htx_get_blk_type(blk);
283
284 if (type == HTX_BLK_EOH)
285 break;
286 if (type != HTX_BLK_HDR)
287 continue;
288
289 htx_debug_hdr("clihdr", s,
290 htx_get_blk_name(htx, blk),
291 htx_get_blk_value(htx, blk));
292 }
293 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200294
295 /*
296 * 1: identify the method
297 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200298 sl = http_find_stline(htx);
299 txn->meth = sl.rq.meth;
300 msg->flags |= HTTP_MSGF_XFER_LEN;
301
302 /* ... and check if the request is HTTP/1.1 or above */
303 if ((sl.rq.v.len == 8) &&
304 ((*(sl.rq.v.ptr + 5) > '1') ||
305 ((*(sl.rq.v.ptr + 5) == '1') && (*(sl.rq.v.ptr + 7) >= '1'))))
306 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307
308 /* we can make use of server redirect on GET and HEAD */
309 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
310 s->flags |= SF_REDIRECTABLE;
Christopher Faulet9768c262018-10-22 09:34:31 +0200311 else if (txn->meth == HTTP_METH_OTHER && isteqi(sl.rq.m, ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200312 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200313 goto return_bad_req;
314 }
315
316 /*
317 * 2: check if the URI matches the monitor_uri.
318 * We have to do this for every request which gets in, because
319 * the monitor-uri is defined by the frontend.
320 */
321 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet9768c262018-10-22 09:34:31 +0200322 isteqi(sl.rq.u, ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 /*
324 * We have found the monitor URI
325 */
326 struct acl_cond *cond;
327
328 s->flags |= SF_MONITOR;
329 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
330
331 /* Check if we want to fail this monitor request or not */
332 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
333 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
334
335 ret = acl_pass(ret);
336 if (cond->pol == ACL_COND_UNLESS)
337 ret = !ret;
338
339 if (ret) {
340 /* we fail this request, let's return 503 service unavail */
341 txn->status = 503;
Christopher Faulet9768c262018-10-22 09:34:31 +0200342 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200343 if (!(s->flags & SF_ERR_MASK))
344 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
345 goto return_prx_cond;
346 }
347 }
348
349 /* nothing to fail, let's reply normaly */
350 txn->status = 200;
Christopher Faulet9768c262018-10-22 09:34:31 +0200351 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200352 if (!(s->flags & SF_ERR_MASK))
353 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
354 goto return_prx_cond;
355 }
356
357 /*
358 * 3: Maybe we have to copy the original REQURI for the logs ?
359 * Note: we cannot log anymore if the request has been
360 * classified as invalid.
361 */
362 if (unlikely(s->logs.logwait & LW_REQ)) {
363 /* we have a complete HTTP request that we must log */
364 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200365 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200366
Christopher Faulet9768c262018-10-22 09:34:31 +0200367 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
368 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200369
370 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
371 s->do_log(s);
372 } else {
373 ha_alert("HTTP logging : out of memory.\n");
374 }
375 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377 /* if the frontend has "option http-use-proxy-header", we'll check if
378 * we have what looks like a proxied connection instead of a connection,
379 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
380 * Note that this is *not* RFC-compliant, however browsers and proxies
381 * happen to do that despite being non-standard :-(
382 * We consider that a request not beginning with either '/' or '*' is
383 * a proxied connection, which covers both "scheme://location" and
384 * CONNECT ip:port.
385 */
386 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Faulet9768c262018-10-22 09:34:31 +0200387 *(sl.rq.u.ptr) != '/' && *(sl.rq.u.ptr) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200388 txn->flags |= TX_USE_PX_CONN;
389
Christopher Faulete0768eb2018-10-03 16:38:02 +0200390 /* 5: we may need to capture headers */
391 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200392 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200393
394 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
395 * only change if both the request and the config reference something else.
396 * Option httpclose by itself sets tunnel mode where headers are mangled.
397 * However, if another mode is set, it will affect it (eg: server-close/
398 * keep-alive + httpclose = close). Note that we avoid to redo the same work
399 * if FE and BE have the same settings (common). The method consists in
400 * checking if options changed between the two calls (implying that either
401 * one is non-null, or one of them is non-null and we are there for the first
402 * time.
403 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200404 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200405 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +0200441 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200442 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
443 if (sess->listener->counters)
444 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Fauletff2759f2018-10-24 11:13:16 +0200491 htx = htx_from_buf(&req->buf);
492
Christopher Faulete0768eb2018-10-03 16:38:02 +0200493 /* just in case we have some per-backend tracking */
494 stream_inc_be_http_req_ctr(s);
495
496 /* evaluate http-request rules */
497 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200498 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200499
500 switch (verdict) {
501 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
502 goto return_prx_yield;
503
504 case HTTP_RULE_RES_CONT:
505 case HTTP_RULE_RES_STOP: /* nothing to do */
506 break;
507
508 case HTTP_RULE_RES_DENY: /* deny or tarpit */
509 if (txn->flags & TX_CLTARPIT)
510 goto tarpit;
511 goto deny;
512
513 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
514 goto return_prx_cond;
515
516 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
517 goto done;
518
519 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
520 goto return_bad_req;
521 }
522 }
523
524 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
525 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200526 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200527
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 ctx.blk = NULL;
529 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
530 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200531 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200532 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 }
534
535 /* OK at this stage, we know that the request was accepted according to
536 * the http-request rules, we can check for the stats. Note that the
537 * URI is detected *before* the req* rules in order not to be affected
538 * by a possible reqrep, while they are processed *after* so that a
539 * reqdeny can still block them. This clearly needs to change in 1.6!
540 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200541 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 s->target = &http_stats_applet.obj_type;
543 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
544 txn->status = 500;
545 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200547
548 if (!(s->flags & SF_ERR_MASK))
549 s->flags |= SF_ERR_RESOURCE;
550 goto return_prx_cond;
551 }
552
553 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200554 htx_handle_stats(s, req);
555 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200556 /* not all actions implemented: deny, allow, auth */
557
558 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
559 goto deny;
560
561 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
562 goto return_prx_cond;
563 }
564
565 /* evaluate the req* rules except reqadd */
566 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200567 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200568 goto return_bad_req;
569
570 if (txn->flags & TX_CLDENY)
571 goto deny;
572
573 if (txn->flags & TX_CLTARPIT) {
574 deny_status = HTTP_ERR_500;
575 goto tarpit;
576 }
577 }
578
579 /* add request headers from the rule sets in the same order */
580 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200581 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200582 if (wl->cond) {
583 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
584 ret = acl_pass(ret);
585 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
586 ret = !ret;
587 if (!ret)
588 continue;
589 }
590
Christopher Fauletff2759f2018-10-24 11:13:16 +0200591 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
592 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200593 goto return_bad_req;
594 }
595
Christopher Faulete0768eb2018-10-03 16:38:02 +0200596 /* Proceed with the stats now. */
597 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
598 unlikely(objt_applet(s->target) == &http_cache_applet)) {
Christopher Fauletef779222018-10-31 08:47:01 +0100599
600 if (unlikely(objt_applet(s->target) == &http_cache_applet)) {
601 // TODO: Disabled for now, waiting to be adapted for HTX implementation
602 goto deny;
603 }
Christopher Fauletff2759f2018-10-24 11:13:16 +0200604
Christopher Faulete0768eb2018-10-03 16:38:02 +0200605 /* process the stats request now */
606 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
607 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
608
609 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
610 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
611 if (!(s->flags & SF_FINST_MASK))
612 s->flags |= SF_FINST_R;
613
614 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
615 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
616 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
617 req->analysers |= AN_REQ_HTTP_XFER_BODY;
618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
666 channel_erase(&s->req);
667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
681 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
682 if (sess->fe != s->be)
683 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
684 if (sess->listener->counters)
685 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200698 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
700 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
701 if (sess->fe != s->be)
702 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
703 if (sess->listener->counters)
704 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200711 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
713 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
714 if (sess->listener->counters)
715 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200766 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200775 union h1_sl sl;
776 struct ist path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200784 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200793 sl = http_find_stline(htx);
794 path = http_get_path(sl.rq.u);
795 if (url2sa(sl.rq.u.ptr, sl.rq.u.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200796 goto return_bad_req;
797
798 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 * uri.ptr and path.ptr (excluded). If it was not found, we need
800 * to replace from all the uri by a single "/".
801 *
802 * Instead of rewritting the whole start line, we just update
803 * <sl.rq.u>. Some space will be lost but it should be
804 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200806 if (path.ptr)
807 sl.rq.u = path;
808 else
809 istcpy(&sl.rq.u, ist("/"), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200810 }
811
812 /*
813 * 7: Now we can work with the cookies.
814 * Note that doing so might move headers in the request, but
815 * the fields will stay coherent and the URI will not move.
816 * This should only be performed in the backend.
817 */
818 if (s->be->cookie_name || sess->fe->capture_name)
819 manage_client_side_cookies(s, req);
820
821 /* add unique-id if "header-unique-id" is specified */
822
823 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
824 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
825 goto return_bad_req;
826 s->unique_id[0] = '\0';
827 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
828 }
829
830 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200831 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
832 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
833
834 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200836 }
837
838 /*
839 * 9: add X-Forwarded-For if either the frontend or the backend
840 * asks for it.
841 */
842 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200843 struct http_hdr_ctx ctx = { .blk = NULL };
844 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
845 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
846
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200848 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 /* The header is set to be added only if none is present
850 * and we found it, so don't do anything.
851 */
852 }
853 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
854 /* Add an X-Forwarded-For header unless the source IP is
855 * in the 'except' network range.
856 */
857 if ((!sess->fe->except_mask.s_addr ||
858 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
859 != sess->fe->except_net.s_addr) &&
860 (!s->be->except_mask.s_addr ||
861 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
862 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200863 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200864
865 /* Note: we rely on the backend to get the header name to be used for
866 * x-forwarded-for, because the header is really meant for the backends.
867 * However, if the backend did not specify any option, we have to rely
868 * on the frontend's header name.
869 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200870 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
871 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200872 goto return_bad_req;
873 }
874 }
875 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
876 /* FIXME: for the sake of completeness, we should also support
877 * 'except' here, although it is mostly useless in this case.
878 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200880
Christopher Faulete0768eb2018-10-03 16:38:02 +0200881 inet_ntop(AF_INET6,
882 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
883 pn, sizeof(pn));
884
885 /* Note: we rely on the backend to get the header name to be used for
886 * x-forwarded-for, because the header is really meant for the backends.
887 * However, if the backend did not specify any option, we have to rely
888 * on the frontend's header name.
889 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200890 chunk_printf(&trash, "%s", pn);
891 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200892 goto return_bad_req;
893 }
894 }
895
896 /*
897 * 10: add X-Original-To if either the frontend or the backend
898 * asks for it.
899 */
900 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
901
902 /* FIXME: don't know if IPv6 can handle that case too. */
903 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
904 /* Add an X-Original-To header unless the destination IP is
905 * in the 'except' network range.
906 */
907 conn_get_to_addr(cli_conn);
908
909 if (cli_conn->addr.to.ss_family == AF_INET &&
910 ((!sess->fe->except_mask_to.s_addr ||
911 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
912 != sess->fe->except_to.s_addr) &&
913 (!s->be->except_mask_to.s_addr ||
914 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
915 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200916 struct ist hdr;
917 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200918
919 /* Note: we rely on the backend to get the header name to be used for
920 * x-original-to, because the header is really meant for the backends.
921 * However, if the backend did not specify any option, we have to rely
922 * on the frontend's header name.
923 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200924 if (s->be->orgto_hdr_len)
925 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
926 else
927 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200929 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
930 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 goto return_bad_req;
932 }
933 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 }
935
Christopher Faulete0768eb2018-10-03 16:38:02 +0200936 /* If we have no server assigned yet and we're balancing on url_param
937 * with a POST request, we may be interested in checking the body for
938 * that parameter. This will be done in another analyser.
939 */
940 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200941 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
948#ifdef TCP_QUICKACK
949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
955 cli_conn && conn_ctrl_ready(cli_conn) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200956 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
958#endif
959
960 /*************************************************************
961 * OK, that's finished for the headers. We have done what we *
962 * could. Let's switch to the DATA state. *
963 ************************************************************/
964 req->analyse_exp = TICK_ETERNITY;
965 req->analysers &= ~an_bit;
966
967 s->logs.tv_request = now;
968 /* OK let's go on with the BODY now */
969 return 1;
970
971 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200972 txn->req.err_state = txn->req.msg_state;
973 txn->req.msg_state = HTTP_MSG_ERROR;
974 txn->status = 400;
975 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200976 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977
978 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
979 if (sess->listener->counters)
980 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
981
982 if (!(s->flags & SF_ERR_MASK))
983 s->flags |= SF_ERR_PRXCOND;
984 if (!(s->flags & SF_FINST_MASK))
985 s->flags |= SF_FINST_R;
986 return 0;
987}
988
989/* This function is an analyser which processes the HTTP tarpit. It always
990 * returns zero, at the beginning because it prevents any other processing
991 * from occurring, and at the end because it terminates the request.
992 */
993int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
994{
995 struct http_txn *txn = s->txn;
996
997 /* This connection is being tarpitted. The CLIENT side has
998 * already set the connect expiration date to the right
999 * timeout. We just have to check that the client is still
1000 * there and that the timeout has not expired.
1001 */
1002 channel_dont_connect(req);
1003 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1004 !tick_is_expired(req->analyse_exp, now_ms))
1005 return 0;
1006
1007 /* We will set the queue timer to the time spent, just for
1008 * logging purposes. We fake a 500 server error, so that the
1009 * attacker will not suspect his connection has been tarpitted.
1010 * It will not cause trouble to the logs because we can exclude
1011 * the tarpitted connections by filtering on the 'PT' status flags.
1012 */
1013 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1014
1015 if (!(req->flags & CF_READ_ERROR))
Christopher Faulet8137c272018-10-24 11:15:09 +02001016 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001017
1018 req->analysers &= AN_REQ_FLT_END;
1019 req->analyse_exp = TICK_ETERNITY;
1020
1021 if (!(s->flags & SF_ERR_MASK))
1022 s->flags |= SF_ERR_PRXCOND;
1023 if (!(s->flags & SF_FINST_MASK))
1024 s->flags |= SF_FINST_T;
1025 return 0;
1026}
1027
1028/* This function is an analyser which waits for the HTTP request body. It waits
1029 * for either the buffer to be full, or the full advertised contents to have
1030 * reached the buffer. It must only be called after the standard HTTP request
1031 * processing has occurred, because it expects the request to be parsed and will
1032 * look for the Expect header. It may send a 100-Continue interim response. It
1033 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1034 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1035 * needs to read more data, or 1 once it has completed its analysis.
1036 */
1037int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1038{
1039 struct session *sess = s->sess;
1040 struct http_txn *txn = s->txn;
1041 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001042 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001043
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001044
1045 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1046 now_ms, __FUNCTION__,
1047 s,
1048 req,
1049 req->rex, req->wex,
1050 req->flags,
1051 ci_data(req),
1052 req->analysers);
1053
1054 htx = htx_from_buf(&req->buf);
1055
1056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
1066 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1067 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 if (msg->flags & HTTP_MSGF_VER_11) {
1070 struct ist hdr = { .ptr = "Expect", .len = 6 };
1071 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001073 ctx.blk = NULL;
1074 /* Expect is allowed in 1.1, look for it */
1075 if (http_find_header(htx, hdr, &ctx, 0) &&
1076 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
1077 struct htx *rsp = htx_from_buf(&s->res.buf);
1078 struct htx_blk *blk;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001080 blk = htx_add_oob(rsp, HTTP_100);
1081 if (!blk)
1082 goto missing_data;
1083 b_set_data(&s->res.buf, b_size(&s->res.buf));
1084 c_adv(&s->res, HTTP_100.len);
1085 s->res.total += HTTP_100.len;
1086 http_remove_header(htx, &ctx);
1087 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001088 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089 }
1090
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001092
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001093 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1094 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001095 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001096 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1097 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001098 goto http_end;
1099
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001100 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001101 if (htx->flags & HTX_FL_PARSING_ERROR)
1102 goto return_bad_req;
1103
Christopher Faulete0768eb2018-10-03 16:38:02 +02001104 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1105 txn->status = 408;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001106 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001107
1108 if (!(s->flags & SF_ERR_MASK))
1109 s->flags |= SF_ERR_CLITO;
1110 if (!(s->flags & SF_FINST_MASK))
1111 s->flags |= SF_FINST_D;
1112 goto return_err_msg;
1113 }
1114
1115 /* we get here if we need to wait for more data */
1116 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1117 /* Not enough data. We'll re-use the http-request
1118 * timeout here. Ideally, we should set the timeout
1119 * relative to the accept() date. We just set the
1120 * request timeout once at the beginning of the
1121 * request.
1122 */
1123 channel_dont_connect(req);
1124 if (!tick_isset(req->analyse_exp))
1125 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1126 return 0;
1127 }
1128
1129 http_end:
1130 /* The situation will not evolve, so let's give up on the analysis. */
1131 s->logs.tv_request = now; /* update the request timer to reflect full request */
1132 req->analysers &= ~an_bit;
1133 req->analyse_exp = TICK_ETERNITY;
1134 return 1;
1135
1136 return_bad_req: /* let's centralize all bad requests */
1137 txn->req.err_state = txn->req.msg_state;
1138 txn->req.msg_state = HTTP_MSG_ERROR;
1139 txn->status = 400;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001140 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001141
1142 if (!(s->flags & SF_ERR_MASK))
1143 s->flags |= SF_ERR_PRXCOND;
1144 if (!(s->flags & SF_FINST_MASK))
1145 s->flags |= SF_FINST_R;
1146
1147 return_err_msg:
1148 req->analysers &= AN_REQ_FLT_END;
1149 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1150 if (sess->listener->counters)
1151 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1152 return 0;
1153}
1154
1155/* This function is an analyser which forwards request body (including chunk
1156 * sizes if any). It is called as soon as we must forward, even if we forward
1157 * zero byte. The only situation where it must not be called is when we're in
1158 * tunnel mode and we want to forward till the close. It's used both to forward
1159 * remaining data and to resync after end of body. It expects the msg_state to
1160 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1161 * read more data, or 1 once we can go on with next request or end the stream.
1162 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1163 * bytes of pending data + the headers if not already done.
1164 */
1165int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1166{
1167 struct session *sess = s->sess;
1168 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001169 struct http_msg *msg = &txn->req;
1170 struct htx *htx;
1171 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001172
1173 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1174 now_ms, __FUNCTION__,
1175 s,
1176 req,
1177 req->rex, req->wex,
1178 req->flags,
1179 ci_data(req),
1180 req->analysers);
1181
Christopher Faulet9768c262018-10-22 09:34:31 +02001182 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001183
1184 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1185 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1186 /* Output closed while we were sending data. We must abort and
1187 * wake the other side up.
1188 */
1189 msg->err_state = msg->msg_state;
1190 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001191 htx_end_request(s);
1192 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001193 return 1;
1194 }
1195
1196 /* Note that we don't have to send 100-continue back because we don't
1197 * need the data to complete our job, and it's up to the server to
1198 * decide whether to return 100, 417 or anything else in return of
1199 * an "Expect: 100-continue" header.
1200 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001201 if (msg->msg_state == HTTP_MSG_BODY)
1202 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001203
1204 /* Some post-connect processing might want us to refrain from starting to
1205 * forward data. Currently, the only reason for this is "balance url_param"
1206 * whichs need to parse/process the request after we've enabled forwarding.
1207 */
1208 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1209 if (!(s->res.flags & CF_READ_ATTACHED)) {
1210 channel_auto_connect(req);
1211 req->flags |= CF_WAKE_CONNECT;
1212 channel_dont_close(req); /* don't fail on early shutr */
1213 goto waiting;
1214 }
1215 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1216 }
1217
1218 /* in most states, we should abort in case of early close */
1219 channel_auto_close(req);
1220
1221 if (req->to_forward) {
1222 /* We can't process the buffer's contents yet */
1223 req->flags |= CF_WAKE_WRITE;
1224 goto missing_data_or_waiting;
1225 }
1226
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 if (msg->msg_state >= HTTP_MSG_DONE)
1228 goto done;
1229
1230 /* Forward all input data. We get it by removing all outgoing data not
1231 * forwarded yet from HTX data size.
1232 */
1233 c_adv(req, htx->data - co_data(req));
1234
1235 /* To let the function channel_forward work as expected we must update
1236 * the channel's buffer to pretend there is no more input data. The
1237 * right length is then restored. We must do that, because when an HTX
1238 * message is stored into a buffer, it appears as full.
1239 */
1240 b_set_data(&req->buf, co_data(req));
1241 if (htx->extra != ULLONG_MAX)
1242 htx->extra -= channel_forward(req, htx->extra);
1243 b_set_data(&req->buf, b_size(&req->buf));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001244
Christopher Faulet9768c262018-10-22 09:34:31 +02001245 /* Check if the end-of-message is reached and if so, switch the message
1246 * in HTTP_MSG_DONE state.
1247 */
1248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1249 goto missing_data_or_waiting;
1250
1251 msg->msg_state = HTTP_MSG_DONE;
1252
1253 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001254 /* other states, DONE...TUNNEL */
1255 /* we don't want to forward closes on DONE except in tunnel mode. */
1256 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1257 channel_dont_close(req);
1258
Christopher Fauletf2824e62018-10-01 12:12:37 +02001259 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001260 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001261 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001262 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1263 if (req->flags & CF_SHUTW) {
1264 /* request errors are most likely due to the
1265 * server aborting the transfer. */
1266 goto aborted_xfer;
1267 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001268 goto return_bad_req;
1269 }
1270 return 1;
1271 }
1272
1273 /* If "option abortonclose" is set on the backend, we want to monitor
1274 * the client's connection and forward any shutdown notification to the
1275 * server, which will decide whether to close or to go on processing the
1276 * request. We only do that in tunnel mode, and not in other modes since
1277 * it can be abused to exhaust source ports. */
1278 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1279 channel_auto_read(req);
1280 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1281 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1282 s->si[1].flags |= SI_FL_NOLINGER;
1283 channel_auto_close(req);
1284 }
1285 else if (s->txn->meth == HTTP_METH_POST) {
1286 /* POST requests may require to read extra CRLF sent by broken
1287 * browsers and which could cause an RST to be sent upon close
1288 * on some systems (eg: Linux). */
1289 channel_auto_read(req);
1290 }
1291 return 0;
1292
1293 missing_data_or_waiting:
1294 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001295 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001296 if (!(s->flags & SF_ERR_MASK))
1297 s->flags |= SF_ERR_CLICL;
1298 if (!(s->flags & SF_FINST_MASK)) {
1299 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1300 s->flags |= SF_FINST_H;
1301 else
1302 s->flags |= SF_FINST_D;
1303 }
1304
1305 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1306 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1307 if (objt_server(s->target))
1308 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1309
1310 goto return_bad_req_stats_ok;
1311 }
1312
1313 waiting:
1314 /* waiting for the last bits to leave the buffer */
1315 if (req->flags & CF_SHUTW)
1316 goto aborted_xfer;
1317
Christopher Faulet47365272018-10-31 17:40:50 +01001318 if (htx->flags & HTX_FL_PARSING_ERROR)
1319 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001320
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321 /* When TE: chunked is used, we need to get there again to parse remaining
1322 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1323 * And when content-length is used, we never want to let the possible
1324 * shutdown be forwarded to the other side, as the state machine will
1325 * take care of it once the client responds. It's also important to
1326 * prevent TIME_WAITs from accumulating on the backend side, and for
1327 * HTTP/2 where the last frame comes with a shutdown.
1328 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001329 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001330 channel_dont_close(req);
1331
Christopher Faulet9768c262018-10-22 09:34:31 +02001332#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
1333 // about if
1334
Christopher Faulete0768eb2018-10-03 16:38:02 +02001335 /* We know that more data are expected, but we couldn't send more that
1336 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1337 * system knows it must not set a PUSH on this first part. Interactive
1338 * modes are already handled by the stream sock layer. We must not do
1339 * this in content-length mode because it could present the MSG_MORE
1340 * flag with the last block of forwarded data, which would cause an
1341 * additional delay to be observed by the receiver.
1342 */
1343 if (msg->flags & HTTP_MSGF_TE_CHNK)
1344 req->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02001345#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02001346
1347 return 0;
1348
1349 return_bad_req: /* let's centralize all bad requests */
1350 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1351 if (sess->listener->counters)
1352 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1353
1354 return_bad_req_stats_ok:
1355 txn->req.err_state = txn->req.msg_state;
1356 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001357 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001359 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360 } else {
1361 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001362 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 }
1364 req->analysers &= AN_REQ_FLT_END;
1365 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1366
1367 if (!(s->flags & SF_ERR_MASK))
1368 s->flags |= SF_ERR_PRXCOND;
1369 if (!(s->flags & SF_FINST_MASK)) {
1370 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1371 s->flags |= SF_FINST_H;
1372 else
1373 s->flags |= SF_FINST_D;
1374 }
1375 return 0;
1376
1377 aborted_xfer:
1378 txn->req.err_state = txn->req.msg_state;
1379 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001380 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001382 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 } else {
1384 txn->status = 502;
Christopher Faulet9768c262018-10-22 09:34:31 +02001385 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 }
1387 req->analysers &= AN_REQ_FLT_END;
1388 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1389
1390 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1391 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1392 if (objt_server(s->target))
1393 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1394
1395 if (!(s->flags & SF_ERR_MASK))
1396 s->flags |= SF_ERR_SRVCL;
1397 if (!(s->flags & SF_FINST_MASK)) {
1398 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1399 s->flags |= SF_FINST_H;
1400 else
1401 s->flags |= SF_FINST_D;
1402 }
1403 return 0;
1404}
1405
1406/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1407 * processing can continue on next analysers, or zero if it either needs more
1408 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1409 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1410 * when it has nothing left to do, and may remove any analyser when it wants to
1411 * abort.
1412 */
1413int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1414{
Christopher Faulet9768c262018-10-22 09:34:31 +02001415 /*
1416 * We will analyze a complete HTTP response to check the its syntax.
1417 *
1418 * Once the start line and all headers are received, we may perform a
1419 * capture of the error (if any), and we will set a few fields. We also
1420 * logging and finally headers capture.
1421 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001422 struct session *sess = s->sess;
1423 struct http_txn *txn = s->txn;
1424 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001425 struct htx *htx;
1426 union h1_sl sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001427 int n;
1428
1429 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1430 now_ms, __FUNCTION__,
1431 s,
1432 rep,
1433 rep->rex, rep->wex,
1434 rep->flags,
1435 ci_data(rep),
1436 rep->analysers);
1437
Christopher Faulet9768c262018-10-22 09:34:31 +02001438 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001439
1440 /*
1441 * Now we quickly check if we have found a full valid response.
1442 * If not so, we check the FD and buffer states before leaving.
1443 * A full response is indicated by the fact that we have seen
1444 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1445 * responses are checked first.
1446 *
1447 * Depending on whether the client is still there or not, we
1448 * may send an error response back or not. Note that normally
1449 * we should only check for HTTP status there, and check I/O
1450 * errors somewhere else.
1451 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001452 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001453 /*
1454 * First catch invalid response
1455 */
1456 if (htx->flags & HTX_FL_PARSING_ERROR)
1457 goto return_bad_res;
1458
Christopher Faulet9768c262018-10-22 09:34:31 +02001459 /* 1: have we encountered a read error ? */
1460 if (rep->flags & CF_READ_ERROR) {
1461 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001462 goto abort_keep_alive;
1463
1464 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1465 if (objt_server(s->target)) {
1466 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1467 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1468 }
1469
Christopher Faulete0768eb2018-10-03 16:38:02 +02001470 rep->analysers &= AN_RES_FLT_END;
1471 txn->status = 502;
1472
1473 /* Check to see if the server refused the early data.
1474 * If so, just send a 425
1475 */
1476 if (objt_cs(s->si[1].end)) {
1477 struct connection *conn = objt_cs(s->si[1].end)->conn;
1478
1479 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1480 txn->status = 425;
1481 }
1482
1483 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001484 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485
1486 if (!(s->flags & SF_ERR_MASK))
1487 s->flags |= SF_ERR_SRVCL;
1488 if (!(s->flags & SF_FINST_MASK))
1489 s->flags |= SF_FINST_H;
1490 return 0;
1491 }
1492
Christopher Faulet9768c262018-10-22 09:34:31 +02001493 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001495 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1496 if (objt_server(s->target)) {
1497 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1498 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1499 }
1500
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 rep->analysers &= AN_RES_FLT_END;
1502 txn->status = 504;
1503 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001504 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505
1506 if (!(s->flags & SF_ERR_MASK))
1507 s->flags |= SF_ERR_SRVTO;
1508 if (!(s->flags & SF_FINST_MASK))
1509 s->flags |= SF_FINST_H;
1510 return 0;
1511 }
1512
Christopher Faulet9768c262018-10-22 09:34:31 +02001513 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1515 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1516 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1517 if (objt_server(s->target))
1518 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1519
1520 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001522 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001523
1524 if (!(s->flags & SF_ERR_MASK))
1525 s->flags |= SF_ERR_CLICL;
1526 if (!(s->flags & SF_FINST_MASK))
1527 s->flags |= SF_FINST_H;
1528
1529 /* process_stream() will take care of the error */
1530 return 0;
1531 }
1532
Christopher Faulet9768c262018-10-22 09:34:31 +02001533 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001535 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 goto abort_keep_alive;
1537
1538 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1539 if (objt_server(s->target)) {
1540 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1541 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1542 }
1543
Christopher Faulete0768eb2018-10-03 16:38:02 +02001544 rep->analysers &= AN_RES_FLT_END;
1545 txn->status = 502;
1546 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548
1549 if (!(s->flags & SF_ERR_MASK))
1550 s->flags |= SF_ERR_SRVCL;
1551 if (!(s->flags & SF_FINST_MASK))
1552 s->flags |= SF_FINST_H;
1553 return 0;
1554 }
1555
Christopher Faulet9768c262018-10-22 09:34:31 +02001556 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001558 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 goto abort_keep_alive;
1560
1561 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1562 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563
1564 if (!(s->flags & SF_ERR_MASK))
1565 s->flags |= SF_ERR_CLICL;
1566 if (!(s->flags & SF_FINST_MASK))
1567 s->flags |= SF_FINST_H;
1568
1569 /* process_stream() will take care of the error */
1570 return 0;
1571 }
1572
1573 channel_dont_close(rep);
1574 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1575 return 0;
1576 }
1577
1578 /* More interesting part now : we know that we have a complete
1579 * response which at least looks like HTTP. We have an indicator
1580 * of each header's length, so we can parse them quickly.
1581 */
1582
Christopher Faulet9768c262018-10-22 09:34:31 +02001583 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001584
Christopher Faulet9768c262018-10-22 09:34:31 +02001585 /* 0: we might have to print this header in debug mode */
1586 if (unlikely((global.mode & MODE_DEBUG) &&
1587 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1588 int32_t pos;
1589
1590 htx_debug_stline("srvrep", s, http_find_stline(htx));
1591
1592 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1593 struct htx_blk *blk = htx_get_blk(htx, pos);
1594 enum htx_blk_type type = htx_get_blk_type(blk);
1595
1596 if (type == HTX_BLK_EOH)
1597 break;
1598 if (type != HTX_BLK_HDR)
1599 continue;
1600
1601 htx_debug_hdr("srvhdr", s,
1602 htx_get_blk_name(htx, blk),
1603 htx_get_blk_value(htx, blk));
1604 }
1605 }
1606
1607 /* 1: get the status code */
1608 sl = http_find_stline(htx);
1609 txn->status = sl.st.status;
1610 if (htx->extra != ULLONG_MAX)
1611 msg->flags |= HTTP_MSGF_XFER_LEN;
1612
1613 /* ... and check if the request is HTTP/1.1 or above */
1614 if ((sl.st.v.len == 8) &&
1615 ((*(sl.st.v.ptr + 5) > '1') ||
1616 ((*(sl.st.v.ptr + 5) == '1') && (*(sl.st.v.ptr + 7) >= '1'))))
1617 msg->flags |= HTTP_MSGF_VER_11;
1618
1619 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001620 if (n < 1 || n > 5)
1621 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001622
Christopher Faulete0768eb2018-10-03 16:38:02 +02001623 /* when the client triggers a 4xx from the server, it's most often due
1624 * to a missing object or permission. These events should be tracked
1625 * because if they happen often, it may indicate a brute force or a
1626 * vulnerability scan.
1627 */
1628 if (n == 4)
1629 stream_inc_http_err_ctr(s);
1630
1631 if (objt_server(s->target))
1632 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
1633
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 /* Adjust server's health based on status code. Note: status codes 501
1635 * and 505 are triggered on demand by client request, so we must not
1636 * count them as server failures.
1637 */
1638 if (objt_server(s->target)) {
1639 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
1640 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
1641 else
1642 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
1643 }
1644
1645 /*
1646 * We may be facing a 100-continue response, or any other informational
1647 * 1xx response which is non-final, in which case this is not the right
1648 * response, and we're waiting for the next one. Let's allow this response
1649 * to go to the client and wait for the next one. There's an exception for
1650 * 101 which is used later in the code to switch protocols.
1651 */
1652 if (txn->status < 200 &&
1653 (txn->status == 100 || txn->status >= 102)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001654 //FLT_STRM_CB(s, flt_htx_reset(s, http, htx));
1655 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001656 msg->msg_state = HTTP_MSG_RPBEFORE;
1657 txn->status = 0;
1658 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001659 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001660 }
1661
1662 /*
1663 * 2: check for cacheability.
1664 */
1665
1666 switch (txn->status) {
1667 case 200:
1668 case 203:
1669 case 204:
1670 case 206:
1671 case 300:
1672 case 301:
1673 case 404:
1674 case 405:
1675 case 410:
1676 case 414:
1677 case 501:
1678 break;
1679 default:
1680 /* RFC7231#6.1:
1681 * Responses with status codes that are defined as
1682 * cacheable by default (e.g., 200, 203, 204, 206,
1683 * 300, 301, 404, 405, 410, 414, and 501 in this
1684 * specification) can be reused by a cache with
1685 * heuristic expiration unless otherwise indicated
1686 * by the method definition or explicit cache
1687 * controls [RFC7234]; all other status codes are
1688 * not cacheable by default.
1689 */
1690 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1691 break;
1692 }
1693
1694 /*
1695 * 3: we may need to capture headers
1696 */
1697 s->logs.logwait &= ~LW_RESP;
1698 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001699 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001700
Christopher Faulet9768c262018-10-22 09:34:31 +02001701 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001702 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1703 txn->status == 101)) {
1704 /* Either we've established an explicit tunnel, or we're
1705 * switching the protocol. In both cases, we're very unlikely
1706 * to understand the next protocols. We have to switch to tunnel
1707 * mode, so that we transfer the request and responses then let
1708 * this protocol pass unmodified. When we later implement specific
1709 * parsers for such protocols, we'll want to check the Upgrade
1710 * header which contains information about that protocol for
1711 * responses with status 101 (eg: see RFC2817 about TLS).
1712 */
1713 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001714 }
1715
Christopher Faulete0768eb2018-10-03 16:38:02 +02001716 /* we want to have the response time before we start processing it */
1717 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1718
1719 /* end of job, return OK */
1720 rep->analysers &= ~an_bit;
1721 rep->analyse_exp = TICK_ETERNITY;
1722 channel_auto_close(rep);
1723 return 1;
1724
Christopher Faulet47365272018-10-31 17:40:50 +01001725 return_bad_res:
1726 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1727 if (objt_server(s->target)) {
1728 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1729 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
1730 }
1731 txn->status = 502;
1732 s->si[1].flags |= SI_FL_NOLINGER;
1733 htx_reply_and_close(s, txn->status, http_error_message(s));
1734 rep->analysers &= AN_RES_FLT_END;
1735
1736 if (!(s->flags & SF_ERR_MASK))
1737 s->flags |= SF_ERR_PRXCOND;
1738 if (!(s->flags & SF_FINST_MASK))
1739 s->flags |= SF_FINST_H;
1740 return 0;
1741
Christopher Faulete0768eb2018-10-03 16:38:02 +02001742 abort_keep_alive:
1743 /* A keep-alive request to the server failed on a network error.
1744 * The client is required to retry. We need to close without returning
1745 * any other information so that the client retries.
1746 */
1747 txn->status = 0;
1748 rep->analysers &= AN_RES_FLT_END;
1749 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001750 s->logs.logwait = 0;
1751 s->logs.level = 0;
1752 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001753 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001754 return 0;
1755}
1756
1757/* This function performs all the processing enabled for the current response.
1758 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1759 * and updates s->res.analysers. It might make sense to explode it into several
1760 * other functions. It works like process_request (see indications above).
1761 */
1762int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1763{
1764 struct session *sess = s->sess;
1765 struct http_txn *txn = s->txn;
1766 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001767 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001768 struct proxy *cur_proxy;
1769 struct cond_wordlist *wl;
1770 enum rule_result ret = HTTP_RULE_RES_CONT;
1771
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001772 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1773 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001774
Christopher Faulete0768eb2018-10-03 16:38:02 +02001775 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1776 now_ms, __FUNCTION__,
1777 s,
1778 rep,
1779 rep->rex, rep->wex,
1780 rep->flags,
1781 ci_data(rep),
1782 rep->analysers);
1783
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001784 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001785
1786 /* The stats applet needs to adjust the Connection header but we don't
1787 * apply any filter there.
1788 */
1789 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1790 rep->analysers &= ~an_bit;
1791 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001792 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001793 }
1794
1795 /*
1796 * We will have to evaluate the filters.
1797 * As opposed to version 1.2, now they will be evaluated in the
1798 * filters order and not in the header order. This means that
1799 * each filter has to be validated among all headers.
1800 *
1801 * Filters are tried with ->be first, then with ->fe if it is
1802 * different from ->be.
1803 *
1804 * Maybe we are in resume condiion. In this case I choose the
1805 * "struct proxy" which contains the rule list matching the resume
1806 * pointer. If none of theses "struct proxy" match, I initialise
1807 * the process with the first one.
1808 *
1809 * In fact, I check only correspondance betwwen the current list
1810 * pointer and the ->fe rule list. If it doesn't match, I initialize
1811 * the loop with the ->be.
1812 */
1813 if (s->current_rule_list == &sess->fe->http_res_rules)
1814 cur_proxy = sess->fe;
1815 else
1816 cur_proxy = s->be;
1817 while (1) {
1818 struct proxy *rule_set = cur_proxy;
1819
1820 /* evaluate http-response rules */
1821 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001822 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001823
1824 if (ret == HTTP_RULE_RES_BADREQ)
1825 goto return_srv_prx_502;
1826
1827 if (ret == HTTP_RULE_RES_DONE) {
1828 rep->analysers &= ~an_bit;
1829 rep->analyse_exp = TICK_ETERNITY;
1830 return 1;
1831 }
1832 }
1833
1834 /* we need to be called again. */
1835 if (ret == HTTP_RULE_RES_YIELD) {
1836 channel_dont_close(rep);
1837 return 0;
1838 }
1839
1840 /* try headers filters */
1841 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001842 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1843 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001844 }
1845
1846 /* has the response been denied ? */
1847 if (txn->flags & TX_SVDENY) {
1848 if (objt_server(s->target))
1849 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
1850
1851 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1852 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1853 if (sess->listener->counters)
1854 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001855 goto return_srv_prx_502;
1856 }
1857
1858 /* add response headers from the rule sets in the same order */
1859 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001860 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861 if (txn->status < 200 && txn->status != 101)
1862 break;
1863 if (wl->cond) {
1864 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1865 ret = acl_pass(ret);
1866 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1867 ret = !ret;
1868 if (!ret)
1869 continue;
1870 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001871
1872 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1873 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001874 goto return_bad_resp;
1875 }
1876
1877 /* check whether we're already working on the frontend */
1878 if (cur_proxy == sess->fe)
1879 break;
1880 cur_proxy = sess->fe;
1881 }
1882
1883 /* After this point, this anayzer can't return yield, so we can
1884 * remove the bit corresponding to this analyzer from the list.
1885 *
1886 * Note that the intermediate returns and goto found previously
1887 * reset the analyzers.
1888 */
1889 rep->analysers &= ~an_bit;
1890 rep->analyse_exp = TICK_ETERNITY;
1891
1892 /* OK that's all we can do for 1xx responses */
1893 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001894 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001895
1896 /*
1897 * Now check for a server cookie.
1898 */
1899 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001900 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001901
1902 /*
1903 * Check for cache-control or pragma headers if required.
1904 */
1905 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1906 check_response_for_cacheability(s, rep);
1907
1908 /*
1909 * Add server cookie in the response if needed
1910 */
1911 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1912 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1913 (!(s->flags & SF_DIRECT) ||
1914 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1915 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1916 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1917 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1918 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1919 !(s->flags & SF_IGNORE_PRST)) {
1920 /* the server is known, it's not the one the client requested, or the
1921 * cookie's last seen date needs to be refreshed. We have to
1922 * insert a set-cookie here, except if we want to insert only on POST
1923 * requests and this one isn't. Note that servers which don't have cookies
1924 * (eg: some backup servers) will return a full cookie removal request.
1925 */
1926 if (!objt_server(s->target)->cookie) {
1927 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001928 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001929 s->be->cookie_name);
1930 }
1931 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001932 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933
1934 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1935 /* emit last_date, which is mandatory */
1936 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1937 s30tob64((date.tv_sec+3) >> 2,
1938 trash.area + trash.data);
1939 trash.data += 5;
1940
1941 if (s->be->cookie_maxlife) {
1942 /* emit first_date, which is either the original one or
1943 * the current date.
1944 */
1945 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1946 s30tob64(txn->cookie_first_date ?
1947 txn->cookie_first_date >> 2 :
1948 (date.tv_sec+3) >> 2,
1949 trash.area + trash.data);
1950 trash.data += 5;
1951 }
1952 }
1953 chunk_appendf(&trash, "; path=/");
1954 }
1955
1956 if (s->be->cookie_domain)
1957 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1958
1959 if (s->be->ck_opts & PR_CK_HTTPONLY)
1960 chunk_appendf(&trash, "; HttpOnly");
1961
1962 if (s->be->ck_opts & PR_CK_SECURE)
1963 chunk_appendf(&trash, "; Secure");
1964
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001965 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001966 goto return_bad_resp;
1967
1968 txn->flags &= ~TX_SCK_MASK;
1969 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1970 /* the server did not change, only the date was updated */
1971 txn->flags |= TX_SCK_UPDATED;
1972 else
1973 txn->flags |= TX_SCK_INSERTED;
1974
1975 /* Here, we will tell an eventual cache on the client side that we don't
1976 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1977 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1978 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1979 */
1980 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
1981
1982 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
1983
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001984 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001985 goto return_bad_resp;
1986 }
1987 }
1988
1989 /*
1990 * Check if result will be cacheable with a cookie.
1991 * We'll block the response if security checks have caught
1992 * nasty things such as a cacheable cookie.
1993 */
1994 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
1995 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
1996 (s->be->options & PR_O_CHK_CACHE)) {
1997 /* we're in presence of a cacheable response containing
1998 * a set-cookie header. We'll block it as requested by
1999 * the 'checkcache' option, and send an alert.
2000 */
2001 if (objt_server(s->target))
2002 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2003
2004 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2005 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2006 if (sess->listener->counters)
2007 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2008
2009 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2010 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2011 send_log(s->be, LOG_ALERT,
2012 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2013 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2014 goto return_srv_prx_502;
2015 }
2016
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002017 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002018 /* Always enter in the body analyzer */
2019 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2020 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2021
2022 /* if the user wants to log as soon as possible, without counting
2023 * bytes from the server, then this is the right moment. We have
2024 * to temporarily assign bytes_out to log what we currently have.
2025 */
2026 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2027 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002028 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002029 s->do_log(s);
2030 s->logs.bytes_out = 0;
2031 }
2032 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002033
2034 return_bad_resp:
2035 if (objt_server(s->target)) {
2036 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2037 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
2038 }
2039 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2040
2041 return_srv_prx_502:
2042 rep->analysers &= AN_RES_FLT_END;
2043 txn->status = 502;
2044 s->logs.t_data = -1; /* was not a valid response */
2045 s->si[1].flags |= SI_FL_NOLINGER;
2046 htx_reply_and_close(s, txn->status, http_error_message(s));
2047 if (!(s->flags & SF_ERR_MASK))
2048 s->flags |= SF_ERR_PRXCOND;
2049 if (!(s->flags & SF_FINST_MASK))
2050 s->flags |= SF_FINST_H;
2051 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002052}
2053
2054/* This function is an analyser which forwards response body (including chunk
2055 * sizes if any). It is called as soon as we must forward, even if we forward
2056 * zero byte. The only situation where it must not be called is when we're in
2057 * tunnel mode and we want to forward till the close. It's used both to forward
2058 * remaining data and to resync after end of body. It expects the msg_state to
2059 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2060 * read more data, or 1 once we can go on with next request or end the stream.
2061 *
2062 * It is capable of compressing response data both in content-length mode and
2063 * in chunked mode. The state machines follows different flows depending on
2064 * whether content-length and chunked modes are used, since there are no
2065 * trailers in content-length :
2066 *
2067 * chk-mode cl-mode
2068 * ,----- BODY -----.
2069 * / \
2070 * V size > 0 V chk-mode
2071 * .--> SIZE -------------> DATA -------------> CRLF
2072 * | | size == 0 | last byte |
2073 * | v final crlf v inspected |
2074 * | TRAILERS -----------> DONE |
2075 * | |
2076 * `----------------------------------------------'
2077 *
2078 * Compression only happens in the DATA state, and must be flushed in final
2079 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2080 * is performed at once on final states for all bytes parsed, or when leaving
2081 * on missing data.
2082 */
2083int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2084{
2085 struct session *sess = s->sess;
2086 struct http_txn *txn = s->txn;
2087 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002088 struct htx *htx;
2089 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090
2091 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2092 now_ms, __FUNCTION__,
2093 s,
2094 res,
2095 res->rex, res->wex,
2096 res->flags,
2097 ci_data(res),
2098 res->analysers);
2099
Christopher Faulet9768c262018-10-22 09:34:31 +02002100 htx = htx_from_buf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002101
2102 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002103 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002104 /* Output closed while we were sending data. We must abort and
2105 * wake the other side up.
2106 */
2107 msg->err_state = msg->msg_state;
2108 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002109 htx_end_response(s);
2110 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002111 return 1;
2112 }
2113
Christopher Faulet9768c262018-10-22 09:34:31 +02002114 if (msg->msg_state == HTTP_MSG_BODY)
2115 msg->msg_state = HTTP_MSG_DATA;
2116
Christopher Faulete0768eb2018-10-03 16:38:02 +02002117 /* in most states, we should abort in case of early close */
2118 channel_auto_close(res);
2119
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120 if (res->to_forward) {
2121 /* We can't process the buffer's contents yet */
2122 res->flags |= CF_WAKE_WRITE;
2123 goto missing_data_or_waiting;
2124 }
2125
Christopher Faulet9768c262018-10-22 09:34:31 +02002126 if (msg->msg_state >= HTTP_MSG_DONE)
2127 goto done;
2128
2129 /* Forward all input data. We get it by removing all outgoing data not
2130 * forwarded yet from HTX data size.
2131 */
2132 c_adv(res, htx->data - co_data(res));
2133
2134 /* To let the function channel_forward work as expected we must update
2135 * the channel's buffer to pretend there is no more input data. The
2136 * right length is then restored. We must do that, because when an HTX
2137 * message is stored into a buffer, it appears as full.
2138 */
2139 b_set_data(&res->buf, co_data(res));
2140 if (htx->extra != ULLONG_MAX)
2141 htx->extra -= channel_forward(res, htx->extra);
2142 b_set_data(&res->buf, b_size(&res->buf));
2143
2144 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2145 /* The server still sending data that should be filtered */
2146 if (res->flags & CF_SHUTR || !HAS_DATA_FILTERS(s, res)) {
2147 msg->msg_state = HTTP_MSG_TUNNEL;
2148 goto done;
2149 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002150 }
2151
Christopher Faulet9768c262018-10-22 09:34:31 +02002152 /* Check if the end-of-message is reached and if so, switch the message
2153 * in HTTP_MSG_DONE state.
2154 */
2155 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2156 goto missing_data_or_waiting;
2157
2158 msg->msg_state = HTTP_MSG_DONE;
2159
2160 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002161 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002162 channel_dont_close(res);
2163
Christopher Fauletf2824e62018-10-01 12:12:37 +02002164 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002165 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002166 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002167 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2168 if (res->flags & CF_SHUTW) {
2169 /* response errors are most likely due to the
2170 * client aborting the transfer. */
2171 goto aborted_xfer;
2172 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002173 goto return_bad_res;
2174 }
2175 return 1;
2176 }
2177 return 0;
2178
2179 missing_data_or_waiting:
2180 if (res->flags & CF_SHUTW)
2181 goto aborted_xfer;
2182
Christopher Faulet47365272018-10-31 17:40:50 +01002183 if (htx->flags & HTX_FL_PARSING_ERROR)
2184 goto return_bad_res;
2185
Christopher Faulete0768eb2018-10-03 16:38:02 +02002186 /* stop waiting for data if the input is closed before the end. If the
2187 * client side was already closed, it means that the client has aborted,
2188 * so we don't want to count this as a server abort. Otherwise it's a
2189 * server abort.
2190 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002191 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2193 goto aborted_xfer;
2194 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002195 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 if (!(s->flags & SF_ERR_MASK))
2197 s->flags |= SF_ERR_SRVCL;
2198 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2199 if (objt_server(s->target))
2200 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2201 goto return_bad_res_stats_ok;
2202 }
2203 }
2204
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 /* When TE: chunked is used, we need to get there again to parse
2206 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002207 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2208 * are filters registered on the stream, we don't want to forward a
2209 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002210 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002211 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_DATA_FILTERS(s, res))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 channel_dont_close(res);
2213
Christopher Faulet9768c262018-10-22 09:34:31 +02002214#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
2215 // about if
2216
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217 /* We know that more data are expected, but we couldn't send more that
2218 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2219 * system knows it must not set a PUSH on this first part. Interactive
2220 * modes are already handled by the stream sock layer. We must not do
2221 * this in content-length mode because it could present the MSG_MORE
2222 * flag with the last block of forwarded data, which would cause an
2223 * additional delay to be observed by the receiver.
2224 */
2225 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2226 res->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02002227#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02002228
2229 /* the stream handler will take care of timeouts and errors */
2230 return 0;
2231
2232 return_bad_res: /* let's centralize all bad responses */
2233 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2234 if (objt_server(s->target))
2235 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2236
2237 return_bad_res_stats_ok:
2238 txn->rsp.err_state = txn->rsp.msg_state;
2239 txn->rsp.msg_state = HTTP_MSG_ERROR;
2240 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002241 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 res->analysers &= AN_RES_FLT_END;
2243 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2244 if (objt_server(s->target))
2245 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
2246
2247 if (!(s->flags & SF_ERR_MASK))
2248 s->flags |= SF_ERR_PRXCOND;
2249 if (!(s->flags & SF_FINST_MASK))
2250 s->flags |= SF_FINST_D;
2251 return 0;
2252
2253 aborted_xfer:
2254 txn->rsp.err_state = txn->rsp.msg_state;
2255 txn->rsp.msg_state = HTTP_MSG_ERROR;
2256 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002257 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258 res->analysers &= AN_RES_FLT_END;
2259 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2260
2261 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2262 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2263 if (objt_server(s->target))
2264 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2265
2266 if (!(s->flags & SF_ERR_MASK))
2267 s->flags |= SF_ERR_CLICL;
2268 if (!(s->flags & SF_FINST_MASK))
2269 s->flags |= SF_FINST_D;
2270 return 0;
2271}
2272
Christopher Faulet0f226952018-10-22 09:29:56 +02002273void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002274{
2275 struct proxy *fe = strm_fe(s);
2276 int tmp = TX_CON_WANT_CLO;
2277
2278 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2279 tmp = TX_CON_WANT_TUN;
2280
2281 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002282 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002283}
2284
2285/* Perform an HTTP redirect based on the information in <rule>. The function
2286 * returns non-zero on success, or zero in case of a, irrecoverable error such
2287 * as too large a request to build a valid response.
2288 */
2289int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2290{
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002291 struct htx *htx = htx_from_buf(&s->req.buf);
2292 union h1_sl sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002293 const char *msg_fmt;
2294 struct buffer *chunk;
2295 int ret = 0;
2296
2297 chunk = alloc_trash_chunk();
2298 if (!chunk)
2299 goto leave;
2300
2301 /* build redirect message */
2302 switch(rule->code) {
2303 case 308:
2304 msg_fmt = HTTP_308;
2305 break;
2306 case 307:
2307 msg_fmt = HTTP_307;
2308 break;
2309 case 303:
2310 msg_fmt = HTTP_303;
2311 break;
2312 case 301:
2313 msg_fmt = HTTP_301;
2314 break;
2315 case 302:
2316 default:
2317 msg_fmt = HTTP_302;
2318 break;
2319 }
2320
2321 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
2322 goto leave;
2323
2324 switch(rule->type) {
2325 case REDIRECT_TYPE_SCHEME: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002326 struct http_hdr_ctx ctx;
2327 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002328
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002329 host = ist("");
2330 ctx.blk = NULL;
2331 if (http_find_header(htx, ist("Host"), &ctx, 0))
2332 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002333
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002334 sl = http_find_stline(htx);
2335 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002336 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002337 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2339 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002340 while (qs < path.len) {
2341 if (*(path.ptr + qs) == '?') {
2342 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002343 break;
2344 }
2345 qs++;
2346 }
2347 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002348 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002349 else
2350 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002351
2352 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353 /* add scheme */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002354 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2355 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356 }
2357 else {
2358 /* add scheme with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002359 chunk->data += build_logline(s, chunk->area + chunk->data,
2360 chunk->size - chunk->data,
2361 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002362 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002363 /* add "://" + host + path */
2364 if (!chunk_memcat(chunk, "://", 3) ||
2365 !chunk_memcat(chunk, host.ptr, host.len) ||
2366 !chunk_memcat(chunk, path.ptr, path.len))
2367 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368
2369 /* append a slash at the end of the location if needed and missing */
2370 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2371 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002372 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002374 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002375 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002376 break;
2377 }
2378 case REDIRECT_TYPE_PREFIX: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002379 struct ist path;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002380
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002381 sl = http_find_stline(htx);
2382 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002384 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2386 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002387 while (qs < path.len) {
2388 if (*(path.ptr + qs) == '?') {
2389 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390 break;
2391 }
2392 qs++;
2393 }
2394 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002396 else
2397 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002398
2399 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 /* add prefix. Note that if prefix == "/", we don't want to
2401 * add anything, otherwise it makes it hard for the user to
2402 * configure a self-redirection.
2403 */
2404 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002405 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2406 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407 }
2408 }
2409 else {
2410 /* add prefix with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002411 chunk->data += build_logline(s, chunk->area + chunk->data,
2412 chunk->size - chunk->data,
2413 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414 }
2415
2416 /* add path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002417 if (!chunk_memcat(chunk, path.ptr, path.len))
2418 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002419
2420 /* append a slash at the end of the location if needed and missing */
2421 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2422 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002423 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002424 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002425 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427 break;
2428 }
2429 case REDIRECT_TYPE_LOCATION:
2430 default:
2431 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 /* add location */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002433 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2434 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 }
2436 else {
2437 /* add location with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002438 chunk->data += build_logline(s, chunk->area + chunk->data,
2439 chunk->size - chunk->data,
2440 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
2442 break;
2443 }
2444
2445 if (rule->cookie_len) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002446 if (!chunk_memcat(chunk, "\r\nSet-Cookie: ", 14) ||
2447 !chunk_memcat(chunk, rule->cookie_str, rule->cookie_len))
2448 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 }
2450
2451 /* add end of headers and the keep-alive/close status. */
2452 txn->status = rule->code;
2453 /* let's log the request time */
2454 s->logs.tv_request = now;
2455
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002456 /* FIXME: close for now, but it could be cool to handle the keep-alive here */
2457 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2458 if (!chunk_memcat(chunk, "\r\nProxy-Connection: close\r\n\r\n", 29))
2459 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002460 } else {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002461 if (!chunk_memcat(chunk, "\r\nConnection: close\r\n\r\n", 23))
2462 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002464 htx_reply_and_close(s, txn->status, chunk);
2465 s->req.analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466
2467 if (!(s->flags & SF_ERR_MASK))
2468 s->flags |= SF_ERR_LOCAL;
2469 if (!(s->flags & SF_FINST_MASK))
2470 s->flags |= SF_FINST_R;
2471
2472 ret = 1;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002473 leave:
Christopher Fauletf2824e62018-10-01 12:12:37 +02002474 free_trash_chunk(chunk);
2475 return ret;
2476}
2477
Christopher Faulet72333522018-10-24 11:25:02 +02002478int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2479 struct ist name, const char *str, struct my_regex *re, int action)
2480{
2481 struct http_hdr_ctx ctx;
2482 struct buffer *output = get_trash_chunk();
2483
2484 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2485 ctx.blk = NULL;
2486 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2487 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2488 continue;
2489
2490 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2491 if (output->data == -1)
2492 return -1;
2493 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2494 return -1;
2495 }
2496 return 0;
2497}
2498
2499static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2500 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2501{
2502 struct buffer *replace;
2503 int ret = -1;
2504
2505 replace = alloc_trash_chunk();
2506 if (!replace)
2507 goto leave;
2508
2509 replace->data = build_logline(s, replace->area, replace->size, fmt);
2510 if (replace->data >= replace->size - 1)
2511 goto leave;
2512
2513 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2514
2515 leave:
2516 free_trash_chunk(replace);
2517 return ret;
2518}
2519
Christopher Faulet6eb92892018-11-15 16:39:29 +01002520/*
2521 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2522 * built according to <fmt> log line format.
2523 * If <early_hints> is NULL, it is allocated and the HTTP 103 response first
2524 * line is inserted before the header. If an error occurred <early_hints> is
2525 * released and NULL is returned. On success the updated buffer is returned.
2526 */
2527static struct buffer *htx_apply_early_hint_rule(struct stream* s, struct buffer *early_hints,
2528 const char* name, unsigned int name_len,
2529 struct list *fmt)
2530{
2531 if (!early_hints) {
2532 early_hints = alloc_trash_chunk();
2533 if (!early_hints)
2534 goto fail;
2535 if (!chunk_memcat(early_hints, HTTP_103.ptr, HTTP_103.len))
2536 goto fail;
2537 }
2538
2539 if (!chunk_memcat(early_hints, name, name_len) || !chunk_memcat(early_hints, ": ", 2))
2540 goto fail;
2541
2542 early_hints->data += build_logline(s, b_tail(early_hints), b_room(early_hints), fmt);
2543 if (!chunk_memcat(early_hints, "\r\n", 2))
2544 goto fail;
2545
2546 return early_hints;
2547
2548 fail:
2549 free_trash_chunk(early_hints);
2550 return NULL;
2551}
2552
2553/* Sends an HTTP 103 response. Before sending it, the last CRLF finishing the
2554 * response is added. If an error occurred or if another response was already
2555 * sent, this function does nothing.
2556 */
2557static void htx_send_early_hints(struct stream *s, struct buffer *early_hints)
2558{
2559 struct channel *chn = s->txn->rsp.chn;
2560 struct htx *htx;
2561
2562 /* If a response was already sent, skip early hints */
2563 if (s->txn->status > 0)
2564 return;
2565
2566 if (!chunk_memcat(early_hints, "\r\n", 2))
2567 return;
2568
2569 htx = htx_from_buf(&chn->buf);
2570 if (!htx_add_oob(htx, ist2(early_hints->area, early_hints->data)))
2571 return;
2572
2573 c_adv(chn, early_hints->data);
2574 chn->total += early_hints->data;
2575}
2576
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002577/* This function executes one of the set-{method,path,query,uri} actions. It
2578 * takes the string from the variable 'replace' with length 'len', then modifies
2579 * the relevant part of the request line accordingly. Then it updates various
2580 * pointers to the next elements which were moved, and the total buffer length.
2581 * It finds the action to be performed in p[2], previously filled by function
2582 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2583 * error, though this can be revisited when this code is finally exploited.
2584 *
2585 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2586 * query string and 3 to replace uri.
2587 *
2588 * In query string case, the mark question '?' must be set at the start of the
2589 * string by the caller, event if the replacement query string is empty.
2590 */
2591int htx_req_replace_stline(int action, const char *replace, int len,
2592 struct proxy *px, struct stream *s)
2593{
2594 struct htx *htx = htx_from_buf(&s->req.buf);
2595
2596 switch (action) {
2597 case 0: // method
2598 if (!http_replace_req_meth(htx, ist2(replace, len)))
2599 return -1;
2600 break;
2601
2602 case 1: // path
2603 if (!http_replace_req_path(htx, ist2(replace, len)))
2604 return -1;
2605 break;
2606
2607 case 2: // query
2608 if (!http_replace_req_query(htx, ist2(replace, len)))
2609 return -1;
2610 break;
2611
2612 case 3: // uri
2613 if (!http_replace_req_uri(htx, ist2(replace, len)))
2614 return -1;
2615 break;
2616
2617 default:
2618 return -1;
2619 }
2620 return 0;
2621}
2622
2623/* This function replace the HTTP status code and the associated message. The
2624 * variable <status> contains the new status code. This function never fails.
2625 */
2626void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2627{
2628 struct htx *htx = htx_from_buf(&s->res.buf);
2629 char *res;
2630
2631 chunk_reset(&trash);
2632 res = ultoa_o(status, trash.area, trash.size);
2633 trash.data = res - trash.area;
2634
2635 /* Do we have a custom reason format string? */
2636 if (reason == NULL)
2637 reason = http_get_reason(status);
2638
2639 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2640 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2641}
2642
Christopher Faulet3e964192018-10-24 11:39:23 +02002643/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2644 * transaction <txn>. Returns the verdict of the first rule that prevents
2645 * further processing of the request (auth, deny, ...), and defaults to
2646 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2647 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2648 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2649 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2650 * status.
2651 */
2652static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2653 struct stream *s, int *deny_status)
2654{
2655 struct session *sess = strm_sess(s);
2656 struct http_txn *txn = s->txn;
2657 struct htx *htx;
2658 struct connection *cli_conn;
2659 struct act_rule *rule;
2660 struct http_hdr_ctx ctx;
2661 const char *auth_realm;
2662 struct buffer *early_hints = NULL;
2663 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2664 int act_flags = 0;
2665
2666 htx = htx_from_buf(&s->req.buf);
2667
2668 /* If "the current_rule_list" match the executed rule list, we are in
2669 * resume condition. If a resume is needed it is always in the action
2670 * and never in the ACL or converters. In this case, we initialise the
2671 * current rule, and go to the action execution point.
2672 */
2673 if (s->current_rule) {
2674 rule = s->current_rule;
2675 s->current_rule = NULL;
2676 if (s->current_rule_list == rules)
2677 goto resume_execution;
2678 }
2679 s->current_rule_list = rules;
2680
2681 list_for_each_entry(rule, rules, list) {
2682 /* check optional condition */
2683 if (rule->cond) {
2684 int ret;
2685
2686 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2687 ret = acl_pass(ret);
2688
2689 if (rule->cond->pol == ACL_COND_UNLESS)
2690 ret = !ret;
2691
2692 if (!ret) /* condition not matched */
2693 continue;
2694 }
2695
2696 act_flags |= ACT_FLAG_FIRST;
2697 resume_execution:
2698 switch (rule->action) {
2699 case ACT_ACTION_ALLOW:
2700 rule_ret = HTTP_RULE_RES_STOP;
2701 goto end;
2702
2703 case ACT_ACTION_DENY:
2704 if (deny_status)
2705 *deny_status = rule->deny_status;
2706 rule_ret = HTTP_RULE_RES_DENY;
2707 goto end;
2708
2709 case ACT_HTTP_REQ_TARPIT:
2710 txn->flags |= TX_CLTARPIT;
2711 if (deny_status)
2712 *deny_status = rule->deny_status;
2713 rule_ret = HTTP_RULE_RES_DENY;
2714 goto end;
2715
2716 case ACT_HTTP_REQ_AUTH:
2717 /* Be sure to sned any pending HTTP 103 response first */
2718 if (early_hints) {
2719 htx_send_early_hints(s, early_hints);
2720 free_trash_chunk(early_hints);
2721 early_hints = NULL;
2722 }
2723 /* Auth might be performed on regular http-req rules as well as on stats */
2724 auth_realm = rule->arg.auth.realm;
2725 if (!auth_realm) {
2726 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2727 auth_realm = STATS_DEFAULT_REALM;
2728 else
2729 auth_realm = px->id;
2730 }
2731 /* send 401/407 depending on whether we use a proxy or not. We still
2732 * count one error, because normal browsing won't significantly
2733 * increase the counter but brute force attempts will.
2734 */
2735 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
2736 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
2737 htx_reply_and_close(s, txn->status, &trash);
2738 stream_inc_http_err_ctr(s);
2739 rule_ret = HTTP_RULE_RES_ABRT;
2740 goto end;
2741
2742 case ACT_HTTP_REDIR:
2743 /* Be sure to sned any pending HTTP 103 response first */
2744 if (early_hints) {
2745 htx_send_early_hints(s, early_hints);
2746 free_trash_chunk(early_hints);
2747 early_hints = NULL;
2748 }
2749 rule_ret = HTTP_RULE_RES_DONE;
2750 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2751 rule_ret = HTTP_RULE_RES_BADREQ;
2752 goto end;
2753
2754 case ACT_HTTP_SET_NICE:
2755 s->task->nice = rule->arg.nice;
2756 break;
2757
2758 case ACT_HTTP_SET_TOS:
2759 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2760 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2761 break;
2762
2763 case ACT_HTTP_SET_MARK:
2764#ifdef SO_MARK
2765 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2766 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2767#endif
2768 break;
2769
2770 case ACT_HTTP_SET_LOGL:
2771 s->logs.level = rule->arg.loglevel;
2772 break;
2773
2774 case ACT_HTTP_REPLACE_HDR:
2775 case ACT_HTTP_REPLACE_VAL:
2776 if (htx_transform_header(s, &s->req, htx,
2777 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2778 &rule->arg.hdr_add.fmt,
2779 &rule->arg.hdr_add.re, rule->action)) {
2780 rule_ret = HTTP_RULE_RES_BADREQ;
2781 goto end;
2782 }
2783 break;
2784
2785 case ACT_HTTP_DEL_HDR:
2786 /* remove all occurrences of the header */
2787 ctx.blk = NULL;
2788 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2789 http_remove_header(htx, &ctx);
2790 break;
2791
2792 case ACT_HTTP_SET_HDR:
2793 case ACT_HTTP_ADD_HDR: {
2794 /* The scope of the trash buffer must be limited to this function. The
2795 * build_logline() function can execute a lot of other function which
2796 * can use the trash buffer. So for limiting the scope of this global
2797 * buffer, we build first the header value using build_logline, and
2798 * after we store the header name.
2799 */
2800 struct buffer *replace;
2801 struct ist n, v;
2802
2803 replace = alloc_trash_chunk();
2804 if (!replace) {
2805 rule_ret = HTTP_RULE_RES_BADREQ;
2806 goto end;
2807 }
2808
2809 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2810 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2811 v = ist2(replace->area, replace->data);
2812
2813 if (rule->action == ACT_HTTP_SET_HDR) {
2814 /* remove all occurrences of the header */
2815 ctx.blk = NULL;
2816 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2817 http_remove_header(htx, &ctx);
2818 }
2819
2820 if (!http_add_header(htx, n, v)) {
2821 static unsigned char rate_limit = 0;
2822
2823 if ((rate_limit++ & 255) == 0) {
2824 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);
2825 }
2826
2827 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2828 if (sess->fe != s->be)
2829 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2830 if (sess->listener->counters)
2831 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2832 }
2833 free_trash_chunk(replace);
2834 break;
2835 }
2836
2837 case ACT_HTTP_DEL_ACL:
2838 case ACT_HTTP_DEL_MAP: {
2839 struct pat_ref *ref;
2840 struct buffer *key;
2841
2842 /* collect reference */
2843 ref = pat_ref_lookup(rule->arg.map.ref);
2844 if (!ref)
2845 continue;
2846
2847 /* allocate key */
2848 key = alloc_trash_chunk();
2849 if (!key) {
2850 rule_ret = HTTP_RULE_RES_BADREQ;
2851 goto end;
2852 }
2853
2854 /* collect key */
2855 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2856 key->area[key->data] = '\0';
2857
2858 /* perform update */
2859 /* returned code: 1=ok, 0=ko */
2860 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2861 pat_ref_delete(ref, key->area);
2862 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2863
2864 free_trash_chunk(key);
2865 break;
2866 }
2867
2868 case ACT_HTTP_ADD_ACL: {
2869 struct pat_ref *ref;
2870 struct buffer *key;
2871
2872 /* collect reference */
2873 ref = pat_ref_lookup(rule->arg.map.ref);
2874 if (!ref)
2875 continue;
2876
2877 /* allocate key */
2878 key = alloc_trash_chunk();
2879 if (!key) {
2880 rule_ret = HTTP_RULE_RES_BADREQ;
2881 goto end;
2882 }
2883
2884 /* collect key */
2885 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2886 key->area[key->data] = '\0';
2887
2888 /* perform update */
2889 /* add entry only if it does not already exist */
2890 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2891 if (pat_ref_find_elt(ref, key->area) == NULL)
2892 pat_ref_add(ref, key->area, NULL, NULL);
2893 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2894
2895 free_trash_chunk(key);
2896 break;
2897 }
2898
2899 case ACT_HTTP_SET_MAP: {
2900 struct pat_ref *ref;
2901 struct buffer *key, *value;
2902
2903 /* collect reference */
2904 ref = pat_ref_lookup(rule->arg.map.ref);
2905 if (!ref)
2906 continue;
2907
2908 /* allocate key */
2909 key = alloc_trash_chunk();
2910 if (!key) {
2911 rule_ret = HTTP_RULE_RES_BADREQ;
2912 goto end;
2913 }
2914
2915 /* allocate value */
2916 value = alloc_trash_chunk();
2917 if (!value) {
2918 free_trash_chunk(key);
2919 rule_ret = HTTP_RULE_RES_BADREQ;
2920 goto end;
2921 }
2922
2923 /* collect key */
2924 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2925 key->area[key->data] = '\0';
2926
2927 /* collect value */
2928 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2929 value->area[value->data] = '\0';
2930
2931 /* perform update */
2932 if (pat_ref_find_elt(ref, key->area) != NULL)
2933 /* update entry if it exists */
2934 pat_ref_set(ref, key->area, value->area, NULL);
2935 else
2936 /* insert a new entry */
2937 pat_ref_add(ref, key->area, value->area, NULL);
2938
2939 free_trash_chunk(key);
2940 free_trash_chunk(value);
2941 break;
2942 }
2943
2944 case ACT_HTTP_EARLY_HINT:
2945 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2946 break;
2947 early_hints = htx_apply_early_hint_rule(s, early_hints,
2948 rule->arg.early_hint.name,
2949 rule->arg.early_hint.name_len,
2950 &rule->arg.early_hint.fmt);
2951 if (!early_hints) {
2952 rule_ret = HTTP_RULE_RES_DONE;
2953 goto end;
2954 }
2955 break;
2956
2957 case ACT_CUSTOM:
2958 if ((s->req.flags & CF_READ_ERROR) ||
2959 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2960 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
2961 (px->options & PR_O_ABRT_CLOSE)))
2962 act_flags |= ACT_FLAG_FINAL;
2963
2964 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
2965 case ACT_RET_ERR:
2966 case ACT_RET_CONT:
2967 break;
2968 case ACT_RET_STOP:
2969 rule_ret = HTTP_RULE_RES_DONE;
2970 goto end;
2971 case ACT_RET_YIELD:
2972 s->current_rule = rule;
2973 rule_ret = HTTP_RULE_RES_YIELD;
2974 goto end;
2975 }
2976 break;
2977
2978 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
2979 /* Note: only the first valid tracking parameter of each
2980 * applies.
2981 */
2982
2983 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
2984 struct stktable *t;
2985 struct stksess *ts;
2986 struct stktable_key *key;
2987 void *ptr1, *ptr2;
2988
2989 t = rule->arg.trk_ctr.table.t;
2990 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
2991 rule->arg.trk_ctr.expr, NULL);
2992
2993 if (key && (ts = stktable_get_entry(t, key))) {
2994 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
2995
2996 /* let's count a new HTTP request as it's the first time we do it */
2997 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
2998 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
2999 if (ptr1 || ptr2) {
3000 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3001
3002 if (ptr1)
3003 stktable_data_cast(ptr1, http_req_cnt)++;
3004
3005 if (ptr2)
3006 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3007 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3008
3009 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3010
3011 /* If data was modified, we need to touch to re-schedule sync */
3012 stktable_touch_local(t, ts, 0);
3013 }
3014
3015 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3016 if (sess->fe != s->be)
3017 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3018 }
3019 }
3020 break;
3021
3022 /* other flags exists, but normaly, they never be matched. */
3023 default:
3024 break;
3025 }
3026 }
3027
3028 end:
3029 if (early_hints) {
3030 htx_send_early_hints(s, early_hints);
3031 free_trash_chunk(early_hints);
3032 }
3033
3034 /* we reached the end of the rules, nothing to report */
3035 return rule_ret;
3036}
3037
3038/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3039 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3040 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3041 * is returned, the process can continue the evaluation of next rule list. If
3042 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3043 * is returned, it means the operation could not be processed and a server error
3044 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3045 * deny rule. If *YIELD is returned, the caller must call again the function
3046 * with the same context.
3047 */
3048static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3049 struct stream *s)
3050{
3051 struct session *sess = strm_sess(s);
3052 struct http_txn *txn = s->txn;
3053 struct htx *htx;
3054 struct connection *cli_conn;
3055 struct act_rule *rule;
3056 struct http_hdr_ctx ctx;
3057 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3058 int act_flags = 0;
3059
3060 htx = htx_from_buf(&s->res.buf);
3061
3062 /* If "the current_rule_list" match the executed rule list, we are in
3063 * resume condition. If a resume is needed it is always in the action
3064 * and never in the ACL or converters. In this case, we initialise the
3065 * current rule, and go to the action execution point.
3066 */
3067 if (s->current_rule) {
3068 rule = s->current_rule;
3069 s->current_rule = NULL;
3070 if (s->current_rule_list == rules)
3071 goto resume_execution;
3072 }
3073 s->current_rule_list = rules;
3074
3075 list_for_each_entry(rule, rules, list) {
3076 /* check optional condition */
3077 if (rule->cond) {
3078 int ret;
3079
3080 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3081 ret = acl_pass(ret);
3082
3083 if (rule->cond->pol == ACL_COND_UNLESS)
3084 ret = !ret;
3085
3086 if (!ret) /* condition not matched */
3087 continue;
3088 }
3089
3090 act_flags |= ACT_FLAG_FIRST;
3091resume_execution:
3092 switch (rule->action) {
3093 case ACT_ACTION_ALLOW:
3094 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3095 goto end;
3096
3097 case ACT_ACTION_DENY:
3098 txn->flags |= TX_SVDENY;
3099 rule_ret = HTTP_RULE_RES_STOP;
3100 goto end;
3101
3102 case ACT_HTTP_SET_NICE:
3103 s->task->nice = rule->arg.nice;
3104 break;
3105
3106 case ACT_HTTP_SET_TOS:
3107 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3108 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3109 break;
3110
3111 case ACT_HTTP_SET_MARK:
3112#ifdef SO_MARK
3113 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3114 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3115#endif
3116 break;
3117
3118 case ACT_HTTP_SET_LOGL:
3119 s->logs.level = rule->arg.loglevel;
3120 break;
3121
3122 case ACT_HTTP_REPLACE_HDR:
3123 case ACT_HTTP_REPLACE_VAL:
3124 if (htx_transform_header(s, &s->res, htx,
3125 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3126 &rule->arg.hdr_add.fmt,
3127 &rule->arg.hdr_add.re, rule->action)) {
3128 rule_ret = HTTP_RULE_RES_BADREQ;
3129 goto end;
3130 }
3131 break;
3132
3133 case ACT_HTTP_DEL_HDR:
3134 /* remove all occurrences of the header */
3135 ctx.blk = NULL;
3136 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3137 http_remove_header(htx, &ctx);
3138 break;
3139
3140 case ACT_HTTP_SET_HDR:
3141 case ACT_HTTP_ADD_HDR: {
3142 struct buffer *replace;
3143 struct ist n, v;
3144
3145 replace = alloc_trash_chunk();
3146 if (!replace) {
3147 rule_ret = HTTP_RULE_RES_BADREQ;
3148 goto end;
3149 }
3150
3151 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3152 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3153 v = ist2(replace->area, replace->data);
3154
3155 if (rule->action == ACT_HTTP_SET_HDR) {
3156 /* remove all occurrences of the header */
3157 ctx.blk = NULL;
3158 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3159 http_remove_header(htx, &ctx);
3160 }
3161
3162 if (!http_add_header(htx, n, v)) {
3163 static unsigned char rate_limit = 0;
3164
3165 if ((rate_limit++ & 255) == 0) {
3166 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);
3167 }
3168
3169 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3170 if (sess->fe != s->be)
3171 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3172 if (sess->listener->counters)
3173 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3174 if (objt_server(s->target))
3175 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3176 }
3177 free_trash_chunk(replace);
3178 break;
3179 }
3180
3181 case ACT_HTTP_DEL_ACL:
3182 case ACT_HTTP_DEL_MAP: {
3183 struct pat_ref *ref;
3184 struct buffer *key;
3185
3186 /* collect reference */
3187 ref = pat_ref_lookup(rule->arg.map.ref);
3188 if (!ref)
3189 continue;
3190
3191 /* allocate key */
3192 key = alloc_trash_chunk();
3193 if (!key) {
3194 rule_ret = HTTP_RULE_RES_BADREQ;
3195 goto end;
3196 }
3197
3198 /* collect key */
3199 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3200 key->area[key->data] = '\0';
3201
3202 /* perform update */
3203 /* returned code: 1=ok, 0=ko */
3204 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3205 pat_ref_delete(ref, key->area);
3206 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3207
3208 free_trash_chunk(key);
3209 break;
3210 }
3211
3212 case ACT_HTTP_ADD_ACL: {
3213 struct pat_ref *ref;
3214 struct buffer *key;
3215
3216 /* collect reference */
3217 ref = pat_ref_lookup(rule->arg.map.ref);
3218 if (!ref)
3219 continue;
3220
3221 /* allocate key */
3222 key = alloc_trash_chunk();
3223 if (!key) {
3224 rule_ret = HTTP_RULE_RES_BADREQ;
3225 goto end;
3226 }
3227
3228 /* collect key */
3229 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3230 key->area[key->data] = '\0';
3231
3232 /* perform update */
3233 /* check if the entry already exists */
3234 if (pat_ref_find_elt(ref, key->area) == NULL)
3235 pat_ref_add(ref, key->area, NULL, NULL);
3236
3237 free_trash_chunk(key);
3238 break;
3239 }
3240
3241 case ACT_HTTP_SET_MAP: {
3242 struct pat_ref *ref;
3243 struct buffer *key, *value;
3244
3245 /* collect reference */
3246 ref = pat_ref_lookup(rule->arg.map.ref);
3247 if (!ref)
3248 continue;
3249
3250 /* allocate key */
3251 key = alloc_trash_chunk();
3252 if (!key) {
3253 rule_ret = HTTP_RULE_RES_BADREQ;
3254 goto end;
3255 }
3256
3257 /* allocate value */
3258 value = alloc_trash_chunk();
3259 if (!value) {
3260 free_trash_chunk(key);
3261 rule_ret = HTTP_RULE_RES_BADREQ;
3262 goto end;
3263 }
3264
3265 /* collect key */
3266 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3267 key->area[key->data] = '\0';
3268
3269 /* collect value */
3270 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3271 value->area[value->data] = '\0';
3272
3273 /* perform update */
3274 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3275 if (pat_ref_find_elt(ref, key->area) != NULL)
3276 /* update entry if it exists */
3277 pat_ref_set(ref, key->area, value->area, NULL);
3278 else
3279 /* insert a new entry */
3280 pat_ref_add(ref, key->area, value->area, NULL);
3281 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3282 free_trash_chunk(key);
3283 free_trash_chunk(value);
3284 break;
3285 }
3286
3287 case ACT_HTTP_REDIR:
3288 rule_ret = HTTP_RULE_RES_DONE;
3289 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3290 rule_ret = HTTP_RULE_RES_BADREQ;
3291 goto end;
3292
3293 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3294 /* Note: only the first valid tracking parameter of each
3295 * applies.
3296 */
3297 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3298 struct stktable *t;
3299 struct stksess *ts;
3300 struct stktable_key *key;
3301 void *ptr;
3302
3303 t = rule->arg.trk_ctr.table.t;
3304 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3305 rule->arg.trk_ctr.expr, NULL);
3306
3307 if (key && (ts = stktable_get_entry(t, key))) {
3308 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3309
3310 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3311
3312 /* let's count a new HTTP request as it's the first time we do it */
3313 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3314 if (ptr)
3315 stktable_data_cast(ptr, http_req_cnt)++;
3316
3317 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3318 if (ptr)
3319 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3320 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3321
3322 /* When the client triggers a 4xx from the server, it's most often due
3323 * to a missing object or permission. These events should be tracked
3324 * because if they happen often, it may indicate a brute force or a
3325 * vulnerability scan. Normally this is done when receiving the response
3326 * but here we're tracking after this ought to have been done so we have
3327 * to do it on purpose.
3328 */
3329 if ((unsigned)(txn->status - 400) < 100) {
3330 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3331 if (ptr)
3332 stktable_data_cast(ptr, http_err_cnt)++;
3333
3334 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3335 if (ptr)
3336 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3337 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3338 }
3339
3340 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3341
3342 /* If data was modified, we need to touch to re-schedule sync */
3343 stktable_touch_local(t, ts, 0);
3344
3345 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3346 if (sess->fe != s->be)
3347 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3348 }
3349 }
3350 break;
3351
3352 case ACT_CUSTOM:
3353 if ((s->req.flags & CF_READ_ERROR) ||
3354 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3355 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3356 (px->options & PR_O_ABRT_CLOSE)))
3357 act_flags |= ACT_FLAG_FINAL;
3358
3359 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3360 case ACT_RET_ERR:
3361 case ACT_RET_CONT:
3362 break;
3363 case ACT_RET_STOP:
3364 rule_ret = HTTP_RULE_RES_STOP;
3365 goto end;
3366 case ACT_RET_YIELD:
3367 s->current_rule = rule;
3368 rule_ret = HTTP_RULE_RES_YIELD;
3369 goto end;
3370 }
3371 break;
3372
3373 /* other flags exists, but normaly, they never be matched. */
3374 default:
3375 break;
3376 }
3377 }
3378
3379 end:
3380 /* we reached the end of the rules, nothing to report */
3381 return rule_ret;
3382}
3383
Christopher Faulet33640082018-10-24 11:53:01 +02003384/* Iterate the same filter through all request headers.
3385 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3386 * Since it can manage the switch to another backend, it updates the per-proxy
3387 * DENY stats.
3388 */
3389static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3390{
3391 struct http_txn *txn = s->txn;
3392 struct htx *htx;
3393 struct buffer *hdr = get_trash_chunk();
3394 int32_t pos;
3395
3396 htx = htx_from_buf(&req->buf);
3397
3398 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3399 struct htx_blk *blk = htx_get_blk(htx, pos);
3400 enum htx_blk_type type;
3401 struct ist n, v;
3402
3403 next_hdr:
3404 type = htx_get_blk_type(blk);
3405 if (type == HTX_BLK_EOH)
3406 break;
3407 if (type != HTX_BLK_HDR)
3408 continue;
3409
3410 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3411 return 1;
3412 else if (unlikely(txn->flags & TX_CLALLOW) &&
3413 (exp->action == ACT_ALLOW ||
3414 exp->action == ACT_DENY ||
3415 exp->action == ACT_TARPIT))
3416 return 0;
3417
3418 n = htx_get_blk_name(htx, blk);
3419 v = htx_get_blk_value(htx, blk);
3420
3421 chunk_memcat(hdr, n.ptr, n.len);
3422 hdr->area[hdr->data++] = ':';
3423 hdr->area[hdr->data++] = ' ';
3424 chunk_memcat(hdr, v.ptr, v.len);
3425
3426 /* Now we have one header in <hdr> */
3427
3428 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3429 struct http_hdr_ctx ctx;
3430 int len;
3431
3432 switch (exp->action) {
3433 case ACT_ALLOW:
3434 txn->flags |= TX_CLALLOW;
3435 goto end;
3436
3437 case ACT_DENY:
3438 txn->flags |= TX_CLDENY;
3439 goto end;
3440
3441 case ACT_TARPIT:
3442 txn->flags |= TX_CLTARPIT;
3443 goto end;
3444
3445 case ACT_REPLACE:
3446 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3447 if (len < 0)
3448 return -1;
3449
3450 http_parse_header(ist2(trash.area, len), &n, &v);
3451 ctx.blk = blk;
3452 ctx.value = v;
3453 if (!http_replace_header(htx, &ctx, n, v))
3454 return -1;
3455 if (!ctx.blk)
3456 goto end;
3457 pos = htx_get_blk_pos(htx, blk);
3458 break;
3459
3460 case ACT_REMOVE:
3461 ctx.blk = blk;
3462 ctx.value = v;
3463 if (!http_remove_header(htx, &ctx))
3464 return -1;
3465 if (!ctx.blk)
3466 goto end;
3467 pos = htx_get_blk_pos(htx, blk);
3468 goto next_hdr;
3469
3470 }
3471 }
3472 }
3473 end:
3474 return 0;
3475}
3476
3477/* Apply the filter to the request line.
3478 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3479 * or -1 if a replacement resulted in an invalid request line.
3480 * Since it can manage the switch to another backend, it updates the per-proxy
3481 * DENY stats.
3482 */
3483static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3484{
3485 struct http_txn *txn = s->txn;
3486 struct htx *htx;
3487 struct buffer *reqline = get_trash_chunk();
3488 int done;
3489
3490 htx = htx_from_buf(&req->buf);
3491
3492 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3493 return 1;
3494 else if (unlikely(txn->flags & TX_CLALLOW) &&
3495 (exp->action == ACT_ALLOW ||
3496 exp->action == ACT_DENY ||
3497 exp->action == ACT_TARPIT))
3498 return 0;
3499 else if (exp->action == ACT_REMOVE)
3500 return 0;
3501
3502 done = 0;
3503
3504 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3505
3506 /* Now we have the request line between cur_ptr and cur_end */
3507 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
3508 union h1_sl sl;
3509 int len;
3510
3511 switch (exp->action) {
3512 case ACT_ALLOW:
3513 txn->flags |= TX_CLALLOW;
3514 done = 1;
3515 break;
3516
3517 case ACT_DENY:
3518 txn->flags |= TX_CLDENY;
3519 done = 1;
3520 break;
3521
3522 case ACT_TARPIT:
3523 txn->flags |= TX_CLTARPIT;
3524 done = 1;
3525 break;
3526
3527 case ACT_REPLACE:
3528 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3529 if (len < 0)
3530 return -1;
3531
3532 http_parse_stline(ist2(trash.area, len),
3533 &sl.rq.m, &sl.rq.u, &sl.rq.v);
3534 sl.rq.meth = find_http_meth(sl.rq.m.ptr, sl.rq.m.len);
3535
3536 if (!http_replace_reqline(htx, sl))
3537 return -1;
3538 done = 1;
3539 break;
3540 }
3541 }
3542 return done;
3543}
3544
3545/*
3546 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3547 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3548 * unparsable request. Since it can manage the switch to another backend, it
3549 * updates the per-proxy DENY stats.
3550 */
3551static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3552{
3553 struct session *sess = s->sess;
3554 struct http_txn *txn = s->txn;
3555 struct hdr_exp *exp;
3556
3557 for (exp = px->req_exp; exp; exp = exp->next) {
3558 int ret;
3559
3560 /*
3561 * The interleaving of transformations and verdicts
3562 * makes it difficult to decide to continue or stop
3563 * the evaluation.
3564 */
3565
3566 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3567 break;
3568
3569 if ((txn->flags & TX_CLALLOW) &&
3570 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3571 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3572 continue;
3573
3574 /* if this filter had a condition, evaluate it now and skip to
3575 * next filter if the condition does not match.
3576 */
3577 if (exp->cond) {
3578 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3579 ret = acl_pass(ret);
3580 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3581 ret = !ret;
3582
3583 if (!ret)
3584 continue;
3585 }
3586
3587 /* Apply the filter to the request line. */
3588 ret = htx_apply_filter_to_req_line(s, req, exp);
3589 if (unlikely(ret < 0))
3590 return -1;
3591
3592 if (likely(ret == 0)) {
3593 /* The filter did not match the request, it can be
3594 * iterated through all headers.
3595 */
3596 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3597 return -1;
3598 }
3599 }
3600 return 0;
3601}
3602
3603/* Iterate the same filter through all response headers contained in <res>.
3604 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3605 */
3606static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3607{
3608 struct http_txn *txn = s->txn;
3609 struct htx *htx;
3610 struct buffer *hdr = get_trash_chunk();
3611 int32_t pos;
3612
3613 htx = htx_from_buf(&res->buf);
3614
3615 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3616 struct htx_blk *blk = htx_get_blk(htx, pos);
3617 enum htx_blk_type type;
3618 struct ist n, v;
3619
3620 next_hdr:
3621 type = htx_get_blk_type(blk);
3622 if (type == HTX_BLK_EOH)
3623 break;
3624 if (type != HTX_BLK_HDR)
3625 continue;
3626
3627 if (unlikely(txn->flags & TX_SVDENY))
3628 return 1;
3629 else if (unlikely(txn->flags & TX_SVALLOW) &&
3630 (exp->action == ACT_ALLOW ||
3631 exp->action == ACT_DENY))
3632 return 0;
3633
3634 n = htx_get_blk_name(htx, blk);
3635 v = htx_get_blk_value(htx, blk);
3636
3637 chunk_memcat(hdr, n.ptr, n.len);
3638 hdr->area[hdr->data++] = ':';
3639 hdr->area[hdr->data++] = ' ';
3640 chunk_memcat(hdr, v.ptr, v.len);
3641
3642 /* Now we have one header in <hdr> */
3643
3644 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3645 struct http_hdr_ctx ctx;
3646 int len;
3647
3648 switch (exp->action) {
3649 case ACT_ALLOW:
3650 txn->flags |= TX_SVALLOW;
3651 goto end;
3652 break;
3653
3654 case ACT_DENY:
3655 txn->flags |= TX_SVDENY;
3656 goto end;
3657 break;
3658
3659 case ACT_REPLACE:
3660 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3661 if (len < 0)
3662 return -1;
3663
3664 http_parse_header(ist2(trash.area, len), &n, &v);
3665 ctx.blk = blk;
3666 ctx.value = v;
3667 if (!http_replace_header(htx, &ctx, n, v))
3668 return -1;
3669 if (!ctx.blk)
3670 goto end;
3671 pos = htx_get_blk_pos(htx, blk);
3672 break;
3673
3674 case ACT_REMOVE:
3675 ctx.blk = blk;
3676 ctx.value = v;
3677 if (!http_remove_header(htx, &ctx))
3678 return -1;
3679 if (!ctx.blk)
3680 goto end;
3681 pos = htx_get_blk_pos(htx, blk);
3682 goto next_hdr;
3683 }
3684 }
3685
3686 }
3687 end:
3688 return 0;
3689}
3690
3691/* Apply the filter to the status line in the response buffer <res>.
3692 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3693 * or -1 if a replacement resulted in an invalid status line.
3694 */
3695static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3696{
3697 struct http_txn *txn = s->txn;
3698 struct htx *htx;
3699 struct buffer *resline = get_trash_chunk();
3700 int done;
3701
3702 htx = htx_from_buf(&res->buf);
3703
3704 if (unlikely(txn->flags & TX_SVDENY))
3705 return 1;
3706 else if (unlikely(txn->flags & TX_SVALLOW) &&
3707 (exp->action == ACT_ALLOW ||
3708 exp->action == ACT_DENY))
3709 return 0;
3710 else if (exp->action == ACT_REMOVE)
3711 return 0;
3712
3713 done = 0;
3714 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3715
3716 /* Now we have the status line between cur_ptr and cur_end */
3717 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
3718 union h1_sl sl;
3719 int len;
3720
3721 switch (exp->action) {
3722 case ACT_ALLOW:
3723 txn->flags |= TX_SVALLOW;
3724 done = 1;
3725 break;
3726
3727 case ACT_DENY:
3728 txn->flags |= TX_SVDENY;
3729 done = 1;
3730 break;
3731
3732 case ACT_REPLACE:
3733 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3734 if (len < 0)
3735 return -1;
3736
3737 http_parse_stline(ist2(trash.area, len),
3738 &sl.st.v, &sl.st.c, &sl.st.r);
3739 sl.st.status = strl2ui(sl.st.c.ptr, sl.st.c.len);
3740
3741 if (!http_replace_resline(htx, sl))
3742 return -1;
3743
3744 done = 1;
3745 return 1;
3746 }
3747 }
3748 return done;
3749}
3750
3751/*
3752 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3753 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3754 * unparsable response.
3755 */
3756static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3757{
3758 struct session *sess = s->sess;
3759 struct http_txn *txn = s->txn;
3760 struct hdr_exp *exp;
3761
3762 for (exp = px->rsp_exp; exp; exp = exp->next) {
3763 int ret;
3764
3765 /*
3766 * The interleaving of transformations and verdicts
3767 * makes it difficult to decide to continue or stop
3768 * the evaluation.
3769 */
3770
3771 if (txn->flags & TX_SVDENY)
3772 break;
3773
3774 if ((txn->flags & TX_SVALLOW) &&
3775 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3776 exp->action == ACT_PASS)) {
3777 exp = exp->next;
3778 continue;
3779 }
3780
3781 /* if this filter had a condition, evaluate it now and skip to
3782 * next filter if the condition does not match.
3783 */
3784 if (exp->cond) {
3785 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3786 ret = acl_pass(ret);
3787 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3788 ret = !ret;
3789 if (!ret)
3790 continue;
3791 }
3792
3793 /* Apply the filter to the status line. */
3794 ret = htx_apply_filter_to_sts_line(s, res, exp);
3795 if (unlikely(ret < 0))
3796 return -1;
3797
3798 if (likely(ret == 0)) {
3799 /* The filter did not match the response, it can be
3800 * iterated through all headers.
3801 */
3802 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3803 return -1;
3804 }
3805 }
3806 return 0;
3807}
3808
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003809/*
3810 * Manage client-side cookie. It can impact performance by about 2% so it is
3811 * desirable to call it only when needed. This code is quite complex because
3812 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3813 * highly recommended not to touch this part without a good reason !
3814 */
3815static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3816{
3817 struct session *sess = s->sess;
3818 struct http_txn *txn = s->txn;
3819 struct htx *htx;
3820 struct http_hdr_ctx ctx;
3821 char *hdr_beg, *hdr_end, *del_from;
3822 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3823 int preserve_hdr;
3824
3825 htx = htx_from_buf(&req->buf);
3826 ctx.blk = NULL;
3827 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3828 del_from = NULL; /* nothing to be deleted */
3829 preserve_hdr = 0; /* assume we may kill the whole header */
3830
3831 /* Now look for cookies. Conforming to RFC2109, we have to support
3832 * attributes whose name begin with a '$', and associate them with
3833 * the right cookie, if we want to delete this cookie.
3834 * So there are 3 cases for each cookie read :
3835 * 1) it's a special attribute, beginning with a '$' : ignore it.
3836 * 2) it's a server id cookie that we *MAY* want to delete : save
3837 * some pointers on it (last semi-colon, beginning of cookie...)
3838 * 3) it's an application cookie : we *MAY* have to delete a previous
3839 * "special" cookie.
3840 * At the end of loop, if a "special" cookie remains, we may have to
3841 * remove it. If no application cookie persists in the header, we
3842 * *MUST* delete it.
3843 *
3844 * Note: RFC2965 is unclear about the processing of spaces around
3845 * the equal sign in the ATTR=VALUE form. A careful inspection of
3846 * the RFC explicitly allows spaces before it, and not within the
3847 * tokens (attrs or values). An inspection of RFC2109 allows that
3848 * too but section 10.1.3 lets one think that spaces may be allowed
3849 * after the equal sign too, resulting in some (rare) buggy
3850 * implementations trying to do that. So let's do what servers do.
3851 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3852 * allowed quoted strings in values, with any possible character
3853 * after a backslash, including control chars and delimitors, which
3854 * causes parsing to become ambiguous. Browsers also allow spaces
3855 * within values even without quotes.
3856 *
3857 * We have to keep multiple pointers in order to support cookie
3858 * removal at the beginning, middle or end of header without
3859 * corrupting the header. All of these headers are valid :
3860 *
3861 * hdr_beg hdr_end
3862 * | |
3863 * v |
3864 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3865 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3866 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3867 * | | | | | | |
3868 * | | | | | | |
3869 * | | | | | | +--> next
3870 * | | | | | +----> val_end
3871 * | | | | +-----------> val_beg
3872 * | | | +--------------> equal
3873 * | | +----------------> att_end
3874 * | +---------------------> att_beg
3875 * +--------------------------> prev
3876 *
3877 */
3878 hdr_beg = ctx.value.ptr;
3879 hdr_end = hdr_beg + ctx.value.len;
3880 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3881 /* Iterate through all cookies on this line */
3882
3883 /* find att_beg */
3884 att_beg = prev;
3885 if (prev > hdr_beg)
3886 att_beg++;
3887
3888 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3889 att_beg++;
3890
3891 /* find att_end : this is the first character after the last non
3892 * space before the equal. It may be equal to hdr_end.
3893 */
3894 equal = att_end = att_beg;
3895 while (equal < hdr_end) {
3896 if (*equal == '=' || *equal == ',' || *equal == ';')
3897 break;
3898 if (HTTP_IS_SPHT(*equal++))
3899 continue;
3900 att_end = equal;
3901 }
3902
3903 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3904 * is between <att_beg> and <equal>, both may be identical.
3905 */
3906 /* look for end of cookie if there is an equal sign */
3907 if (equal < hdr_end && *equal == '=') {
3908 /* look for the beginning of the value */
3909 val_beg = equal + 1;
3910 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3911 val_beg++;
3912
3913 /* find the end of the value, respecting quotes */
3914 next = http_find_cookie_value_end(val_beg, hdr_end);
3915
3916 /* make val_end point to the first white space or delimitor after the value */
3917 val_end = next;
3918 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3919 val_end--;
3920 }
3921 else
3922 val_beg = val_end = next = equal;
3923
3924 /* We have nothing to do with attributes beginning with
3925 * '$'. However, they will automatically be removed if a
3926 * header before them is removed, since they're supposed
3927 * to be linked together.
3928 */
3929 if (*att_beg == '$')
3930 continue;
3931
3932 /* Ignore cookies with no equal sign */
3933 if (equal == next) {
3934 /* This is not our cookie, so we must preserve it. But if we already
3935 * scheduled another cookie for removal, we cannot remove the
3936 * complete header, but we can remove the previous block itself.
3937 */
3938 preserve_hdr = 1;
3939 if (del_from != NULL) {
3940 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3941 val_end += delta;
3942 next += delta;
3943 hdr_end += delta;
3944 prev = del_from;
3945 del_from = NULL;
3946 }
3947 continue;
3948 }
3949
3950 /* if there are spaces around the equal sign, we need to
3951 * strip them otherwise we'll get trouble for cookie captures,
3952 * or even for rewrites. Since this happens extremely rarely,
3953 * it does not hurt performance.
3954 */
3955 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3956 int stripped_before = 0;
3957 int stripped_after = 0;
3958
3959 if (att_end != equal) {
3960 memmove(att_end, equal, hdr_end - equal);
3961 stripped_before = (att_end - equal);
3962 equal += stripped_before;
3963 val_beg += stripped_before;
3964 }
3965
3966 if (val_beg > equal + 1) {
3967 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3968 stripped_after = (equal + 1) - val_beg;
3969 val_beg += stripped_after;
3970 stripped_before += stripped_after;
3971 }
3972
3973 val_end += stripped_before;
3974 next += stripped_before;
3975 hdr_end += stripped_before;
3976 }
3977 /* now everything is as on the diagram above */
3978
3979 /* First, let's see if we want to capture this cookie. We check
3980 * that we don't already have a client side cookie, because we
3981 * can only capture one. Also as an optimisation, we ignore
3982 * cookies shorter than the declared name.
3983 */
3984 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
3985 (val_end - att_beg >= sess->fe->capture_namelen) &&
3986 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
3987 int log_len = val_end - att_beg;
3988
3989 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
3990 ha_alert("HTTP logging : out of memory.\n");
3991 } else {
3992 if (log_len > sess->fe->capture_len)
3993 log_len = sess->fe->capture_len;
3994 memcpy(txn->cli_cookie, att_beg, log_len);
3995 txn->cli_cookie[log_len] = 0;
3996 }
3997 }
3998
3999 /* Persistence cookies in passive, rewrite or insert mode have the
4000 * following form :
4001 *
4002 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4003 *
4004 * For cookies in prefix mode, the form is :
4005 *
4006 * Cookie: NAME=SRV~VALUE
4007 */
4008 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4009 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4010 struct server *srv = s->be->srv;
4011 char *delim;
4012
4013 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4014 * have the server ID between val_beg and delim, and the original cookie between
4015 * delim+1 and val_end. Otherwise, delim==val_end :
4016 *
4017 * hdr_beg
4018 * |
4019 * v
4020 * NAME=SRV; # in all but prefix modes
4021 * NAME=SRV~OPAQUE ; # in prefix mode
4022 * || || | |+-> next
4023 * || || | +--> val_end
4024 * || || +---------> delim
4025 * || |+------------> val_beg
4026 * || +-------------> att_end = equal
4027 * |+-----------------> att_beg
4028 * +------------------> prev
4029 *
4030 */
4031 if (s->be->ck_opts & PR_CK_PFX) {
4032 for (delim = val_beg; delim < val_end; delim++)
4033 if (*delim == COOKIE_DELIM)
4034 break;
4035 }
4036 else {
4037 char *vbar1;
4038 delim = val_end;
4039 /* Now check if the cookie contains a date field, which would
4040 * appear after a vertical bar ('|') just after the server name
4041 * and before the delimiter.
4042 */
4043 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4044 if (vbar1) {
4045 /* OK, so left of the bar is the server's cookie and
4046 * right is the last seen date. It is a base64 encoded
4047 * 30-bit value representing the UNIX date since the
4048 * epoch in 4-second quantities.
4049 */
4050 int val;
4051 delim = vbar1++;
4052 if (val_end - vbar1 >= 5) {
4053 val = b64tos30(vbar1);
4054 if (val > 0)
4055 txn->cookie_last_date = val << 2;
4056 }
4057 /* look for a second vertical bar */
4058 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4059 if (vbar1 && (val_end - vbar1 > 5)) {
4060 val = b64tos30(vbar1 + 1);
4061 if (val > 0)
4062 txn->cookie_first_date = val << 2;
4063 }
4064 }
4065 }
4066
4067 /* if the cookie has an expiration date and the proxy wants to check
4068 * it, then we do that now. We first check if the cookie is too old,
4069 * then only if it has expired. We detect strict overflow because the
4070 * time resolution here is not great (4 seconds). Cookies with dates
4071 * in the future are ignored if their offset is beyond one day. This
4072 * allows an admin to fix timezone issues without expiring everyone
4073 * and at the same time avoids keeping unwanted side effects for too
4074 * long.
4075 */
4076 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4077 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4078 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4079 txn->flags &= ~TX_CK_MASK;
4080 txn->flags |= TX_CK_OLD;
4081 delim = val_beg; // let's pretend we have not found the cookie
4082 txn->cookie_first_date = 0;
4083 txn->cookie_last_date = 0;
4084 }
4085 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4086 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4087 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4088 txn->flags &= ~TX_CK_MASK;
4089 txn->flags |= TX_CK_EXPIRED;
4090 delim = val_beg; // let's pretend we have not found the cookie
4091 txn->cookie_first_date = 0;
4092 txn->cookie_last_date = 0;
4093 }
4094
4095 /* Here, we'll look for the first running server which supports the cookie.
4096 * This allows to share a same cookie between several servers, for example
4097 * to dedicate backup servers to specific servers only.
4098 * However, to prevent clients from sticking to cookie-less backup server
4099 * when they have incidentely learned an empty cookie, we simply ignore
4100 * empty cookies and mark them as invalid.
4101 * The same behaviour is applied when persistence must be ignored.
4102 */
4103 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4104 srv = NULL;
4105
4106 while (srv) {
4107 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4108 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4109 if ((srv->cur_state != SRV_ST_STOPPED) ||
4110 (s->be->options & PR_O_PERSIST) ||
4111 (s->flags & SF_FORCE_PRST)) {
4112 /* we found the server and we can use it */
4113 txn->flags &= ~TX_CK_MASK;
4114 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4115 s->flags |= SF_DIRECT | SF_ASSIGNED;
4116 s->target = &srv->obj_type;
4117 break;
4118 } else {
4119 /* we found a server, but it's down,
4120 * mark it as such and go on in case
4121 * another one is available.
4122 */
4123 txn->flags &= ~TX_CK_MASK;
4124 txn->flags |= TX_CK_DOWN;
4125 }
4126 }
4127 srv = srv->next;
4128 }
4129
4130 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4131 /* no server matched this cookie or we deliberately skipped it */
4132 txn->flags &= ~TX_CK_MASK;
4133 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4134 txn->flags |= TX_CK_UNUSED;
4135 else
4136 txn->flags |= TX_CK_INVALID;
4137 }
4138
4139 /* depending on the cookie mode, we may have to either :
4140 * - delete the complete cookie if we're in insert+indirect mode, so that
4141 * the server never sees it ;
4142 * - remove the server id from the cookie value, and tag the cookie as an
4143 * application cookie so that it does not get accidentely removed later,
4144 * if we're in cookie prefix mode
4145 */
4146 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4147 int delta; /* negative */
4148
4149 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4150 delta = val_beg - (delim + 1);
4151 val_end += delta;
4152 next += delta;
4153 hdr_end += delta;
4154 del_from = NULL;
4155 preserve_hdr = 1; /* we want to keep this cookie */
4156 }
4157 else if (del_from == NULL &&
4158 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4159 del_from = prev;
4160 }
4161 }
4162 else {
4163 /* This is not our cookie, so we must preserve it. But if we already
4164 * scheduled another cookie for removal, we cannot remove the
4165 * complete header, but we can remove the previous block itself.
4166 */
4167 preserve_hdr = 1;
4168
4169 if (del_from != NULL) {
4170 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4171 if (att_beg >= del_from)
4172 att_beg += delta;
4173 if (att_end >= del_from)
4174 att_end += delta;
4175 val_beg += delta;
4176 val_end += delta;
4177 next += delta;
4178 hdr_end += delta;
4179 prev = del_from;
4180 del_from = NULL;
4181 }
4182 }
4183
4184 /* continue with next cookie on this header line */
4185 att_beg = next;
4186 } /* for each cookie */
4187
4188
4189 /* There are no more cookies on this line.
4190 * We may still have one (or several) marked for deletion at the
4191 * end of the line. We must do this now in two ways :
4192 * - if some cookies must be preserved, we only delete from the
4193 * mark to the end of line ;
4194 * - if nothing needs to be preserved, simply delete the whole header
4195 */
4196 if (del_from) {
4197 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4198 }
4199 if ((hdr_end - hdr_beg) != ctx.value.len) {
4200 if (hdr_beg != hdr_end) {
4201 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4202 htx->data -= (hdr_end - ctx.value.ptr);
4203 }
4204 else
4205 http_remove_header(htx, &ctx);
4206 }
4207 } /* for each "Cookie header */
4208}
4209
4210/*
4211 * Manage server-side cookies. It can impact performance by about 2% so it is
4212 * desirable to call it only when needed. This function is also used when we
4213 * just need to know if there is a cookie (eg: for check-cache).
4214 */
4215static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4216{
4217 struct session *sess = s->sess;
4218 struct http_txn *txn = s->txn;
4219 struct htx *htx;
4220 struct http_hdr_ctx ctx;
4221 struct server *srv;
4222 char *hdr_beg, *hdr_end;
4223 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4224 int is_cookie2;
4225
4226 htx = htx_from_buf(&res->buf);
4227
4228 ctx.blk = NULL;
4229 while (1) {
4230 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4231 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4232 break;
4233 is_cookie2 = 1;
4234 }
4235
4236 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4237 * <prev> points to the colon.
4238 */
4239 txn->flags |= TX_SCK_PRESENT;
4240
4241 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4242 * check-cache is enabled) and we are not interested in checking
4243 * them. Warning, the cookie capture is declared in the frontend.
4244 */
4245 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4246 break;
4247
4248 /* OK so now we know we have to process this response cookie.
4249 * The format of the Set-Cookie header is slightly different
4250 * from the format of the Cookie header in that it does not
4251 * support the comma as a cookie delimiter (thus the header
4252 * cannot be folded) because the Expires attribute described in
4253 * the original Netscape's spec may contain an unquoted date
4254 * with a comma inside. We have to live with this because
4255 * many browsers don't support Max-Age and some browsers don't
4256 * support quoted strings. However the Set-Cookie2 header is
4257 * clean.
4258 *
4259 * We have to keep multiple pointers in order to support cookie
4260 * removal at the beginning, middle or end of header without
4261 * corrupting the header (in case of set-cookie2). A special
4262 * pointer, <scav> points to the beginning of the set-cookie-av
4263 * fields after the first semi-colon. The <next> pointer points
4264 * either to the end of line (set-cookie) or next unquoted comma
4265 * (set-cookie2). All of these headers are valid :
4266 *
4267 * hdr_beg hdr_end
4268 * | |
4269 * v |
4270 * NAME1 = VALUE 1 ; Secure; Path="/" |
4271 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4272 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4273 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4274 * | | | | | | | |
4275 * | | | | | | | +-> next
4276 * | | | | | | +------------> scav
4277 * | | | | | +--------------> val_end
4278 * | | | | +--------------------> val_beg
4279 * | | | +----------------------> equal
4280 * | | +------------------------> att_end
4281 * | +----------------------------> att_beg
4282 * +------------------------------> prev
4283 * -------------------------------> hdr_beg
4284 */
4285 hdr_beg = ctx.value.ptr;
4286 hdr_end = hdr_beg + ctx.value.len;
4287 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4288
4289 /* Iterate through all cookies on this line */
4290
4291 /* find att_beg */
4292 att_beg = prev;
4293 if (prev > hdr_beg)
4294 att_beg++;
4295
4296 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4297 att_beg++;
4298
4299 /* find att_end : this is the first character after the last non
4300 * space before the equal. It may be equal to hdr_end.
4301 */
4302 equal = att_end = att_beg;
4303
4304 while (equal < hdr_end) {
4305 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4306 break;
4307 if (HTTP_IS_SPHT(*equal++))
4308 continue;
4309 att_end = equal;
4310 }
4311
4312 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4313 * is between <att_beg> and <equal>, both may be identical.
4314 */
4315
4316 /* look for end of cookie if there is an equal sign */
4317 if (equal < hdr_end && *equal == '=') {
4318 /* look for the beginning of the value */
4319 val_beg = equal + 1;
4320 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4321 val_beg++;
4322
4323 /* find the end of the value, respecting quotes */
4324 next = http_find_cookie_value_end(val_beg, hdr_end);
4325
4326 /* make val_end point to the first white space or delimitor after the value */
4327 val_end = next;
4328 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4329 val_end--;
4330 }
4331 else {
4332 /* <equal> points to next comma, semi-colon or EOL */
4333 val_beg = val_end = next = equal;
4334 }
4335
4336 if (next < hdr_end) {
4337 /* Set-Cookie2 supports multiple cookies, and <next> points to
4338 * a colon or semi-colon before the end. So skip all attr-value
4339 * pairs and look for the next comma. For Set-Cookie, since
4340 * commas are permitted in values, skip to the end.
4341 */
4342 if (is_cookie2)
4343 next = http_find_hdr_value_end(next, hdr_end);
4344 else
4345 next = hdr_end;
4346 }
4347
4348 /* Now everything is as on the diagram above */
4349
4350 /* Ignore cookies with no equal sign */
4351 if (equal == val_end)
4352 continue;
4353
4354 /* If there are spaces around the equal sign, we need to
4355 * strip them otherwise we'll get trouble for cookie captures,
4356 * or even for rewrites. Since this happens extremely rarely,
4357 * it does not hurt performance.
4358 */
4359 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4360 int stripped_before = 0;
4361 int stripped_after = 0;
4362
4363 if (att_end != equal) {
4364 memmove(att_end, equal, hdr_end - equal);
4365 stripped_before = (att_end - equal);
4366 equal += stripped_before;
4367 val_beg += stripped_before;
4368 }
4369
4370 if (val_beg > equal + 1) {
4371 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4372 stripped_after = (equal + 1) - val_beg;
4373 val_beg += stripped_after;
4374 stripped_before += stripped_after;
4375 }
4376
4377 val_end += stripped_before;
4378 next += stripped_before;
4379 hdr_end += stripped_before;
4380
4381 ctx.value.len = hdr_end - hdr_beg;
4382 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4383 htx->data -= (hdr_end - ctx.value.ptr);
4384 }
4385
4386 /* First, let's see if we want to capture this cookie. We check
4387 * that we don't already have a server side cookie, because we
4388 * can only capture one. Also as an optimisation, we ignore
4389 * cookies shorter than the declared name.
4390 */
4391 if (sess->fe->capture_name != NULL &&
4392 txn->srv_cookie == NULL &&
4393 (val_end - att_beg >= sess->fe->capture_namelen) &&
4394 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4395 int log_len = val_end - att_beg;
4396 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4397 ha_alert("HTTP logging : out of memory.\n");
4398 }
4399 else {
4400 if (log_len > sess->fe->capture_len)
4401 log_len = sess->fe->capture_len;
4402 memcpy(txn->srv_cookie, att_beg, log_len);
4403 txn->srv_cookie[log_len] = 0;
4404 }
4405 }
4406
4407 srv = objt_server(s->target);
4408 /* now check if we need to process it for persistence */
4409 if (!(s->flags & SF_IGNORE_PRST) &&
4410 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4411 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4412 /* assume passive cookie by default */
4413 txn->flags &= ~TX_SCK_MASK;
4414 txn->flags |= TX_SCK_FOUND;
4415
4416 /* If the cookie is in insert mode on a known server, we'll delete
4417 * this occurrence because we'll insert another one later.
4418 * We'll delete it too if the "indirect" option is set and we're in
4419 * a direct access.
4420 */
4421 if (s->be->ck_opts & PR_CK_PSV) {
4422 /* The "preserve" flag was set, we don't want to touch the
4423 * server's cookie.
4424 */
4425 }
4426 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4427 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4428 /* this cookie must be deleted */
4429 if (prev == hdr_beg && next == hdr_end) {
4430 /* whole header */
4431 http_remove_header(htx, &ctx);
4432 /* note: while both invalid now, <next> and <hdr_end>
4433 * are still equal, so the for() will stop as expected.
4434 */
4435 } else {
4436 /* just remove the value */
4437 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4438 next = prev;
4439 hdr_end += delta;
4440 }
4441 txn->flags &= ~TX_SCK_MASK;
4442 txn->flags |= TX_SCK_DELETED;
4443 /* and go on with next cookie */
4444 }
4445 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4446 /* replace bytes val_beg->val_end with the cookie name associated
4447 * with this server since we know it.
4448 */
4449 int sliding, delta;
4450
4451 ctx.value = ist2(val_beg, val_end - val_beg);
4452 ctx.lws_before = ctx.lws_after = 0;
4453 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4454 delta = srv->cklen - (val_end - val_beg);
4455 sliding = (ctx.value.ptr - val_beg);
4456 hdr_beg += sliding;
4457 val_beg += sliding;
4458 next += sliding + delta;
4459 hdr_end += sliding + delta;
4460
4461 txn->flags &= ~TX_SCK_MASK;
4462 txn->flags |= TX_SCK_REPLACED;
4463 }
4464 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4465 /* insert the cookie name associated with this server
4466 * before existing cookie, and insert a delimiter between them..
4467 */
4468 int sliding, delta;
4469 ctx.value = ist2(val_beg, 0);
4470 ctx.lws_before = ctx.lws_after = 0;
4471 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4472 delta = srv->cklen + 1;
4473 sliding = (ctx.value.ptr - val_beg);
4474 hdr_beg += sliding;
4475 val_beg += sliding;
4476 next += sliding + delta;
4477 hdr_end += sliding + delta;
4478
4479 val_beg[srv->cklen] = COOKIE_DELIM;
4480 txn->flags &= ~TX_SCK_MASK;
4481 txn->flags |= TX_SCK_REPLACED;
4482 }
4483 }
4484 /* that's done for this cookie, check the next one on the same
4485 * line when next != hdr_end (only if is_cookie2).
4486 */
4487 }
4488 }
4489}
4490
Christopher Faulet25a02f62018-10-24 12:00:25 +02004491/*
4492 * Parses the Cache-Control and Pragma request header fields to determine if
4493 * the request may be served from the cache and/or if it is cacheable. Updates
4494 * s->txn->flags.
4495 */
4496void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4497{
4498 struct http_txn *txn = s->txn;
4499 struct htx *htx;
4500 int32_t pos;
4501 int pragma_found, cc_found, i;
4502
4503 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4504 return; /* nothing more to do here */
4505
4506 htx = htx_from_buf(&req->buf);
4507 pragma_found = cc_found = 0;
4508 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4509 struct htx_blk *blk = htx_get_blk(htx, pos);
4510 enum htx_blk_type type = htx_get_blk_type(blk);
4511 struct ist n, v;
4512
4513 if (type == HTX_BLK_EOH)
4514 break;
4515 if (type != HTX_BLK_HDR)
4516 continue;
4517
4518 n = htx_get_blk_name(htx, blk);
4519 v = htx_get_blk_value(htx, blk);
4520
4521 if (isteqi(n, ist("Pragma"))) {
4522 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4523 pragma_found = 1;
4524 continue;
4525 }
4526 }
4527
4528 /* Don't use the cache and don't try to store if we found the
4529 * Authorization header */
4530 if (isteqi(n, ist("Authorization"))) {
4531 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4532 txn->flags |= TX_CACHE_IGNORE;
4533 continue;
4534 }
4535
4536 if (!isteqi(n, ist("Cache-control")))
4537 continue;
4538
4539 /* OK, right now we know we have a cache-control header */
4540 cc_found = 1;
4541 if (!v.len) /* no info */
4542 continue;
4543
4544 i = 0;
4545 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4546 !isspace((unsigned char)*(v.ptr+i)))
4547 i++;
4548
4549 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4550 * values after max-age, max-stale nor min-fresh, we simply don't
4551 * use the cache when they're specified.
4552 */
4553 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4554 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4555 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4556 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4557 txn->flags |= TX_CACHE_IGNORE;
4558 continue;
4559 }
4560
4561 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4562 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4563 continue;
4564 }
4565 }
4566
4567 /* RFC7234#5.4:
4568 * When the Cache-Control header field is also present and
4569 * understood in a request, Pragma is ignored.
4570 * When the Cache-Control header field is not present in a
4571 * request, caches MUST consider the no-cache request
4572 * pragma-directive as having the same effect as if
4573 * "Cache-Control: no-cache" were present.
4574 */
4575 if (!cc_found && pragma_found)
4576 txn->flags |= TX_CACHE_IGNORE;
4577}
4578
4579/*
4580 * Check if response is cacheable or not. Updates s->txn->flags.
4581 */
4582void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4583{
4584 struct http_txn *txn = s->txn;
4585 struct htx *htx;
4586 int32_t pos;
4587 int i;
4588
4589 if (txn->status < 200) {
4590 /* do not try to cache interim responses! */
4591 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4592 return;
4593 }
4594
4595 htx = htx_from_buf(&res->buf);
4596 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4597 struct htx_blk *blk = htx_get_blk(htx, pos);
4598 enum htx_blk_type type = htx_get_blk_type(blk);
4599 struct ist n, v;
4600
4601 if (type == HTX_BLK_EOH)
4602 break;
4603 if (type != HTX_BLK_HDR)
4604 continue;
4605
4606 n = htx_get_blk_name(htx, blk);
4607 v = htx_get_blk_value(htx, blk);
4608
4609 if (isteqi(n, ist("Pragma"))) {
4610 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4611 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4612 return;
4613 }
4614 }
4615
4616 if (!isteqi(n, ist("Cache-control")))
4617 continue;
4618
4619 /* OK, right now we know we have a cache-control header */
4620 if (!v.len) /* no info */
4621 continue;
4622
4623 i = 0;
4624 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4625 !isspace((unsigned char)*(v.ptr+i)))
4626 i++;
4627
4628 /* we have a complete value between v.ptr and (v.ptr+i) */
4629 if (i < v.len && *(v.ptr + i) == '=') {
4630 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4631 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4632 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4633 continue;
4634 }
4635
4636 /* we have something of the form no-cache="set-cookie" */
4637 if ((v.len >= 21) &&
4638 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4639 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4640 txn->flags &= ~TX_CACHE_COOK;
4641 continue;
4642 }
4643
4644 /* OK, so we know that either p2 points to the end of string or to a comma */
4645 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4646 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4647 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4648 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4649 return;
4650 }
4651
4652 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4653 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4654 continue;
4655 }
4656 }
4657}
4658
Christopher Faulet64159df2018-10-24 21:15:35 +02004659/* send a server's name with an outgoing request over an established connection.
4660 * Note: this function is designed to be called once the request has been
4661 * scheduled for being forwarded. This is the reason why the number of forwarded
4662 * bytes have to be adjusted.
4663 */
4664int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4665{
4666 struct htx *htx;
4667 struct http_hdr_ctx ctx;
4668 struct ist hdr;
4669 uint32_t data;
4670
4671 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
4672 htx = htx_from_buf(&s->req.buf);
4673 data = htx->data;
4674
4675 ctx.blk = NULL;
4676 while (http_find_header(htx, hdr, &ctx, 1))
4677 http_remove_header(htx, &ctx);
4678 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4679
4680 if (co_data(&s->req)) {
4681 if (data >= htx->data)
4682 c_rew(&s->req, data - htx->data);
4683 else
4684 c_adv(&s->req, htx->data - data);
4685 }
4686 return 0;
4687}
4688
Christopher Faulet377c5a52018-10-24 21:21:30 +02004689/*
4690 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4691 * for the current backend.
4692 *
4693 * It is assumed that the request is either a HEAD, GET, or POST and that the
4694 * uri_auth field is valid.
4695 *
4696 * Returns 1 if stats should be provided, otherwise 0.
4697 */
4698static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4699{
4700 struct uri_auth *uri_auth = backend->uri_auth;
4701 struct htx *htx;
4702 struct ist uri;
4703 union h1_sl sl;
4704
4705 if (!uri_auth)
4706 return 0;
4707
4708 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4709 return 0;
4710
4711 htx = htx_from_buf(&s->req.buf);
4712 sl = http_find_stline(htx);
4713 uri = sl.rq.u;
4714
4715 /* check URI size */
4716 if (uri_auth->uri_len > uri.len)
4717 return 0;
4718
4719 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4720 return 0;
4721
4722 return 1;
4723}
4724
4725/* This function prepares an applet to handle the stats. It can deal with the
4726 * "100-continue" expectation, check that admin rules are met for POST requests,
4727 * and program a response message if something was unexpected. It cannot fail
4728 * and always relies on the stats applet to complete the job. It does not touch
4729 * analysers nor counters, which are left to the caller. It does not touch
4730 * s->target which is supposed to already point to the stats applet. The caller
4731 * is expected to have already assigned an appctx to the stream.
4732 */
4733static int htx_handle_stats(struct stream *s, struct channel *req)
4734{
4735 struct stats_admin_rule *stats_admin_rule;
4736 struct stream_interface *si = &s->si[1];
4737 struct session *sess = s->sess;
4738 struct http_txn *txn = s->txn;
4739 struct http_msg *msg = &txn->req;
4740 struct uri_auth *uri_auth = s->be->uri_auth;
4741 const char *h, *lookup, *end;
4742 struct appctx *appctx;
4743 struct htx *htx;
4744 union h1_sl sl;
4745
4746 appctx = si_appctx(si);
4747 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4748 appctx->st1 = appctx->st2 = 0;
4749 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4750 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4751 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4752 appctx->ctx.stats.flags |= STAT_CHUNKED;
4753
4754 htx = htx_from_buf(&req->buf);
4755 sl = http_find_stline(htx);
4756 lookup = sl.rq.u.ptr + uri_auth->uri_len;
4757 end = sl.rq.u.ptr + sl.rq.u.len;
4758
4759 for (h = lookup; h <= end - 3; h++) {
4760 if (memcmp(h, ";up", 3) == 0) {
4761 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4762 break;
4763 }
4764 }
4765
4766 if (uri_auth->refresh) {
4767 for (h = lookup; h <= end - 10; h++) {
4768 if (memcmp(h, ";norefresh", 10) == 0) {
4769 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4770 break;
4771 }
4772 }
4773 }
4774
4775 for (h = lookup; h <= end - 4; h++) {
4776 if (memcmp(h, ";csv", 4) == 0) {
4777 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4778 break;
4779 }
4780 }
4781
4782 for (h = lookup; h <= end - 6; h++) {
4783 if (memcmp(h, ";typed", 6) == 0) {
4784 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4785 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4786 break;
4787 }
4788 }
4789
4790 for (h = lookup; h <= end - 8; h++) {
4791 if (memcmp(h, ";st=", 4) == 0) {
4792 int i;
4793 h += 4;
4794 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4795 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4796 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4797 appctx->ctx.stats.st_code = i;
4798 break;
4799 }
4800 }
4801 break;
4802 }
4803 }
4804
4805 appctx->ctx.stats.scope_str = 0;
4806 appctx->ctx.stats.scope_len = 0;
4807 for (h = lookup; h <= end - 8; h++) {
4808 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4809 int itx = 0;
4810 const char *h2;
4811 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4812 const char *err;
4813
4814 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4815 h2 = h;
4816 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4817 while (h <= end) {
4818 if (*h == ';' || *h == '&' || *h == ' ')
4819 break;
4820 itx++;
4821 h++;
4822 }
4823
4824 if (itx > STAT_SCOPE_TXT_MAXLEN)
4825 itx = STAT_SCOPE_TXT_MAXLEN;
4826 appctx->ctx.stats.scope_len = itx;
4827
4828 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4829 memcpy(scope_txt, h2, itx);
4830 scope_txt[itx] = '\0';
4831 err = invalid_char(scope_txt);
4832 if (err) {
4833 /* bad char in search text => clear scope */
4834 appctx->ctx.stats.scope_str = 0;
4835 appctx->ctx.stats.scope_len = 0;
4836 }
4837 break;
4838 }
4839 }
4840
4841 /* now check whether we have some admin rules for this request */
4842 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4843 int ret = 1;
4844
4845 if (stats_admin_rule->cond) {
4846 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4847 ret = acl_pass(ret);
4848 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4849 ret = !ret;
4850 }
4851
4852 if (ret) {
4853 /* no rule, or the rule matches */
4854 appctx->ctx.stats.flags |= STAT_ADMIN;
4855 break;
4856 }
4857 }
4858
4859 /* Was the status page requested with a POST ? */
4860 if (unlikely(txn->meth == HTTP_METH_POST)) {
4861 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4862 /* we'll need the request body, possibly after sending 100-continue */
4863 if (msg->msg_state < HTTP_MSG_DATA)
4864 req->analysers |= AN_REQ_HTTP_BODY;
4865 appctx->st0 = STAT_HTTP_POST;
4866 }
4867 else {
4868 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4869 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4870 appctx->st0 = STAT_HTTP_LAST;
4871 }
4872 }
4873 else {
4874 /* So it was another method (GET/HEAD) */
4875 appctx->st0 = STAT_HTTP_HEAD;
4876 }
4877
4878 s->task->nice = -32; /* small boost for HTTP statistics */
4879 return 1;
4880}
4881
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004882void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4883{
4884 struct http_txn *txn = s->txn;
4885 struct htx *htx;
4886 struct server *srv;
4887 union h1_sl sl;
4888 struct ist path;
4889
4890 /* 1: create the response header */
4891 if (!chunk_memcat(&trash, HTTP_302, strlen(HTTP_302)))
4892 return;
4893
4894 /* 2: add the server's prefix */
4895 /* special prefix "/" means don't change URL */
4896 srv = __objt_server(s->target);
4897 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4898 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4899 return;
4900 }
4901
4902 /* 3: add the request Path */
4903 htx = htx_from_buf(&s->req.buf);
4904 sl = http_find_stline(htx);
4905 path = http_get_path(sl.rq.u);
4906 if (!path.ptr)
4907 return;
4908
4909 if (!chunk_memcat(&trash, path.ptr, path.len))
4910 return;
4911
4912 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4913 if (!chunk_memcat(&trash, "\r\nProxy-Connection: close\r\n\r\n", 29))
4914 return;
4915 }
4916 else {
4917 if (!chunk_memcat(&trash, "\r\nConnection: close\r\n\r\n", 23))
4918 return;
4919 }
4920
4921 /* prepare to return without error. */
4922 si_shutr(si);
4923 si_shutw(si);
4924 si->err_type = SI_ET_NONE;
4925 si->state = SI_ST_CLO;
4926
4927 /* send the message */
4928 txn->status = 302;
4929 htx_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, &trash);
4930
4931 /* FIXME: we should increase a counter of redirects per server and per backend. */
4932 srv_inc_sess_ctr(srv);
4933 srv_set_sess_last(srv);
4934}
4935
Christopher Fauletf2824e62018-10-01 12:12:37 +02004936/* This function terminates the request because it was completly analyzed or
4937 * because an error was triggered during the body forwarding.
4938 */
4939static void htx_end_request(struct stream *s)
4940{
4941 struct channel *chn = &s->req;
4942 struct http_txn *txn = s->txn;
4943
4944 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4945 now_ms, __FUNCTION__, s,
4946 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4947 s->req.analysers, s->res.analysers);
4948
4949 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR)) {
4950 channel_abort(chn);
4951 channel_truncate(chn);
4952 goto end;
4953 }
4954
4955 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4956 return;
4957
4958 if (txn->req.msg_state == HTTP_MSG_DONE) {
4959 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4960 /* The server has not finished to respond, so we
4961 * don't want to move in order not to upset it.
4962 */
4963 return;
4964 }
4965
4966 /* No need to read anymore, the request was completely parsed.
4967 * We can shut the read side unless we want to abort_on_close,
4968 * or we have a POST request. The issue with POST requests is
4969 * that some browsers still send a CRLF after the request, and
4970 * this CRLF must be read so that it does not remain in the kernel
4971 * buffers, otherwise a close could cause an RST on some systems
4972 * (eg: Linux).
4973 */
4974 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
4975 txn->meth != HTTP_METH_POST)
4976 channel_dont_read(chn);
4977
4978 /* if the server closes the connection, we want to immediately react
4979 * and close the socket to save packets and syscalls.
4980 */
4981 s->si[1].flags |= SI_FL_NOHALF;
4982
4983 /* In any case we've finished parsing the request so we must
4984 * disable Nagle when sending data because 1) we're not going
4985 * to shut this side, and 2) the server is waiting for us to
4986 * send pending data.
4987 */
4988 chn->flags |= CF_NEVER_WAIT;
4989
4990 /* When we get here, it means that both the request and the
4991 * response have finished receiving. Depending on the connection
4992 * mode, we'll have to wait for the last bytes to leave in either
4993 * direction, and sometimes for a close to be effective.
4994 */
4995 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
4996 /* Tunnel mode will not have any analyser so it needs to
4997 * poll for reads.
4998 */
4999 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005000 if (b_data(&chn->buf))
5001 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005002 txn->req.msg_state = HTTP_MSG_TUNNEL;
5003 }
5004 else {
5005 /* we're not expecting any new data to come for this
5006 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005007 *
5008 * However, there is an exception if the response
5009 * length is undefined. In this case, we need to wait
5010 * the close from the server. The response will be
5011 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005012 */
5013 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5014 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005015 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005016
5017 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5018 channel_shutr_now(chn);
5019 channel_shutw_now(chn);
5020 }
5021 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005022 goto check_channel_flags;
5023 }
5024
5025 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5026 http_msg_closing:
5027 /* nothing else to forward, just waiting for the output buffer
5028 * to be empty and for the shutw_now to take effect.
5029 */
5030 if (channel_is_empty(chn)) {
5031 txn->req.msg_state = HTTP_MSG_CLOSED;
5032 goto http_msg_closed;
5033 }
5034 else if (chn->flags & CF_SHUTW) {
5035 txn->req.err_state = txn->req.msg_state;
5036 txn->req.msg_state = HTTP_MSG_ERROR;
5037 goto end;
5038 }
5039 return;
5040 }
5041
5042 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5043 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005044 /* if we don't know whether the server will close, we need to hard close */
5045 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5046 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005047 /* see above in MSG_DONE why we only do this in these states */
5048 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5049 channel_dont_read(chn);
5050 goto end;
5051 }
5052
5053 check_channel_flags:
5054 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5055 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5056 /* if we've just closed an output, let's switch */
5057 txn->req.msg_state = HTTP_MSG_CLOSING;
5058 goto http_msg_closing;
5059 }
5060
5061 end:
5062 chn->analysers &= AN_REQ_FLT_END;
5063 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5064 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5065 channel_auto_close(chn);
5066 channel_auto_read(chn);
5067}
5068
5069
5070/* This function terminates the response because it was completly analyzed or
5071 * because an error was triggered during the body forwarding.
5072 */
5073static void htx_end_response(struct stream *s)
5074{
5075 struct channel *chn = &s->res;
5076 struct http_txn *txn = s->txn;
5077
5078 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5079 now_ms, __FUNCTION__, s,
5080 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5081 s->req.analysers, s->res.analysers);
5082
5083 if (unlikely(txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005084 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005085 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005086 goto end;
5087 }
5088
5089 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5090 return;
5091
5092 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5093 /* In theory, we don't need to read anymore, but we must
5094 * still monitor the server connection for a possible close
5095 * while the request is being uploaded, so we don't disable
5096 * reading.
5097 */
5098 /* channel_dont_read(chn); */
5099
5100 if (txn->req.msg_state < HTTP_MSG_DONE) {
5101 /* The client seems to still be sending data, probably
5102 * because we got an error response during an upload.
5103 * We have the choice of either breaking the connection
5104 * or letting it pass through. Let's do the later.
5105 */
5106 return;
5107 }
5108
5109 /* When we get here, it means that both the request and the
5110 * response have finished receiving. Depending on the connection
5111 * mode, we'll have to wait for the last bytes to leave in either
5112 * direction, and sometimes for a close to be effective.
5113 */
5114 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5115 channel_auto_read(chn);
5116 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005117 if (b_data(&chn->buf))
5118 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005119 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5120 }
5121 else {
5122 /* we're not expecting any new data to come for this
5123 * transaction, so we can close it.
5124 */
5125 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5126 channel_shutr_now(chn);
5127 channel_shutw_now(chn);
5128 }
5129 }
5130 goto check_channel_flags;
5131 }
5132
5133 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5134 http_msg_closing:
5135 /* nothing else to forward, just waiting for the output buffer
5136 * to be empty and for the shutw_now to take effect.
5137 */
5138 if (channel_is_empty(chn)) {
5139 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5140 goto http_msg_closed;
5141 }
5142 else if (chn->flags & CF_SHUTW) {
5143 txn->rsp.err_state = txn->rsp.msg_state;
5144 txn->rsp.msg_state = HTTP_MSG_ERROR;
5145 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5146 if (objt_server(s->target))
5147 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5148 goto end;
5149 }
5150 return;
5151 }
5152
5153 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5154 http_msg_closed:
5155 /* drop any pending data */
5156 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005157 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005158 goto end;
5159 }
5160
5161 check_channel_flags:
5162 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5163 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5164 /* if we've just closed an output, let's switch */
5165 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5166 goto http_msg_closing;
5167 }
5168
5169 end:
5170 chn->analysers &= AN_RES_FLT_END;
5171 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5172 chn->analysers |= AN_RES_FLT_XFER_DATA;
5173 channel_auto_close(chn);
5174 channel_auto_read(chn);
5175}
5176
Christopher Faulet0f226952018-10-22 09:29:56 +02005177void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5178 int finst, const struct buffer *msg)
5179{
5180 channel_auto_read(si_oc(si));
5181 channel_abort(si_oc(si));
5182 channel_auto_close(si_oc(si));
5183 channel_erase(si_oc(si));
5184 channel_auto_close(si_ic(si));
5185 channel_auto_read(si_ic(si));
5186 if (msg) {
5187 struct channel *chn = si_ic(si);
5188 struct htx *htx;
5189
5190 htx = htx_from_buf(&chn->buf);
5191 htx_add_oob(htx, ist2(msg->area, msg->data));
5192 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5193 b_set_data(&chn->buf, b_size(&chn->buf));
5194 c_adv(chn, htx->data);
5195 chn->total += htx->data;
5196 }
5197 if (!(s->flags & SF_ERR_MASK))
5198 s->flags |= err;
5199 if (!(s->flags & SF_FINST_MASK))
5200 s->flags |= finst;
5201}
5202
5203void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5204{
5205 channel_auto_read(&s->req);
5206 channel_abort(&s->req);
5207 channel_auto_close(&s->req);
5208 channel_erase(&s->req);
5209 channel_truncate(&s->res);
5210
5211 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
5212 if (msg) {
5213 struct channel *chn = &s->res;
5214 struct htx *htx;
5215
5216 htx = htx_from_buf(&chn->buf);
5217 htx_add_oob(htx, ist2(msg->area, msg->data));
5218 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5219 b_set_data(&chn->buf, b_size(&chn->buf));
5220 c_adv(chn, htx->data);
5221 chn->total += htx->data;
5222 }
5223
5224 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5225 channel_auto_read(&s->res);
5226 channel_auto_close(&s->res);
5227 channel_shutr_now(&s->res);
5228}
5229
5230/*
5231 * Capture headers from message <htx> according to header list <cap_hdr>, and
5232 * fill the <cap> pointers appropriately.
5233 */
5234static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5235{
5236 struct cap_hdr *h;
5237 int32_t pos;
5238
5239 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5240 struct htx_blk *blk = htx_get_blk(htx, pos);
5241 enum htx_blk_type type = htx_get_blk_type(blk);
5242 struct ist n, v;
5243
5244 if (type == HTX_BLK_EOH)
5245 break;
5246 if (type != HTX_BLK_HDR)
5247 continue;
5248
5249 n = htx_get_blk_name(htx, blk);
5250
5251 for (h = cap_hdr; h; h = h->next) {
5252 if (h->namelen && (h->namelen == n.len) &&
5253 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5254 if (cap[h->index] == NULL)
5255 cap[h->index] =
5256 pool_alloc(h->pool);
5257
5258 if (cap[h->index] == NULL) {
5259 ha_alert("HTTP capture : out of memory.\n");
5260 break;
5261 }
5262
5263 v = htx_get_blk_value(htx, blk);
5264 if (v.len > h->len)
5265 v.len = h->len;
5266
5267 memcpy(cap[h->index], v.ptr, v.len);
5268 cap[h->index][v.len]=0;
5269 }
5270 }
5271 }
5272}
5273
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005274/* Delete a value in a header between delimiters <from> and <next>. The header
5275 * itself is delimited by <start> and <end> pointers. The number of characters
5276 * displaced is returned, and the pointer to the first delimiter is updated if
5277 * required. The function tries as much as possible to respect the following
5278 * principles :
5279 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5280 * in which case <next> is simply removed
5281 * - set exactly one space character after the new first delimiter, unless there
5282 * are not enough characters in the block being moved to do so.
5283 * - remove unneeded spaces before the previous delimiter and after the new
5284 * one.
5285 *
5286 * It is the caller's responsibility to ensure that :
5287 * - <from> points to a valid delimiter or <start> ;
5288 * - <next> points to a valid delimiter or <end> ;
5289 * - there are non-space chars before <from>.
5290 */
5291static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5292{
5293 char *prev = *from;
5294
5295 if (prev == start) {
5296 /* We're removing the first value. eat the semicolon, if <next>
5297 * is lower than <end> */
5298 if (next < end)
5299 next++;
5300
5301 while (next < end && HTTP_IS_SPHT(*next))
5302 next++;
5303 }
5304 else {
5305 /* Remove useless spaces before the old delimiter. */
5306 while (HTTP_IS_SPHT(*(prev-1)))
5307 prev--;
5308 *from = prev;
5309
5310 /* copy the delimiter and if possible a space if we're
5311 * not at the end of the line.
5312 */
5313 if (next < end) {
5314 *prev++ = *next++;
5315 if (prev + 1 < next)
5316 *prev++ = ' ';
5317 while (next < end && HTTP_IS_SPHT(*next))
5318 next++;
5319 }
5320 }
5321 memmove(prev, next, end - next);
5322 return (prev - next);
5323}
5324
Christopher Faulet0f226952018-10-22 09:29:56 +02005325
5326/* Formats the start line of the request (without CRLF) and puts it in <str> and
5327 * return the written lenght. The line can be truncated if it exceeds <len>.
5328 */
5329static size_t htx_fmt_req_line(const union h1_sl sl, char *str, size_t len)
5330{
5331 struct ist dst = ist2(str, 0);
5332
5333 if (istcat(&dst, sl.rq.m, len) == -1)
5334 goto end;
5335 if (dst.len + 1 > len)
5336 goto end;
5337 dst.ptr[dst.len++] = ' ';
5338
5339 if (istcat(&dst, sl.rq.u, len) == -1)
5340 goto end;
5341 if (dst.len + 1 > len)
5342 goto end;
5343 dst.ptr[dst.len++] = ' ';
5344
5345 istcat(&dst, sl.rq.v, len);
5346 end:
5347 return dst.len;
5348}
5349
Christopher Fauletf0523542018-10-24 11:06:58 +02005350/* Formats the start line of the response (without CRLF) and puts it in <str> and
5351 * return the written lenght. The line can be truncated if it exceeds <len>.
5352 */
5353static size_t htx_fmt_res_line(const union h1_sl sl, char *str, size_t len)
5354{
5355 struct ist dst = ist2(str, 0);
5356
5357 if (istcat(&dst, sl.st.v, len) == -1)
5358 goto end;
5359 if (dst.len + 1 > len)
5360 goto end;
5361 dst.ptr[dst.len++] = ' ';
5362
5363 if (istcat(&dst, sl.st.c, len) == -1)
5364 goto end;
5365 if (dst.len + 1 > len)
5366 goto end;
5367 dst.ptr[dst.len++] = ' ';
5368
5369 istcat(&dst, sl.st.r, len);
5370 end:
5371 return dst.len;
5372}
5373
5374
Christopher Faulet0f226952018-10-22 09:29:56 +02005375/*
5376 * Print a debug line with a start line.
5377 */
5378static void htx_debug_stline(const char *dir, struct stream *s, const union h1_sl sl)
5379{
5380 struct session *sess = strm_sess(s);
5381 int max;
5382
5383 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5384 dir,
5385 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5386 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5387
5388 max = sl.rq.m.len;
5389 UBOUND(max, trash.size - trash.data - 3);
5390 chunk_memcat(&trash, sl.rq.m.ptr, max);
5391 trash.area[trash.data++] = ' ';
5392
5393 max = sl.rq.u.len;
5394 UBOUND(max, trash.size - trash.data - 2);
5395 chunk_memcat(&trash, sl.rq.u.ptr, max);
5396 trash.area[trash.data++] = ' ';
5397
5398 max = sl.rq.v.len;
5399 UBOUND(max, trash.size - trash.data - 1);
5400 chunk_memcat(&trash, sl.rq.v.ptr, max);
5401 trash.area[trash.data++] = '\n';
5402
5403 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5404}
5405
5406/*
5407 * Print a debug line with a header.
5408 */
5409static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5410{
5411 struct session *sess = strm_sess(s);
5412 int max;
5413
5414 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5415 dir,
5416 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5417 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5418
5419 max = n.len;
5420 UBOUND(max, trash.size - trash.data - 3);
5421 chunk_memcat(&trash, n.ptr, max);
5422 trash.area[trash.data++] = ':';
5423 trash.area[trash.data++] = ' ';
5424
5425 max = v.len;
5426 UBOUND(max, trash.size - trash.data - 1);
5427 chunk_memcat(&trash, v.ptr, max);
5428 trash.area[trash.data++] = '\n';
5429
5430 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5431}
5432
5433
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005434__attribute__((constructor))
5435static void __htx_protocol_init(void)
5436{
5437}
5438
5439
5440/*
5441 * Local variables:
5442 * c-indent-level: 8
5443 * c-basic-offset: 8
5444 * End:
5445 */