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