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