blob: b8d412d77ba0ebd1ca62d9ab705841142577438a [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 Fauletff2759f2018-10-24 11:13:16 +0200592 // TODO: Disabled for now, waiting to be adapted for HTX implementation
593 goto deny;
594
Christopher Faulete0768eb2018-10-03 16:38:02 +0200595 /* process the stats request now */
596 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
597 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
598
599 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
600 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
601 if (!(s->flags & SF_FINST_MASK))
602 s->flags |= SF_FINST_R;
603
604 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
605 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
606 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
607 req->analysers |= AN_REQ_HTTP_XFER_BODY;
608 goto done;
609 }
610
611 /* check whether we have some ACLs set to redirect this request */
612 list_for_each_entry(rule, &px->redirect_rules, list) {
613 if (rule->cond) {
614 int ret;
615
616 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
617 ret = acl_pass(ret);
618 if (rule->cond->pol == ACL_COND_UNLESS)
619 ret = !ret;
620 if (!ret)
621 continue;
622 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200623 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200624 goto return_bad_req;
625 goto done;
626 }
627
628 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
629 * If this happens, then the data will not come immediately, so we must
630 * send all what we have without waiting. Note that due to the small gain
631 * in waiting for the body of the request, it's easier to simply put the
632 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
633 * itself once used.
634 */
635 req->flags |= CF_SEND_DONTWAIT;
636
637 done: /* done with this analyser, continue with next ones that the calling
638 * points will have set, if any.
639 */
640 req->analyse_exp = TICK_ETERNITY;
641 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
642 req->analysers &= ~an_bit;
643 return 1;
644
645 tarpit:
646 /* Allow cookie logging
647 */
648 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200649 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200650
651 /* When a connection is tarpitted, we use the tarpit timeout,
652 * which may be the same as the connect timeout if unspecified.
653 * If unset, then set it to zero because we really want it to
654 * eventually expire. We build the tarpit as an analyser.
655 */
656 channel_erase(&s->req);
657
658 /* wipe the request out so that we can drop the connection early
659 * if the client closes first.
660 */
661 channel_dont_connect(req);
662
663 txn->status = http_err_codes[deny_status];
664
665 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
666 req->analysers |= AN_REQ_HTTP_TARPIT;
667 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
668 if (!req->analyse_exp)
669 req->analyse_exp = tick_add(now_ms, 0);
670 stream_inc_http_err_ctr(s);
671 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
672 if (sess->fe != s->be)
673 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
674 if (sess->listener->counters)
675 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
676 goto done_without_exp;
677
678 deny: /* this request was blocked (denied) */
679
680 /* Allow cookie logging
681 */
682 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200683 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200684
685 txn->flags |= TX_CLDENY;
686 txn->status = http_err_codes[deny_status];
687 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200688 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200689 stream_inc_http_err_ctr(s);
690 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
691 if (sess->fe != s->be)
692 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
693 if (sess->listener->counters)
694 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
695 goto return_prx_cond;
696
697 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 txn->req.err_state = txn->req.msg_state;
699 txn->req.msg_state = HTTP_MSG_ERROR;
700 txn->status = 400;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200701 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702
703 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
704 if (sess->listener->counters)
705 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
706
707 return_prx_cond:
708 if (!(s->flags & SF_ERR_MASK))
709 s->flags |= SF_ERR_PRXCOND;
710 if (!(s->flags & SF_FINST_MASK))
711 s->flags |= SF_FINST_R;
712
713 req->analysers &= AN_REQ_FLT_END;
714 req->analyse_exp = TICK_ETERNITY;
715 return 0;
716
717 return_prx_yield:
718 channel_dont_connect(req);
719 return 0;
720}
721
722/* This function performs all the processing enabled for the current request.
723 * It returns 1 if the processing can continue on next analysers, or zero if it
724 * needs more data, encounters an error, or wants to immediately abort the
725 * request. It relies on buffers flags, and updates s->req.analysers.
726 */
727int htx_process_request(struct stream *s, struct channel *req, int an_bit)
728{
729 struct session *sess = s->sess;
730 struct http_txn *txn = s->txn;
731 struct http_msg *msg = &txn->req;
732 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
733
Christopher Faulet9768c262018-10-22 09:34:31 +0200734 // TODO: Disabled for now
735 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
736 req->analysers |= AN_REQ_HTTP_XFER_BODY;
737 req->analyse_exp = TICK_ETERNITY;
738 req->analysers &= ~an_bit;
739 return 1;
740
Christopher Faulete0768eb2018-10-03 16:38:02 +0200741 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
742 /* we need more data */
743 channel_dont_connect(req);
744 return 0;
745 }
746
747 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
748 now_ms, __FUNCTION__,
749 s,
750 req,
751 req->rex, req->wex,
752 req->flags,
753 ci_data(req),
754 req->analysers);
755
756 /*
757 * Right now, we know that we have processed the entire headers
758 * and that unwanted requests have been filtered out. We can do
759 * whatever we want with the remaining request. Also, now we
760 * may have separate values for ->fe, ->be.
761 */
762
763 /*
764 * If HTTP PROXY is set we simply get remote server address parsing
765 * incoming request. Note that this requires that a connection is
766 * allocated on the server side.
767 */
768 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
769 struct connection *conn;
770 char *path;
771
772 /* Note that for now we don't reuse existing proxy connections */
773 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
774 txn->req.err_state = txn->req.msg_state;
775 txn->req.msg_state = HTTP_MSG_ERROR;
776 txn->status = 500;
777 req->analysers &= AN_REQ_FLT_END;
778 http_reply_and_close(s, txn->status, http_error_message(s));
779
780 if (!(s->flags & SF_ERR_MASK))
781 s->flags |= SF_ERR_RESOURCE;
782 if (!(s->flags & SF_FINST_MASK))
783 s->flags |= SF_FINST_R;
784
785 return 0;
786 }
787
788 path = http_txn_get_path(txn);
789 if (url2sa(ci_head(req) + msg->sl.rq.u,
790 path ? path - (ci_head(req) + msg->sl.rq.u) : msg->sl.rq.u_l,
791 &conn->addr.to, NULL) == -1)
792 goto return_bad_req;
793
794 /* if the path was found, we have to remove everything between
795 * ci_head(req) + msg->sl.rq.u and path (excluded). If it was not
796 * found, we need to replace from ci_head(req) + msg->sl.rq.u for
797 * u_l characters by a single "/".
798 */
799 if (path) {
800 char *cur_ptr = ci_head(req);
801 char *cur_end = cur_ptr + txn->req.sl.rq.l;
802 int delta;
803
804 delta = b_rep_blk(&req->buf, cur_ptr + msg->sl.rq.u, path, NULL, 0);
805 http_msg_move_end(&txn->req, delta);
806 cur_end += delta;
807 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
808 goto return_bad_req;
809 }
810 else {
811 char *cur_ptr = ci_head(req);
812 char *cur_end = cur_ptr + txn->req.sl.rq.l;
813 int delta;
814
815 delta = b_rep_blk(&req->buf, cur_ptr + msg->sl.rq.u,
816 cur_ptr + msg->sl.rq.u + msg->sl.rq.u_l, "/", 1);
817 http_msg_move_end(&txn->req, delta);
818 cur_end += delta;
819 if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)
820 goto return_bad_req;
821 }
822 }
823
824 /*
825 * 7: Now we can work with the cookies.
826 * Note that doing so might move headers in the request, but
827 * the fields will stay coherent and the URI will not move.
828 * This should only be performed in the backend.
829 */
830 if (s->be->cookie_name || sess->fe->capture_name)
831 manage_client_side_cookies(s, req);
832
833 /* add unique-id if "header-unique-id" is specified */
834
835 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
836 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
837 goto return_bad_req;
838 s->unique_id[0] = '\0';
839 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
840 }
841
842 if (sess->fe->header_unique_id && s->unique_id) {
843 if (chunk_printf(&trash, "%s: %s", sess->fe->header_unique_id, s->unique_id) < 0)
844 goto return_bad_req;
845 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, trash.data) < 0))
846 goto return_bad_req;
847 }
848
849 /*
850 * 9: add X-Forwarded-For if either the frontend or the backend
851 * asks for it.
852 */
853 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
854 struct hdr_ctx ctx = { .idx = 0 };
855 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
856 http_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
857 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len,
858 ci_head(req), &txn->hdr_idx, &ctx)) {
859 /* The header is set to be added only if none is present
860 * and we found it, so don't do anything.
861 */
862 }
863 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
864 /* Add an X-Forwarded-For header unless the source IP is
865 * in the 'except' network range.
866 */
867 if ((!sess->fe->except_mask.s_addr ||
868 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
869 != sess->fe->except_net.s_addr) &&
870 (!s->be->except_mask.s_addr ||
871 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
872 != s->be->except_net.s_addr)) {
873 int len;
874 unsigned char *pn;
875 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
876
877 /* Note: we rely on the backend to get the header name to be used for
878 * x-forwarded-for, because the header is really meant for the backends.
879 * However, if the backend did not specify any option, we have to rely
880 * on the frontend's header name.
881 */
882 if (s->be->fwdfor_hdr_len) {
883 len = s->be->fwdfor_hdr_len;
884 memcpy(trash.area,
885 s->be->fwdfor_hdr_name, len);
886 } else {
887 len = sess->fe->fwdfor_hdr_len;
888 memcpy(trash.area,
889 sess->fe->fwdfor_hdr_name, len);
890 }
891 len += snprintf(trash.area + len,
892 trash.size - len,
893 ": %d.%d.%d.%d", pn[0], pn[1],
894 pn[2], pn[3]);
895
896 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
897 goto return_bad_req;
898 }
899 }
900 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
901 /* FIXME: for the sake of completeness, we should also support
902 * 'except' here, although it is mostly useless in this case.
903 */
904 int len;
905 char pn[INET6_ADDRSTRLEN];
906 inet_ntop(AF_INET6,
907 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
908 pn, sizeof(pn));
909
910 /* Note: we rely on the backend to get the header name to be used for
911 * x-forwarded-for, because the header is really meant for the backends.
912 * However, if the backend did not specify any option, we have to rely
913 * on the frontend's header name.
914 */
915 if (s->be->fwdfor_hdr_len) {
916 len = s->be->fwdfor_hdr_len;
917 memcpy(trash.area, s->be->fwdfor_hdr_name,
918 len);
919 } else {
920 len = sess->fe->fwdfor_hdr_len;
921 memcpy(trash.area, sess->fe->fwdfor_hdr_name,
922 len);
923 }
924 len += snprintf(trash.area + len, trash.size - len,
925 ": %s", pn);
926
927 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
928 goto return_bad_req;
929 }
930 }
931
932 /*
933 * 10: add X-Original-To if either the frontend or the backend
934 * asks for it.
935 */
936 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
937
938 /* FIXME: don't know if IPv6 can handle that case too. */
939 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
940 /* Add an X-Original-To header unless the destination IP is
941 * in the 'except' network range.
942 */
943 conn_get_to_addr(cli_conn);
944
945 if (cli_conn->addr.to.ss_family == AF_INET &&
946 ((!sess->fe->except_mask_to.s_addr ||
947 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
948 != sess->fe->except_to.s_addr) &&
949 (!s->be->except_mask_to.s_addr ||
950 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
951 != s->be->except_to.s_addr))) {
952 int len;
953 unsigned char *pn;
954 pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
955
956 /* Note: we rely on the backend to get the header name to be used for
957 * x-original-to, because the header is really meant for the backends.
958 * However, if the backend did not specify any option, we have to rely
959 * on the frontend's header name.
960 */
961 if (s->be->orgto_hdr_len) {
962 len = s->be->orgto_hdr_len;
963 memcpy(trash.area,
964 s->be->orgto_hdr_name, len);
965 } else {
966 len = sess->fe->orgto_hdr_len;
967 memcpy(trash.area,
968 sess->fe->orgto_hdr_name, len);
969 }
970 len += snprintf(trash.area + len,
971 trash.size - len,
972 ": %d.%d.%d.%d", pn[0], pn[1],
973 pn[2], pn[3]);
974
975 if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.area, len) < 0))
976 goto return_bad_req;
977 }
978 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979 }
980
Christopher Faulete0768eb2018-10-03 16:38:02 +0200981 /* If we have no server assigned yet and we're balancing on url_param
982 * with a POST request, we may be interested in checking the body for
983 * that parameter. This will be done in another analyser.
984 */
985 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
986 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL &&
987 (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {
988 channel_dont_connect(req);
989 req->analysers |= AN_REQ_HTTP_BODY;
990 }
991
992 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
993 req->analysers |= AN_REQ_HTTP_XFER_BODY;
994#ifdef TCP_QUICKACK
995 /* We expect some data from the client. Unless we know for sure
996 * we already have a full request, we have to re-enable quick-ack
997 * in case we previously disabled it, otherwise we might cause
998 * the client to delay further data.
999 */
1000 if ((sess->listener->options & LI_O_NOQUICKACK) &&
1001 cli_conn && conn_ctrl_ready(cli_conn) &&
1002 ((msg->flags & HTTP_MSGF_TE_CHNK) ||
1003 (msg->body_len > ci_data(req) - txn->req.eoh - 2)))
1004 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
1005#endif
1006
1007 /*************************************************************
1008 * OK, that's finished for the headers. We have done what we *
1009 * could. Let's switch to the DATA state. *
1010 ************************************************************/
1011 req->analyse_exp = TICK_ETERNITY;
1012 req->analysers &= ~an_bit;
1013
1014 s->logs.tv_request = now;
1015 /* OK let's go on with the BODY now */
1016 return 1;
1017
1018 return_bad_req: /* let's centralize all bad requests */
1019 if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {
1020 /* we detected a parsing error. We want to archive this request
1021 * in the dedicated proxy area for later troubleshooting.
1022 */
1023 http_capture_bad_message(sess->fe, s, msg, msg->err_state, sess->fe);
1024 }
1025
1026 txn->req.err_state = txn->req.msg_state;
1027 txn->req.msg_state = HTTP_MSG_ERROR;
1028 txn->status = 400;
1029 req->analysers &= AN_REQ_FLT_END;
1030 http_reply_and_close(s, txn->status, http_error_message(s));
1031
1032 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1033 if (sess->listener->counters)
1034 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1035
1036 if (!(s->flags & SF_ERR_MASK))
1037 s->flags |= SF_ERR_PRXCOND;
1038 if (!(s->flags & SF_FINST_MASK))
1039 s->flags |= SF_FINST_R;
1040 return 0;
1041}
1042
1043/* This function is an analyser which processes the HTTP tarpit. It always
1044 * returns zero, at the beginning because it prevents any other processing
1045 * from occurring, and at the end because it terminates the request.
1046 */
1047int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1048{
1049 struct http_txn *txn = s->txn;
1050
Christopher Faulet9768c262018-10-22 09:34:31 +02001051 // TODO: Disabled for now
1052 req->analyse_exp = TICK_ETERNITY;
1053 req->analysers &= ~an_bit;
1054 return 1;
1055
Christopher Faulete0768eb2018-10-03 16:38:02 +02001056 /* This connection is being tarpitted. The CLIENT side has
1057 * already set the connect expiration date to the right
1058 * timeout. We just have to check that the client is still
1059 * there and that the timeout has not expired.
1060 */
1061 channel_dont_connect(req);
1062 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1063 !tick_is_expired(req->analyse_exp, now_ms))
1064 return 0;
1065
1066 /* We will set the queue timer to the time spent, just for
1067 * logging purposes. We fake a 500 server error, so that the
1068 * attacker will not suspect his connection has been tarpitted.
1069 * It will not cause trouble to the logs because we can exclude
1070 * the tarpitted connections by filtering on the 'PT' status flags.
1071 */
1072 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1073
1074 if (!(req->flags & CF_READ_ERROR))
1075 http_reply_and_close(s, txn->status, http_error_message(s));
1076
1077 req->analysers &= AN_REQ_FLT_END;
1078 req->analyse_exp = TICK_ETERNITY;
1079
1080 if (!(s->flags & SF_ERR_MASK))
1081 s->flags |= SF_ERR_PRXCOND;
1082 if (!(s->flags & SF_FINST_MASK))
1083 s->flags |= SF_FINST_T;
1084 return 0;
1085}
1086
1087/* This function is an analyser which waits for the HTTP request body. It waits
1088 * for either the buffer to be full, or the full advertised contents to have
1089 * reached the buffer. It must only be called after the standard HTTP request
1090 * processing has occurred, because it expects the request to be parsed and will
1091 * look for the Expect header. It may send a 100-Continue interim response. It
1092 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1093 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1094 * needs to read more data, or 1 once it has completed its analysis.
1095 */
1096int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1097{
1098 struct session *sess = s->sess;
1099 struct http_txn *txn = s->txn;
1100 struct http_msg *msg = &s->txn->req;
1101
Christopher Faulet9768c262018-10-22 09:34:31 +02001102 // TODO: Disabled for now
1103 req->analyse_exp = TICK_ETERNITY;
1104 req->analysers &= ~an_bit;
1105 return 1;
1106
Christopher Faulete0768eb2018-10-03 16:38:02 +02001107 /* We have to parse the HTTP request body to find any required data.
1108 * "balance url_param check_post" should have been the only way to get
1109 * into this. We were brought here after HTTP header analysis, so all
1110 * related structures are ready.
1111 */
1112
1113 if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) {
1114 /* This is the first call */
1115 if (msg->msg_state < HTTP_MSG_BODY)
1116 goto missing_data;
1117
1118 if (msg->msg_state < HTTP_MSG_100_SENT) {
1119 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1120 * send an HTTP/1.1 100 Continue intermediate response.
1121 */
1122 if (msg->flags & HTTP_MSGF_VER_11) {
1123 struct hdr_ctx ctx;
1124 ctx.idx = 0;
1125 /* Expect is allowed in 1.1, look for it */
1126 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &ctx) &&
1127 unlikely(ctx.vlen == 12 && strncasecmp(ctx.line+ctx.val, "100-continue", 12) == 0)) {
1128 co_inject(&s->res, HTTP_100.ptr, HTTP_100.len);
1129 http_remove_header2(&txn->req, &txn->hdr_idx, &ctx);
1130 }
1131 }
1132 msg->msg_state = HTTP_MSG_100_SENT;
1133 }
1134
1135 /* we have msg->sov which points to the first byte of message body.
1136 * ci_head(req) still points to the beginning of the message. We
1137 * must save the body in msg->next because it survives buffer
1138 * re-alignments.
1139 */
1140 msg->next = msg->sov;
1141
1142 if (msg->flags & HTTP_MSGF_TE_CHNK)
1143 msg->msg_state = HTTP_MSG_CHUNK_SIZE;
1144 else
1145 msg->msg_state = HTTP_MSG_DATA;
1146 }
1147
1148 if (!(msg->flags & HTTP_MSGF_TE_CHNK)) {
1149 /* We're in content-length mode, we just have to wait for enough data. */
1150 if (http_body_bytes(msg) < msg->body_len)
1151 goto missing_data;
1152
1153 /* OK we have everything we need now */
1154 goto http_end;
1155 }
1156
1157 /* OK here we're parsing a chunked-encoded message */
1158
1159 if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) {
1160 /* read the chunk size and assign it to ->chunk_len, then
1161 * set ->sov and ->next to point to the body and switch to DATA or
1162 * TRAILERS state.
1163 */
1164 unsigned int chunk;
1165 int ret = h1_parse_chunk_size(&req->buf, co_data(req) + msg->next, c_data(req), &chunk);
1166
1167 if (!ret)
1168 goto missing_data;
1169 else if (ret < 0) {
1170 msg->err_pos = ci_data(req) + ret;
1171 if (msg->err_pos < 0)
1172 msg->err_pos += req->buf.size;
1173 stream_inc_http_err_ctr(s);
1174 goto return_bad_req;
1175 }
1176
1177 msg->chunk_len = chunk;
1178 msg->body_len += chunk;
1179
1180 msg->sol = ret;
1181 msg->next += ret;
1182 msg->msg_state = msg->chunk_len ? HTTP_MSG_DATA : HTTP_MSG_TRAILERS;
1183 }
1184
1185 /* Now we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state.
1186 * We have the first data byte is in msg->sov + msg->sol. We're waiting
1187 * for at least a whole chunk or the whole content length bytes after
1188 * msg->sov + msg->sol.
1189 */
1190 if (msg->msg_state == HTTP_MSG_TRAILERS)
1191 goto http_end;
1192
1193 if (http_body_bytes(msg) >= msg->body_len) /* we have enough bytes now */
1194 goto http_end;
1195
1196 missing_data:
1197 /* we get here if we need to wait for more data. If the buffer is full,
1198 * we have the maximum we can expect.
1199 */
1200 if (channel_full(req, global.tune.maxrewrite))
1201 goto http_end;
1202
1203 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1204 txn->status = 408;
1205 http_reply_and_close(s, txn->status, http_error_message(s));
1206
1207 if (!(s->flags & SF_ERR_MASK))
1208 s->flags |= SF_ERR_CLITO;
1209 if (!(s->flags & SF_FINST_MASK))
1210 s->flags |= SF_FINST_D;
1211 goto return_err_msg;
1212 }
1213
1214 /* we get here if we need to wait for more data */
1215 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1216 /* Not enough data. We'll re-use the http-request
1217 * timeout here. Ideally, we should set the timeout
1218 * relative to the accept() date. We just set the
1219 * request timeout once at the beginning of the
1220 * request.
1221 */
1222 channel_dont_connect(req);
1223 if (!tick_isset(req->analyse_exp))
1224 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1225 return 0;
1226 }
1227
1228 http_end:
1229 /* The situation will not evolve, so let's give up on the analysis. */
1230 s->logs.tv_request = now; /* update the request timer to reflect full request */
1231 req->analysers &= ~an_bit;
1232 req->analyse_exp = TICK_ETERNITY;
1233 return 1;
1234
1235 return_bad_req: /* let's centralize all bad requests */
1236 txn->req.err_state = txn->req.msg_state;
1237 txn->req.msg_state = HTTP_MSG_ERROR;
1238 txn->status = 400;
1239 http_reply_and_close(s, txn->status, http_error_message(s));
1240
1241 if (!(s->flags & SF_ERR_MASK))
1242 s->flags |= SF_ERR_PRXCOND;
1243 if (!(s->flags & SF_FINST_MASK))
1244 s->flags |= SF_FINST_R;
1245
1246 return_err_msg:
1247 req->analysers &= AN_REQ_FLT_END;
1248 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1249 if (sess->listener->counters)
1250 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1251 return 0;
1252}
1253
1254/* This function is an analyser which forwards request body (including chunk
1255 * sizes if any). It is called as soon as we must forward, even if we forward
1256 * zero byte. The only situation where it must not be called is when we're in
1257 * tunnel mode and we want to forward till the close. It's used both to forward
1258 * remaining data and to resync after end of body. It expects the msg_state to
1259 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1260 * read more data, or 1 once we can go on with next request or end the stream.
1261 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1262 * bytes of pending data + the headers if not already done.
1263 */
1264int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1265{
1266 struct session *sess = s->sess;
1267 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001268 struct http_msg *msg = &txn->req;
1269 struct htx *htx;
1270 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271
1272 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1273 now_ms, __FUNCTION__,
1274 s,
1275 req,
1276 req->rex, req->wex,
1277 req->flags,
1278 ci_data(req),
1279 req->analysers);
1280
Christopher Faulet9768c262018-10-22 09:34:31 +02001281 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282
1283 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1284 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1285 /* Output closed while we were sending data. We must abort and
1286 * wake the other side up.
1287 */
1288 msg->err_state = msg->msg_state;
1289 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001290 htx_end_request(s);
1291 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001292 return 1;
1293 }
1294
1295 /* Note that we don't have to send 100-continue back because we don't
1296 * need the data to complete our job, and it's up to the server to
1297 * decide whether to return 100, 417 or anything else in return of
1298 * an "Expect: 100-continue" header.
1299 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001300 if (msg->msg_state == HTTP_MSG_BODY)
1301 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001302
1303 /* Some post-connect processing might want us to refrain from starting to
1304 * forward data. Currently, the only reason for this is "balance url_param"
1305 * whichs need to parse/process the request after we've enabled forwarding.
1306 */
1307 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1308 if (!(s->res.flags & CF_READ_ATTACHED)) {
1309 channel_auto_connect(req);
1310 req->flags |= CF_WAKE_CONNECT;
1311 channel_dont_close(req); /* don't fail on early shutr */
1312 goto waiting;
1313 }
1314 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1315 }
1316
1317 /* in most states, we should abort in case of early close */
1318 channel_auto_close(req);
1319
1320 if (req->to_forward) {
1321 /* We can't process the buffer's contents yet */
1322 req->flags |= CF_WAKE_WRITE;
1323 goto missing_data_or_waiting;
1324 }
1325
Christopher Faulet9768c262018-10-22 09:34:31 +02001326 if (msg->msg_state >= HTTP_MSG_DONE)
1327 goto done;
1328
1329 /* Forward all input data. We get it by removing all outgoing data not
1330 * forwarded yet from HTX data size.
1331 */
1332 c_adv(req, htx->data - co_data(req));
1333
1334 /* To let the function channel_forward work as expected we must update
1335 * the channel's buffer to pretend there is no more input data. The
1336 * right length is then restored. We must do that, because when an HTX
1337 * message is stored into a buffer, it appears as full.
1338 */
1339 b_set_data(&req->buf, co_data(req));
1340 if (htx->extra != ULLONG_MAX)
1341 htx->extra -= channel_forward(req, htx->extra);
1342 b_set_data(&req->buf, b_size(&req->buf));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001343
Christopher Faulet9768c262018-10-22 09:34:31 +02001344 /* Check if the end-of-message is reached and if so, switch the message
1345 * in HTTP_MSG_DONE state.
1346 */
1347 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1348 goto missing_data_or_waiting;
1349
1350 msg->msg_state = HTTP_MSG_DONE;
1351
1352 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001353 /* other states, DONE...TUNNEL */
1354 /* we don't want to forward closes on DONE except in tunnel mode. */
1355 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1356 channel_dont_close(req);
1357
Christopher Fauletf2824e62018-10-01 12:12:37 +02001358 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001359 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001360 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001361 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1362 if (req->flags & CF_SHUTW) {
1363 /* request errors are most likely due to the
1364 * server aborting the transfer. */
1365 goto aborted_xfer;
1366 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 goto return_bad_req;
1368 }
1369 return 1;
1370 }
1371
1372 /* If "option abortonclose" is set on the backend, we want to monitor
1373 * the client's connection and forward any shutdown notification to the
1374 * server, which will decide whether to close or to go on processing the
1375 * request. We only do that in tunnel mode, and not in other modes since
1376 * it can be abused to exhaust source ports. */
1377 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1378 channel_auto_read(req);
1379 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1380 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1381 s->si[1].flags |= SI_FL_NOLINGER;
1382 channel_auto_close(req);
1383 }
1384 else if (s->txn->meth == HTTP_METH_POST) {
1385 /* POST requests may require to read extra CRLF sent by broken
1386 * browsers and which could cause an RST to be sent upon close
1387 * on some systems (eg: Linux). */
1388 channel_auto_read(req);
1389 }
1390 return 0;
1391
1392 missing_data_or_waiting:
1393 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001394 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 if (!(s->flags & SF_ERR_MASK))
1396 s->flags |= SF_ERR_CLICL;
1397 if (!(s->flags & SF_FINST_MASK)) {
1398 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1399 s->flags |= SF_FINST_H;
1400 else
1401 s->flags |= SF_FINST_D;
1402 }
1403
1404 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1405 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1406 if (objt_server(s->target))
1407 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1408
1409 goto return_bad_req_stats_ok;
1410 }
1411
1412 waiting:
1413 /* waiting for the last bits to leave the buffer */
1414 if (req->flags & CF_SHUTW)
1415 goto aborted_xfer;
1416
Christopher Faulet9768c262018-10-22 09:34:31 +02001417
Christopher Faulete0768eb2018-10-03 16:38:02 +02001418 /* When TE: chunked is used, we need to get there again to parse remaining
1419 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1420 * And when content-length is used, we never want to let the possible
1421 * shutdown be forwarded to the other side, as the state machine will
1422 * take care of it once the client responds. It's also important to
1423 * prevent TIME_WAITs from accumulating on the backend side, and for
1424 * HTTP/2 where the last frame comes with a shutdown.
1425 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001426 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001427 channel_dont_close(req);
1428
Christopher Faulet9768c262018-10-22 09:34:31 +02001429#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
1430 // about if
1431
Christopher Faulete0768eb2018-10-03 16:38:02 +02001432 /* We know that more data are expected, but we couldn't send more that
1433 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1434 * system knows it must not set a PUSH on this first part. Interactive
1435 * modes are already handled by the stream sock layer. We must not do
1436 * this in content-length mode because it could present the MSG_MORE
1437 * flag with the last block of forwarded data, which would cause an
1438 * additional delay to be observed by the receiver.
1439 */
1440 if (msg->flags & HTTP_MSGF_TE_CHNK)
1441 req->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02001442#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02001443
1444 return 0;
1445
1446 return_bad_req: /* let's centralize all bad requests */
1447 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1448 if (sess->listener->counters)
1449 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1450
1451 return_bad_req_stats_ok:
1452 txn->req.err_state = txn->req.msg_state;
1453 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001454 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001455 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001456 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 } else {
1458 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001459 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 }
1461 req->analysers &= AN_REQ_FLT_END;
1462 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1463
1464 if (!(s->flags & SF_ERR_MASK))
1465 s->flags |= SF_ERR_PRXCOND;
1466 if (!(s->flags & SF_FINST_MASK)) {
1467 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1468 s->flags |= SF_FINST_H;
1469 else
1470 s->flags |= SF_FINST_D;
1471 }
1472 return 0;
1473
1474 aborted_xfer:
1475 txn->req.err_state = txn->req.msg_state;
1476 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001477 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001478 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001479 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001480 } else {
1481 txn->status = 502;
Christopher Faulet9768c262018-10-22 09:34:31 +02001482 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 }
1484 req->analysers &= AN_REQ_FLT_END;
1485 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1486
1487 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1488 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1489 if (objt_server(s->target))
1490 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1491
1492 if (!(s->flags & SF_ERR_MASK))
1493 s->flags |= SF_ERR_SRVCL;
1494 if (!(s->flags & SF_FINST_MASK)) {
1495 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1496 s->flags |= SF_FINST_H;
1497 else
1498 s->flags |= SF_FINST_D;
1499 }
1500 return 0;
1501}
1502
1503/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1504 * processing can continue on next analysers, or zero if it either needs more
1505 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1506 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1507 * when it has nothing left to do, and may remove any analyser when it wants to
1508 * abort.
1509 */
1510int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1511{
Christopher Faulet9768c262018-10-22 09:34:31 +02001512 /*
1513 * We will analyze a complete HTTP response to check the its syntax.
1514 *
1515 * Once the start line and all headers are received, we may perform a
1516 * capture of the error (if any), and we will set a few fields. We also
1517 * logging and finally headers capture.
1518 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 struct session *sess = s->sess;
1520 struct http_txn *txn = s->txn;
1521 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001522 struct htx *htx;
1523 union h1_sl sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524 int n;
1525
1526 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1527 now_ms, __FUNCTION__,
1528 s,
1529 rep,
1530 rep->rex, rep->wex,
1531 rep->flags,
1532 ci_data(rep),
1533 rep->analysers);
1534
Christopher Faulet9768c262018-10-22 09:34:31 +02001535 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536
1537 /*
1538 * Now we quickly check if we have found a full valid response.
1539 * If not so, we check the FD and buffer states before leaving.
1540 * A full response is indicated by the fact that we have seen
1541 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1542 * responses are checked first.
1543 *
1544 * Depending on whether the client is still there or not, we
1545 * may send an error response back or not. Note that normally
1546 * we should only check for HTTP status there, and check I/O
1547 * errors somewhere else.
1548 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001549 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
1550 /* 1: have we encountered a read error ? */
1551 if (rep->flags & CF_READ_ERROR) {
1552 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553 goto abort_keep_alive;
1554
1555 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1556 if (objt_server(s->target)) {
1557 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1558 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1559 }
1560
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561 rep->analysers &= AN_RES_FLT_END;
1562 txn->status = 502;
1563
1564 /* Check to see if the server refused the early data.
1565 * If so, just send a 425
1566 */
1567 if (objt_cs(s->si[1].end)) {
1568 struct connection *conn = objt_cs(s->si[1].end)->conn;
1569
1570 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1571 txn->status = 425;
1572 }
1573
1574 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001575 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001576
1577 if (!(s->flags & SF_ERR_MASK))
1578 s->flags |= SF_ERR_SRVCL;
1579 if (!(s->flags & SF_FINST_MASK))
1580 s->flags |= SF_FINST_H;
1581 return 0;
1582 }
1583
Christopher Faulet9768c262018-10-22 09:34:31 +02001584 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001586 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1587 if (objt_server(s->target)) {
1588 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1589 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1590 }
1591
Christopher Faulete0768eb2018-10-03 16:38:02 +02001592 rep->analysers &= AN_RES_FLT_END;
1593 txn->status = 504;
1594 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001595 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001596
1597 if (!(s->flags & SF_ERR_MASK))
1598 s->flags |= SF_ERR_SRVTO;
1599 if (!(s->flags & SF_FINST_MASK))
1600 s->flags |= SF_FINST_H;
1601 return 0;
1602 }
1603
Christopher Faulet9768c262018-10-22 09:34:31 +02001604 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001605 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1606 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1607 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1608 if (objt_server(s->target))
1609 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1610
1611 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001612 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001613 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001614
1615 if (!(s->flags & SF_ERR_MASK))
1616 s->flags |= SF_ERR_CLICL;
1617 if (!(s->flags & SF_FINST_MASK))
1618 s->flags |= SF_FINST_H;
1619
1620 /* process_stream() will take care of the error */
1621 return 0;
1622 }
1623
Christopher Faulet9768c262018-10-22 09:34:31 +02001624 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001626 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001627 goto abort_keep_alive;
1628
1629 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1630 if (objt_server(s->target)) {
1631 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1632 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1633 }
1634
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 rep->analysers &= AN_RES_FLT_END;
1636 txn->status = 502;
1637 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001638 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639
1640 if (!(s->flags & SF_ERR_MASK))
1641 s->flags |= SF_ERR_SRVCL;
1642 if (!(s->flags & SF_FINST_MASK))
1643 s->flags |= SF_FINST_H;
1644 return 0;
1645 }
1646
Christopher Faulet9768c262018-10-22 09:34:31 +02001647 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001649 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001650 goto abort_keep_alive;
1651
1652 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1653 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001654
1655 if (!(s->flags & SF_ERR_MASK))
1656 s->flags |= SF_ERR_CLICL;
1657 if (!(s->flags & SF_FINST_MASK))
1658 s->flags |= SF_FINST_H;
1659
1660 /* process_stream() will take care of the error */
1661 return 0;
1662 }
1663
1664 channel_dont_close(rep);
1665 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1666 return 0;
1667 }
1668
1669 /* More interesting part now : we know that we have a complete
1670 * response which at least looks like HTTP. We have an indicator
1671 * of each header's length, so we can parse them quickly.
1672 */
1673
Christopher Faulet9768c262018-10-22 09:34:31 +02001674 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675
Christopher Faulet9768c262018-10-22 09:34:31 +02001676 /* 0: we might have to print this header in debug mode */
1677 if (unlikely((global.mode & MODE_DEBUG) &&
1678 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1679 int32_t pos;
1680
1681 htx_debug_stline("srvrep", s, http_find_stline(htx));
1682
1683 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1684 struct htx_blk *blk = htx_get_blk(htx, pos);
1685 enum htx_blk_type type = htx_get_blk_type(blk);
1686
1687 if (type == HTX_BLK_EOH)
1688 break;
1689 if (type != HTX_BLK_HDR)
1690 continue;
1691
1692 htx_debug_hdr("srvhdr", s,
1693 htx_get_blk_name(htx, blk),
1694 htx_get_blk_value(htx, blk));
1695 }
1696 }
1697
1698 /* 1: get the status code */
1699 sl = http_find_stline(htx);
1700 txn->status = sl.st.status;
1701 if (htx->extra != ULLONG_MAX)
1702 msg->flags |= HTTP_MSGF_XFER_LEN;
1703
1704 /* ... and check if the request is HTTP/1.1 or above */
1705 if ((sl.st.v.len == 8) &&
1706 ((*(sl.st.v.ptr + 5) > '1') ||
1707 ((*(sl.st.v.ptr + 5) == '1') && (*(sl.st.v.ptr + 7) >= '1'))))
1708 msg->flags |= HTTP_MSGF_VER_11;
1709
1710 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001711 if (n < 1 || n > 5)
1712 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001713
Christopher Faulete0768eb2018-10-03 16:38:02 +02001714 /* when the client triggers a 4xx from the server, it's most often due
1715 * to a missing object or permission. These events should be tracked
1716 * because if they happen often, it may indicate a brute force or a
1717 * vulnerability scan.
1718 */
1719 if (n == 4)
1720 stream_inc_http_err_ctr(s);
1721
1722 if (objt_server(s->target))
1723 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
1724
Christopher Faulete0768eb2018-10-03 16:38:02 +02001725 /* Adjust server's health based on status code. Note: status codes 501
1726 * and 505 are triggered on demand by client request, so we must not
1727 * count them as server failures.
1728 */
1729 if (objt_server(s->target)) {
1730 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
1731 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
1732 else
1733 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
1734 }
1735
1736 /*
1737 * We may be facing a 100-continue response, or any other informational
1738 * 1xx response which is non-final, in which case this is not the right
1739 * response, and we're waiting for the next one. Let's allow this response
1740 * to go to the client and wait for the next one. There's an exception for
1741 * 101 which is used later in the code to switch protocols.
1742 */
1743 if (txn->status < 200 &&
1744 (txn->status == 100 || txn->status >= 102)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001745 //FLT_STRM_CB(s, flt_htx_reset(s, http, htx));
1746 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001747 msg->msg_state = HTTP_MSG_RPBEFORE;
1748 txn->status = 0;
1749 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001750 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001751 }
1752
1753 /*
1754 * 2: check for cacheability.
1755 */
1756
1757 switch (txn->status) {
1758 case 200:
1759 case 203:
1760 case 204:
1761 case 206:
1762 case 300:
1763 case 301:
1764 case 404:
1765 case 405:
1766 case 410:
1767 case 414:
1768 case 501:
1769 break;
1770 default:
1771 /* RFC7231#6.1:
1772 * Responses with status codes that are defined as
1773 * cacheable by default (e.g., 200, 203, 204, 206,
1774 * 300, 301, 404, 405, 410, 414, and 501 in this
1775 * specification) can be reused by a cache with
1776 * heuristic expiration unless otherwise indicated
1777 * by the method definition or explicit cache
1778 * controls [RFC7234]; all other status codes are
1779 * not cacheable by default.
1780 */
1781 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1782 break;
1783 }
1784
1785 /*
1786 * 3: we may need to capture headers
1787 */
1788 s->logs.logwait &= ~LW_RESP;
1789 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001790 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001791
Christopher Faulet9768c262018-10-22 09:34:31 +02001792 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001793 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1794 txn->status == 101)) {
1795 /* Either we've established an explicit tunnel, or we're
1796 * switching the protocol. In both cases, we're very unlikely
1797 * to understand the next protocols. We have to switch to tunnel
1798 * mode, so that we transfer the request and responses then let
1799 * this protocol pass unmodified. When we later implement specific
1800 * parsers for such protocols, we'll want to check the Upgrade
1801 * header which contains information about that protocol for
1802 * responses with status 101 (eg: see RFC2817 about TLS).
1803 */
1804 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 }
1806
Christopher Faulete0768eb2018-10-03 16:38:02 +02001807 /* we want to have the response time before we start processing it */
1808 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1809
1810 /* end of job, return OK */
1811 rep->analysers &= ~an_bit;
1812 rep->analyse_exp = TICK_ETERNITY;
1813 channel_auto_close(rep);
1814 return 1;
1815
1816 abort_keep_alive:
1817 /* A keep-alive request to the server failed on a network error.
1818 * The client is required to retry. We need to close without returning
1819 * any other information so that the client retries.
1820 */
1821 txn->status = 0;
1822 rep->analysers &= AN_RES_FLT_END;
1823 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001824 s->logs.logwait = 0;
1825 s->logs.level = 0;
1826 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001827 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001828 return 0;
1829}
1830
1831/* This function performs all the processing enabled for the current response.
1832 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1833 * and updates s->res.analysers. It might make sense to explode it into several
1834 * other functions. It works like process_request (see indications above).
1835 */
1836int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1837{
1838 struct session *sess = s->sess;
1839 struct http_txn *txn = s->txn;
1840 struct http_msg *msg = &txn->rsp;
1841 struct proxy *cur_proxy;
1842 struct cond_wordlist *wl;
1843 enum rule_result ret = HTTP_RULE_RES_CONT;
1844
Christopher Faulet9768c262018-10-22 09:34:31 +02001845 // TODO: Disabled for now
1846 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
1847 rep->analysers |= AN_RES_HTTP_XFER_BODY;
1848 rep->analyse_exp = TICK_ETERNITY;
1849 rep->analysers &= ~an_bit;
1850 return 1;
1851
Christopher Faulete0768eb2018-10-03 16:38:02 +02001852 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1853 now_ms, __FUNCTION__,
1854 s,
1855 rep,
1856 rep->rex, rep->wex,
1857 rep->flags,
1858 ci_data(rep),
1859 rep->analysers);
1860
1861 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1862 return 0;
1863
1864 /* The stats applet needs to adjust the Connection header but we don't
1865 * apply any filter there.
1866 */
1867 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1868 rep->analysers &= ~an_bit;
1869 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001870 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001871 }
1872
1873 /*
1874 * We will have to evaluate the filters.
1875 * As opposed to version 1.2, now they will be evaluated in the
1876 * filters order and not in the header order. This means that
1877 * each filter has to be validated among all headers.
1878 *
1879 * Filters are tried with ->be first, then with ->fe if it is
1880 * different from ->be.
1881 *
1882 * Maybe we are in resume condiion. In this case I choose the
1883 * "struct proxy" which contains the rule list matching the resume
1884 * pointer. If none of theses "struct proxy" match, I initialise
1885 * the process with the first one.
1886 *
1887 * In fact, I check only correspondance betwwen the current list
1888 * pointer and the ->fe rule list. If it doesn't match, I initialize
1889 * the loop with the ->be.
1890 */
1891 if (s->current_rule_list == &sess->fe->http_res_rules)
1892 cur_proxy = sess->fe;
1893 else
1894 cur_proxy = s->be;
1895 while (1) {
1896 struct proxy *rule_set = cur_proxy;
1897
1898 /* evaluate http-response rules */
1899 if (ret == HTTP_RULE_RES_CONT) {
1900 ret = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
1901
1902 if (ret == HTTP_RULE_RES_BADREQ)
1903 goto return_srv_prx_502;
1904
1905 if (ret == HTTP_RULE_RES_DONE) {
1906 rep->analysers &= ~an_bit;
1907 rep->analyse_exp = TICK_ETERNITY;
1908 return 1;
1909 }
1910 }
1911
1912 /* we need to be called again. */
1913 if (ret == HTTP_RULE_RES_YIELD) {
1914 channel_dont_close(rep);
1915 return 0;
1916 }
1917
1918 /* try headers filters */
1919 if (rule_set->rsp_exp != NULL) {
1920 if (apply_filters_to_response(s, rep, rule_set) < 0) {
1921 return_bad_resp:
1922 if (objt_server(s->target)) {
1923 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1924 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
1925 }
1926 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1927 return_srv_prx_502:
1928 rep->analysers &= AN_RES_FLT_END;
1929 txn->status = 502;
1930 s->logs.t_data = -1; /* was not a valid response */
1931 s->si[1].flags |= SI_FL_NOLINGER;
1932 channel_truncate(rep);
1933 http_reply_and_close(s, txn->status, http_error_message(s));
1934 if (!(s->flags & SF_ERR_MASK))
1935 s->flags |= SF_ERR_PRXCOND;
1936 if (!(s->flags & SF_FINST_MASK))
1937 s->flags |= SF_FINST_H;
1938 return 0;
1939 }
1940 }
1941
1942 /* has the response been denied ? */
1943 if (txn->flags & TX_SVDENY) {
1944 if (objt_server(s->target))
1945 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
1946
1947 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1948 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1949 if (sess->listener->counters)
1950 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
1951
1952 goto return_srv_prx_502;
1953 }
1954
1955 /* add response headers from the rule sets in the same order */
1956 list_for_each_entry(wl, &rule_set->rsp_add, list) {
1957 if (txn->status < 200 && txn->status != 101)
1958 break;
1959 if (wl->cond) {
1960 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1961 ret = acl_pass(ret);
1962 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1963 ret = !ret;
1964 if (!ret)
1965 continue;
1966 }
1967 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, wl->s, strlen(wl->s)) < 0))
1968 goto return_bad_resp;
1969 }
1970
1971 /* check whether we're already working on the frontend */
1972 if (cur_proxy == sess->fe)
1973 break;
1974 cur_proxy = sess->fe;
1975 }
1976
1977 /* After this point, this anayzer can't return yield, so we can
1978 * remove the bit corresponding to this analyzer from the list.
1979 *
1980 * Note that the intermediate returns and goto found previously
1981 * reset the analyzers.
1982 */
1983 rep->analysers &= ~an_bit;
1984 rep->analyse_exp = TICK_ETERNITY;
1985
1986 /* OK that's all we can do for 1xx responses */
1987 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001988 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001989
1990 /*
1991 * Now check for a server cookie.
1992 */
1993 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
1994 manage_server_side_cookies(s, rep);
1995
1996 /*
1997 * Check for cache-control or pragma headers if required.
1998 */
1999 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
2000 check_response_for_cacheability(s, rep);
2001
2002 /*
2003 * Add server cookie in the response if needed
2004 */
2005 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
2006 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
2007 (!(s->flags & SF_DIRECT) ||
2008 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
2009 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
2010 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
2011 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
2012 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
2013 !(s->flags & SF_IGNORE_PRST)) {
2014 /* the server is known, it's not the one the client requested, or the
2015 * cookie's last seen date needs to be refreshed. We have to
2016 * insert a set-cookie here, except if we want to insert only on POST
2017 * requests and this one isn't. Note that servers which don't have cookies
2018 * (eg: some backup servers) will return a full cookie removal request.
2019 */
2020 if (!objt_server(s->target)->cookie) {
2021 chunk_printf(&trash,
2022 "Set-Cookie: %s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
2023 s->be->cookie_name);
2024 }
2025 else {
2026 chunk_printf(&trash, "Set-Cookie: %s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
2027
2028 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
2029 /* emit last_date, which is mandatory */
2030 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2031 s30tob64((date.tv_sec+3) >> 2,
2032 trash.area + trash.data);
2033 trash.data += 5;
2034
2035 if (s->be->cookie_maxlife) {
2036 /* emit first_date, which is either the original one or
2037 * the current date.
2038 */
2039 trash.area[trash.data++] = COOKIE_DELIM_DATE;
2040 s30tob64(txn->cookie_first_date ?
2041 txn->cookie_first_date >> 2 :
2042 (date.tv_sec+3) >> 2,
2043 trash.area + trash.data);
2044 trash.data += 5;
2045 }
2046 }
2047 chunk_appendf(&trash, "; path=/");
2048 }
2049
2050 if (s->be->cookie_domain)
2051 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
2052
2053 if (s->be->ck_opts & PR_CK_HTTPONLY)
2054 chunk_appendf(&trash, "; HttpOnly");
2055
2056 if (s->be->ck_opts & PR_CK_SECURE)
2057 chunk_appendf(&trash, "; Secure");
2058
2059 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.area, trash.data) < 0))
2060 goto return_bad_resp;
2061
2062 txn->flags &= ~TX_SCK_MASK;
2063 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2064 /* the server did not change, only the date was updated */
2065 txn->flags |= TX_SCK_UPDATED;
2066 else
2067 txn->flags |= TX_SCK_INSERTED;
2068
2069 /* Here, we will tell an eventual cache on the client side that we don't
2070 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2071 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2072 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2073 */
2074 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2075
2076 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2077
2078 if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx,
2079 "Cache-control: private", 22) < 0))
2080 goto return_bad_resp;
2081 }
2082 }
2083
2084 /*
2085 * Check if result will be cacheable with a cookie.
2086 * We'll block the response if security checks have caught
2087 * nasty things such as a cacheable cookie.
2088 */
2089 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2090 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2091 (s->be->options & PR_O_CHK_CACHE)) {
2092 /* we're in presence of a cacheable response containing
2093 * a set-cookie header. We'll block it as requested by
2094 * the 'checkcache' option, and send an alert.
2095 */
2096 if (objt_server(s->target))
2097 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2098
2099 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2100 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2101 if (sess->listener->counters)
2102 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2103
2104 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2105 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2106 send_log(s->be, LOG_ALERT,
2107 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2108 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2109 goto return_srv_prx_502;
2110 }
2111
Christopher Fauletf2824e62018-10-01 12:12:37 +02002112 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002113 /* Always enter in the body analyzer */
2114 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2115 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2116
2117 /* if the user wants to log as soon as possible, without counting
2118 * bytes from the server, then this is the right moment. We have
2119 * to temporarily assign bytes_out to log what we currently have.
2120 */
2121 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2122 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
2123 s->logs.bytes_out = txn->rsp.eoh;
2124 s->do_log(s);
2125 s->logs.bytes_out = 0;
2126 }
2127 return 1;
2128}
2129
2130/* This function is an analyser which forwards response body (including chunk
2131 * sizes if any). It is called as soon as we must forward, even if we forward
2132 * zero byte. The only situation where it must not be called is when we're in
2133 * tunnel mode and we want to forward till the close. It's used both to forward
2134 * remaining data and to resync after end of body. It expects the msg_state to
2135 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2136 * read more data, or 1 once we can go on with next request or end the stream.
2137 *
2138 * It is capable of compressing response data both in content-length mode and
2139 * in chunked mode. The state machines follows different flows depending on
2140 * whether content-length and chunked modes are used, since there are no
2141 * trailers in content-length :
2142 *
2143 * chk-mode cl-mode
2144 * ,----- BODY -----.
2145 * / \
2146 * V size > 0 V chk-mode
2147 * .--> SIZE -------------> DATA -------------> CRLF
2148 * | | size == 0 | last byte |
2149 * | v final crlf v inspected |
2150 * | TRAILERS -----------> DONE |
2151 * | |
2152 * `----------------------------------------------'
2153 *
2154 * Compression only happens in the DATA state, and must be flushed in final
2155 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2156 * is performed at once on final states for all bytes parsed, or when leaving
2157 * on missing data.
2158 */
2159int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2160{
2161 struct session *sess = s->sess;
2162 struct http_txn *txn = s->txn;
2163 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002164 struct htx *htx;
2165 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002166
2167 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2168 now_ms, __FUNCTION__,
2169 s,
2170 res,
2171 res->rex, res->wex,
2172 res->flags,
2173 ci_data(res),
2174 res->analysers);
2175
Christopher Faulet9768c262018-10-22 09:34:31 +02002176 htx = htx_from_buf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002177
2178 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002179 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002180 /* Output closed while we were sending data. We must abort and
2181 * wake the other side up.
2182 */
2183 msg->err_state = msg->msg_state;
2184 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002185 htx_end_response(s);
2186 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002187 return 1;
2188 }
2189
Christopher Faulet9768c262018-10-22 09:34:31 +02002190 if (msg->msg_state == HTTP_MSG_BODY)
2191 msg->msg_state = HTTP_MSG_DATA;
2192
Christopher Faulete0768eb2018-10-03 16:38:02 +02002193 /* in most states, we should abort in case of early close */
2194 channel_auto_close(res);
2195
Christopher Faulete0768eb2018-10-03 16:38:02 +02002196 if (res->to_forward) {
2197 /* We can't process the buffer's contents yet */
2198 res->flags |= CF_WAKE_WRITE;
2199 goto missing_data_or_waiting;
2200 }
2201
Christopher Faulet9768c262018-10-22 09:34:31 +02002202 if (msg->msg_state >= HTTP_MSG_DONE)
2203 goto done;
2204
2205 /* Forward all input data. We get it by removing all outgoing data not
2206 * forwarded yet from HTX data size.
2207 */
2208 c_adv(res, htx->data - co_data(res));
2209
2210 /* To let the function channel_forward work as expected we must update
2211 * the channel's buffer to pretend there is no more input data. The
2212 * right length is then restored. We must do that, because when an HTX
2213 * message is stored into a buffer, it appears as full.
2214 */
2215 b_set_data(&res->buf, co_data(res));
2216 if (htx->extra != ULLONG_MAX)
2217 htx->extra -= channel_forward(res, htx->extra);
2218 b_set_data(&res->buf, b_size(&res->buf));
2219
2220 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2221 /* The server still sending data that should be filtered */
2222 if (res->flags & CF_SHUTR || !HAS_DATA_FILTERS(s, res)) {
2223 msg->msg_state = HTTP_MSG_TUNNEL;
2224 goto done;
2225 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 }
2227
Christopher Faulet9768c262018-10-22 09:34:31 +02002228 /* Check if the end-of-message is reached and if so, switch the message
2229 * in HTTP_MSG_DONE state.
2230 */
2231 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2232 goto missing_data_or_waiting;
2233
2234 msg->msg_state = HTTP_MSG_DONE;
2235
2236 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002238 channel_dont_close(res);
2239
Christopher Fauletf2824e62018-10-01 12:12:37 +02002240 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002241 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002242 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002243 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2244 if (res->flags & CF_SHUTW) {
2245 /* response errors are most likely due to the
2246 * client aborting the transfer. */
2247 goto aborted_xfer;
2248 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002249 goto return_bad_res;
2250 }
2251 return 1;
2252 }
2253 return 0;
2254
2255 missing_data_or_waiting:
2256 if (res->flags & CF_SHUTW)
2257 goto aborted_xfer;
2258
2259 /* stop waiting for data if the input is closed before the end. If the
2260 * client side was already closed, it means that the client has aborted,
2261 * so we don't want to count this as a server abort. Otherwise it's a
2262 * server abort.
2263 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002264 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2266 goto aborted_xfer;
2267 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002268 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 if (!(s->flags & SF_ERR_MASK))
2270 s->flags |= SF_ERR_SRVCL;
2271 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2272 if (objt_server(s->target))
2273 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2274 goto return_bad_res_stats_ok;
2275 }
2276 }
2277
Christopher Faulete0768eb2018-10-03 16:38:02 +02002278 /* When TE: chunked is used, we need to get there again to parse
2279 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002280 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2281 * are filters registered on the stream, we don't want to forward a
2282 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002284 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_DATA_FILTERS(s, res))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 channel_dont_close(res);
2286
Christopher Faulet9768c262018-10-22 09:34:31 +02002287#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
2288 // about if
2289
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 /* We know that more data are expected, but we couldn't send more that
2291 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2292 * system knows it must not set a PUSH on this first part. Interactive
2293 * modes are already handled by the stream sock layer. We must not do
2294 * this in content-length mode because it could present the MSG_MORE
2295 * flag with the last block of forwarded data, which would cause an
2296 * additional delay to be observed by the receiver.
2297 */
2298 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2299 res->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02002300#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301
2302 /* the stream handler will take care of timeouts and errors */
2303 return 0;
2304
2305 return_bad_res: /* let's centralize all bad responses */
2306 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2307 if (objt_server(s->target))
2308 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2309
2310 return_bad_res_stats_ok:
2311 txn->rsp.err_state = txn->rsp.msg_state;
2312 txn->rsp.msg_state = HTTP_MSG_ERROR;
2313 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002314 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002315 res->analysers &= AN_RES_FLT_END;
2316 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2317 if (objt_server(s->target))
2318 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
2319
2320 if (!(s->flags & SF_ERR_MASK))
2321 s->flags |= SF_ERR_PRXCOND;
2322 if (!(s->flags & SF_FINST_MASK))
2323 s->flags |= SF_FINST_D;
2324 return 0;
2325
2326 aborted_xfer:
2327 txn->rsp.err_state = txn->rsp.msg_state;
2328 txn->rsp.msg_state = HTTP_MSG_ERROR;
2329 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002330 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002331 res->analysers &= AN_RES_FLT_END;
2332 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2333
2334 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2335 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2336 if (objt_server(s->target))
2337 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2338
2339 if (!(s->flags & SF_ERR_MASK))
2340 s->flags |= SF_ERR_CLICL;
2341 if (!(s->flags & SF_FINST_MASK))
2342 s->flags |= SF_FINST_D;
2343 return 0;
2344}
2345
Christopher Faulet0f226952018-10-22 09:29:56 +02002346void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002347{
2348 struct proxy *fe = strm_fe(s);
2349 int tmp = TX_CON_WANT_CLO;
2350
2351 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2352 tmp = TX_CON_WANT_TUN;
2353
2354 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002355 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356}
2357
2358/* Perform an HTTP redirect based on the information in <rule>. The function
2359 * returns non-zero on success, or zero in case of a, irrecoverable error such
2360 * as too large a request to build a valid response.
2361 */
2362int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2363{
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002364 struct htx *htx = htx_from_buf(&s->req.buf);
2365 union h1_sl sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366 const char *msg_fmt;
2367 struct buffer *chunk;
2368 int ret = 0;
2369
2370 chunk = alloc_trash_chunk();
2371 if (!chunk)
2372 goto leave;
2373
2374 /* build redirect message */
2375 switch(rule->code) {
2376 case 308:
2377 msg_fmt = HTTP_308;
2378 break;
2379 case 307:
2380 msg_fmt = HTTP_307;
2381 break;
2382 case 303:
2383 msg_fmt = HTTP_303;
2384 break;
2385 case 301:
2386 msg_fmt = HTTP_301;
2387 break;
2388 case 302:
2389 default:
2390 msg_fmt = HTTP_302;
2391 break;
2392 }
2393
2394 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
2395 goto leave;
2396
2397 switch(rule->type) {
2398 case REDIRECT_TYPE_SCHEME: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002399 struct http_hdr_ctx ctx;
2400 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002402 host = ist("");
2403 ctx.blk = NULL;
2404 if (http_find_header(htx, ist("Host"), &ctx, 0))
2405 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002407 sl = http_find_stline(htx);
2408 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002409 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002410 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2412 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002413 while (qs < path.len) {
2414 if (*(path.ptr + qs) == '?') {
2415 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 break;
2417 }
2418 qs++;
2419 }
2420 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002421 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002422 else
2423 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002424
2425 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426 /* add scheme */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002427 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2428 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429 }
2430 else {
2431 /* add scheme with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002432 chunk->data += build_logline(s, chunk->area + chunk->data,
2433 chunk->size - chunk->data,
2434 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002436 /* add "://" + host + path */
2437 if (!chunk_memcat(chunk, "://", 3) ||
2438 !chunk_memcat(chunk, host.ptr, host.len) ||
2439 !chunk_memcat(chunk, path.ptr, path.len))
2440 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441
2442 /* append a slash at the end of the location if needed and missing */
2443 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2444 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002445 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002446 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002447 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 break;
2450 }
2451 case REDIRECT_TYPE_PREFIX: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002452 struct ist path;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002453
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002454 sl = http_find_stline(htx);
2455 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002457 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002458 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2459 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002460 while (qs < path.len) {
2461 if (*(path.ptr + qs) == '?') {
2462 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002463 break;
2464 }
2465 qs++;
2466 }
2467 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002469 else
2470 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471
2472 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002473 /* add prefix. Note that if prefix == "/", we don't want to
2474 * add anything, otherwise it makes it hard for the user to
2475 * configure a self-redirection.
2476 */
2477 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002478 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2479 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002480 }
2481 }
2482 else {
2483 /* add prefix with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002484 chunk->data += build_logline(s, chunk->area + chunk->data,
2485 chunk->size - chunk->data,
2486 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002487 }
2488
2489 /* add path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002490 if (!chunk_memcat(chunk, path.ptr, path.len))
2491 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002492
2493 /* append a slash at the end of the location if needed and missing */
2494 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2495 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002496 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002497 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002498 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002499 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002500 break;
2501 }
2502 case REDIRECT_TYPE_LOCATION:
2503 default:
2504 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002505 /* add location */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002506 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2507 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002508 }
2509 else {
2510 /* add location with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002511 chunk->data += build_logline(s, chunk->area + chunk->data,
2512 chunk->size - chunk->data,
2513 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002514 }
2515 break;
2516 }
2517
2518 if (rule->cookie_len) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002519 if (!chunk_memcat(chunk, "\r\nSet-Cookie: ", 14) ||
2520 !chunk_memcat(chunk, rule->cookie_str, rule->cookie_len))
2521 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002522 }
2523
2524 /* add end of headers and the keep-alive/close status. */
2525 txn->status = rule->code;
2526 /* let's log the request time */
2527 s->logs.tv_request = now;
2528
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002529 /* FIXME: close for now, but it could be cool to handle the keep-alive here */
2530 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2531 if (!chunk_memcat(chunk, "\r\nProxy-Connection: close\r\n\r\n", 29))
2532 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002533 } else {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002534 if (!chunk_memcat(chunk, "\r\nConnection: close\r\n\r\n", 23))
2535 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002536 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002537 htx_reply_and_close(s, txn->status, chunk);
2538 s->req.analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539
2540 if (!(s->flags & SF_ERR_MASK))
2541 s->flags |= SF_ERR_LOCAL;
2542 if (!(s->flags & SF_FINST_MASK))
2543 s->flags |= SF_FINST_R;
2544
2545 ret = 1;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002546 leave:
Christopher Fauletf2824e62018-10-01 12:12:37 +02002547 free_trash_chunk(chunk);
2548 return ret;
2549}
2550
Christopher Faulet72333522018-10-24 11:25:02 +02002551int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2552 struct ist name, const char *str, struct my_regex *re, int action)
2553{
2554 struct http_hdr_ctx ctx;
2555 struct buffer *output = get_trash_chunk();
2556
2557 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2558 ctx.blk = NULL;
2559 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2560 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2561 continue;
2562
2563 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2564 if (output->data == -1)
2565 return -1;
2566 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2567 return -1;
2568 }
2569 return 0;
2570}
2571
2572static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2573 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2574{
2575 struct buffer *replace;
2576 int ret = -1;
2577
2578 replace = alloc_trash_chunk();
2579 if (!replace)
2580 goto leave;
2581
2582 replace->data = build_logline(s, replace->area, replace->size, fmt);
2583 if (replace->data >= replace->size - 1)
2584 goto leave;
2585
2586 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2587
2588 leave:
2589 free_trash_chunk(replace);
2590 return ret;
2591}
2592
Christopher Faulet6eb92892018-11-15 16:39:29 +01002593/*
2594 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2595 * built according to <fmt> log line format.
2596 * If <early_hints> is NULL, it is allocated and the HTTP 103 response first
2597 * line is inserted before the header. If an error occurred <early_hints> is
2598 * released and NULL is returned. On success the updated buffer is returned.
2599 */
2600static struct buffer *htx_apply_early_hint_rule(struct stream* s, struct buffer *early_hints,
2601 const char* name, unsigned int name_len,
2602 struct list *fmt)
2603{
2604 if (!early_hints) {
2605 early_hints = alloc_trash_chunk();
2606 if (!early_hints)
2607 goto fail;
2608 if (!chunk_memcat(early_hints, HTTP_103.ptr, HTTP_103.len))
2609 goto fail;
2610 }
2611
2612 if (!chunk_memcat(early_hints, name, name_len) || !chunk_memcat(early_hints, ": ", 2))
2613 goto fail;
2614
2615 early_hints->data += build_logline(s, b_tail(early_hints), b_room(early_hints), fmt);
2616 if (!chunk_memcat(early_hints, "\r\n", 2))
2617 goto fail;
2618
2619 return early_hints;
2620
2621 fail:
2622 free_trash_chunk(early_hints);
2623 return NULL;
2624}
2625
2626/* Sends an HTTP 103 response. Before sending it, the last CRLF finishing the
2627 * response is added. If an error occurred or if another response was already
2628 * sent, this function does nothing.
2629 */
2630static void htx_send_early_hints(struct stream *s, struct buffer *early_hints)
2631{
2632 struct channel *chn = s->txn->rsp.chn;
2633 struct htx *htx;
2634
2635 /* If a response was already sent, skip early hints */
2636 if (s->txn->status > 0)
2637 return;
2638
2639 if (!chunk_memcat(early_hints, "\r\n", 2))
2640 return;
2641
2642 htx = htx_from_buf(&chn->buf);
2643 if (!htx_add_oob(htx, ist2(early_hints->area, early_hints->data)))
2644 return;
2645
2646 c_adv(chn, early_hints->data);
2647 chn->total += early_hints->data;
2648}
2649
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002650/* This function executes one of the set-{method,path,query,uri} actions. It
2651 * takes the string from the variable 'replace' with length 'len', then modifies
2652 * the relevant part of the request line accordingly. Then it updates various
2653 * pointers to the next elements which were moved, and the total buffer length.
2654 * It finds the action to be performed in p[2], previously filled by function
2655 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2656 * error, though this can be revisited when this code is finally exploited.
2657 *
2658 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2659 * query string and 3 to replace uri.
2660 *
2661 * In query string case, the mark question '?' must be set at the start of the
2662 * string by the caller, event if the replacement query string is empty.
2663 */
2664int htx_req_replace_stline(int action, const char *replace, int len,
2665 struct proxy *px, struct stream *s)
2666{
2667 struct htx *htx = htx_from_buf(&s->req.buf);
2668
2669 switch (action) {
2670 case 0: // method
2671 if (!http_replace_req_meth(htx, ist2(replace, len)))
2672 return -1;
2673 break;
2674
2675 case 1: // path
2676 if (!http_replace_req_path(htx, ist2(replace, len)))
2677 return -1;
2678 break;
2679
2680 case 2: // query
2681 if (!http_replace_req_query(htx, ist2(replace, len)))
2682 return -1;
2683 break;
2684
2685 case 3: // uri
2686 if (!http_replace_req_uri(htx, ist2(replace, len)))
2687 return -1;
2688 break;
2689
2690 default:
2691 return -1;
2692 }
2693 return 0;
2694}
2695
2696/* This function replace the HTTP status code and the associated message. The
2697 * variable <status> contains the new status code. This function never fails.
2698 */
2699void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2700{
2701 struct htx *htx = htx_from_buf(&s->res.buf);
2702 char *res;
2703
2704 chunk_reset(&trash);
2705 res = ultoa_o(status, trash.area, trash.size);
2706 trash.data = res - trash.area;
2707
2708 /* Do we have a custom reason format string? */
2709 if (reason == NULL)
2710 reason = http_get_reason(status);
2711
2712 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2713 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2714}
2715
Christopher Faulet3e964192018-10-24 11:39:23 +02002716/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2717 * transaction <txn>. Returns the verdict of the first rule that prevents
2718 * further processing of the request (auth, deny, ...), and defaults to
2719 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2720 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2721 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2722 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2723 * status.
2724 */
2725static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2726 struct stream *s, int *deny_status)
2727{
2728 struct session *sess = strm_sess(s);
2729 struct http_txn *txn = s->txn;
2730 struct htx *htx;
2731 struct connection *cli_conn;
2732 struct act_rule *rule;
2733 struct http_hdr_ctx ctx;
2734 const char *auth_realm;
2735 struct buffer *early_hints = NULL;
2736 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2737 int act_flags = 0;
2738
2739 htx = htx_from_buf(&s->req.buf);
2740
2741 /* If "the current_rule_list" match the executed rule list, we are in
2742 * resume condition. If a resume is needed it is always in the action
2743 * and never in the ACL or converters. In this case, we initialise the
2744 * current rule, and go to the action execution point.
2745 */
2746 if (s->current_rule) {
2747 rule = s->current_rule;
2748 s->current_rule = NULL;
2749 if (s->current_rule_list == rules)
2750 goto resume_execution;
2751 }
2752 s->current_rule_list = rules;
2753
2754 list_for_each_entry(rule, rules, list) {
2755 /* check optional condition */
2756 if (rule->cond) {
2757 int ret;
2758
2759 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2760 ret = acl_pass(ret);
2761
2762 if (rule->cond->pol == ACL_COND_UNLESS)
2763 ret = !ret;
2764
2765 if (!ret) /* condition not matched */
2766 continue;
2767 }
2768
2769 act_flags |= ACT_FLAG_FIRST;
2770 resume_execution:
2771 switch (rule->action) {
2772 case ACT_ACTION_ALLOW:
2773 rule_ret = HTTP_RULE_RES_STOP;
2774 goto end;
2775
2776 case ACT_ACTION_DENY:
2777 if (deny_status)
2778 *deny_status = rule->deny_status;
2779 rule_ret = HTTP_RULE_RES_DENY;
2780 goto end;
2781
2782 case ACT_HTTP_REQ_TARPIT:
2783 txn->flags |= TX_CLTARPIT;
2784 if (deny_status)
2785 *deny_status = rule->deny_status;
2786 rule_ret = HTTP_RULE_RES_DENY;
2787 goto end;
2788
2789 case ACT_HTTP_REQ_AUTH:
2790 /* Be sure to sned any pending HTTP 103 response first */
2791 if (early_hints) {
2792 htx_send_early_hints(s, early_hints);
2793 free_trash_chunk(early_hints);
2794 early_hints = NULL;
2795 }
2796 /* Auth might be performed on regular http-req rules as well as on stats */
2797 auth_realm = rule->arg.auth.realm;
2798 if (!auth_realm) {
2799 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2800 auth_realm = STATS_DEFAULT_REALM;
2801 else
2802 auth_realm = px->id;
2803 }
2804 /* send 401/407 depending on whether we use a proxy or not. We still
2805 * count one error, because normal browsing won't significantly
2806 * increase the counter but brute force attempts will.
2807 */
2808 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
2809 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
2810 htx_reply_and_close(s, txn->status, &trash);
2811 stream_inc_http_err_ctr(s);
2812 rule_ret = HTTP_RULE_RES_ABRT;
2813 goto end;
2814
2815 case ACT_HTTP_REDIR:
2816 /* Be sure to sned any pending HTTP 103 response first */
2817 if (early_hints) {
2818 htx_send_early_hints(s, early_hints);
2819 free_trash_chunk(early_hints);
2820 early_hints = NULL;
2821 }
2822 rule_ret = HTTP_RULE_RES_DONE;
2823 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2824 rule_ret = HTTP_RULE_RES_BADREQ;
2825 goto end;
2826
2827 case ACT_HTTP_SET_NICE:
2828 s->task->nice = rule->arg.nice;
2829 break;
2830
2831 case ACT_HTTP_SET_TOS:
2832 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2833 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2834 break;
2835
2836 case ACT_HTTP_SET_MARK:
2837#ifdef SO_MARK
2838 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2839 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2840#endif
2841 break;
2842
2843 case ACT_HTTP_SET_LOGL:
2844 s->logs.level = rule->arg.loglevel;
2845 break;
2846
2847 case ACT_HTTP_REPLACE_HDR:
2848 case ACT_HTTP_REPLACE_VAL:
2849 if (htx_transform_header(s, &s->req, htx,
2850 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2851 &rule->arg.hdr_add.fmt,
2852 &rule->arg.hdr_add.re, rule->action)) {
2853 rule_ret = HTTP_RULE_RES_BADREQ;
2854 goto end;
2855 }
2856 break;
2857
2858 case ACT_HTTP_DEL_HDR:
2859 /* remove all occurrences of the header */
2860 ctx.blk = NULL;
2861 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2862 http_remove_header(htx, &ctx);
2863 break;
2864
2865 case ACT_HTTP_SET_HDR:
2866 case ACT_HTTP_ADD_HDR: {
2867 /* The scope of the trash buffer must be limited to this function. The
2868 * build_logline() function can execute a lot of other function which
2869 * can use the trash buffer. So for limiting the scope of this global
2870 * buffer, we build first the header value using build_logline, and
2871 * after we store the header name.
2872 */
2873 struct buffer *replace;
2874 struct ist n, v;
2875
2876 replace = alloc_trash_chunk();
2877 if (!replace) {
2878 rule_ret = HTTP_RULE_RES_BADREQ;
2879 goto end;
2880 }
2881
2882 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2883 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2884 v = ist2(replace->area, replace->data);
2885
2886 if (rule->action == ACT_HTTP_SET_HDR) {
2887 /* remove all occurrences of the header */
2888 ctx.blk = NULL;
2889 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2890 http_remove_header(htx, &ctx);
2891 }
2892
2893 if (!http_add_header(htx, n, v)) {
2894 static unsigned char rate_limit = 0;
2895
2896 if ((rate_limit++ & 255) == 0) {
2897 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);
2898 }
2899
2900 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2901 if (sess->fe != s->be)
2902 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2903 if (sess->listener->counters)
2904 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2905 }
2906 free_trash_chunk(replace);
2907 break;
2908 }
2909
2910 case ACT_HTTP_DEL_ACL:
2911 case ACT_HTTP_DEL_MAP: {
2912 struct pat_ref *ref;
2913 struct buffer *key;
2914
2915 /* collect reference */
2916 ref = pat_ref_lookup(rule->arg.map.ref);
2917 if (!ref)
2918 continue;
2919
2920 /* allocate key */
2921 key = alloc_trash_chunk();
2922 if (!key) {
2923 rule_ret = HTTP_RULE_RES_BADREQ;
2924 goto end;
2925 }
2926
2927 /* collect key */
2928 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2929 key->area[key->data] = '\0';
2930
2931 /* perform update */
2932 /* returned code: 1=ok, 0=ko */
2933 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2934 pat_ref_delete(ref, key->area);
2935 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2936
2937 free_trash_chunk(key);
2938 break;
2939 }
2940
2941 case ACT_HTTP_ADD_ACL: {
2942 struct pat_ref *ref;
2943 struct buffer *key;
2944
2945 /* collect reference */
2946 ref = pat_ref_lookup(rule->arg.map.ref);
2947 if (!ref)
2948 continue;
2949
2950 /* allocate key */
2951 key = alloc_trash_chunk();
2952 if (!key) {
2953 rule_ret = HTTP_RULE_RES_BADREQ;
2954 goto end;
2955 }
2956
2957 /* collect key */
2958 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2959 key->area[key->data] = '\0';
2960
2961 /* perform update */
2962 /* add entry only if it does not already exist */
2963 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2964 if (pat_ref_find_elt(ref, key->area) == NULL)
2965 pat_ref_add(ref, key->area, NULL, NULL);
2966 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2967
2968 free_trash_chunk(key);
2969 break;
2970 }
2971
2972 case ACT_HTTP_SET_MAP: {
2973 struct pat_ref *ref;
2974 struct buffer *key, *value;
2975
2976 /* collect reference */
2977 ref = pat_ref_lookup(rule->arg.map.ref);
2978 if (!ref)
2979 continue;
2980
2981 /* allocate key */
2982 key = alloc_trash_chunk();
2983 if (!key) {
2984 rule_ret = HTTP_RULE_RES_BADREQ;
2985 goto end;
2986 }
2987
2988 /* allocate value */
2989 value = alloc_trash_chunk();
2990 if (!value) {
2991 free_trash_chunk(key);
2992 rule_ret = HTTP_RULE_RES_BADREQ;
2993 goto end;
2994 }
2995
2996 /* collect key */
2997 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2998 key->area[key->data] = '\0';
2999
3000 /* collect value */
3001 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3002 value->area[value->data] = '\0';
3003
3004 /* perform update */
3005 if (pat_ref_find_elt(ref, key->area) != NULL)
3006 /* update entry if it exists */
3007 pat_ref_set(ref, key->area, value->area, NULL);
3008 else
3009 /* insert a new entry */
3010 pat_ref_add(ref, key->area, value->area, NULL);
3011
3012 free_trash_chunk(key);
3013 free_trash_chunk(value);
3014 break;
3015 }
3016
3017 case ACT_HTTP_EARLY_HINT:
3018 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3019 break;
3020 early_hints = htx_apply_early_hint_rule(s, early_hints,
3021 rule->arg.early_hint.name,
3022 rule->arg.early_hint.name_len,
3023 &rule->arg.early_hint.fmt);
3024 if (!early_hints) {
3025 rule_ret = HTTP_RULE_RES_DONE;
3026 goto end;
3027 }
3028 break;
3029
3030 case ACT_CUSTOM:
3031 if ((s->req.flags & CF_READ_ERROR) ||
3032 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3033 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3034 (px->options & PR_O_ABRT_CLOSE)))
3035 act_flags |= ACT_FLAG_FINAL;
3036
3037 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3038 case ACT_RET_ERR:
3039 case ACT_RET_CONT:
3040 break;
3041 case ACT_RET_STOP:
3042 rule_ret = HTTP_RULE_RES_DONE;
3043 goto end;
3044 case ACT_RET_YIELD:
3045 s->current_rule = rule;
3046 rule_ret = HTTP_RULE_RES_YIELD;
3047 goto end;
3048 }
3049 break;
3050
3051 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3052 /* Note: only the first valid tracking parameter of each
3053 * applies.
3054 */
3055
3056 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3057 struct stktable *t;
3058 struct stksess *ts;
3059 struct stktable_key *key;
3060 void *ptr1, *ptr2;
3061
3062 t = rule->arg.trk_ctr.table.t;
3063 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3064 rule->arg.trk_ctr.expr, NULL);
3065
3066 if (key && (ts = stktable_get_entry(t, key))) {
3067 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3068
3069 /* let's count a new HTTP request as it's the first time we do it */
3070 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3071 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3072 if (ptr1 || ptr2) {
3073 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3074
3075 if (ptr1)
3076 stktable_data_cast(ptr1, http_req_cnt)++;
3077
3078 if (ptr2)
3079 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3080 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3081
3082 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3083
3084 /* If data was modified, we need to touch to re-schedule sync */
3085 stktable_touch_local(t, ts, 0);
3086 }
3087
3088 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3089 if (sess->fe != s->be)
3090 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3091 }
3092 }
3093 break;
3094
3095 /* other flags exists, but normaly, they never be matched. */
3096 default:
3097 break;
3098 }
3099 }
3100
3101 end:
3102 if (early_hints) {
3103 htx_send_early_hints(s, early_hints);
3104 free_trash_chunk(early_hints);
3105 }
3106
3107 /* we reached the end of the rules, nothing to report */
3108 return rule_ret;
3109}
3110
3111/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3112 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3113 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3114 * is returned, the process can continue the evaluation of next rule list. If
3115 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3116 * is returned, it means the operation could not be processed and a server error
3117 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3118 * deny rule. If *YIELD is returned, the caller must call again the function
3119 * with the same context.
3120 */
3121static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3122 struct stream *s)
3123{
3124 struct session *sess = strm_sess(s);
3125 struct http_txn *txn = s->txn;
3126 struct htx *htx;
3127 struct connection *cli_conn;
3128 struct act_rule *rule;
3129 struct http_hdr_ctx ctx;
3130 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3131 int act_flags = 0;
3132
3133 htx = htx_from_buf(&s->res.buf);
3134
3135 /* If "the current_rule_list" match the executed rule list, we are in
3136 * resume condition. If a resume is needed it is always in the action
3137 * and never in the ACL or converters. In this case, we initialise the
3138 * current rule, and go to the action execution point.
3139 */
3140 if (s->current_rule) {
3141 rule = s->current_rule;
3142 s->current_rule = NULL;
3143 if (s->current_rule_list == rules)
3144 goto resume_execution;
3145 }
3146 s->current_rule_list = rules;
3147
3148 list_for_each_entry(rule, rules, list) {
3149 /* check optional condition */
3150 if (rule->cond) {
3151 int ret;
3152
3153 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3154 ret = acl_pass(ret);
3155
3156 if (rule->cond->pol == ACL_COND_UNLESS)
3157 ret = !ret;
3158
3159 if (!ret) /* condition not matched */
3160 continue;
3161 }
3162
3163 act_flags |= ACT_FLAG_FIRST;
3164resume_execution:
3165 switch (rule->action) {
3166 case ACT_ACTION_ALLOW:
3167 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3168 goto end;
3169
3170 case ACT_ACTION_DENY:
3171 txn->flags |= TX_SVDENY;
3172 rule_ret = HTTP_RULE_RES_STOP;
3173 goto end;
3174
3175 case ACT_HTTP_SET_NICE:
3176 s->task->nice = rule->arg.nice;
3177 break;
3178
3179 case ACT_HTTP_SET_TOS:
3180 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3181 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3182 break;
3183
3184 case ACT_HTTP_SET_MARK:
3185#ifdef SO_MARK
3186 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3187 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3188#endif
3189 break;
3190
3191 case ACT_HTTP_SET_LOGL:
3192 s->logs.level = rule->arg.loglevel;
3193 break;
3194
3195 case ACT_HTTP_REPLACE_HDR:
3196 case ACT_HTTP_REPLACE_VAL:
3197 if (htx_transform_header(s, &s->res, htx,
3198 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3199 &rule->arg.hdr_add.fmt,
3200 &rule->arg.hdr_add.re, rule->action)) {
3201 rule_ret = HTTP_RULE_RES_BADREQ;
3202 goto end;
3203 }
3204 break;
3205
3206 case ACT_HTTP_DEL_HDR:
3207 /* remove all occurrences of the header */
3208 ctx.blk = NULL;
3209 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3210 http_remove_header(htx, &ctx);
3211 break;
3212
3213 case ACT_HTTP_SET_HDR:
3214 case ACT_HTTP_ADD_HDR: {
3215 struct buffer *replace;
3216 struct ist n, v;
3217
3218 replace = alloc_trash_chunk();
3219 if (!replace) {
3220 rule_ret = HTTP_RULE_RES_BADREQ;
3221 goto end;
3222 }
3223
3224 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3225 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3226 v = ist2(replace->area, replace->data);
3227
3228 if (rule->action == ACT_HTTP_SET_HDR) {
3229 /* remove all occurrences of the header */
3230 ctx.blk = NULL;
3231 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3232 http_remove_header(htx, &ctx);
3233 }
3234
3235 if (!http_add_header(htx, n, v)) {
3236 static unsigned char rate_limit = 0;
3237
3238 if ((rate_limit++ & 255) == 0) {
3239 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);
3240 }
3241
3242 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3243 if (sess->fe != s->be)
3244 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3245 if (sess->listener->counters)
3246 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3247 if (objt_server(s->target))
3248 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3249 }
3250 free_trash_chunk(replace);
3251 break;
3252 }
3253
3254 case ACT_HTTP_DEL_ACL:
3255 case ACT_HTTP_DEL_MAP: {
3256 struct pat_ref *ref;
3257 struct buffer *key;
3258
3259 /* collect reference */
3260 ref = pat_ref_lookup(rule->arg.map.ref);
3261 if (!ref)
3262 continue;
3263
3264 /* allocate key */
3265 key = alloc_trash_chunk();
3266 if (!key) {
3267 rule_ret = HTTP_RULE_RES_BADREQ;
3268 goto end;
3269 }
3270
3271 /* collect key */
3272 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3273 key->area[key->data] = '\0';
3274
3275 /* perform update */
3276 /* returned code: 1=ok, 0=ko */
3277 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3278 pat_ref_delete(ref, key->area);
3279 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3280
3281 free_trash_chunk(key);
3282 break;
3283 }
3284
3285 case ACT_HTTP_ADD_ACL: {
3286 struct pat_ref *ref;
3287 struct buffer *key;
3288
3289 /* collect reference */
3290 ref = pat_ref_lookup(rule->arg.map.ref);
3291 if (!ref)
3292 continue;
3293
3294 /* allocate key */
3295 key = alloc_trash_chunk();
3296 if (!key) {
3297 rule_ret = HTTP_RULE_RES_BADREQ;
3298 goto end;
3299 }
3300
3301 /* collect key */
3302 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3303 key->area[key->data] = '\0';
3304
3305 /* perform update */
3306 /* check if the entry already exists */
3307 if (pat_ref_find_elt(ref, key->area) == NULL)
3308 pat_ref_add(ref, key->area, NULL, NULL);
3309
3310 free_trash_chunk(key);
3311 break;
3312 }
3313
3314 case ACT_HTTP_SET_MAP: {
3315 struct pat_ref *ref;
3316 struct buffer *key, *value;
3317
3318 /* collect reference */
3319 ref = pat_ref_lookup(rule->arg.map.ref);
3320 if (!ref)
3321 continue;
3322
3323 /* allocate key */
3324 key = alloc_trash_chunk();
3325 if (!key) {
3326 rule_ret = HTTP_RULE_RES_BADREQ;
3327 goto end;
3328 }
3329
3330 /* allocate value */
3331 value = alloc_trash_chunk();
3332 if (!value) {
3333 free_trash_chunk(key);
3334 rule_ret = HTTP_RULE_RES_BADREQ;
3335 goto end;
3336 }
3337
3338 /* collect key */
3339 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3340 key->area[key->data] = '\0';
3341
3342 /* collect value */
3343 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3344 value->area[value->data] = '\0';
3345
3346 /* perform update */
3347 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3348 if (pat_ref_find_elt(ref, key->area) != NULL)
3349 /* update entry if it exists */
3350 pat_ref_set(ref, key->area, value->area, NULL);
3351 else
3352 /* insert a new entry */
3353 pat_ref_add(ref, key->area, value->area, NULL);
3354 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3355 free_trash_chunk(key);
3356 free_trash_chunk(value);
3357 break;
3358 }
3359
3360 case ACT_HTTP_REDIR:
3361 rule_ret = HTTP_RULE_RES_DONE;
3362 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3363 rule_ret = HTTP_RULE_RES_BADREQ;
3364 goto end;
3365
3366 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3367 /* Note: only the first valid tracking parameter of each
3368 * applies.
3369 */
3370 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3371 struct stktable *t;
3372 struct stksess *ts;
3373 struct stktable_key *key;
3374 void *ptr;
3375
3376 t = rule->arg.trk_ctr.table.t;
3377 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3378 rule->arg.trk_ctr.expr, NULL);
3379
3380 if (key && (ts = stktable_get_entry(t, key))) {
3381 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3382
3383 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3384
3385 /* let's count a new HTTP request as it's the first time we do it */
3386 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3387 if (ptr)
3388 stktable_data_cast(ptr, http_req_cnt)++;
3389
3390 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3391 if (ptr)
3392 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3393 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3394
3395 /* When the client triggers a 4xx from the server, it's most often due
3396 * to a missing object or permission. These events should be tracked
3397 * because if they happen often, it may indicate a brute force or a
3398 * vulnerability scan. Normally this is done when receiving the response
3399 * but here we're tracking after this ought to have been done so we have
3400 * to do it on purpose.
3401 */
3402 if ((unsigned)(txn->status - 400) < 100) {
3403 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3404 if (ptr)
3405 stktable_data_cast(ptr, http_err_cnt)++;
3406
3407 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3408 if (ptr)
3409 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3410 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3411 }
3412
3413 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3414
3415 /* If data was modified, we need to touch to re-schedule sync */
3416 stktable_touch_local(t, ts, 0);
3417
3418 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3419 if (sess->fe != s->be)
3420 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3421 }
3422 }
3423 break;
3424
3425 case ACT_CUSTOM:
3426 if ((s->req.flags & CF_READ_ERROR) ||
3427 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3428 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3429 (px->options & PR_O_ABRT_CLOSE)))
3430 act_flags |= ACT_FLAG_FINAL;
3431
3432 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3433 case ACT_RET_ERR:
3434 case ACT_RET_CONT:
3435 break;
3436 case ACT_RET_STOP:
3437 rule_ret = HTTP_RULE_RES_STOP;
3438 goto end;
3439 case ACT_RET_YIELD:
3440 s->current_rule = rule;
3441 rule_ret = HTTP_RULE_RES_YIELD;
3442 goto end;
3443 }
3444 break;
3445
3446 /* other flags exists, but normaly, they never be matched. */
3447 default:
3448 break;
3449 }
3450 }
3451
3452 end:
3453 /* we reached the end of the rules, nothing to report */
3454 return rule_ret;
3455}
3456
Christopher Faulet33640082018-10-24 11:53:01 +02003457/* Iterate the same filter through all request headers.
3458 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3459 * Since it can manage the switch to another backend, it updates the per-proxy
3460 * DENY stats.
3461 */
3462static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3463{
3464 struct http_txn *txn = s->txn;
3465 struct htx *htx;
3466 struct buffer *hdr = get_trash_chunk();
3467 int32_t pos;
3468
3469 htx = htx_from_buf(&req->buf);
3470
3471 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3472 struct htx_blk *blk = htx_get_blk(htx, pos);
3473 enum htx_blk_type type;
3474 struct ist n, v;
3475
3476 next_hdr:
3477 type = htx_get_blk_type(blk);
3478 if (type == HTX_BLK_EOH)
3479 break;
3480 if (type != HTX_BLK_HDR)
3481 continue;
3482
3483 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3484 return 1;
3485 else if (unlikely(txn->flags & TX_CLALLOW) &&
3486 (exp->action == ACT_ALLOW ||
3487 exp->action == ACT_DENY ||
3488 exp->action == ACT_TARPIT))
3489 return 0;
3490
3491 n = htx_get_blk_name(htx, blk);
3492 v = htx_get_blk_value(htx, blk);
3493
3494 chunk_memcat(hdr, n.ptr, n.len);
3495 hdr->area[hdr->data++] = ':';
3496 hdr->area[hdr->data++] = ' ';
3497 chunk_memcat(hdr, v.ptr, v.len);
3498
3499 /* Now we have one header in <hdr> */
3500
3501 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3502 struct http_hdr_ctx ctx;
3503 int len;
3504
3505 switch (exp->action) {
3506 case ACT_ALLOW:
3507 txn->flags |= TX_CLALLOW;
3508 goto end;
3509
3510 case ACT_DENY:
3511 txn->flags |= TX_CLDENY;
3512 goto end;
3513
3514 case ACT_TARPIT:
3515 txn->flags |= TX_CLTARPIT;
3516 goto end;
3517
3518 case ACT_REPLACE:
3519 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3520 if (len < 0)
3521 return -1;
3522
3523 http_parse_header(ist2(trash.area, len), &n, &v);
3524 ctx.blk = blk;
3525 ctx.value = v;
3526 if (!http_replace_header(htx, &ctx, n, v))
3527 return -1;
3528 if (!ctx.blk)
3529 goto end;
3530 pos = htx_get_blk_pos(htx, blk);
3531 break;
3532
3533 case ACT_REMOVE:
3534 ctx.blk = blk;
3535 ctx.value = v;
3536 if (!http_remove_header(htx, &ctx))
3537 return -1;
3538 if (!ctx.blk)
3539 goto end;
3540 pos = htx_get_blk_pos(htx, blk);
3541 goto next_hdr;
3542
3543 }
3544 }
3545 }
3546 end:
3547 return 0;
3548}
3549
3550/* Apply the filter to the request line.
3551 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3552 * or -1 if a replacement resulted in an invalid request line.
3553 * Since it can manage the switch to another backend, it updates the per-proxy
3554 * DENY stats.
3555 */
3556static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3557{
3558 struct http_txn *txn = s->txn;
3559 struct htx *htx;
3560 struct buffer *reqline = get_trash_chunk();
3561 int done;
3562
3563 htx = htx_from_buf(&req->buf);
3564
3565 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3566 return 1;
3567 else if (unlikely(txn->flags & TX_CLALLOW) &&
3568 (exp->action == ACT_ALLOW ||
3569 exp->action == ACT_DENY ||
3570 exp->action == ACT_TARPIT))
3571 return 0;
3572 else if (exp->action == ACT_REMOVE)
3573 return 0;
3574
3575 done = 0;
3576
3577 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3578
3579 /* Now we have the request line between cur_ptr and cur_end */
3580 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
3581 union h1_sl sl;
3582 int len;
3583
3584 switch (exp->action) {
3585 case ACT_ALLOW:
3586 txn->flags |= TX_CLALLOW;
3587 done = 1;
3588 break;
3589
3590 case ACT_DENY:
3591 txn->flags |= TX_CLDENY;
3592 done = 1;
3593 break;
3594
3595 case ACT_TARPIT:
3596 txn->flags |= TX_CLTARPIT;
3597 done = 1;
3598 break;
3599
3600 case ACT_REPLACE:
3601 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3602 if (len < 0)
3603 return -1;
3604
3605 http_parse_stline(ist2(trash.area, len),
3606 &sl.rq.m, &sl.rq.u, &sl.rq.v);
3607 sl.rq.meth = find_http_meth(sl.rq.m.ptr, sl.rq.m.len);
3608
3609 if (!http_replace_reqline(htx, sl))
3610 return -1;
3611 done = 1;
3612 break;
3613 }
3614 }
3615 return done;
3616}
3617
3618/*
3619 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3620 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3621 * unparsable request. Since it can manage the switch to another backend, it
3622 * updates the per-proxy DENY stats.
3623 */
3624static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3625{
3626 struct session *sess = s->sess;
3627 struct http_txn *txn = s->txn;
3628 struct hdr_exp *exp;
3629
3630 for (exp = px->req_exp; exp; exp = exp->next) {
3631 int ret;
3632
3633 /*
3634 * The interleaving of transformations and verdicts
3635 * makes it difficult to decide to continue or stop
3636 * the evaluation.
3637 */
3638
3639 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3640 break;
3641
3642 if ((txn->flags & TX_CLALLOW) &&
3643 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3644 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3645 continue;
3646
3647 /* if this filter had a condition, evaluate it now and skip to
3648 * next filter if the condition does not match.
3649 */
3650 if (exp->cond) {
3651 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3652 ret = acl_pass(ret);
3653 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3654 ret = !ret;
3655
3656 if (!ret)
3657 continue;
3658 }
3659
3660 /* Apply the filter to the request line. */
3661 ret = htx_apply_filter_to_req_line(s, req, exp);
3662 if (unlikely(ret < 0))
3663 return -1;
3664
3665 if (likely(ret == 0)) {
3666 /* The filter did not match the request, it can be
3667 * iterated through all headers.
3668 */
3669 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3670 return -1;
3671 }
3672 }
3673 return 0;
3674}
3675
3676/* Iterate the same filter through all response headers contained in <res>.
3677 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3678 */
3679static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3680{
3681 struct http_txn *txn = s->txn;
3682 struct htx *htx;
3683 struct buffer *hdr = get_trash_chunk();
3684 int32_t pos;
3685
3686 htx = htx_from_buf(&res->buf);
3687
3688 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3689 struct htx_blk *blk = htx_get_blk(htx, pos);
3690 enum htx_blk_type type;
3691 struct ist n, v;
3692
3693 next_hdr:
3694 type = htx_get_blk_type(blk);
3695 if (type == HTX_BLK_EOH)
3696 break;
3697 if (type != HTX_BLK_HDR)
3698 continue;
3699
3700 if (unlikely(txn->flags & TX_SVDENY))
3701 return 1;
3702 else if (unlikely(txn->flags & TX_SVALLOW) &&
3703 (exp->action == ACT_ALLOW ||
3704 exp->action == ACT_DENY))
3705 return 0;
3706
3707 n = htx_get_blk_name(htx, blk);
3708 v = htx_get_blk_value(htx, blk);
3709
3710 chunk_memcat(hdr, n.ptr, n.len);
3711 hdr->area[hdr->data++] = ':';
3712 hdr->area[hdr->data++] = ' ';
3713 chunk_memcat(hdr, v.ptr, v.len);
3714
3715 /* Now we have one header in <hdr> */
3716
3717 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3718 struct http_hdr_ctx ctx;
3719 int len;
3720
3721 switch (exp->action) {
3722 case ACT_ALLOW:
3723 txn->flags |= TX_SVALLOW;
3724 goto end;
3725 break;
3726
3727 case ACT_DENY:
3728 txn->flags |= TX_SVDENY;
3729 goto end;
3730 break;
3731
3732 case ACT_REPLACE:
3733 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3734 if (len < 0)
3735 return -1;
3736
3737 http_parse_header(ist2(trash.area, len), &n, &v);
3738 ctx.blk = blk;
3739 ctx.value = v;
3740 if (!http_replace_header(htx, &ctx, n, v))
3741 return -1;
3742 if (!ctx.blk)
3743 goto end;
3744 pos = htx_get_blk_pos(htx, blk);
3745 break;
3746
3747 case ACT_REMOVE:
3748 ctx.blk = blk;
3749 ctx.value = v;
3750 if (!http_remove_header(htx, &ctx))
3751 return -1;
3752 if (!ctx.blk)
3753 goto end;
3754 pos = htx_get_blk_pos(htx, blk);
3755 goto next_hdr;
3756 }
3757 }
3758
3759 }
3760 end:
3761 return 0;
3762}
3763
3764/* Apply the filter to the status line in the response buffer <res>.
3765 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3766 * or -1 if a replacement resulted in an invalid status line.
3767 */
3768static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3769{
3770 struct http_txn *txn = s->txn;
3771 struct htx *htx;
3772 struct buffer *resline = get_trash_chunk();
3773 int done;
3774
3775 htx = htx_from_buf(&res->buf);
3776
3777 if (unlikely(txn->flags & TX_SVDENY))
3778 return 1;
3779 else if (unlikely(txn->flags & TX_SVALLOW) &&
3780 (exp->action == ACT_ALLOW ||
3781 exp->action == ACT_DENY))
3782 return 0;
3783 else if (exp->action == ACT_REMOVE)
3784 return 0;
3785
3786 done = 0;
3787 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3788
3789 /* Now we have the status line between cur_ptr and cur_end */
3790 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
3791 union h1_sl sl;
3792 int len;
3793
3794 switch (exp->action) {
3795 case ACT_ALLOW:
3796 txn->flags |= TX_SVALLOW;
3797 done = 1;
3798 break;
3799
3800 case ACT_DENY:
3801 txn->flags |= TX_SVDENY;
3802 done = 1;
3803 break;
3804
3805 case ACT_REPLACE:
3806 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3807 if (len < 0)
3808 return -1;
3809
3810 http_parse_stline(ist2(trash.area, len),
3811 &sl.st.v, &sl.st.c, &sl.st.r);
3812 sl.st.status = strl2ui(sl.st.c.ptr, sl.st.c.len);
3813
3814 if (!http_replace_resline(htx, sl))
3815 return -1;
3816
3817 done = 1;
3818 return 1;
3819 }
3820 }
3821 return done;
3822}
3823
3824/*
3825 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3826 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3827 * unparsable response.
3828 */
3829static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3830{
3831 struct session *sess = s->sess;
3832 struct http_txn *txn = s->txn;
3833 struct hdr_exp *exp;
3834
3835 for (exp = px->rsp_exp; exp; exp = exp->next) {
3836 int ret;
3837
3838 /*
3839 * The interleaving of transformations and verdicts
3840 * makes it difficult to decide to continue or stop
3841 * the evaluation.
3842 */
3843
3844 if (txn->flags & TX_SVDENY)
3845 break;
3846
3847 if ((txn->flags & TX_SVALLOW) &&
3848 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3849 exp->action == ACT_PASS)) {
3850 exp = exp->next;
3851 continue;
3852 }
3853
3854 /* if this filter had a condition, evaluate it now and skip to
3855 * next filter if the condition does not match.
3856 */
3857 if (exp->cond) {
3858 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3859 ret = acl_pass(ret);
3860 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3861 ret = !ret;
3862 if (!ret)
3863 continue;
3864 }
3865
3866 /* Apply the filter to the status line. */
3867 ret = htx_apply_filter_to_sts_line(s, res, exp);
3868 if (unlikely(ret < 0))
3869 return -1;
3870
3871 if (likely(ret == 0)) {
3872 /* The filter did not match the response, it can be
3873 * iterated through all headers.
3874 */
3875 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3876 return -1;
3877 }
3878 }
3879 return 0;
3880}
3881
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003882/*
3883 * Manage client-side cookie. It can impact performance by about 2% so it is
3884 * desirable to call it only when needed. This code is quite complex because
3885 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3886 * highly recommended not to touch this part without a good reason !
3887 */
3888static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3889{
3890 struct session *sess = s->sess;
3891 struct http_txn *txn = s->txn;
3892 struct htx *htx;
3893 struct http_hdr_ctx ctx;
3894 char *hdr_beg, *hdr_end, *del_from;
3895 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3896 int preserve_hdr;
3897
3898 htx = htx_from_buf(&req->buf);
3899 ctx.blk = NULL;
3900 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3901 del_from = NULL; /* nothing to be deleted */
3902 preserve_hdr = 0; /* assume we may kill the whole header */
3903
3904 /* Now look for cookies. Conforming to RFC2109, we have to support
3905 * attributes whose name begin with a '$', and associate them with
3906 * the right cookie, if we want to delete this cookie.
3907 * So there are 3 cases for each cookie read :
3908 * 1) it's a special attribute, beginning with a '$' : ignore it.
3909 * 2) it's a server id cookie that we *MAY* want to delete : save
3910 * some pointers on it (last semi-colon, beginning of cookie...)
3911 * 3) it's an application cookie : we *MAY* have to delete a previous
3912 * "special" cookie.
3913 * At the end of loop, if a "special" cookie remains, we may have to
3914 * remove it. If no application cookie persists in the header, we
3915 * *MUST* delete it.
3916 *
3917 * Note: RFC2965 is unclear about the processing of spaces around
3918 * the equal sign in the ATTR=VALUE form. A careful inspection of
3919 * the RFC explicitly allows spaces before it, and not within the
3920 * tokens (attrs or values). An inspection of RFC2109 allows that
3921 * too but section 10.1.3 lets one think that spaces may be allowed
3922 * after the equal sign too, resulting in some (rare) buggy
3923 * implementations trying to do that. So let's do what servers do.
3924 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3925 * allowed quoted strings in values, with any possible character
3926 * after a backslash, including control chars and delimitors, which
3927 * causes parsing to become ambiguous. Browsers also allow spaces
3928 * within values even without quotes.
3929 *
3930 * We have to keep multiple pointers in order to support cookie
3931 * removal at the beginning, middle or end of header without
3932 * corrupting the header. All of these headers are valid :
3933 *
3934 * hdr_beg hdr_end
3935 * | |
3936 * v |
3937 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3938 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3939 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3940 * | | | | | | |
3941 * | | | | | | |
3942 * | | | | | | +--> next
3943 * | | | | | +----> val_end
3944 * | | | | +-----------> val_beg
3945 * | | | +--------------> equal
3946 * | | +----------------> att_end
3947 * | +---------------------> att_beg
3948 * +--------------------------> prev
3949 *
3950 */
3951 hdr_beg = ctx.value.ptr;
3952 hdr_end = hdr_beg + ctx.value.len;
3953 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3954 /* Iterate through all cookies on this line */
3955
3956 /* find att_beg */
3957 att_beg = prev;
3958 if (prev > hdr_beg)
3959 att_beg++;
3960
3961 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3962 att_beg++;
3963
3964 /* find att_end : this is the first character after the last non
3965 * space before the equal. It may be equal to hdr_end.
3966 */
3967 equal = att_end = att_beg;
3968 while (equal < hdr_end) {
3969 if (*equal == '=' || *equal == ',' || *equal == ';')
3970 break;
3971 if (HTTP_IS_SPHT(*equal++))
3972 continue;
3973 att_end = equal;
3974 }
3975
3976 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3977 * is between <att_beg> and <equal>, both may be identical.
3978 */
3979 /* look for end of cookie if there is an equal sign */
3980 if (equal < hdr_end && *equal == '=') {
3981 /* look for the beginning of the value */
3982 val_beg = equal + 1;
3983 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3984 val_beg++;
3985
3986 /* find the end of the value, respecting quotes */
3987 next = http_find_cookie_value_end(val_beg, hdr_end);
3988
3989 /* make val_end point to the first white space or delimitor after the value */
3990 val_end = next;
3991 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3992 val_end--;
3993 }
3994 else
3995 val_beg = val_end = next = equal;
3996
3997 /* We have nothing to do with attributes beginning with
3998 * '$'. However, they will automatically be removed if a
3999 * header before them is removed, since they're supposed
4000 * to be linked together.
4001 */
4002 if (*att_beg == '$')
4003 continue;
4004
4005 /* Ignore cookies with no equal sign */
4006 if (equal == next) {
4007 /* This is not our cookie, so we must preserve it. But if we already
4008 * scheduled another cookie for removal, we cannot remove the
4009 * complete header, but we can remove the previous block itself.
4010 */
4011 preserve_hdr = 1;
4012 if (del_from != NULL) {
4013 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4014 val_end += delta;
4015 next += delta;
4016 hdr_end += delta;
4017 prev = del_from;
4018 del_from = NULL;
4019 }
4020 continue;
4021 }
4022
4023 /* if there are spaces around the equal sign, we need to
4024 * strip them otherwise we'll get trouble for cookie captures,
4025 * or even for rewrites. Since this happens extremely rarely,
4026 * it does not hurt performance.
4027 */
4028 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4029 int stripped_before = 0;
4030 int stripped_after = 0;
4031
4032 if (att_end != equal) {
4033 memmove(att_end, equal, hdr_end - equal);
4034 stripped_before = (att_end - equal);
4035 equal += stripped_before;
4036 val_beg += stripped_before;
4037 }
4038
4039 if (val_beg > equal + 1) {
4040 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4041 stripped_after = (equal + 1) - val_beg;
4042 val_beg += stripped_after;
4043 stripped_before += stripped_after;
4044 }
4045
4046 val_end += stripped_before;
4047 next += stripped_before;
4048 hdr_end += stripped_before;
4049 }
4050 /* now everything is as on the diagram above */
4051
4052 /* First, let's see if we want to capture this cookie. We check
4053 * that we don't already have a client side cookie, because we
4054 * can only capture one. Also as an optimisation, we ignore
4055 * cookies shorter than the declared name.
4056 */
4057 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4058 (val_end - att_beg >= sess->fe->capture_namelen) &&
4059 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4060 int log_len = val_end - att_beg;
4061
4062 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4063 ha_alert("HTTP logging : out of memory.\n");
4064 } else {
4065 if (log_len > sess->fe->capture_len)
4066 log_len = sess->fe->capture_len;
4067 memcpy(txn->cli_cookie, att_beg, log_len);
4068 txn->cli_cookie[log_len] = 0;
4069 }
4070 }
4071
4072 /* Persistence cookies in passive, rewrite or insert mode have the
4073 * following form :
4074 *
4075 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4076 *
4077 * For cookies in prefix mode, the form is :
4078 *
4079 * Cookie: NAME=SRV~VALUE
4080 */
4081 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4082 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4083 struct server *srv = s->be->srv;
4084 char *delim;
4085
4086 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4087 * have the server ID between val_beg and delim, and the original cookie between
4088 * delim+1 and val_end. Otherwise, delim==val_end :
4089 *
4090 * hdr_beg
4091 * |
4092 * v
4093 * NAME=SRV; # in all but prefix modes
4094 * NAME=SRV~OPAQUE ; # in prefix mode
4095 * || || | |+-> next
4096 * || || | +--> val_end
4097 * || || +---------> delim
4098 * || |+------------> val_beg
4099 * || +-------------> att_end = equal
4100 * |+-----------------> att_beg
4101 * +------------------> prev
4102 *
4103 */
4104 if (s->be->ck_opts & PR_CK_PFX) {
4105 for (delim = val_beg; delim < val_end; delim++)
4106 if (*delim == COOKIE_DELIM)
4107 break;
4108 }
4109 else {
4110 char *vbar1;
4111 delim = val_end;
4112 /* Now check if the cookie contains a date field, which would
4113 * appear after a vertical bar ('|') just after the server name
4114 * and before the delimiter.
4115 */
4116 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4117 if (vbar1) {
4118 /* OK, so left of the bar is the server's cookie and
4119 * right is the last seen date. It is a base64 encoded
4120 * 30-bit value representing the UNIX date since the
4121 * epoch in 4-second quantities.
4122 */
4123 int val;
4124 delim = vbar1++;
4125 if (val_end - vbar1 >= 5) {
4126 val = b64tos30(vbar1);
4127 if (val > 0)
4128 txn->cookie_last_date = val << 2;
4129 }
4130 /* look for a second vertical bar */
4131 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4132 if (vbar1 && (val_end - vbar1 > 5)) {
4133 val = b64tos30(vbar1 + 1);
4134 if (val > 0)
4135 txn->cookie_first_date = val << 2;
4136 }
4137 }
4138 }
4139
4140 /* if the cookie has an expiration date and the proxy wants to check
4141 * it, then we do that now. We first check if the cookie is too old,
4142 * then only if it has expired. We detect strict overflow because the
4143 * time resolution here is not great (4 seconds). Cookies with dates
4144 * in the future are ignored if their offset is beyond one day. This
4145 * allows an admin to fix timezone issues without expiring everyone
4146 * and at the same time avoids keeping unwanted side effects for too
4147 * long.
4148 */
4149 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4150 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4151 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4152 txn->flags &= ~TX_CK_MASK;
4153 txn->flags |= TX_CK_OLD;
4154 delim = val_beg; // let's pretend we have not found the cookie
4155 txn->cookie_first_date = 0;
4156 txn->cookie_last_date = 0;
4157 }
4158 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4159 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4160 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4161 txn->flags &= ~TX_CK_MASK;
4162 txn->flags |= TX_CK_EXPIRED;
4163 delim = val_beg; // let's pretend we have not found the cookie
4164 txn->cookie_first_date = 0;
4165 txn->cookie_last_date = 0;
4166 }
4167
4168 /* Here, we'll look for the first running server which supports the cookie.
4169 * This allows to share a same cookie between several servers, for example
4170 * to dedicate backup servers to specific servers only.
4171 * However, to prevent clients from sticking to cookie-less backup server
4172 * when they have incidentely learned an empty cookie, we simply ignore
4173 * empty cookies and mark them as invalid.
4174 * The same behaviour is applied when persistence must be ignored.
4175 */
4176 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4177 srv = NULL;
4178
4179 while (srv) {
4180 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4181 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4182 if ((srv->cur_state != SRV_ST_STOPPED) ||
4183 (s->be->options & PR_O_PERSIST) ||
4184 (s->flags & SF_FORCE_PRST)) {
4185 /* we found the server and we can use it */
4186 txn->flags &= ~TX_CK_MASK;
4187 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4188 s->flags |= SF_DIRECT | SF_ASSIGNED;
4189 s->target = &srv->obj_type;
4190 break;
4191 } else {
4192 /* we found a server, but it's down,
4193 * mark it as such and go on in case
4194 * another one is available.
4195 */
4196 txn->flags &= ~TX_CK_MASK;
4197 txn->flags |= TX_CK_DOWN;
4198 }
4199 }
4200 srv = srv->next;
4201 }
4202
4203 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4204 /* no server matched this cookie or we deliberately skipped it */
4205 txn->flags &= ~TX_CK_MASK;
4206 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4207 txn->flags |= TX_CK_UNUSED;
4208 else
4209 txn->flags |= TX_CK_INVALID;
4210 }
4211
4212 /* depending on the cookie mode, we may have to either :
4213 * - delete the complete cookie if we're in insert+indirect mode, so that
4214 * the server never sees it ;
4215 * - remove the server id from the cookie value, and tag the cookie as an
4216 * application cookie so that it does not get accidentely removed later,
4217 * if we're in cookie prefix mode
4218 */
4219 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4220 int delta; /* negative */
4221
4222 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4223 delta = val_beg - (delim + 1);
4224 val_end += delta;
4225 next += delta;
4226 hdr_end += delta;
4227 del_from = NULL;
4228 preserve_hdr = 1; /* we want to keep this cookie */
4229 }
4230 else if (del_from == NULL &&
4231 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4232 del_from = prev;
4233 }
4234 }
4235 else {
4236 /* This is not our cookie, so we must preserve it. But if we already
4237 * scheduled another cookie for removal, we cannot remove the
4238 * complete header, but we can remove the previous block itself.
4239 */
4240 preserve_hdr = 1;
4241
4242 if (del_from != NULL) {
4243 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4244 if (att_beg >= del_from)
4245 att_beg += delta;
4246 if (att_end >= del_from)
4247 att_end += delta;
4248 val_beg += delta;
4249 val_end += delta;
4250 next += delta;
4251 hdr_end += delta;
4252 prev = del_from;
4253 del_from = NULL;
4254 }
4255 }
4256
4257 /* continue with next cookie on this header line */
4258 att_beg = next;
4259 } /* for each cookie */
4260
4261
4262 /* There are no more cookies on this line.
4263 * We may still have one (or several) marked for deletion at the
4264 * end of the line. We must do this now in two ways :
4265 * - if some cookies must be preserved, we only delete from the
4266 * mark to the end of line ;
4267 * - if nothing needs to be preserved, simply delete the whole header
4268 */
4269 if (del_from) {
4270 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4271 }
4272 if ((hdr_end - hdr_beg) != ctx.value.len) {
4273 if (hdr_beg != hdr_end) {
4274 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4275 htx->data -= (hdr_end - ctx.value.ptr);
4276 }
4277 else
4278 http_remove_header(htx, &ctx);
4279 }
4280 } /* for each "Cookie header */
4281}
4282
4283/*
4284 * Manage server-side cookies. It can impact performance by about 2% so it is
4285 * desirable to call it only when needed. This function is also used when we
4286 * just need to know if there is a cookie (eg: for check-cache).
4287 */
4288static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4289{
4290 struct session *sess = s->sess;
4291 struct http_txn *txn = s->txn;
4292 struct htx *htx;
4293 struct http_hdr_ctx ctx;
4294 struct server *srv;
4295 char *hdr_beg, *hdr_end;
4296 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4297 int is_cookie2;
4298
4299 htx = htx_from_buf(&res->buf);
4300
4301 ctx.blk = NULL;
4302 while (1) {
4303 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4304 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4305 break;
4306 is_cookie2 = 1;
4307 }
4308
4309 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4310 * <prev> points to the colon.
4311 */
4312 txn->flags |= TX_SCK_PRESENT;
4313
4314 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4315 * check-cache is enabled) and we are not interested in checking
4316 * them. Warning, the cookie capture is declared in the frontend.
4317 */
4318 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4319 break;
4320
4321 /* OK so now we know we have to process this response cookie.
4322 * The format of the Set-Cookie header is slightly different
4323 * from the format of the Cookie header in that it does not
4324 * support the comma as a cookie delimiter (thus the header
4325 * cannot be folded) because the Expires attribute described in
4326 * the original Netscape's spec may contain an unquoted date
4327 * with a comma inside. We have to live with this because
4328 * many browsers don't support Max-Age and some browsers don't
4329 * support quoted strings. However the Set-Cookie2 header is
4330 * clean.
4331 *
4332 * We have to keep multiple pointers in order to support cookie
4333 * removal at the beginning, middle or end of header without
4334 * corrupting the header (in case of set-cookie2). A special
4335 * pointer, <scav> points to the beginning of the set-cookie-av
4336 * fields after the first semi-colon. The <next> pointer points
4337 * either to the end of line (set-cookie) or next unquoted comma
4338 * (set-cookie2). All of these headers are valid :
4339 *
4340 * hdr_beg hdr_end
4341 * | |
4342 * v |
4343 * NAME1 = VALUE 1 ; Secure; Path="/" |
4344 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4345 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4346 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4347 * | | | | | | | |
4348 * | | | | | | | +-> next
4349 * | | | | | | +------------> scav
4350 * | | | | | +--------------> val_end
4351 * | | | | +--------------------> val_beg
4352 * | | | +----------------------> equal
4353 * | | +------------------------> att_end
4354 * | +----------------------------> att_beg
4355 * +------------------------------> prev
4356 * -------------------------------> hdr_beg
4357 */
4358 hdr_beg = ctx.value.ptr;
4359 hdr_end = hdr_beg + ctx.value.len;
4360 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4361
4362 /* Iterate through all cookies on this line */
4363
4364 /* find att_beg */
4365 att_beg = prev;
4366 if (prev > hdr_beg)
4367 att_beg++;
4368
4369 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4370 att_beg++;
4371
4372 /* find att_end : this is the first character after the last non
4373 * space before the equal. It may be equal to hdr_end.
4374 */
4375 equal = att_end = att_beg;
4376
4377 while (equal < hdr_end) {
4378 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4379 break;
4380 if (HTTP_IS_SPHT(*equal++))
4381 continue;
4382 att_end = equal;
4383 }
4384
4385 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4386 * is between <att_beg> and <equal>, both may be identical.
4387 */
4388
4389 /* look for end of cookie if there is an equal sign */
4390 if (equal < hdr_end && *equal == '=') {
4391 /* look for the beginning of the value */
4392 val_beg = equal + 1;
4393 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4394 val_beg++;
4395
4396 /* find the end of the value, respecting quotes */
4397 next = http_find_cookie_value_end(val_beg, hdr_end);
4398
4399 /* make val_end point to the first white space or delimitor after the value */
4400 val_end = next;
4401 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4402 val_end--;
4403 }
4404 else {
4405 /* <equal> points to next comma, semi-colon or EOL */
4406 val_beg = val_end = next = equal;
4407 }
4408
4409 if (next < hdr_end) {
4410 /* Set-Cookie2 supports multiple cookies, and <next> points to
4411 * a colon or semi-colon before the end. So skip all attr-value
4412 * pairs and look for the next comma. For Set-Cookie, since
4413 * commas are permitted in values, skip to the end.
4414 */
4415 if (is_cookie2)
4416 next = http_find_hdr_value_end(next, hdr_end);
4417 else
4418 next = hdr_end;
4419 }
4420
4421 /* Now everything is as on the diagram above */
4422
4423 /* Ignore cookies with no equal sign */
4424 if (equal == val_end)
4425 continue;
4426
4427 /* If there are spaces around the equal sign, we need to
4428 * strip them otherwise we'll get trouble for cookie captures,
4429 * or even for rewrites. Since this happens extremely rarely,
4430 * it does not hurt performance.
4431 */
4432 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4433 int stripped_before = 0;
4434 int stripped_after = 0;
4435
4436 if (att_end != equal) {
4437 memmove(att_end, equal, hdr_end - equal);
4438 stripped_before = (att_end - equal);
4439 equal += stripped_before;
4440 val_beg += stripped_before;
4441 }
4442
4443 if (val_beg > equal + 1) {
4444 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4445 stripped_after = (equal + 1) - val_beg;
4446 val_beg += stripped_after;
4447 stripped_before += stripped_after;
4448 }
4449
4450 val_end += stripped_before;
4451 next += stripped_before;
4452 hdr_end += stripped_before;
4453
4454 ctx.value.len = hdr_end - hdr_beg;
4455 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4456 htx->data -= (hdr_end - ctx.value.ptr);
4457 }
4458
4459 /* First, let's see if we want to capture this cookie. We check
4460 * that we don't already have a server side cookie, because we
4461 * can only capture one. Also as an optimisation, we ignore
4462 * cookies shorter than the declared name.
4463 */
4464 if (sess->fe->capture_name != NULL &&
4465 txn->srv_cookie == NULL &&
4466 (val_end - att_beg >= sess->fe->capture_namelen) &&
4467 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4468 int log_len = val_end - att_beg;
4469 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4470 ha_alert("HTTP logging : out of memory.\n");
4471 }
4472 else {
4473 if (log_len > sess->fe->capture_len)
4474 log_len = sess->fe->capture_len;
4475 memcpy(txn->srv_cookie, att_beg, log_len);
4476 txn->srv_cookie[log_len] = 0;
4477 }
4478 }
4479
4480 srv = objt_server(s->target);
4481 /* now check if we need to process it for persistence */
4482 if (!(s->flags & SF_IGNORE_PRST) &&
4483 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4484 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4485 /* assume passive cookie by default */
4486 txn->flags &= ~TX_SCK_MASK;
4487 txn->flags |= TX_SCK_FOUND;
4488
4489 /* If the cookie is in insert mode on a known server, we'll delete
4490 * this occurrence because we'll insert another one later.
4491 * We'll delete it too if the "indirect" option is set and we're in
4492 * a direct access.
4493 */
4494 if (s->be->ck_opts & PR_CK_PSV) {
4495 /* The "preserve" flag was set, we don't want to touch the
4496 * server's cookie.
4497 */
4498 }
4499 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4500 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4501 /* this cookie must be deleted */
4502 if (prev == hdr_beg && next == hdr_end) {
4503 /* whole header */
4504 http_remove_header(htx, &ctx);
4505 /* note: while both invalid now, <next> and <hdr_end>
4506 * are still equal, so the for() will stop as expected.
4507 */
4508 } else {
4509 /* just remove the value */
4510 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4511 next = prev;
4512 hdr_end += delta;
4513 }
4514 txn->flags &= ~TX_SCK_MASK;
4515 txn->flags |= TX_SCK_DELETED;
4516 /* and go on with next cookie */
4517 }
4518 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4519 /* replace bytes val_beg->val_end with the cookie name associated
4520 * with this server since we know it.
4521 */
4522 int sliding, delta;
4523
4524 ctx.value = ist2(val_beg, val_end - val_beg);
4525 ctx.lws_before = ctx.lws_after = 0;
4526 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4527 delta = srv->cklen - (val_end - val_beg);
4528 sliding = (ctx.value.ptr - val_beg);
4529 hdr_beg += sliding;
4530 val_beg += sliding;
4531 next += sliding + delta;
4532 hdr_end += sliding + delta;
4533
4534 txn->flags &= ~TX_SCK_MASK;
4535 txn->flags |= TX_SCK_REPLACED;
4536 }
4537 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4538 /* insert the cookie name associated with this server
4539 * before existing cookie, and insert a delimiter between them..
4540 */
4541 int sliding, delta;
4542 ctx.value = ist2(val_beg, 0);
4543 ctx.lws_before = ctx.lws_after = 0;
4544 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4545 delta = srv->cklen + 1;
4546 sliding = (ctx.value.ptr - val_beg);
4547 hdr_beg += sliding;
4548 val_beg += sliding;
4549 next += sliding + delta;
4550 hdr_end += sliding + delta;
4551
4552 val_beg[srv->cklen] = COOKIE_DELIM;
4553 txn->flags &= ~TX_SCK_MASK;
4554 txn->flags |= TX_SCK_REPLACED;
4555 }
4556 }
4557 /* that's done for this cookie, check the next one on the same
4558 * line when next != hdr_end (only if is_cookie2).
4559 */
4560 }
4561 }
4562}
4563
Christopher Faulet25a02f62018-10-24 12:00:25 +02004564/*
4565 * Parses the Cache-Control and Pragma request header fields to determine if
4566 * the request may be served from the cache and/or if it is cacheable. Updates
4567 * s->txn->flags.
4568 */
4569void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4570{
4571 struct http_txn *txn = s->txn;
4572 struct htx *htx;
4573 int32_t pos;
4574 int pragma_found, cc_found, i;
4575
4576 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4577 return; /* nothing more to do here */
4578
4579 htx = htx_from_buf(&req->buf);
4580 pragma_found = cc_found = 0;
4581 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4582 struct htx_blk *blk = htx_get_blk(htx, pos);
4583 enum htx_blk_type type = htx_get_blk_type(blk);
4584 struct ist n, v;
4585
4586 if (type == HTX_BLK_EOH)
4587 break;
4588 if (type != HTX_BLK_HDR)
4589 continue;
4590
4591 n = htx_get_blk_name(htx, blk);
4592 v = htx_get_blk_value(htx, blk);
4593
4594 if (isteqi(n, ist("Pragma"))) {
4595 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4596 pragma_found = 1;
4597 continue;
4598 }
4599 }
4600
4601 /* Don't use the cache and don't try to store if we found the
4602 * Authorization header */
4603 if (isteqi(n, ist("Authorization"))) {
4604 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4605 txn->flags |= TX_CACHE_IGNORE;
4606 continue;
4607 }
4608
4609 if (!isteqi(n, ist("Cache-control")))
4610 continue;
4611
4612 /* OK, right now we know we have a cache-control header */
4613 cc_found = 1;
4614 if (!v.len) /* no info */
4615 continue;
4616
4617 i = 0;
4618 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4619 !isspace((unsigned char)*(v.ptr+i)))
4620 i++;
4621
4622 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4623 * values after max-age, max-stale nor min-fresh, we simply don't
4624 * use the cache when they're specified.
4625 */
4626 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4627 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4628 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4629 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4630 txn->flags |= TX_CACHE_IGNORE;
4631 continue;
4632 }
4633
4634 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4635 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4636 continue;
4637 }
4638 }
4639
4640 /* RFC7234#5.4:
4641 * When the Cache-Control header field is also present and
4642 * understood in a request, Pragma is ignored.
4643 * When the Cache-Control header field is not present in a
4644 * request, caches MUST consider the no-cache request
4645 * pragma-directive as having the same effect as if
4646 * "Cache-Control: no-cache" were present.
4647 */
4648 if (!cc_found && pragma_found)
4649 txn->flags |= TX_CACHE_IGNORE;
4650}
4651
4652/*
4653 * Check if response is cacheable or not. Updates s->txn->flags.
4654 */
4655void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4656{
4657 struct http_txn *txn = s->txn;
4658 struct htx *htx;
4659 int32_t pos;
4660 int i;
4661
4662 if (txn->status < 200) {
4663 /* do not try to cache interim responses! */
4664 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4665 return;
4666 }
4667
4668 htx = htx_from_buf(&res->buf);
4669 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4670 struct htx_blk *blk = htx_get_blk(htx, pos);
4671 enum htx_blk_type type = htx_get_blk_type(blk);
4672 struct ist n, v;
4673
4674 if (type == HTX_BLK_EOH)
4675 break;
4676 if (type != HTX_BLK_HDR)
4677 continue;
4678
4679 n = htx_get_blk_name(htx, blk);
4680 v = htx_get_blk_value(htx, blk);
4681
4682 if (isteqi(n, ist("Pragma"))) {
4683 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4684 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4685 return;
4686 }
4687 }
4688
4689 if (!isteqi(n, ist("Cache-control")))
4690 continue;
4691
4692 /* OK, right now we know we have a cache-control header */
4693 if (!v.len) /* no info */
4694 continue;
4695
4696 i = 0;
4697 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4698 !isspace((unsigned char)*(v.ptr+i)))
4699 i++;
4700
4701 /* we have a complete value between v.ptr and (v.ptr+i) */
4702 if (i < v.len && *(v.ptr + i) == '=') {
4703 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4704 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4705 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4706 continue;
4707 }
4708
4709 /* we have something of the form no-cache="set-cookie" */
4710 if ((v.len >= 21) &&
4711 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4712 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4713 txn->flags &= ~TX_CACHE_COOK;
4714 continue;
4715 }
4716
4717 /* OK, so we know that either p2 points to the end of string or to a comma */
4718 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4719 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4720 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4721 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4722 return;
4723 }
4724
4725 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4726 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4727 continue;
4728 }
4729 }
4730}
4731
Christopher Faulet64159df2018-10-24 21:15:35 +02004732/* send a server's name with an outgoing request over an established connection.
4733 * Note: this function is designed to be called once the request has been
4734 * scheduled for being forwarded. This is the reason why the number of forwarded
4735 * bytes have to be adjusted.
4736 */
4737int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4738{
4739 struct htx *htx;
4740 struct http_hdr_ctx ctx;
4741 struct ist hdr;
4742 uint32_t data;
4743
4744 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
4745 htx = htx_from_buf(&s->req.buf);
4746 data = htx->data;
4747
4748 ctx.blk = NULL;
4749 while (http_find_header(htx, hdr, &ctx, 1))
4750 http_remove_header(htx, &ctx);
4751 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4752
4753 if (co_data(&s->req)) {
4754 if (data >= htx->data)
4755 c_rew(&s->req, data - htx->data);
4756 else
4757 c_adv(&s->req, htx->data - data);
4758 }
4759 return 0;
4760}
4761
Christopher Faulet377c5a52018-10-24 21:21:30 +02004762/*
4763 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4764 * for the current backend.
4765 *
4766 * It is assumed that the request is either a HEAD, GET, or POST and that the
4767 * uri_auth field is valid.
4768 *
4769 * Returns 1 if stats should be provided, otherwise 0.
4770 */
4771static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4772{
4773 struct uri_auth *uri_auth = backend->uri_auth;
4774 struct htx *htx;
4775 struct ist uri;
4776 union h1_sl sl;
4777
4778 if (!uri_auth)
4779 return 0;
4780
4781 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4782 return 0;
4783
4784 htx = htx_from_buf(&s->req.buf);
4785 sl = http_find_stline(htx);
4786 uri = sl.rq.u;
4787
4788 /* check URI size */
4789 if (uri_auth->uri_len > uri.len)
4790 return 0;
4791
4792 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4793 return 0;
4794
4795 return 1;
4796}
4797
4798/* This function prepares an applet to handle the stats. It can deal with the
4799 * "100-continue" expectation, check that admin rules are met for POST requests,
4800 * and program a response message if something was unexpected. It cannot fail
4801 * and always relies on the stats applet to complete the job. It does not touch
4802 * analysers nor counters, which are left to the caller. It does not touch
4803 * s->target which is supposed to already point to the stats applet. The caller
4804 * is expected to have already assigned an appctx to the stream.
4805 */
4806static int htx_handle_stats(struct stream *s, struct channel *req)
4807{
4808 struct stats_admin_rule *stats_admin_rule;
4809 struct stream_interface *si = &s->si[1];
4810 struct session *sess = s->sess;
4811 struct http_txn *txn = s->txn;
4812 struct http_msg *msg = &txn->req;
4813 struct uri_auth *uri_auth = s->be->uri_auth;
4814 const char *h, *lookup, *end;
4815 struct appctx *appctx;
4816 struct htx *htx;
4817 union h1_sl sl;
4818
4819 appctx = si_appctx(si);
4820 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4821 appctx->st1 = appctx->st2 = 0;
4822 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4823 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4824 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4825 appctx->ctx.stats.flags |= STAT_CHUNKED;
4826
4827 htx = htx_from_buf(&req->buf);
4828 sl = http_find_stline(htx);
4829 lookup = sl.rq.u.ptr + uri_auth->uri_len;
4830 end = sl.rq.u.ptr + sl.rq.u.len;
4831
4832 for (h = lookup; h <= end - 3; h++) {
4833 if (memcmp(h, ";up", 3) == 0) {
4834 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4835 break;
4836 }
4837 }
4838
4839 if (uri_auth->refresh) {
4840 for (h = lookup; h <= end - 10; h++) {
4841 if (memcmp(h, ";norefresh", 10) == 0) {
4842 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4843 break;
4844 }
4845 }
4846 }
4847
4848 for (h = lookup; h <= end - 4; h++) {
4849 if (memcmp(h, ";csv", 4) == 0) {
4850 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4851 break;
4852 }
4853 }
4854
4855 for (h = lookup; h <= end - 6; h++) {
4856 if (memcmp(h, ";typed", 6) == 0) {
4857 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4858 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4859 break;
4860 }
4861 }
4862
4863 for (h = lookup; h <= end - 8; h++) {
4864 if (memcmp(h, ";st=", 4) == 0) {
4865 int i;
4866 h += 4;
4867 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4868 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4869 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4870 appctx->ctx.stats.st_code = i;
4871 break;
4872 }
4873 }
4874 break;
4875 }
4876 }
4877
4878 appctx->ctx.stats.scope_str = 0;
4879 appctx->ctx.stats.scope_len = 0;
4880 for (h = lookup; h <= end - 8; h++) {
4881 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4882 int itx = 0;
4883 const char *h2;
4884 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4885 const char *err;
4886
4887 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4888 h2 = h;
4889 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4890 while (h <= end) {
4891 if (*h == ';' || *h == '&' || *h == ' ')
4892 break;
4893 itx++;
4894 h++;
4895 }
4896
4897 if (itx > STAT_SCOPE_TXT_MAXLEN)
4898 itx = STAT_SCOPE_TXT_MAXLEN;
4899 appctx->ctx.stats.scope_len = itx;
4900
4901 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4902 memcpy(scope_txt, h2, itx);
4903 scope_txt[itx] = '\0';
4904 err = invalid_char(scope_txt);
4905 if (err) {
4906 /* bad char in search text => clear scope */
4907 appctx->ctx.stats.scope_str = 0;
4908 appctx->ctx.stats.scope_len = 0;
4909 }
4910 break;
4911 }
4912 }
4913
4914 /* now check whether we have some admin rules for this request */
4915 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4916 int ret = 1;
4917
4918 if (stats_admin_rule->cond) {
4919 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4920 ret = acl_pass(ret);
4921 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4922 ret = !ret;
4923 }
4924
4925 if (ret) {
4926 /* no rule, or the rule matches */
4927 appctx->ctx.stats.flags |= STAT_ADMIN;
4928 break;
4929 }
4930 }
4931
4932 /* Was the status page requested with a POST ? */
4933 if (unlikely(txn->meth == HTTP_METH_POST)) {
4934 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4935 /* we'll need the request body, possibly after sending 100-continue */
4936 if (msg->msg_state < HTTP_MSG_DATA)
4937 req->analysers |= AN_REQ_HTTP_BODY;
4938 appctx->st0 = STAT_HTTP_POST;
4939 }
4940 else {
4941 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4942 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4943 appctx->st0 = STAT_HTTP_LAST;
4944 }
4945 }
4946 else {
4947 /* So it was another method (GET/HEAD) */
4948 appctx->st0 = STAT_HTTP_HEAD;
4949 }
4950
4951 s->task->nice = -32; /* small boost for HTTP statistics */
4952 return 1;
4953}
4954
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004955void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4956{
4957 struct http_txn *txn = s->txn;
4958 struct htx *htx;
4959 struct server *srv;
4960 union h1_sl sl;
4961 struct ist path;
4962
4963 /* 1: create the response header */
4964 if (!chunk_memcat(&trash, HTTP_302, strlen(HTTP_302)))
4965 return;
4966
4967 /* 2: add the server's prefix */
4968 /* special prefix "/" means don't change URL */
4969 srv = __objt_server(s->target);
4970 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4971 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4972 return;
4973 }
4974
4975 /* 3: add the request Path */
4976 htx = htx_from_buf(&s->req.buf);
4977 sl = http_find_stline(htx);
4978 path = http_get_path(sl.rq.u);
4979 if (!path.ptr)
4980 return;
4981
4982 if (!chunk_memcat(&trash, path.ptr, path.len))
4983 return;
4984
4985 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4986 if (!chunk_memcat(&trash, "\r\nProxy-Connection: close\r\n\r\n", 29))
4987 return;
4988 }
4989 else {
4990 if (!chunk_memcat(&trash, "\r\nConnection: close\r\n\r\n", 23))
4991 return;
4992 }
4993
4994 /* prepare to return without error. */
4995 si_shutr(si);
4996 si_shutw(si);
4997 si->err_type = SI_ET_NONE;
4998 si->state = SI_ST_CLO;
4999
5000 /* send the message */
5001 txn->status = 302;
5002 htx_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, &trash);
5003
5004 /* FIXME: we should increase a counter of redirects per server and per backend. */
5005 srv_inc_sess_ctr(srv);
5006 srv_set_sess_last(srv);
5007}
5008
Christopher Fauletf2824e62018-10-01 12:12:37 +02005009/* This function terminates the request because it was completly analyzed or
5010 * because an error was triggered during the body forwarding.
5011 */
5012static void htx_end_request(struct stream *s)
5013{
5014 struct channel *chn = &s->req;
5015 struct http_txn *txn = s->txn;
5016
5017 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5018 now_ms, __FUNCTION__, s,
5019 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5020 s->req.analysers, s->res.analysers);
5021
5022 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR)) {
5023 channel_abort(chn);
5024 channel_truncate(chn);
5025 goto end;
5026 }
5027
5028 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5029 return;
5030
5031 if (txn->req.msg_state == HTTP_MSG_DONE) {
5032 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5033 /* The server has not finished to respond, so we
5034 * don't want to move in order not to upset it.
5035 */
5036 return;
5037 }
5038
5039 /* No need to read anymore, the request was completely parsed.
5040 * We can shut the read side unless we want to abort_on_close,
5041 * or we have a POST request. The issue with POST requests is
5042 * that some browsers still send a CRLF after the request, and
5043 * this CRLF must be read so that it does not remain in the kernel
5044 * buffers, otherwise a close could cause an RST on some systems
5045 * (eg: Linux).
5046 */
5047 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5048 txn->meth != HTTP_METH_POST)
5049 channel_dont_read(chn);
5050
5051 /* if the server closes the connection, we want to immediately react
5052 * and close the socket to save packets and syscalls.
5053 */
5054 s->si[1].flags |= SI_FL_NOHALF;
5055
5056 /* In any case we've finished parsing the request so we must
5057 * disable Nagle when sending data because 1) we're not going
5058 * to shut this side, and 2) the server is waiting for us to
5059 * send pending data.
5060 */
5061 chn->flags |= CF_NEVER_WAIT;
5062
5063 /* When we get here, it means that both the request and the
5064 * response have finished receiving. Depending on the connection
5065 * mode, we'll have to wait for the last bytes to leave in either
5066 * direction, and sometimes for a close to be effective.
5067 */
5068 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5069 /* Tunnel mode will not have any analyser so it needs to
5070 * poll for reads.
5071 */
5072 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005073 if (b_data(&chn->buf))
5074 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005075 txn->req.msg_state = HTTP_MSG_TUNNEL;
5076 }
5077 else {
5078 /* we're not expecting any new data to come for this
5079 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005080 *
5081 * However, there is an exception if the response
5082 * length is undefined. In this case, we need to wait
5083 * the close from the server. The response will be
5084 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005085 */
5086 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5087 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005088 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005089
5090 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5091 channel_shutr_now(chn);
5092 channel_shutw_now(chn);
5093 }
5094 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005095 goto check_channel_flags;
5096 }
5097
5098 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5099 http_msg_closing:
5100 /* nothing else to forward, just waiting for the output buffer
5101 * to be empty and for the shutw_now to take effect.
5102 */
5103 if (channel_is_empty(chn)) {
5104 txn->req.msg_state = HTTP_MSG_CLOSED;
5105 goto http_msg_closed;
5106 }
5107 else if (chn->flags & CF_SHUTW) {
5108 txn->req.err_state = txn->req.msg_state;
5109 txn->req.msg_state = HTTP_MSG_ERROR;
5110 goto end;
5111 }
5112 return;
5113 }
5114
5115 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5116 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005117 /* if we don't know whether the server will close, we need to hard close */
5118 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5119 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005120 /* see above in MSG_DONE why we only do this in these states */
5121 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5122 channel_dont_read(chn);
5123 goto end;
5124 }
5125
5126 check_channel_flags:
5127 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5128 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5129 /* if we've just closed an output, let's switch */
5130 txn->req.msg_state = HTTP_MSG_CLOSING;
5131 goto http_msg_closing;
5132 }
5133
5134 end:
5135 chn->analysers &= AN_REQ_FLT_END;
5136 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5137 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5138 channel_auto_close(chn);
5139 channel_auto_read(chn);
5140}
5141
5142
5143/* This function terminates the response because it was completly analyzed or
5144 * because an error was triggered during the body forwarding.
5145 */
5146static void htx_end_response(struct stream *s)
5147{
5148 struct channel *chn = &s->res;
5149 struct http_txn *txn = s->txn;
5150
5151 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5152 now_ms, __FUNCTION__, s,
5153 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5154 s->req.analysers, s->res.analysers);
5155
5156 if (unlikely(txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005157 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005158 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005159 goto end;
5160 }
5161
5162 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5163 return;
5164
5165 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5166 /* In theory, we don't need to read anymore, but we must
5167 * still monitor the server connection for a possible close
5168 * while the request is being uploaded, so we don't disable
5169 * reading.
5170 */
5171 /* channel_dont_read(chn); */
5172
5173 if (txn->req.msg_state < HTTP_MSG_DONE) {
5174 /* The client seems to still be sending data, probably
5175 * because we got an error response during an upload.
5176 * We have the choice of either breaking the connection
5177 * or letting it pass through. Let's do the later.
5178 */
5179 return;
5180 }
5181
5182 /* When we get here, it means that both the request and the
5183 * response have finished receiving. Depending on the connection
5184 * mode, we'll have to wait for the last bytes to leave in either
5185 * direction, and sometimes for a close to be effective.
5186 */
5187 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5188 channel_auto_read(chn);
5189 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005190 if (b_data(&chn->buf))
5191 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005192 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5193 }
5194 else {
5195 /* we're not expecting any new data to come for this
5196 * transaction, so we can close it.
5197 */
5198 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5199 channel_shutr_now(chn);
5200 channel_shutw_now(chn);
5201 }
5202 }
5203 goto check_channel_flags;
5204 }
5205
5206 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5207 http_msg_closing:
5208 /* nothing else to forward, just waiting for the output buffer
5209 * to be empty and for the shutw_now to take effect.
5210 */
5211 if (channel_is_empty(chn)) {
5212 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5213 goto http_msg_closed;
5214 }
5215 else if (chn->flags & CF_SHUTW) {
5216 txn->rsp.err_state = txn->rsp.msg_state;
5217 txn->rsp.msg_state = HTTP_MSG_ERROR;
5218 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5219 if (objt_server(s->target))
5220 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5221 goto end;
5222 }
5223 return;
5224 }
5225
5226 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5227 http_msg_closed:
5228 /* drop any pending data */
5229 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005230 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005231 goto end;
5232 }
5233
5234 check_channel_flags:
5235 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5236 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5237 /* if we've just closed an output, let's switch */
5238 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5239 goto http_msg_closing;
5240 }
5241
5242 end:
5243 chn->analysers &= AN_RES_FLT_END;
5244 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5245 chn->analysers |= AN_RES_FLT_XFER_DATA;
5246 channel_auto_close(chn);
5247 channel_auto_read(chn);
5248}
5249
Christopher Faulet0f226952018-10-22 09:29:56 +02005250void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5251 int finst, const struct buffer *msg)
5252{
5253 channel_auto_read(si_oc(si));
5254 channel_abort(si_oc(si));
5255 channel_auto_close(si_oc(si));
5256 channel_erase(si_oc(si));
5257 channel_auto_close(si_ic(si));
5258 channel_auto_read(si_ic(si));
5259 if (msg) {
5260 struct channel *chn = si_ic(si);
5261 struct htx *htx;
5262
5263 htx = htx_from_buf(&chn->buf);
5264 htx_add_oob(htx, ist2(msg->area, msg->data));
5265 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5266 b_set_data(&chn->buf, b_size(&chn->buf));
5267 c_adv(chn, htx->data);
5268 chn->total += htx->data;
5269 }
5270 if (!(s->flags & SF_ERR_MASK))
5271 s->flags |= err;
5272 if (!(s->flags & SF_FINST_MASK))
5273 s->flags |= finst;
5274}
5275
5276void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5277{
5278 channel_auto_read(&s->req);
5279 channel_abort(&s->req);
5280 channel_auto_close(&s->req);
5281 channel_erase(&s->req);
5282 channel_truncate(&s->res);
5283
5284 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
5285 if (msg) {
5286 struct channel *chn = &s->res;
5287 struct htx *htx;
5288
5289 htx = htx_from_buf(&chn->buf);
5290 htx_add_oob(htx, ist2(msg->area, msg->data));
5291 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5292 b_set_data(&chn->buf, b_size(&chn->buf));
5293 c_adv(chn, htx->data);
5294 chn->total += htx->data;
5295 }
5296
5297 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5298 channel_auto_read(&s->res);
5299 channel_auto_close(&s->res);
5300 channel_shutr_now(&s->res);
5301}
5302
5303/*
5304 * Capture headers from message <htx> according to header list <cap_hdr>, and
5305 * fill the <cap> pointers appropriately.
5306 */
5307static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5308{
5309 struct cap_hdr *h;
5310 int32_t pos;
5311
5312 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5313 struct htx_blk *blk = htx_get_blk(htx, pos);
5314 enum htx_blk_type type = htx_get_blk_type(blk);
5315 struct ist n, v;
5316
5317 if (type == HTX_BLK_EOH)
5318 break;
5319 if (type != HTX_BLK_HDR)
5320 continue;
5321
5322 n = htx_get_blk_name(htx, blk);
5323
5324 for (h = cap_hdr; h; h = h->next) {
5325 if (h->namelen && (h->namelen == n.len) &&
5326 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5327 if (cap[h->index] == NULL)
5328 cap[h->index] =
5329 pool_alloc(h->pool);
5330
5331 if (cap[h->index] == NULL) {
5332 ha_alert("HTTP capture : out of memory.\n");
5333 break;
5334 }
5335
5336 v = htx_get_blk_value(htx, blk);
5337 if (v.len > h->len)
5338 v.len = h->len;
5339
5340 memcpy(cap[h->index], v.ptr, v.len);
5341 cap[h->index][v.len]=0;
5342 }
5343 }
5344 }
5345}
5346
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005347/* Delete a value in a header between delimiters <from> and <next>. The header
5348 * itself is delimited by <start> and <end> pointers. The number of characters
5349 * displaced is returned, and the pointer to the first delimiter is updated if
5350 * required. The function tries as much as possible to respect the following
5351 * principles :
5352 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5353 * in which case <next> is simply removed
5354 * - set exactly one space character after the new first delimiter, unless there
5355 * are not enough characters in the block being moved to do so.
5356 * - remove unneeded spaces before the previous delimiter and after the new
5357 * one.
5358 *
5359 * It is the caller's responsibility to ensure that :
5360 * - <from> points to a valid delimiter or <start> ;
5361 * - <next> points to a valid delimiter or <end> ;
5362 * - there are non-space chars before <from>.
5363 */
5364static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5365{
5366 char *prev = *from;
5367
5368 if (prev == start) {
5369 /* We're removing the first value. eat the semicolon, if <next>
5370 * is lower than <end> */
5371 if (next < end)
5372 next++;
5373
5374 while (next < end && HTTP_IS_SPHT(*next))
5375 next++;
5376 }
5377 else {
5378 /* Remove useless spaces before the old delimiter. */
5379 while (HTTP_IS_SPHT(*(prev-1)))
5380 prev--;
5381 *from = prev;
5382
5383 /* copy the delimiter and if possible a space if we're
5384 * not at the end of the line.
5385 */
5386 if (next < end) {
5387 *prev++ = *next++;
5388 if (prev + 1 < next)
5389 *prev++ = ' ';
5390 while (next < end && HTTP_IS_SPHT(*next))
5391 next++;
5392 }
5393 }
5394 memmove(prev, next, end - next);
5395 return (prev - next);
5396}
5397
Christopher Faulet0f226952018-10-22 09:29:56 +02005398
5399/* Formats the start line of the request (without CRLF) and puts it in <str> and
5400 * return the written lenght. The line can be truncated if it exceeds <len>.
5401 */
5402static size_t htx_fmt_req_line(const union h1_sl sl, char *str, size_t len)
5403{
5404 struct ist dst = ist2(str, 0);
5405
5406 if (istcat(&dst, sl.rq.m, len) == -1)
5407 goto end;
5408 if (dst.len + 1 > len)
5409 goto end;
5410 dst.ptr[dst.len++] = ' ';
5411
5412 if (istcat(&dst, sl.rq.u, len) == -1)
5413 goto end;
5414 if (dst.len + 1 > len)
5415 goto end;
5416 dst.ptr[dst.len++] = ' ';
5417
5418 istcat(&dst, sl.rq.v, len);
5419 end:
5420 return dst.len;
5421}
5422
Christopher Fauletf0523542018-10-24 11:06:58 +02005423/* Formats the start line of the response (without CRLF) and puts it in <str> and
5424 * return the written lenght. The line can be truncated if it exceeds <len>.
5425 */
5426static size_t htx_fmt_res_line(const union h1_sl sl, char *str, size_t len)
5427{
5428 struct ist dst = ist2(str, 0);
5429
5430 if (istcat(&dst, sl.st.v, len) == -1)
5431 goto end;
5432 if (dst.len + 1 > len)
5433 goto end;
5434 dst.ptr[dst.len++] = ' ';
5435
5436 if (istcat(&dst, sl.st.c, len) == -1)
5437 goto end;
5438 if (dst.len + 1 > len)
5439 goto end;
5440 dst.ptr[dst.len++] = ' ';
5441
5442 istcat(&dst, sl.st.r, len);
5443 end:
5444 return dst.len;
5445}
5446
5447
Christopher Faulet0f226952018-10-22 09:29:56 +02005448/*
5449 * Print a debug line with a start line.
5450 */
5451static void htx_debug_stline(const char *dir, struct stream *s, const union h1_sl sl)
5452{
5453 struct session *sess = strm_sess(s);
5454 int max;
5455
5456 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5457 dir,
5458 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5459 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5460
5461 max = sl.rq.m.len;
5462 UBOUND(max, trash.size - trash.data - 3);
5463 chunk_memcat(&trash, sl.rq.m.ptr, max);
5464 trash.area[trash.data++] = ' ';
5465
5466 max = sl.rq.u.len;
5467 UBOUND(max, trash.size - trash.data - 2);
5468 chunk_memcat(&trash, sl.rq.u.ptr, max);
5469 trash.area[trash.data++] = ' ';
5470
5471 max = sl.rq.v.len;
5472 UBOUND(max, trash.size - trash.data - 1);
5473 chunk_memcat(&trash, sl.rq.v.ptr, max);
5474 trash.area[trash.data++] = '\n';
5475
5476 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5477}
5478
5479/*
5480 * Print a debug line with a header.
5481 */
5482static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5483{
5484 struct session *sess = strm_sess(s);
5485 int max;
5486
5487 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5488 dir,
5489 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5490 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5491
5492 max = n.len;
5493 UBOUND(max, trash.size - trash.data - 3);
5494 chunk_memcat(&trash, n.ptr, max);
5495 trash.area[trash.data++] = ':';
5496 trash.area[trash.data++] = ' ';
5497
5498 max = v.len;
5499 UBOUND(max, trash.size - trash.data - 1);
5500 chunk_memcat(&trash, v.ptr, max);
5501 trash.area[trash.data++] = '\n';
5502
5503 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5504}
5505
5506
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005507__attribute__((constructor))
5508static void __htx_protocol_init(void)
5509{
5510}
5511
5512
5513/*
5514 * Local variables:
5515 * c-indent-level: 8
5516 * c-basic-offset: 8
5517 * End:
5518 */