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