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