blob: 00712d3cd83d72545b3fdc8c073013540ffd63ca [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)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100120 /*
121 * First catch invalid request
122 */
123 if (htx->flags & HTX_FL_PARSING_ERROR) {
124 stream_inc_http_req_ctr(s);
125 stream_inc_http_err_ctr(s);
126 proxy_inc_fe_req_ctr(sess->fe);
127 goto return_bad_req;
128 }
129
Christopher Faulet9768c262018-10-22 09:34:31 +0200130 /* 1: have we encountered a read error ? */
131 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200132 if (!(s->flags & SF_ERR_MASK))
133 s->flags |= SF_ERR_CLICL;
134
135 if (txn->flags & TX_WAIT_NEXT_RQ)
136 goto failed_keep_alive;
137
138 if (sess->fe->options & PR_O_IGNORE_PRB)
139 goto failed_keep_alive;
140
Christopher Faulet9768c262018-10-22 09:34:31 +0200141 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200142 stream_inc_http_req_ctr(s);
143 proxy_inc_fe_req_ctr(sess->fe);
144 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
145 if (sess->listener->counters)
146 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 txn->status = 400;
149 msg->err_state = msg->msg_state;
150 msg->msg_state = HTTP_MSG_ERROR;
151 htx_reply_and_close(s, txn->status, NULL);
152 req->analysers &= AN_REQ_FLT_END;
153
Christopher Faulete0768eb2018-10-03 16:38:02 +0200154 if (!(s->flags & SF_FINST_MASK))
155 s->flags |= SF_FINST_R;
156 return 0;
157 }
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
161 if (!(s->flags & SF_ERR_MASK))
162 s->flags |= SF_ERR_CLITO;
163
164 if (txn->flags & TX_WAIT_NEXT_RQ)
165 goto failed_keep_alive;
166
167 if (sess->fe->options & PR_O_IGNORE_PRB)
168 goto failed_keep_alive;
169
Christopher Faulet9768c262018-10-22 09:34:31 +0200170 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200171 stream_inc_http_req_ctr(s);
172 proxy_inc_fe_req_ctr(sess->fe);
173 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
174 if (sess->listener->counters)
175 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 txn->status = 408;
178 msg->err_state = msg->msg_state;
179 msg->msg_state = HTTP_MSG_ERROR;
180 htx_reply_and_close(s, txn->status, http_error_message(s));
181 req->analysers &= AN_REQ_FLT_END;
182
Christopher Faulete0768eb2018-10-03 16:38:02 +0200183 if (!(s->flags & SF_FINST_MASK))
184 s->flags |= SF_FINST_R;
185 return 0;
186 }
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 else if (req->flags & CF_SHUTR) {
190 if (!(s->flags & SF_ERR_MASK))
191 s->flags |= SF_ERR_CLICL;
192
193 if (txn->flags & TX_WAIT_NEXT_RQ)
194 goto failed_keep_alive;
195
196 if (sess->fe->options & PR_O_IGNORE_PRB)
197 goto failed_keep_alive;
198
Christopher Faulete0768eb2018-10-03 16:38:02 +0200199 stream_inc_http_err_ctr(s);
200 stream_inc_http_req_ctr(s);
201 proxy_inc_fe_req_ctr(sess->fe);
202 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
203 if (sess->listener->counters)
204 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 txn->status = 400;
207 msg->err_state = msg->msg_state;
208 msg->msg_state = HTTP_MSG_ERROR;
209 htx_reply_and_close(s, txn->status, http_error_message(s));
210 req->analysers &= AN_REQ_FLT_END;
211
Christopher Faulete0768eb2018-10-03 16:38:02 +0200212 if (!(s->flags & SF_FINST_MASK))
213 s->flags |= SF_FINST_R;
214 return 0;
215 }
216
217 channel_dont_connect(req);
218 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
219 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
220#ifdef TCP_QUICKACK
Christopher Faulet9768c262018-10-22 09:34:31 +0200221 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200222 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
223 /* We need more data, we have to re-enable quick-ack in case we
224 * previously disabled it, otherwise we might cause the client
225 * to delay next data.
226 */
227 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
228 }
229#endif
Christopher Faulet47365272018-10-31 17:40:50 +0100230 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200231 /* If the client starts to talk, let's fall back to
232 * request timeout processing.
233 */
234 txn->flags &= ~TX_WAIT_NEXT_RQ;
235 req->analyse_exp = TICK_ETERNITY;
236 }
237
238 /* just set the request timeout once at the beginning of the request */
239 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100240 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200241 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
242 else
243 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
244 }
245
246 /* we're not ready yet */
247 return 0;
248
249 failed_keep_alive:
250 /* Here we process low-level errors for keep-alive requests. In
251 * short, if the request is not the first one and it experiences
252 * a timeout, read error or shutdown, we just silently close so
253 * that the client can try again.
254 */
255 txn->status = 0;
256 msg->msg_state = HTTP_MSG_RQBEFORE;
257 req->analysers &= AN_REQ_FLT_END;
258 s->logs.logwait = 0;
259 s->logs.level = 0;
260 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200261 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200262 return 0;
263 }
264
Christopher Faulet9768c262018-10-22 09:34:31 +0200265 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200266 stream_inc_http_req_ctr(s);
267 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
268
Christopher Faulet9768c262018-10-22 09:34:31 +0200269 /* kill the pending keep-alive timeout */
270 txn->flags &= ~TX_WAIT_NEXT_RQ;
271 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200272
Christopher Faulet9768c262018-10-22 09:34:31 +0200273 /* 0: we might have to print this header in debug mode */
274 if (unlikely((global.mode & MODE_DEBUG) &&
275 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
276 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200277
Christopher Faulet9768c262018-10-22 09:34:31 +0200278 htx_debug_stline("clireq", s, http_find_stline(htx));
279
280 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
281 struct htx_blk *blk = htx_get_blk(htx, pos);
282 enum htx_blk_type type = htx_get_blk_type(blk);
283
284 if (type == HTX_BLK_EOH)
285 break;
286 if (type != HTX_BLK_HDR)
287 continue;
288
289 htx_debug_hdr("clihdr", s,
290 htx_get_blk_name(htx, blk),
291 htx_get_blk_value(htx, blk));
292 }
293 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200294
295 /*
296 * 1: identify the method
297 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200298 sl = http_find_stline(htx);
299 txn->meth = sl.rq.meth;
300 msg->flags |= HTTP_MSGF_XFER_LEN;
301
302 /* ... and check if the request is HTTP/1.1 or above */
303 if ((sl.rq.v.len == 8) &&
304 ((*(sl.rq.v.ptr + 5) > '1') ||
305 ((*(sl.rq.v.ptr + 5) == '1') && (*(sl.rq.v.ptr + 7) >= '1'))))
306 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307
308 /* we can make use of server redirect on GET and HEAD */
309 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
310 s->flags |= SF_REDIRECTABLE;
Christopher Faulet9768c262018-10-22 09:34:31 +0200311 else if (txn->meth == HTTP_METH_OTHER && isteqi(sl.rq.m, ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200312 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200313 goto return_bad_req;
314 }
315
316 /*
317 * 2: check if the URI matches the monitor_uri.
318 * We have to do this for every request which gets in, because
319 * the monitor-uri is defined by the frontend.
320 */
321 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Faulet9768c262018-10-22 09:34:31 +0200322 isteqi(sl.rq.u, ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 /*
324 * We have found the monitor URI
325 */
326 struct acl_cond *cond;
327
328 s->flags |= SF_MONITOR;
329 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
330
331 /* Check if we want to fail this monitor request or not */
332 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
333 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
334
335 ret = acl_pass(ret);
336 if (cond->pol == ACL_COND_UNLESS)
337 ret = !ret;
338
339 if (ret) {
340 /* we fail this request, let's return 503 service unavail */
341 txn->status = 503;
Christopher Faulet9768c262018-10-22 09:34:31 +0200342 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200343 if (!(s->flags & SF_ERR_MASK))
344 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
345 goto return_prx_cond;
346 }
347 }
348
349 /* nothing to fail, let's reply normaly */
350 txn->status = 200;
Christopher Faulet9768c262018-10-22 09:34:31 +0200351 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200352 if (!(s->flags & SF_ERR_MASK))
353 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
354 goto return_prx_cond;
355 }
356
357 /*
358 * 3: Maybe we have to copy the original REQURI for the logs ?
359 * Note: we cannot log anymore if the request has been
360 * classified as invalid.
361 */
362 if (unlikely(s->logs.logwait & LW_REQ)) {
363 /* we have a complete HTTP request that we must log */
364 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200365 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200366
Christopher Faulet9768c262018-10-22 09:34:31 +0200367 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
368 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200369
370 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
371 s->do_log(s);
372 } else {
373 ha_alert("HTTP logging : out of memory.\n");
374 }
375 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377 /* if the frontend has "option http-use-proxy-header", we'll check if
378 * we have what looks like a proxied connection instead of a connection,
379 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
380 * Note that this is *not* RFC-compliant, however browsers and proxies
381 * happen to do that despite being non-standard :-(
382 * We consider that a request not beginning with either '/' or '*' is
383 * a proxied connection, which covers both "scheme://location" and
384 * CONNECT ip:port.
385 */
386 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Faulet9768c262018-10-22 09:34:31 +0200387 *(sl.rq.u.ptr) != '/' && *(sl.rq.u.ptr) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200388 txn->flags |= TX_USE_PX_CONN;
389
Christopher Faulete0768eb2018-10-03 16:38:02 +0200390 /* 5: we may need to capture headers */
391 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200392 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200393
394 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
395 * only change if both the request and the config reference something else.
396 * Option httpclose by itself sets tunnel mode where headers are mangled.
397 * However, if another mode is set, it will affect it (eg: server-close/
398 * keep-alive + httpclose = close). Note that we avoid to redo the same work
399 * if FE and BE have the same settings (common). The method consists in
400 * checking if options changed between the two calls (implying that either
401 * one is non-null, or one of them is non-null and we are there for the first
402 * time.
403 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200404 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200405 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406
407 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200408 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200409 req->analysers |= AN_REQ_HTTP_BODY;
410
411 /*
412 * RFC7234#4:
413 * A cache MUST write through requests with methods
414 * that are unsafe (Section 4.2.1 of [RFC7231]) to
415 * the origin server; i.e., a cache is not allowed
416 * to generate a reply to such a request before
417 * having forwarded the request and having received
418 * a corresponding response.
419 *
420 * RFC7231#4.2.1:
421 * Of the request methods defined by this
422 * specification, the GET, HEAD, OPTIONS, and TRACE
423 * methods are defined to be safe.
424 */
425 if (likely(txn->meth == HTTP_METH_GET ||
426 txn->meth == HTTP_METH_HEAD ||
427 txn->meth == HTTP_METH_OPTIONS ||
428 txn->meth == HTTP_METH_TRACE))
429 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
430
431 /* end of job, return OK */
432 req->analysers &= ~an_bit;
433 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200434
Christopher Faulete0768eb2018-10-03 16:38:02 +0200435 return 1;
436
437 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200438 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200439 txn->req.err_state = txn->req.msg_state;
440 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +0200441 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200442 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
443 if (sess->listener->counters)
444 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
445
446 return_prx_cond:
447 if (!(s->flags & SF_ERR_MASK))
448 s->flags |= SF_ERR_PRXCOND;
449 if (!(s->flags & SF_FINST_MASK))
450 s->flags |= SF_FINST_R;
451
452 req->analysers &= AN_REQ_FLT_END;
453 req->analyse_exp = TICK_ETERNITY;
454 return 0;
455}
456
457
458/* This stream analyser runs all HTTP request processing which is common to
459 * frontends and backends, which means blocking ACLs, filters, connection-close,
460 * reqadd, stats and redirects. This is performed for the designated proxy.
461 * It returns 1 if the processing can continue on next analysers, or zero if it
462 * either needs more data or wants to immediately abort the request (eg: deny,
463 * error, ...).
464 */
465int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
466{
467 struct session *sess = s->sess;
468 struct http_txn *txn = s->txn;
469 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200470 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200471 struct redirect_rule *rule;
472 struct cond_wordlist *wl;
473 enum rule_result verdict;
474 int deny_status = HTTP_ERR_403;
475 struct connection *conn = objt_conn(sess->origin);
476
477 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
478 /* we need more data */
479 goto return_prx_yield;
480 }
481
482 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
483 now_ms, __FUNCTION__,
484 s,
485 req,
486 req->rex, req->wex,
487 req->flags,
488 ci_data(req),
489 req->analysers);
490
Christopher Fauletff2759f2018-10-24 11:13:16 +0200491 htx = htx_from_buf(&req->buf);
492
Christopher Faulete0768eb2018-10-03 16:38:02 +0200493 /* just in case we have some per-backend tracking */
494 stream_inc_be_http_req_ctr(s);
495
496 /* evaluate http-request rules */
497 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200498 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200499
500 switch (verdict) {
501 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
502 goto return_prx_yield;
503
504 case HTTP_RULE_RES_CONT:
505 case HTTP_RULE_RES_STOP: /* nothing to do */
506 break;
507
508 case HTTP_RULE_RES_DENY: /* deny or tarpit */
509 if (txn->flags & TX_CLTARPIT)
510 goto tarpit;
511 goto deny;
512
513 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
514 goto return_prx_cond;
515
516 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
517 goto done;
518
519 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
520 goto return_bad_req;
521 }
522 }
523
524 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
525 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200526 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200527
Christopher Fauletff2759f2018-10-24 11:13:16 +0200528 ctx.blk = NULL;
529 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
530 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200531 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200532 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200533 }
534
535 /* OK at this stage, we know that the request was accepted according to
536 * the http-request rules, we can check for the stats. Note that the
537 * URI is detected *before* the req* rules in order not to be affected
538 * by a possible reqrep, while they are processed *after* so that a
539 * reqdeny can still block them. This clearly needs to change in 1.6!
540 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200541 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 s->target = &http_stats_applet.obj_type;
543 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
544 txn->status = 500;
545 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200547
548 if (!(s->flags & SF_ERR_MASK))
549 s->flags |= SF_ERR_RESOURCE;
550 goto return_prx_cond;
551 }
552
553 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200554 htx_handle_stats(s, req);
555 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200556 /* not all actions implemented: deny, allow, auth */
557
558 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
559 goto deny;
560
561 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
562 goto return_prx_cond;
563 }
564
565 /* evaluate the req* rules except reqadd */
566 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200567 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200568 goto return_bad_req;
569
570 if (txn->flags & TX_CLDENY)
571 goto deny;
572
573 if (txn->flags & TX_CLTARPIT) {
574 deny_status = HTTP_ERR_500;
575 goto tarpit;
576 }
577 }
578
579 /* add request headers from the rule sets in the same order */
580 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200581 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200582 if (wl->cond) {
583 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
584 ret = acl_pass(ret);
585 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
586 ret = !ret;
587 if (!ret)
588 continue;
589 }
590
Christopher Fauletff2759f2018-10-24 11:13:16 +0200591 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
592 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200593 goto return_bad_req;
594 }
595
Christopher Faulete0768eb2018-10-03 16:38:02 +0200596 /* Proceed with the stats now. */
597 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
598 unlikely(objt_applet(s->target) == &http_cache_applet)) {
Christopher Fauletef779222018-10-31 08:47:01 +0100599
600 if (unlikely(objt_applet(s->target) == &http_cache_applet)) {
601 // TODO: Disabled for now, waiting to be adapted for HTX implementation
602 goto deny;
603 }
Christopher Fauletff2759f2018-10-24 11:13:16 +0200604
Christopher Faulete0768eb2018-10-03 16:38:02 +0200605 /* process the stats request now */
606 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
607 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
608
609 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
610 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
611 if (!(s->flags & SF_FINST_MASK))
612 s->flags |= SF_FINST_R;
613
614 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
615 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
616 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
617 req->analysers |= AN_REQ_HTTP_XFER_BODY;
618 goto done;
619 }
620
621 /* check whether we have some ACLs set to redirect this request */
622 list_for_each_entry(rule, &px->redirect_rules, list) {
623 if (rule->cond) {
624 int ret;
625
626 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
627 ret = acl_pass(ret);
628 if (rule->cond->pol == ACL_COND_UNLESS)
629 ret = !ret;
630 if (!ret)
631 continue;
632 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200633 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200634 goto return_bad_req;
635 goto done;
636 }
637
638 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
639 * If this happens, then the data will not come immediately, so we must
640 * send all what we have without waiting. Note that due to the small gain
641 * in waiting for the body of the request, it's easier to simply put the
642 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
643 * itself once used.
644 */
645 req->flags |= CF_SEND_DONTWAIT;
646
647 done: /* done with this analyser, continue with next ones that the calling
648 * points will have set, if any.
649 */
650 req->analyse_exp = TICK_ETERNITY;
651 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
652 req->analysers &= ~an_bit;
653 return 1;
654
655 tarpit:
656 /* Allow cookie logging
657 */
658 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200659 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200660
661 /* When a connection is tarpitted, we use the tarpit timeout,
662 * which may be the same as the connect timeout if unspecified.
663 * If unset, then set it to zero because we really want it to
664 * eventually expire. We build the tarpit as an analyser.
665 */
666 channel_erase(&s->req);
667
668 /* wipe the request out so that we can drop the connection early
669 * if the client closes first.
670 */
671 channel_dont_connect(req);
672
673 txn->status = http_err_codes[deny_status];
674
675 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
676 req->analysers |= AN_REQ_HTTP_TARPIT;
677 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
678 if (!req->analyse_exp)
679 req->analyse_exp = tick_add(now_ms, 0);
680 stream_inc_http_err_ctr(s);
681 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
682 if (sess->fe != s->be)
683 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
684 if (sess->listener->counters)
685 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
686 goto done_without_exp;
687
688 deny: /* this request was blocked (denied) */
689
690 /* Allow cookie logging
691 */
692 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200693 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694
695 txn->flags |= TX_CLDENY;
696 txn->status = http_err_codes[deny_status];
697 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200698 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699 stream_inc_http_err_ctr(s);
700 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
701 if (sess->fe != s->be)
702 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
703 if (sess->listener->counters)
704 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
705 goto return_prx_cond;
706
707 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200708 txn->req.err_state = txn->req.msg_state;
709 txn->req.msg_state = HTTP_MSG_ERROR;
710 txn->status = 400;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200711 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200712
713 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
714 if (sess->listener->counters)
715 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
716
717 return_prx_cond:
718 if (!(s->flags & SF_ERR_MASK))
719 s->flags |= SF_ERR_PRXCOND;
720 if (!(s->flags & SF_FINST_MASK))
721 s->flags |= SF_FINST_R;
722
723 req->analysers &= AN_REQ_FLT_END;
724 req->analyse_exp = TICK_ETERNITY;
725 return 0;
726
727 return_prx_yield:
728 channel_dont_connect(req);
729 return 0;
730}
731
732/* This function performs all the processing enabled for the current request.
733 * It returns 1 if the processing can continue on next analysers, or zero if it
734 * needs more data, encounters an error, or wants to immediately abort the
735 * request. It relies on buffers flags, and updates s->req.analysers.
736 */
737int htx_process_request(struct stream *s, struct channel *req, int an_bit)
738{
739 struct session *sess = s->sess;
740 struct http_txn *txn = s->txn;
741 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200742 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200743 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
744
745 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
746 /* we need more data */
747 channel_dont_connect(req);
748 return 0;
749 }
750
751 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
752 now_ms, __FUNCTION__,
753 s,
754 req,
755 req->rex, req->wex,
756 req->flags,
757 ci_data(req),
758 req->analysers);
759
760 /*
761 * Right now, we know that we have processed the entire headers
762 * and that unwanted requests have been filtered out. We can do
763 * whatever we want with the remaining request. Also, now we
764 * may have separate values for ->fe, ->be.
765 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200766 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200767
768 /*
769 * If HTTP PROXY is set we simply get remote server address parsing
770 * incoming request. Note that this requires that a connection is
771 * allocated on the server side.
772 */
773 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
774 struct connection *conn;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200775 union h1_sl sl;
776 struct ist path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200777
778 /* Note that for now we don't reuse existing proxy connections */
779 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
780 txn->req.err_state = txn->req.msg_state;
781 txn->req.msg_state = HTTP_MSG_ERROR;
782 txn->status = 500;
783 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200784 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 if (!(s->flags & SF_ERR_MASK))
787 s->flags |= SF_ERR_RESOURCE;
788 if (!(s->flags & SF_FINST_MASK))
789 s->flags |= SF_FINST_R;
790
791 return 0;
792 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200793 sl = http_find_stline(htx);
794 path = http_get_path(sl.rq.u);
795 if (url2sa(sl.rq.u.ptr, sl.rq.u.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200796 goto return_bad_req;
797
798 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200799 * uri.ptr and path.ptr (excluded). If it was not found, we need
800 * to replace from all the uri by a single "/".
801 *
802 * Instead of rewritting the whole start line, we just update
803 * <sl.rq.u>. Some space will be lost but it should be
804 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200806 if (path.ptr)
807 sl.rq.u = path;
808 else
809 istcpy(&sl.rq.u, ist("/"), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200810 }
811
812 /*
813 * 7: Now we can work with the cookies.
814 * Note that doing so might move headers in the request, but
815 * the fields will stay coherent and the URI will not move.
816 * This should only be performed in the backend.
817 */
818 if (s->be->cookie_name || sess->fe->capture_name)
819 manage_client_side_cookies(s, req);
820
821 /* add unique-id if "header-unique-id" is specified */
822
823 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
824 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
825 goto return_bad_req;
826 s->unique_id[0] = '\0';
827 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
828 }
829
830 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200831 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
832 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
833
834 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200836 }
837
838 /*
839 * 9: add X-Forwarded-For if either the frontend or the backend
840 * asks for it.
841 */
842 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200843 struct http_hdr_ctx ctx = { .blk = NULL };
844 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
845 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
846
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200848 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 /* The header is set to be added only if none is present
850 * and we found it, so don't do anything.
851 */
852 }
853 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
854 /* Add an X-Forwarded-For header unless the source IP is
855 * in the 'except' network range.
856 */
857 if ((!sess->fe->except_mask.s_addr ||
858 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
859 != sess->fe->except_net.s_addr) &&
860 (!s->be->except_mask.s_addr ||
861 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
862 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200863 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200864
865 /* Note: we rely on the backend to get the header name to be used for
866 * x-forwarded-for, because the header is really meant for the backends.
867 * However, if the backend did not specify any option, we have to rely
868 * on the frontend's header name.
869 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200870 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
871 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200872 goto return_bad_req;
873 }
874 }
875 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
876 /* FIXME: for the sake of completeness, we should also support
877 * 'except' here, although it is mostly useless in this case.
878 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200880
Christopher Faulete0768eb2018-10-03 16:38:02 +0200881 inet_ntop(AF_INET6,
882 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
883 pn, sizeof(pn));
884
885 /* Note: we rely on the backend to get the header name to be used for
886 * x-forwarded-for, because the header is really meant for the backends.
887 * However, if the backend did not specify any option, we have to rely
888 * on the frontend's header name.
889 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200890 chunk_printf(&trash, "%s", pn);
891 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200892 goto return_bad_req;
893 }
894 }
895
896 /*
897 * 10: add X-Original-To if either the frontend or the backend
898 * asks for it.
899 */
900 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
901
902 /* FIXME: don't know if IPv6 can handle that case too. */
903 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
904 /* Add an X-Original-To header unless the destination IP is
905 * in the 'except' network range.
906 */
907 conn_get_to_addr(cli_conn);
908
909 if (cli_conn->addr.to.ss_family == AF_INET &&
910 ((!sess->fe->except_mask_to.s_addr ||
911 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
912 != sess->fe->except_to.s_addr) &&
913 (!s->be->except_mask_to.s_addr ||
914 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
915 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200916 struct ist hdr;
917 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200918
919 /* Note: we rely on the backend to get the header name to be used for
920 * x-original-to, because the header is really meant for the backends.
921 * However, if the backend did not specify any option, we have to rely
922 * on the frontend's header name.
923 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200924 if (s->be->orgto_hdr_len)
925 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
926 else
927 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200929 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
930 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 goto return_bad_req;
932 }
933 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 }
935
Christopher Faulete0768eb2018-10-03 16:38:02 +0200936 /* If we have no server assigned yet and we're balancing on url_param
937 * with a POST request, we may be interested in checking the body for
938 * that parameter. This will be done in another analyser.
939 */
940 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200941 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
948#ifdef TCP_QUICKACK
949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
955 cli_conn && conn_ctrl_ready(cli_conn) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200956 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
958#endif
959
960 /*************************************************************
961 * OK, that's finished for the headers. We have done what we *
962 * could. Let's switch to the DATA state. *
963 ************************************************************/
964 req->analyse_exp = TICK_ETERNITY;
965 req->analysers &= ~an_bit;
966
967 s->logs.tv_request = now;
968 /* OK let's go on with the BODY now */
969 return 1;
970
971 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200972 txn->req.err_state = txn->req.msg_state;
973 txn->req.msg_state = HTTP_MSG_ERROR;
974 txn->status = 400;
975 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200976 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200977
978 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
979 if (sess->listener->counters)
980 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
981
982 if (!(s->flags & SF_ERR_MASK))
983 s->flags |= SF_ERR_PRXCOND;
984 if (!(s->flags & SF_FINST_MASK))
985 s->flags |= SF_FINST_R;
986 return 0;
987}
988
989/* This function is an analyser which processes the HTTP tarpit. It always
990 * returns zero, at the beginning because it prevents any other processing
991 * from occurring, and at the end because it terminates the request.
992 */
993int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
994{
995 struct http_txn *txn = s->txn;
996
997 /* This connection is being tarpitted. The CLIENT side has
998 * already set the connect expiration date to the right
999 * timeout. We just have to check that the client is still
1000 * there and that the timeout has not expired.
1001 */
1002 channel_dont_connect(req);
1003 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1004 !tick_is_expired(req->analyse_exp, now_ms))
1005 return 0;
1006
1007 /* We will set the queue timer to the time spent, just for
1008 * logging purposes. We fake a 500 server error, so that the
1009 * attacker will not suspect his connection has been tarpitted.
1010 * It will not cause trouble to the logs because we can exclude
1011 * the tarpitted connections by filtering on the 'PT' status flags.
1012 */
1013 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1014
1015 if (!(req->flags & CF_READ_ERROR))
Christopher Faulet8137c272018-10-24 11:15:09 +02001016 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001017
1018 req->analysers &= AN_REQ_FLT_END;
1019 req->analyse_exp = TICK_ETERNITY;
1020
1021 if (!(s->flags & SF_ERR_MASK))
1022 s->flags |= SF_ERR_PRXCOND;
1023 if (!(s->flags & SF_FINST_MASK))
1024 s->flags |= SF_FINST_T;
1025 return 0;
1026}
1027
1028/* This function is an analyser which waits for the HTTP request body. It waits
1029 * for either the buffer to be full, or the full advertised contents to have
1030 * reached the buffer. It must only be called after the standard HTTP request
1031 * processing has occurred, because it expects the request to be parsed and will
1032 * look for the Expect header. It may send a 100-Continue interim response. It
1033 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1034 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1035 * needs to read more data, or 1 once it has completed its analysis.
1036 */
1037int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1038{
1039 struct session *sess = s->sess;
1040 struct http_txn *txn = s->txn;
1041 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001042 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001043
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001044
1045 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1046 now_ms, __FUNCTION__,
1047 s,
1048 req,
1049 req->rex, req->wex,
1050 req->flags,
1051 ci_data(req),
1052 req->analysers);
1053
1054 htx = htx_from_buf(&req->buf);
1055
1056 if (msg->msg_state < HTTP_MSG_BODY)
1057 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001058
Christopher Faulete0768eb2018-10-03 16:38:02 +02001059 /* We have to parse the HTTP request body to find any required data.
1060 * "balance url_param check_post" should have been the only way to get
1061 * into this. We were brought here after HTTP header analysis, so all
1062 * related structures are ready.
1063 */
1064
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001065 if (msg->msg_state < HTTP_MSG_DATA) {
1066 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1067 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001068 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001069 if (msg->flags & HTTP_MSGF_VER_11) {
1070 struct ist hdr = { .ptr = "Expect", .len = 6 };
1071 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001072
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001073 ctx.blk = NULL;
1074 /* Expect is allowed in 1.1, look for it */
1075 if (http_find_header(htx, hdr, &ctx, 0) &&
1076 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
1077 struct htx *rsp = htx_from_buf(&s->res.buf);
1078 struct htx_blk *blk;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001080 blk = htx_add_oob(rsp, HTTP_100);
1081 if (!blk)
1082 goto missing_data;
1083 b_set_data(&s->res.buf, b_size(&s->res.buf));
1084 c_adv(&s->res, HTTP_100.len);
1085 s->res.total += HTTP_100.len;
1086 http_remove_header(htx, &ctx);
1087 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001088 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089 }
1090
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001092
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001093 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1094 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001095 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001096 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1097 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001098 goto http_end;
1099
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001100 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001101 if (htx->flags & HTX_FL_PARSING_ERROR)
1102 goto return_bad_req;
1103
Christopher Faulete0768eb2018-10-03 16:38:02 +02001104 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1105 txn->status = 408;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001106 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001107
1108 if (!(s->flags & SF_ERR_MASK))
1109 s->flags |= SF_ERR_CLITO;
1110 if (!(s->flags & SF_FINST_MASK))
1111 s->flags |= SF_FINST_D;
1112 goto return_err_msg;
1113 }
1114
1115 /* we get here if we need to wait for more data */
1116 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1117 /* Not enough data. We'll re-use the http-request
1118 * timeout here. Ideally, we should set the timeout
1119 * relative to the accept() date. We just set the
1120 * request timeout once at the beginning of the
1121 * request.
1122 */
1123 channel_dont_connect(req);
1124 if (!tick_isset(req->analyse_exp))
1125 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1126 return 0;
1127 }
1128
1129 http_end:
1130 /* The situation will not evolve, so let's give up on the analysis. */
1131 s->logs.tv_request = now; /* update the request timer to reflect full request */
1132 req->analysers &= ~an_bit;
1133 req->analyse_exp = TICK_ETERNITY;
1134 return 1;
1135
1136 return_bad_req: /* let's centralize all bad requests */
1137 txn->req.err_state = txn->req.msg_state;
1138 txn->req.msg_state = HTTP_MSG_ERROR;
1139 txn->status = 400;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001140 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001141
1142 if (!(s->flags & SF_ERR_MASK))
1143 s->flags |= SF_ERR_PRXCOND;
1144 if (!(s->flags & SF_FINST_MASK))
1145 s->flags |= SF_FINST_R;
1146
1147 return_err_msg:
1148 req->analysers &= AN_REQ_FLT_END;
1149 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1150 if (sess->listener->counters)
1151 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1152 return 0;
1153}
1154
1155/* This function is an analyser which forwards request body (including chunk
1156 * sizes if any). It is called as soon as we must forward, even if we forward
1157 * zero byte. The only situation where it must not be called is when we're in
1158 * tunnel mode and we want to forward till the close. It's used both to forward
1159 * remaining data and to resync after end of body. It expects the msg_state to
1160 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1161 * read more data, or 1 once we can go on with next request or end the stream.
1162 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1163 * bytes of pending data + the headers if not already done.
1164 */
1165int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1166{
1167 struct session *sess = s->sess;
1168 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001169 struct http_msg *msg = &txn->req;
1170 struct htx *htx;
1171 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001172
1173 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1174 now_ms, __FUNCTION__,
1175 s,
1176 req,
1177 req->rex, req->wex,
1178 req->flags,
1179 ci_data(req),
1180 req->analysers);
1181
Christopher Faulet9768c262018-10-22 09:34:31 +02001182 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001183
1184 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1185 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1186 /* Output closed while we were sending data. We must abort and
1187 * wake the other side up.
1188 */
1189 msg->err_state = msg->msg_state;
1190 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001191 htx_end_request(s);
1192 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001193 return 1;
1194 }
1195
1196 /* Note that we don't have to send 100-continue back because we don't
1197 * need the data to complete our job, and it's up to the server to
1198 * decide whether to return 100, 417 or anything else in return of
1199 * an "Expect: 100-continue" header.
1200 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001201 if (msg->msg_state == HTTP_MSG_BODY)
1202 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001203
1204 /* Some post-connect processing might want us to refrain from starting to
1205 * forward data. Currently, the only reason for this is "balance url_param"
1206 * whichs need to parse/process the request after we've enabled forwarding.
1207 */
1208 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1209 if (!(s->res.flags & CF_READ_ATTACHED)) {
1210 channel_auto_connect(req);
1211 req->flags |= CF_WAKE_CONNECT;
1212 channel_dont_close(req); /* don't fail on early shutr */
1213 goto waiting;
1214 }
1215 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1216 }
1217
1218 /* in most states, we should abort in case of early close */
1219 channel_auto_close(req);
1220
1221 if (req->to_forward) {
1222 /* We can't process the buffer's contents yet */
1223 req->flags |= CF_WAKE_WRITE;
1224 goto missing_data_or_waiting;
1225 }
1226
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 if (msg->msg_state >= HTTP_MSG_DONE)
1228 goto done;
1229
1230 /* Forward all input data. We get it by removing all outgoing data not
1231 * forwarded yet from HTX data size.
1232 */
1233 c_adv(req, htx->data - co_data(req));
1234
1235 /* To let the function channel_forward work as expected we must update
1236 * the channel's buffer to pretend there is no more input data. The
1237 * right length is then restored. We must do that, because when an HTX
1238 * message is stored into a buffer, it appears as full.
1239 */
1240 b_set_data(&req->buf, co_data(req));
1241 if (htx->extra != ULLONG_MAX)
1242 htx->extra -= channel_forward(req, htx->extra);
1243 b_set_data(&req->buf, b_size(&req->buf));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001244
Christopher Faulet9768c262018-10-22 09:34:31 +02001245 /* Check if the end-of-message is reached and if so, switch the message
1246 * in HTTP_MSG_DONE state.
1247 */
1248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1249 goto missing_data_or_waiting;
1250
1251 msg->msg_state = HTTP_MSG_DONE;
1252
1253 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001254 /* other states, DONE...TUNNEL */
1255 /* we don't want to forward closes on DONE except in tunnel mode. */
1256 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1257 channel_dont_close(req);
1258
Christopher Fauletf2824e62018-10-01 12:12:37 +02001259 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001260 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001261 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001262 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1263 if (req->flags & CF_SHUTW) {
1264 /* request errors are most likely due to the
1265 * server aborting the transfer. */
1266 goto aborted_xfer;
1267 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001268 goto return_bad_req;
1269 }
1270 return 1;
1271 }
1272
1273 /* If "option abortonclose" is set on the backend, we want to monitor
1274 * the client's connection and forward any shutdown notification to the
1275 * server, which will decide whether to close or to go on processing the
1276 * request. We only do that in tunnel mode, and not in other modes since
1277 * it can be abused to exhaust source ports. */
1278 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1279 channel_auto_read(req);
1280 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1281 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1282 s->si[1].flags |= SI_FL_NOLINGER;
1283 channel_auto_close(req);
1284 }
1285 else if (s->txn->meth == HTTP_METH_POST) {
1286 /* POST requests may require to read extra CRLF sent by broken
1287 * browsers and which could cause an RST to be sent upon close
1288 * on some systems (eg: Linux). */
1289 channel_auto_read(req);
1290 }
1291 return 0;
1292
1293 missing_data_or_waiting:
1294 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001295 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001296 if (!(s->flags & SF_ERR_MASK))
1297 s->flags |= SF_ERR_CLICL;
1298 if (!(s->flags & SF_FINST_MASK)) {
1299 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1300 s->flags |= SF_FINST_H;
1301 else
1302 s->flags |= SF_FINST_D;
1303 }
1304
1305 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1306 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1307 if (objt_server(s->target))
1308 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1309
1310 goto return_bad_req_stats_ok;
1311 }
1312
1313 waiting:
1314 /* waiting for the last bits to leave the buffer */
1315 if (req->flags & CF_SHUTW)
1316 goto aborted_xfer;
1317
Christopher Faulet47365272018-10-31 17:40:50 +01001318 if (htx->flags & HTX_FL_PARSING_ERROR)
1319 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001320
Christopher Faulete0768eb2018-10-03 16:38:02 +02001321 /* When TE: chunked is used, we need to get there again to parse remaining
1322 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1323 * And when content-length is used, we never want to let the possible
1324 * shutdown be forwarded to the other side, as the state machine will
1325 * take care of it once the client responds. It's also important to
1326 * prevent TIME_WAITs from accumulating on the backend side, and for
1327 * HTTP/2 where the last frame comes with a shutdown.
1328 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001329 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001330 channel_dont_close(req);
1331
Christopher Faulet9768c262018-10-22 09:34:31 +02001332#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
1333 // about if
1334
Christopher Faulete0768eb2018-10-03 16:38:02 +02001335 /* We know that more data are expected, but we couldn't send more that
1336 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1337 * system knows it must not set a PUSH on this first part. Interactive
1338 * modes are already handled by the stream sock layer. We must not do
1339 * this in content-length mode because it could present the MSG_MORE
1340 * flag with the last block of forwarded data, which would cause an
1341 * additional delay to be observed by the receiver.
1342 */
1343 if (msg->flags & HTTP_MSGF_TE_CHNK)
1344 req->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02001345#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02001346
1347 return 0;
1348
1349 return_bad_req: /* let's centralize all bad requests */
1350 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1351 if (sess->listener->counters)
1352 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1353
1354 return_bad_req_stats_ok:
1355 txn->req.err_state = txn->req.msg_state;
1356 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001357 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001358 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001359 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001360 } else {
1361 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001362 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 }
1364 req->analysers &= AN_REQ_FLT_END;
1365 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1366
1367 if (!(s->flags & SF_ERR_MASK))
1368 s->flags |= SF_ERR_PRXCOND;
1369 if (!(s->flags & SF_FINST_MASK)) {
1370 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1371 s->flags |= SF_FINST_H;
1372 else
1373 s->flags |= SF_FINST_D;
1374 }
1375 return 0;
1376
1377 aborted_xfer:
1378 txn->req.err_state = txn->req.msg_state;
1379 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001380 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001381 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001382 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001383 } else {
1384 txn->status = 502;
Christopher Faulet9768c262018-10-22 09:34:31 +02001385 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 }
1387 req->analysers &= AN_REQ_FLT_END;
1388 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1389
1390 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1391 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1392 if (objt_server(s->target))
1393 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1394
1395 if (!(s->flags & SF_ERR_MASK))
1396 s->flags |= SF_ERR_SRVCL;
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
1406/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1407 * processing can continue on next analysers, or zero if it either needs more
1408 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1409 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1410 * when it has nothing left to do, and may remove any analyser when it wants to
1411 * abort.
1412 */
1413int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1414{
Christopher Faulet9768c262018-10-22 09:34:31 +02001415 /*
1416 * We will analyze a complete HTTP response to check the its syntax.
1417 *
1418 * Once the start line and all headers are received, we may perform a
1419 * capture of the error (if any), and we will set a few fields. We also
1420 * logging and finally headers capture.
1421 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001422 struct session *sess = s->sess;
1423 struct http_txn *txn = s->txn;
1424 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001425 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001426 struct connection *srv_conn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001427 union h1_sl sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001428 int n;
1429
1430 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1431 now_ms, __FUNCTION__,
1432 s,
1433 rep,
1434 rep->rex, rep->wex,
1435 rep->flags,
1436 ci_data(rep),
1437 rep->analysers);
1438
Christopher Faulet9768c262018-10-22 09:34:31 +02001439 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001440
1441 /*
1442 * Now we quickly check if we have found a full valid response.
1443 * If not so, we check the FD and buffer states before leaving.
1444 * A full response is indicated by the fact that we have seen
1445 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1446 * responses are checked first.
1447 *
1448 * Depending on whether the client is still there or not, we
1449 * may send an error response back or not. Note that normally
1450 * we should only check for HTTP status there, and check I/O
1451 * errors somewhere else.
1452 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001453 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001454 /*
1455 * First catch invalid response
1456 */
1457 if (htx->flags & HTX_FL_PARSING_ERROR)
1458 goto return_bad_res;
1459
Christopher Faulet9768c262018-10-22 09:34:31 +02001460 /* 1: have we encountered a read error ? */
1461 if (rep->flags & CF_READ_ERROR) {
1462 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001463 goto abort_keep_alive;
1464
1465 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1466 if (objt_server(s->target)) {
1467 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1468 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1469 }
1470
Christopher Faulete0768eb2018-10-03 16:38:02 +02001471 rep->analysers &= AN_RES_FLT_END;
1472 txn->status = 502;
1473
1474 /* Check to see if the server refused the early data.
1475 * If so, just send a 425
1476 */
1477 if (objt_cs(s->si[1].end)) {
1478 struct connection *conn = objt_cs(s->si[1].end)->conn;
1479
1480 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1481 txn->status = 425;
1482 }
1483
1484 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001485 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001486
1487 if (!(s->flags & SF_ERR_MASK))
1488 s->flags |= SF_ERR_SRVCL;
1489 if (!(s->flags & SF_FINST_MASK))
1490 s->flags |= SF_FINST_H;
1491 return 0;
1492 }
1493
Christopher Faulet9768c262018-10-22 09:34:31 +02001494 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001495 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1497 if (objt_server(s->target)) {
1498 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1499 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1500 }
1501
Christopher Faulete0768eb2018-10-03 16:38:02 +02001502 rep->analysers &= AN_RES_FLT_END;
1503 txn->status = 504;
1504 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001505 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506
1507 if (!(s->flags & SF_ERR_MASK))
1508 s->flags |= SF_ERR_SRVTO;
1509 if (!(s->flags & SF_FINST_MASK))
1510 s->flags |= SF_FINST_H;
1511 return 0;
1512 }
1513
Christopher Faulet9768c262018-10-22 09:34:31 +02001514 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1516 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1517 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1518 if (objt_server(s->target))
1519 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1520
1521 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001522 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001523 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524
1525 if (!(s->flags & SF_ERR_MASK))
1526 s->flags |= SF_ERR_CLICL;
1527 if (!(s->flags & SF_FINST_MASK))
1528 s->flags |= SF_FINST_H;
1529
1530 /* process_stream() will take care of the error */
1531 return 0;
1532 }
1533
Christopher Faulet9768c262018-10-22 09:34:31 +02001534 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001536 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537 goto abort_keep_alive;
1538
1539 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1540 if (objt_server(s->target)) {
1541 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1542 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1543 }
1544
Christopher Faulete0768eb2018-10-03 16:38:02 +02001545 rep->analysers &= AN_RES_FLT_END;
1546 txn->status = 502;
1547 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549
1550 if (!(s->flags & SF_ERR_MASK))
1551 s->flags |= SF_ERR_SRVCL;
1552 if (!(s->flags & SF_FINST_MASK))
1553 s->flags |= SF_FINST_H;
1554 return 0;
1555 }
1556
Christopher Faulet9768c262018-10-22 09:34:31 +02001557 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001559 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560 goto abort_keep_alive;
1561
1562 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1563 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564
1565 if (!(s->flags & SF_ERR_MASK))
1566 s->flags |= SF_ERR_CLICL;
1567 if (!(s->flags & SF_FINST_MASK))
1568 s->flags |= SF_FINST_H;
1569
1570 /* process_stream() will take care of the error */
1571 return 0;
1572 }
1573
1574 channel_dont_close(rep);
1575 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1576 return 0;
1577 }
1578
1579 /* More interesting part now : we know that we have a complete
1580 * response which at least looks like HTTP. We have an indicator
1581 * of each header's length, so we can parse them quickly.
1582 */
1583
Christopher Faulet9768c262018-10-22 09:34:31 +02001584 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001585
Christopher Faulet9768c262018-10-22 09:34:31 +02001586 /* 0: we might have to print this header in debug mode */
1587 if (unlikely((global.mode & MODE_DEBUG) &&
1588 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1589 int32_t pos;
1590
1591 htx_debug_stline("srvrep", s, http_find_stline(htx));
1592
1593 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1594 struct htx_blk *blk = htx_get_blk(htx, pos);
1595 enum htx_blk_type type = htx_get_blk_type(blk);
1596
1597 if (type == HTX_BLK_EOH)
1598 break;
1599 if (type != HTX_BLK_HDR)
1600 continue;
1601
1602 htx_debug_hdr("srvhdr", s,
1603 htx_get_blk_name(htx, blk),
1604 htx_get_blk_value(htx, blk));
1605 }
1606 }
1607
1608 /* 1: get the status code */
1609 sl = http_find_stline(htx);
1610 txn->status = sl.st.status;
1611 if (htx->extra != ULLONG_MAX)
1612 msg->flags |= HTTP_MSGF_XFER_LEN;
1613
1614 /* ... and check if the request is HTTP/1.1 or above */
1615 if ((sl.st.v.len == 8) &&
1616 ((*(sl.st.v.ptr + 5) > '1') ||
1617 ((*(sl.st.v.ptr + 5) == '1') && (*(sl.st.v.ptr + 7) >= '1'))))
1618 msg->flags |= HTTP_MSGF_VER_11;
1619
1620 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621 if (n < 1 || n > 5)
1622 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001623
Christopher Faulete0768eb2018-10-03 16:38:02 +02001624 /* when the client triggers a 4xx from the server, it's most often due
1625 * to a missing object or permission. These events should be tracked
1626 * because if they happen often, it may indicate a brute force or a
1627 * vulnerability scan.
1628 */
1629 if (n == 4)
1630 stream_inc_http_err_ctr(s);
1631
1632 if (objt_server(s->target))
1633 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
1634
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 /* Adjust server's health based on status code. Note: status codes 501
1636 * and 505 are triggered on demand by client request, so we must not
1637 * count them as server failures.
1638 */
1639 if (objt_server(s->target)) {
1640 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
1641 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
1642 else
1643 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
1644 }
1645
1646 /*
1647 * We may be facing a 100-continue response, or any other informational
1648 * 1xx response which is non-final, in which case this is not the right
1649 * response, and we're waiting for the next one. Let's allow this response
1650 * to go to the client and wait for the next one. There's an exception for
1651 * 101 which is used later in the code to switch protocols.
1652 */
1653 if (txn->status < 200 &&
1654 (txn->status == 100 || txn->status >= 102)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001655 //FLT_STRM_CB(s, flt_htx_reset(s, http, htx));
1656 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001657 msg->msg_state = HTTP_MSG_RPBEFORE;
1658 txn->status = 0;
1659 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001660 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001661 }
1662
1663 /*
1664 * 2: check for cacheability.
1665 */
1666
1667 switch (txn->status) {
1668 case 200:
1669 case 203:
1670 case 204:
1671 case 206:
1672 case 300:
1673 case 301:
1674 case 404:
1675 case 405:
1676 case 410:
1677 case 414:
1678 case 501:
1679 break;
1680 default:
1681 /* RFC7231#6.1:
1682 * Responses with status codes that are defined as
1683 * cacheable by default (e.g., 200, 203, 204, 206,
1684 * 300, 301, 404, 405, 410, 414, and 501 in this
1685 * specification) can be reused by a cache with
1686 * heuristic expiration unless otherwise indicated
1687 * by the method definition or explicit cache
1688 * controls [RFC7234]; all other status codes are
1689 * not cacheable by default.
1690 */
1691 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1692 break;
1693 }
1694
1695 /*
1696 * 3: we may need to capture headers
1697 */
1698 s->logs.logwait &= ~LW_RESP;
1699 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001700 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001701
Christopher Faulet9768c262018-10-22 09:34:31 +02001702 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001703 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1704 txn->status == 101)) {
1705 /* Either we've established an explicit tunnel, or we're
1706 * switching the protocol. In both cases, we're very unlikely
1707 * to understand the next protocols. We have to switch to tunnel
1708 * mode, so that we transfer the request and responses then let
1709 * this protocol pass unmodified. When we later implement specific
1710 * parsers for such protocols, we'll want to check the Upgrade
1711 * header which contains information about that protocol for
1712 * responses with status 101 (eg: see RFC2817 about TLS).
1713 */
1714 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715 }
1716
Christopher Faulet61608322018-11-23 16:23:45 +01001717 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1718 * 407 (Proxy-Authenticate) responses and set the connection to private
1719 */
1720 srv_conn = cs_conn(objt_cs(s->si[1].end));
1721 if (srv_conn) {
1722 struct ist hdr;
1723 struct http_hdr_ctx ctx;
1724
1725 if (txn->status == 401)
1726 hdr = ist("WWW-Authenticate");
1727 else if (txn->status == 407)
1728 hdr = ist("Proxy-Authenticate");
1729 else
1730 goto end;
1731
1732 ctx.blk = NULL;
1733 while (http_find_header(htx, hdr, &ctx, 0)) {
1734 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1735 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1736 srv_conn->flags |= CO_FL_PRIVATE;
1737 }
1738 }
1739
1740 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001741 /* we want to have the response time before we start processing it */
1742 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1743
1744 /* end of job, return OK */
1745 rep->analysers &= ~an_bit;
1746 rep->analyse_exp = TICK_ETERNITY;
1747 channel_auto_close(rep);
1748 return 1;
1749
Christopher Faulet47365272018-10-31 17:40:50 +01001750 return_bad_res:
1751 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1752 if (objt_server(s->target)) {
1753 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1754 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
1755 }
1756 txn->status = 502;
1757 s->si[1].flags |= SI_FL_NOLINGER;
1758 htx_reply_and_close(s, txn->status, http_error_message(s));
1759 rep->analysers &= AN_RES_FLT_END;
1760
1761 if (!(s->flags & SF_ERR_MASK))
1762 s->flags |= SF_ERR_PRXCOND;
1763 if (!(s->flags & SF_FINST_MASK))
1764 s->flags |= SF_FINST_H;
1765 return 0;
1766
Christopher Faulete0768eb2018-10-03 16:38:02 +02001767 abort_keep_alive:
1768 /* A keep-alive request to the server failed on a network error.
1769 * The client is required to retry. We need to close without returning
1770 * any other information so that the client retries.
1771 */
1772 txn->status = 0;
1773 rep->analysers &= AN_RES_FLT_END;
1774 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001775 s->logs.logwait = 0;
1776 s->logs.level = 0;
1777 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001778 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 return 0;
1780}
1781
1782/* This function performs all the processing enabled for the current response.
1783 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1784 * and updates s->res.analysers. It might make sense to explode it into several
1785 * other functions. It works like process_request (see indications above).
1786 */
1787int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1788{
1789 struct session *sess = s->sess;
1790 struct http_txn *txn = s->txn;
1791 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001792 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001793 struct proxy *cur_proxy;
1794 struct cond_wordlist *wl;
1795 enum rule_result ret = HTTP_RULE_RES_CONT;
1796
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001797 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1798 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001799
Christopher Faulete0768eb2018-10-03 16:38:02 +02001800 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1801 now_ms, __FUNCTION__,
1802 s,
1803 rep,
1804 rep->rex, rep->wex,
1805 rep->flags,
1806 ci_data(rep),
1807 rep->analysers);
1808
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001809 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001810
1811 /* The stats applet needs to adjust the Connection header but we don't
1812 * apply any filter there.
1813 */
1814 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1815 rep->analysers &= ~an_bit;
1816 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001817 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001818 }
1819
1820 /*
1821 * We will have to evaluate the filters.
1822 * As opposed to version 1.2, now they will be evaluated in the
1823 * filters order and not in the header order. This means that
1824 * each filter has to be validated among all headers.
1825 *
1826 * Filters are tried with ->be first, then with ->fe if it is
1827 * different from ->be.
1828 *
1829 * Maybe we are in resume condiion. In this case I choose the
1830 * "struct proxy" which contains the rule list matching the resume
1831 * pointer. If none of theses "struct proxy" match, I initialise
1832 * the process with the first one.
1833 *
1834 * In fact, I check only correspondance betwwen the current list
1835 * pointer and the ->fe rule list. If it doesn't match, I initialize
1836 * the loop with the ->be.
1837 */
1838 if (s->current_rule_list == &sess->fe->http_res_rules)
1839 cur_proxy = sess->fe;
1840 else
1841 cur_proxy = s->be;
1842 while (1) {
1843 struct proxy *rule_set = cur_proxy;
1844
1845 /* evaluate http-response rules */
1846 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001847 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001848
1849 if (ret == HTTP_RULE_RES_BADREQ)
1850 goto return_srv_prx_502;
1851
1852 if (ret == HTTP_RULE_RES_DONE) {
1853 rep->analysers &= ~an_bit;
1854 rep->analyse_exp = TICK_ETERNITY;
1855 return 1;
1856 }
1857 }
1858
1859 /* we need to be called again. */
1860 if (ret == HTTP_RULE_RES_YIELD) {
1861 channel_dont_close(rep);
1862 return 0;
1863 }
1864
1865 /* try headers filters */
1866 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001867 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1868 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001869 }
1870
1871 /* has the response been denied ? */
1872 if (txn->flags & TX_SVDENY) {
1873 if (objt_server(s->target))
1874 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
1875
1876 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1877 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1878 if (sess->listener->counters)
1879 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001880 goto return_srv_prx_502;
1881 }
1882
1883 /* add response headers from the rule sets in the same order */
1884 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001885 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001886 if (txn->status < 200 && txn->status != 101)
1887 break;
1888 if (wl->cond) {
1889 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1890 ret = acl_pass(ret);
1891 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1892 ret = !ret;
1893 if (!ret)
1894 continue;
1895 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001896
1897 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1898 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001899 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))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001925 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001926
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,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001953 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001954 s->be->cookie_name);
1955 }
1956 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001957 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001958
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
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001990 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001991 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
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002009 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002010 goto return_bad_resp;
2011 }
2012 }
2013
2014 /*
2015 * Check if result will be cacheable with a cookie.
2016 * We'll block the response if security checks have caught
2017 * nasty things such as a cacheable cookie.
2018 */
2019 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2020 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2021 (s->be->options & PR_O_CHK_CACHE)) {
2022 /* we're in presence of a cacheable response containing
2023 * a set-cookie header. We'll block it as requested by
2024 * the 'checkcache' option, and send an alert.
2025 */
2026 if (objt_server(s->target))
2027 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2028
2029 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2030 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2031 if (sess->listener->counters)
2032 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2033
2034 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2035 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2036 send_log(s->be, LOG_ALERT,
2037 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2038 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2039 goto return_srv_prx_502;
2040 }
2041
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002042 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002043 /* Always enter in the body analyzer */
2044 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2045 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2046
2047 /* if the user wants to log as soon as possible, without counting
2048 * bytes from the server, then this is the right moment. We have
2049 * to temporarily assign bytes_out to log what we currently have.
2050 */
2051 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2052 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002053 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002054 s->do_log(s);
2055 s->logs.bytes_out = 0;
2056 }
2057 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002058
2059 return_bad_resp:
2060 if (objt_server(s->target)) {
2061 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2062 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
2063 }
2064 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2065
2066 return_srv_prx_502:
2067 rep->analysers &= AN_RES_FLT_END;
2068 txn->status = 502;
2069 s->logs.t_data = -1; /* was not a valid response */
2070 s->si[1].flags |= SI_FL_NOLINGER;
2071 htx_reply_and_close(s, txn->status, http_error_message(s));
2072 if (!(s->flags & SF_ERR_MASK))
2073 s->flags |= SF_ERR_PRXCOND;
2074 if (!(s->flags & SF_FINST_MASK))
2075 s->flags |= SF_FINST_H;
2076 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002077}
2078
2079/* This function is an analyser which forwards response body (including chunk
2080 * sizes if any). It is called as soon as we must forward, even if we forward
2081 * zero byte. The only situation where it must not be called is when we're in
2082 * tunnel mode and we want to forward till the close. It's used both to forward
2083 * remaining data and to resync after end of body. It expects the msg_state to
2084 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2085 * read more data, or 1 once we can go on with next request or end the stream.
2086 *
2087 * It is capable of compressing response data both in content-length mode and
2088 * in chunked mode. The state machines follows different flows depending on
2089 * whether content-length and chunked modes are used, since there are no
2090 * trailers in content-length :
2091 *
2092 * chk-mode cl-mode
2093 * ,----- BODY -----.
2094 * / \
2095 * V size > 0 V chk-mode
2096 * .--> SIZE -------------> DATA -------------> CRLF
2097 * | | size == 0 | last byte |
2098 * | v final crlf v inspected |
2099 * | TRAILERS -----------> DONE |
2100 * | |
2101 * `----------------------------------------------'
2102 *
2103 * Compression only happens in the DATA state, and must be flushed in final
2104 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2105 * is performed at once on final states for all bytes parsed, or when leaving
2106 * on missing data.
2107 */
2108int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2109{
2110 struct session *sess = s->sess;
2111 struct http_txn *txn = s->txn;
2112 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002113 struct htx *htx;
2114 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002115
2116 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2117 now_ms, __FUNCTION__,
2118 s,
2119 res,
2120 res->rex, res->wex,
2121 res->flags,
2122 ci_data(res),
2123 res->analysers);
2124
Christopher Faulet9768c262018-10-22 09:34:31 +02002125 htx = htx_from_buf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126
2127 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002128 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002129 /* Output closed while we were sending data. We must abort and
2130 * wake the other side up.
2131 */
2132 msg->err_state = msg->msg_state;
2133 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002134 htx_end_response(s);
2135 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 return 1;
2137 }
2138
Christopher Faulet9768c262018-10-22 09:34:31 +02002139 if (msg->msg_state == HTTP_MSG_BODY)
2140 msg->msg_state = HTTP_MSG_DATA;
2141
Christopher Faulete0768eb2018-10-03 16:38:02 +02002142 /* in most states, we should abort in case of early close */
2143 channel_auto_close(res);
2144
Christopher Faulete0768eb2018-10-03 16:38:02 +02002145 if (res->to_forward) {
2146 /* We can't process the buffer's contents yet */
2147 res->flags |= CF_WAKE_WRITE;
2148 goto missing_data_or_waiting;
2149 }
2150
Christopher Faulet9768c262018-10-22 09:34:31 +02002151 if (msg->msg_state >= HTTP_MSG_DONE)
2152 goto done;
2153
2154 /* Forward all input data. We get it by removing all outgoing data not
2155 * forwarded yet from HTX data size.
2156 */
2157 c_adv(res, htx->data - co_data(res));
2158
2159 /* To let the function channel_forward work as expected we must update
2160 * the channel's buffer to pretend there is no more input data. The
2161 * right length is then restored. We must do that, because when an HTX
2162 * message is stored into a buffer, it appears as full.
2163 */
2164 b_set_data(&res->buf, co_data(res));
2165 if (htx->extra != ULLONG_MAX)
2166 htx->extra -= channel_forward(res, htx->extra);
2167 b_set_data(&res->buf, b_size(&res->buf));
2168
2169 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2170 /* The server still sending data that should be filtered */
2171 if (res->flags & CF_SHUTR || !HAS_DATA_FILTERS(s, res)) {
2172 msg->msg_state = HTTP_MSG_TUNNEL;
2173 goto done;
2174 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002175 }
2176
Christopher Faulet9768c262018-10-22 09:34:31 +02002177 /* Check if the end-of-message is reached and if so, switch the message
2178 * in HTTP_MSG_DONE state.
2179 */
2180 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2181 goto missing_data_or_waiting;
2182
2183 msg->msg_state = HTTP_MSG_DONE;
2184
2185 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002186 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002187 channel_dont_close(res);
2188
Christopher Fauletf2824e62018-10-01 12:12:37 +02002189 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002190 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002191 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2193 if (res->flags & CF_SHUTW) {
2194 /* response errors are most likely due to the
2195 * client aborting the transfer. */
2196 goto aborted_xfer;
2197 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002198 goto return_bad_res;
2199 }
2200 return 1;
2201 }
2202 return 0;
2203
2204 missing_data_or_waiting:
2205 if (res->flags & CF_SHUTW)
2206 goto aborted_xfer;
2207
Christopher Faulet47365272018-10-31 17:40:50 +01002208 if (htx->flags & HTX_FL_PARSING_ERROR)
2209 goto return_bad_res;
2210
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 /* stop waiting for data if the input is closed before the end. If the
2212 * client side was already closed, it means that the client has aborted,
2213 * so we don't want to count this as a server abort. Otherwise it's a
2214 * server abort.
2215 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002216 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002217 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2218 goto aborted_xfer;
2219 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002220 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002221 if (!(s->flags & SF_ERR_MASK))
2222 s->flags |= SF_ERR_SRVCL;
2223 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2224 if (objt_server(s->target))
2225 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2226 goto return_bad_res_stats_ok;
2227 }
2228 }
2229
Christopher Faulete0768eb2018-10-03 16:38:02 +02002230 /* When TE: chunked is used, we need to get there again to parse
2231 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002232 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2233 * are filters registered on the stream, we don't want to forward a
2234 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002235 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002236 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_DATA_FILTERS(s, res))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 channel_dont_close(res);
2238
Christopher Faulet9768c262018-10-22 09:34:31 +02002239#if 0 // FIXME [Cf]: Probably not required now, but I need more time to think
2240 // about if
2241
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 /* We know that more data are expected, but we couldn't send more that
2243 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2244 * system knows it must not set a PUSH on this first part. Interactive
2245 * modes are already handled by the stream sock layer. We must not do
2246 * this in content-length mode because it could present the MSG_MORE
2247 * flag with the last block of forwarded data, which would cause an
2248 * additional delay to be observed by the receiver.
2249 */
2250 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2251 res->flags |= CF_EXPECT_MORE;
Christopher Faulet9768c262018-10-22 09:34:31 +02002252#endif
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253
2254 /* the stream handler will take care of timeouts and errors */
2255 return 0;
2256
2257 return_bad_res: /* let's centralize all bad responses */
2258 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2259 if (objt_server(s->target))
2260 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2261
2262 return_bad_res_stats_ok:
2263 txn->rsp.err_state = txn->rsp.msg_state;
2264 txn->rsp.msg_state = HTTP_MSG_ERROR;
2265 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002266 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002267 res->analysers &= AN_RES_FLT_END;
2268 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2269 if (objt_server(s->target))
2270 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
2271
2272 if (!(s->flags & SF_ERR_MASK))
2273 s->flags |= SF_ERR_PRXCOND;
2274 if (!(s->flags & SF_FINST_MASK))
2275 s->flags |= SF_FINST_D;
2276 return 0;
2277
2278 aborted_xfer:
2279 txn->rsp.err_state = txn->rsp.msg_state;
2280 txn->rsp.msg_state = HTTP_MSG_ERROR;
2281 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002282 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002283 res->analysers &= AN_RES_FLT_END;
2284 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2285
2286 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2287 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2288 if (objt_server(s->target))
2289 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2290
2291 if (!(s->flags & SF_ERR_MASK))
2292 s->flags |= SF_ERR_CLICL;
2293 if (!(s->flags & SF_FINST_MASK))
2294 s->flags |= SF_FINST_D;
2295 return 0;
2296}
2297
Christopher Faulet0f226952018-10-22 09:29:56 +02002298void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002299{
2300 struct proxy *fe = strm_fe(s);
2301 int tmp = TX_CON_WANT_CLO;
2302
2303 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2304 tmp = TX_CON_WANT_TUN;
2305
2306 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002307 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002308}
2309
2310/* Perform an HTTP redirect based on the information in <rule>. The function
2311 * returns non-zero on success, or zero in case of a, irrecoverable error such
2312 * as too large a request to build a valid response.
2313 */
2314int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2315{
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002316 struct htx *htx = htx_from_buf(&s->req.buf);
2317 union h1_sl sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002318 const char *msg_fmt;
2319 struct buffer *chunk;
2320 int ret = 0;
2321
2322 chunk = alloc_trash_chunk();
2323 if (!chunk)
2324 goto leave;
2325
2326 /* build redirect message */
2327 switch(rule->code) {
2328 case 308:
2329 msg_fmt = HTTP_308;
2330 break;
2331 case 307:
2332 msg_fmt = HTTP_307;
2333 break;
2334 case 303:
2335 msg_fmt = HTTP_303;
2336 break;
2337 case 301:
2338 msg_fmt = HTTP_301;
2339 break;
2340 case 302:
2341 default:
2342 msg_fmt = HTTP_302;
2343 break;
2344 }
2345
2346 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
2347 goto leave;
2348
2349 switch(rule->type) {
2350 case REDIRECT_TYPE_SCHEME: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002351 struct http_hdr_ctx ctx;
2352 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002354 host = ist("");
2355 ctx.blk = NULL;
2356 if (http_find_header(htx, ist("Host"), &ctx, 0))
2357 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002359 sl = http_find_stline(htx);
2360 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002361 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002362 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2364 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002365 while (qs < path.len) {
2366 if (*(path.ptr + qs) == '?') {
2367 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368 break;
2369 }
2370 qs++;
2371 }
2372 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002374 else
2375 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002376
2377 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002378 /* add scheme */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002379 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2380 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002381 }
2382 else {
2383 /* add scheme with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002384 chunk->data += build_logline(s, chunk->area + chunk->data,
2385 chunk->size - chunk->data,
2386 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002387 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002388 /* add "://" + host + path */
2389 if (!chunk_memcat(chunk, "://", 3) ||
2390 !chunk_memcat(chunk, host.ptr, host.len) ||
2391 !chunk_memcat(chunk, path.ptr, path.len))
2392 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002393
2394 /* append a slash at the end of the location if needed and missing */
2395 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2396 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002397 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002398 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002399 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002401 break;
2402 }
2403 case REDIRECT_TYPE_PREFIX: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002404 struct ist path;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002406 sl = http_find_stline(htx);
2407 path = http_get_path(sl.rq.u);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002408 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002409 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2411 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002412 while (qs < path.len) {
2413 if (*(path.ptr + qs) == '?') {
2414 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415 break;
2416 }
2417 qs++;
2418 }
2419 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002420 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002421 else
2422 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423
2424 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002425 /* add prefix. Note that if prefix == "/", we don't want to
2426 * add anything, otherwise it makes it hard for the user to
2427 * configure a self-redirection.
2428 */
2429 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002430 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2431 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432 }
2433 }
2434 else {
2435 /* add prefix with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002436 chunk->data += build_logline(s, chunk->area + chunk->data,
2437 chunk->size - chunk->data,
2438 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439 }
2440
2441 /* add path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002442 if (!chunk_memcat(chunk, path.ptr, path.len))
2443 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444
2445 /* append a slash at the end of the location if needed and missing */
2446 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2447 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002448 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002449 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002450 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002451 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452 break;
2453 }
2454 case REDIRECT_TYPE_LOCATION:
2455 default:
2456 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002457 /* add location */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002458 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2459 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002460 }
2461 else {
2462 /* add location with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002463 chunk->data += build_logline(s, chunk->area + chunk->data,
2464 chunk->size - chunk->data,
2465 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002466 }
2467 break;
2468 }
2469
2470 if (rule->cookie_len) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002471 if (!chunk_memcat(chunk, "\r\nSet-Cookie: ", 14) ||
2472 !chunk_memcat(chunk, rule->cookie_str, rule->cookie_len))
2473 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002474 }
2475
2476 /* add end of headers and the keep-alive/close status. */
2477 txn->status = rule->code;
2478 /* let's log the request time */
2479 s->logs.tv_request = now;
2480
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002481 /* FIXME: close for now, but it could be cool to handle the keep-alive here */
2482 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2483 if (!chunk_memcat(chunk, "\r\nProxy-Connection: close\r\n\r\n", 29))
2484 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002485 } else {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002486 if (!chunk_memcat(chunk, "\r\nConnection: close\r\n\r\n", 23))
2487 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002488 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002489 htx_reply_and_close(s, txn->status, chunk);
2490 s->req.analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002491
2492 if (!(s->flags & SF_ERR_MASK))
2493 s->flags |= SF_ERR_LOCAL;
2494 if (!(s->flags & SF_FINST_MASK))
2495 s->flags |= SF_FINST_R;
2496
2497 ret = 1;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002498 leave:
Christopher Fauletf2824e62018-10-01 12:12:37 +02002499 free_trash_chunk(chunk);
2500 return ret;
2501}
2502
Christopher Faulet72333522018-10-24 11:25:02 +02002503int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2504 struct ist name, const char *str, struct my_regex *re, int action)
2505{
2506 struct http_hdr_ctx ctx;
2507 struct buffer *output = get_trash_chunk();
2508
2509 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2510 ctx.blk = NULL;
2511 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2512 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2513 continue;
2514
2515 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2516 if (output->data == -1)
2517 return -1;
2518 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2519 return -1;
2520 }
2521 return 0;
2522}
2523
2524static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2525 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2526{
2527 struct buffer *replace;
2528 int ret = -1;
2529
2530 replace = alloc_trash_chunk();
2531 if (!replace)
2532 goto leave;
2533
2534 replace->data = build_logline(s, replace->area, replace->size, fmt);
2535 if (replace->data >= replace->size - 1)
2536 goto leave;
2537
2538 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2539
2540 leave:
2541 free_trash_chunk(replace);
2542 return ret;
2543}
2544
Christopher Faulet6eb92892018-11-15 16:39:29 +01002545/*
2546 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2547 * built according to <fmt> log line format.
2548 * If <early_hints> is NULL, it is allocated and the HTTP 103 response first
2549 * line is inserted before the header. If an error occurred <early_hints> is
2550 * released and NULL is returned. On success the updated buffer is returned.
2551 */
2552static struct buffer *htx_apply_early_hint_rule(struct stream* s, struct buffer *early_hints,
2553 const char* name, unsigned int name_len,
2554 struct list *fmt)
2555{
2556 if (!early_hints) {
2557 early_hints = alloc_trash_chunk();
2558 if (!early_hints)
2559 goto fail;
2560 if (!chunk_memcat(early_hints, HTTP_103.ptr, HTTP_103.len))
2561 goto fail;
2562 }
2563
2564 if (!chunk_memcat(early_hints, name, name_len) || !chunk_memcat(early_hints, ": ", 2))
2565 goto fail;
2566
2567 early_hints->data += build_logline(s, b_tail(early_hints), b_room(early_hints), fmt);
2568 if (!chunk_memcat(early_hints, "\r\n", 2))
2569 goto fail;
2570
2571 return early_hints;
2572
2573 fail:
2574 free_trash_chunk(early_hints);
2575 return NULL;
2576}
2577
2578/* Sends an HTTP 103 response. Before sending it, the last CRLF finishing the
2579 * response is added. If an error occurred or if another response was already
2580 * sent, this function does nothing.
2581 */
2582static void htx_send_early_hints(struct stream *s, struct buffer *early_hints)
2583{
2584 struct channel *chn = s->txn->rsp.chn;
2585 struct htx *htx;
2586
2587 /* If a response was already sent, skip early hints */
2588 if (s->txn->status > 0)
2589 return;
2590
2591 if (!chunk_memcat(early_hints, "\r\n", 2))
2592 return;
2593
2594 htx = htx_from_buf(&chn->buf);
2595 if (!htx_add_oob(htx, ist2(early_hints->area, early_hints->data)))
2596 return;
2597
2598 c_adv(chn, early_hints->data);
2599 chn->total += early_hints->data;
2600}
2601
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002602/* This function executes one of the set-{method,path,query,uri} actions. It
2603 * takes the string from the variable 'replace' with length 'len', then modifies
2604 * the relevant part of the request line accordingly. Then it updates various
2605 * pointers to the next elements which were moved, and the total buffer length.
2606 * It finds the action to be performed in p[2], previously filled by function
2607 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2608 * error, though this can be revisited when this code is finally exploited.
2609 *
2610 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2611 * query string and 3 to replace uri.
2612 *
2613 * In query string case, the mark question '?' must be set at the start of the
2614 * string by the caller, event if the replacement query string is empty.
2615 */
2616int htx_req_replace_stline(int action, const char *replace, int len,
2617 struct proxy *px, struct stream *s)
2618{
2619 struct htx *htx = htx_from_buf(&s->req.buf);
2620
2621 switch (action) {
2622 case 0: // method
2623 if (!http_replace_req_meth(htx, ist2(replace, len)))
2624 return -1;
2625 break;
2626
2627 case 1: // path
2628 if (!http_replace_req_path(htx, ist2(replace, len)))
2629 return -1;
2630 break;
2631
2632 case 2: // query
2633 if (!http_replace_req_query(htx, ist2(replace, len)))
2634 return -1;
2635 break;
2636
2637 case 3: // uri
2638 if (!http_replace_req_uri(htx, ist2(replace, len)))
2639 return -1;
2640 break;
2641
2642 default:
2643 return -1;
2644 }
2645 return 0;
2646}
2647
2648/* This function replace the HTTP status code and the associated message. The
2649 * variable <status> contains the new status code. This function never fails.
2650 */
2651void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2652{
2653 struct htx *htx = htx_from_buf(&s->res.buf);
2654 char *res;
2655
2656 chunk_reset(&trash);
2657 res = ultoa_o(status, trash.area, trash.size);
2658 trash.data = res - trash.area;
2659
2660 /* Do we have a custom reason format string? */
2661 if (reason == NULL)
2662 reason = http_get_reason(status);
2663
2664 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2665 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2666}
2667
Christopher Faulet3e964192018-10-24 11:39:23 +02002668/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2669 * transaction <txn>. Returns the verdict of the first rule that prevents
2670 * further processing of the request (auth, deny, ...), and defaults to
2671 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2672 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2673 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2674 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2675 * status.
2676 */
2677static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2678 struct stream *s, int *deny_status)
2679{
2680 struct session *sess = strm_sess(s);
2681 struct http_txn *txn = s->txn;
2682 struct htx *htx;
2683 struct connection *cli_conn;
2684 struct act_rule *rule;
2685 struct http_hdr_ctx ctx;
2686 const char *auth_realm;
2687 struct buffer *early_hints = NULL;
2688 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2689 int act_flags = 0;
2690
2691 htx = htx_from_buf(&s->req.buf);
2692
2693 /* If "the current_rule_list" match the executed rule list, we are in
2694 * resume condition. If a resume is needed it is always in the action
2695 * and never in the ACL or converters. In this case, we initialise the
2696 * current rule, and go to the action execution point.
2697 */
2698 if (s->current_rule) {
2699 rule = s->current_rule;
2700 s->current_rule = NULL;
2701 if (s->current_rule_list == rules)
2702 goto resume_execution;
2703 }
2704 s->current_rule_list = rules;
2705
2706 list_for_each_entry(rule, rules, list) {
2707 /* check optional condition */
2708 if (rule->cond) {
2709 int ret;
2710
2711 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2712 ret = acl_pass(ret);
2713
2714 if (rule->cond->pol == ACL_COND_UNLESS)
2715 ret = !ret;
2716
2717 if (!ret) /* condition not matched */
2718 continue;
2719 }
2720
2721 act_flags |= ACT_FLAG_FIRST;
2722 resume_execution:
2723 switch (rule->action) {
2724 case ACT_ACTION_ALLOW:
2725 rule_ret = HTTP_RULE_RES_STOP;
2726 goto end;
2727
2728 case ACT_ACTION_DENY:
2729 if (deny_status)
2730 *deny_status = rule->deny_status;
2731 rule_ret = HTTP_RULE_RES_DENY;
2732 goto end;
2733
2734 case ACT_HTTP_REQ_TARPIT:
2735 txn->flags |= TX_CLTARPIT;
2736 if (deny_status)
2737 *deny_status = rule->deny_status;
2738 rule_ret = HTTP_RULE_RES_DENY;
2739 goto end;
2740
2741 case ACT_HTTP_REQ_AUTH:
2742 /* Be sure to sned any pending HTTP 103 response first */
2743 if (early_hints) {
2744 htx_send_early_hints(s, early_hints);
2745 free_trash_chunk(early_hints);
2746 early_hints = NULL;
2747 }
2748 /* Auth might be performed on regular http-req rules as well as on stats */
2749 auth_realm = rule->arg.auth.realm;
2750 if (!auth_realm) {
2751 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2752 auth_realm = STATS_DEFAULT_REALM;
2753 else
2754 auth_realm = px->id;
2755 }
2756 /* send 401/407 depending on whether we use a proxy or not. We still
2757 * count one error, because normal browsing won't significantly
2758 * increase the counter but brute force attempts will.
2759 */
2760 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
2761 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
2762 htx_reply_and_close(s, txn->status, &trash);
2763 stream_inc_http_err_ctr(s);
2764 rule_ret = HTTP_RULE_RES_ABRT;
2765 goto end;
2766
2767 case ACT_HTTP_REDIR:
2768 /* Be sure to sned any pending HTTP 103 response first */
2769 if (early_hints) {
2770 htx_send_early_hints(s, early_hints);
2771 free_trash_chunk(early_hints);
2772 early_hints = NULL;
2773 }
2774 rule_ret = HTTP_RULE_RES_DONE;
2775 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2776 rule_ret = HTTP_RULE_RES_BADREQ;
2777 goto end;
2778
2779 case ACT_HTTP_SET_NICE:
2780 s->task->nice = rule->arg.nice;
2781 break;
2782
2783 case ACT_HTTP_SET_TOS:
2784 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2785 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2786 break;
2787
2788 case ACT_HTTP_SET_MARK:
2789#ifdef SO_MARK
2790 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2791 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2792#endif
2793 break;
2794
2795 case ACT_HTTP_SET_LOGL:
2796 s->logs.level = rule->arg.loglevel;
2797 break;
2798
2799 case ACT_HTTP_REPLACE_HDR:
2800 case ACT_HTTP_REPLACE_VAL:
2801 if (htx_transform_header(s, &s->req, htx,
2802 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2803 &rule->arg.hdr_add.fmt,
2804 &rule->arg.hdr_add.re, rule->action)) {
2805 rule_ret = HTTP_RULE_RES_BADREQ;
2806 goto end;
2807 }
2808 break;
2809
2810 case ACT_HTTP_DEL_HDR:
2811 /* remove all occurrences of the header */
2812 ctx.blk = NULL;
2813 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2814 http_remove_header(htx, &ctx);
2815 break;
2816
2817 case ACT_HTTP_SET_HDR:
2818 case ACT_HTTP_ADD_HDR: {
2819 /* The scope of the trash buffer must be limited to this function. The
2820 * build_logline() function can execute a lot of other function which
2821 * can use the trash buffer. So for limiting the scope of this global
2822 * buffer, we build first the header value using build_logline, and
2823 * after we store the header name.
2824 */
2825 struct buffer *replace;
2826 struct ist n, v;
2827
2828 replace = alloc_trash_chunk();
2829 if (!replace) {
2830 rule_ret = HTTP_RULE_RES_BADREQ;
2831 goto end;
2832 }
2833
2834 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2835 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2836 v = ist2(replace->area, replace->data);
2837
2838 if (rule->action == ACT_HTTP_SET_HDR) {
2839 /* remove all occurrences of the header */
2840 ctx.blk = NULL;
2841 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2842 http_remove_header(htx, &ctx);
2843 }
2844
2845 if (!http_add_header(htx, n, v)) {
2846 static unsigned char rate_limit = 0;
2847
2848 if ((rate_limit++ & 255) == 0) {
2849 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);
2850 }
2851
2852 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2853 if (sess->fe != s->be)
2854 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2855 if (sess->listener->counters)
2856 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2857 }
2858 free_trash_chunk(replace);
2859 break;
2860 }
2861
2862 case ACT_HTTP_DEL_ACL:
2863 case ACT_HTTP_DEL_MAP: {
2864 struct pat_ref *ref;
2865 struct buffer *key;
2866
2867 /* collect reference */
2868 ref = pat_ref_lookup(rule->arg.map.ref);
2869 if (!ref)
2870 continue;
2871
2872 /* allocate key */
2873 key = alloc_trash_chunk();
2874 if (!key) {
2875 rule_ret = HTTP_RULE_RES_BADREQ;
2876 goto end;
2877 }
2878
2879 /* collect key */
2880 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2881 key->area[key->data] = '\0';
2882
2883 /* perform update */
2884 /* returned code: 1=ok, 0=ko */
2885 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2886 pat_ref_delete(ref, key->area);
2887 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2888
2889 free_trash_chunk(key);
2890 break;
2891 }
2892
2893 case ACT_HTTP_ADD_ACL: {
2894 struct pat_ref *ref;
2895 struct buffer *key;
2896
2897 /* collect reference */
2898 ref = pat_ref_lookup(rule->arg.map.ref);
2899 if (!ref)
2900 continue;
2901
2902 /* allocate key */
2903 key = alloc_trash_chunk();
2904 if (!key) {
2905 rule_ret = HTTP_RULE_RES_BADREQ;
2906 goto end;
2907 }
2908
2909 /* collect key */
2910 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2911 key->area[key->data] = '\0';
2912
2913 /* perform update */
2914 /* add entry only if it does not already exist */
2915 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2916 if (pat_ref_find_elt(ref, key->area) == NULL)
2917 pat_ref_add(ref, key->area, NULL, NULL);
2918 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2919
2920 free_trash_chunk(key);
2921 break;
2922 }
2923
2924 case ACT_HTTP_SET_MAP: {
2925 struct pat_ref *ref;
2926 struct buffer *key, *value;
2927
2928 /* collect reference */
2929 ref = pat_ref_lookup(rule->arg.map.ref);
2930 if (!ref)
2931 continue;
2932
2933 /* allocate key */
2934 key = alloc_trash_chunk();
2935 if (!key) {
2936 rule_ret = HTTP_RULE_RES_BADREQ;
2937 goto end;
2938 }
2939
2940 /* allocate value */
2941 value = alloc_trash_chunk();
2942 if (!value) {
2943 free_trash_chunk(key);
2944 rule_ret = HTTP_RULE_RES_BADREQ;
2945 goto end;
2946 }
2947
2948 /* collect key */
2949 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2950 key->area[key->data] = '\0';
2951
2952 /* collect value */
2953 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2954 value->area[value->data] = '\0';
2955
2956 /* perform update */
2957 if (pat_ref_find_elt(ref, key->area) != NULL)
2958 /* update entry if it exists */
2959 pat_ref_set(ref, key->area, value->area, NULL);
2960 else
2961 /* insert a new entry */
2962 pat_ref_add(ref, key->area, value->area, NULL);
2963
2964 free_trash_chunk(key);
2965 free_trash_chunk(value);
2966 break;
2967 }
2968
2969 case ACT_HTTP_EARLY_HINT:
2970 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2971 break;
2972 early_hints = htx_apply_early_hint_rule(s, early_hints,
2973 rule->arg.early_hint.name,
2974 rule->arg.early_hint.name_len,
2975 &rule->arg.early_hint.fmt);
2976 if (!early_hints) {
2977 rule_ret = HTTP_RULE_RES_DONE;
2978 goto end;
2979 }
2980 break;
2981
2982 case ACT_CUSTOM:
2983 if ((s->req.flags & CF_READ_ERROR) ||
2984 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2985 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
2986 (px->options & PR_O_ABRT_CLOSE)))
2987 act_flags |= ACT_FLAG_FINAL;
2988
2989 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
2990 case ACT_RET_ERR:
2991 case ACT_RET_CONT:
2992 break;
2993 case ACT_RET_STOP:
2994 rule_ret = HTTP_RULE_RES_DONE;
2995 goto end;
2996 case ACT_RET_YIELD:
2997 s->current_rule = rule;
2998 rule_ret = HTTP_RULE_RES_YIELD;
2999 goto end;
3000 }
3001 break;
3002
3003 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3004 /* Note: only the first valid tracking parameter of each
3005 * applies.
3006 */
3007
3008 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3009 struct stktable *t;
3010 struct stksess *ts;
3011 struct stktable_key *key;
3012 void *ptr1, *ptr2;
3013
3014 t = rule->arg.trk_ctr.table.t;
3015 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3016 rule->arg.trk_ctr.expr, NULL);
3017
3018 if (key && (ts = stktable_get_entry(t, key))) {
3019 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3020
3021 /* let's count a new HTTP request as it's the first time we do it */
3022 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3023 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3024 if (ptr1 || ptr2) {
3025 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3026
3027 if (ptr1)
3028 stktable_data_cast(ptr1, http_req_cnt)++;
3029
3030 if (ptr2)
3031 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3032 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3033
3034 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3035
3036 /* If data was modified, we need to touch to re-schedule sync */
3037 stktable_touch_local(t, ts, 0);
3038 }
3039
3040 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3041 if (sess->fe != s->be)
3042 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3043 }
3044 }
3045 break;
3046
3047 /* other flags exists, but normaly, they never be matched. */
3048 default:
3049 break;
3050 }
3051 }
3052
3053 end:
3054 if (early_hints) {
3055 htx_send_early_hints(s, early_hints);
3056 free_trash_chunk(early_hints);
3057 }
3058
3059 /* we reached the end of the rules, nothing to report */
3060 return rule_ret;
3061}
3062
3063/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3064 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3065 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3066 * is returned, the process can continue the evaluation of next rule list. If
3067 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3068 * is returned, it means the operation could not be processed and a server error
3069 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3070 * deny rule. If *YIELD is returned, the caller must call again the function
3071 * with the same context.
3072 */
3073static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3074 struct stream *s)
3075{
3076 struct session *sess = strm_sess(s);
3077 struct http_txn *txn = s->txn;
3078 struct htx *htx;
3079 struct connection *cli_conn;
3080 struct act_rule *rule;
3081 struct http_hdr_ctx ctx;
3082 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3083 int act_flags = 0;
3084
3085 htx = htx_from_buf(&s->res.buf);
3086
3087 /* If "the current_rule_list" match the executed rule list, we are in
3088 * resume condition. If a resume is needed it is always in the action
3089 * and never in the ACL or converters. In this case, we initialise the
3090 * current rule, and go to the action execution point.
3091 */
3092 if (s->current_rule) {
3093 rule = s->current_rule;
3094 s->current_rule = NULL;
3095 if (s->current_rule_list == rules)
3096 goto resume_execution;
3097 }
3098 s->current_rule_list = rules;
3099
3100 list_for_each_entry(rule, rules, list) {
3101 /* check optional condition */
3102 if (rule->cond) {
3103 int ret;
3104
3105 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3106 ret = acl_pass(ret);
3107
3108 if (rule->cond->pol == ACL_COND_UNLESS)
3109 ret = !ret;
3110
3111 if (!ret) /* condition not matched */
3112 continue;
3113 }
3114
3115 act_flags |= ACT_FLAG_FIRST;
3116resume_execution:
3117 switch (rule->action) {
3118 case ACT_ACTION_ALLOW:
3119 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3120 goto end;
3121
3122 case ACT_ACTION_DENY:
3123 txn->flags |= TX_SVDENY;
3124 rule_ret = HTTP_RULE_RES_STOP;
3125 goto end;
3126
3127 case ACT_HTTP_SET_NICE:
3128 s->task->nice = rule->arg.nice;
3129 break;
3130
3131 case ACT_HTTP_SET_TOS:
3132 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3133 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3134 break;
3135
3136 case ACT_HTTP_SET_MARK:
3137#ifdef SO_MARK
3138 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3139 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3140#endif
3141 break;
3142
3143 case ACT_HTTP_SET_LOGL:
3144 s->logs.level = rule->arg.loglevel;
3145 break;
3146
3147 case ACT_HTTP_REPLACE_HDR:
3148 case ACT_HTTP_REPLACE_VAL:
3149 if (htx_transform_header(s, &s->res, htx,
3150 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3151 &rule->arg.hdr_add.fmt,
3152 &rule->arg.hdr_add.re, rule->action)) {
3153 rule_ret = HTTP_RULE_RES_BADREQ;
3154 goto end;
3155 }
3156 break;
3157
3158 case ACT_HTTP_DEL_HDR:
3159 /* remove all occurrences of the header */
3160 ctx.blk = NULL;
3161 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3162 http_remove_header(htx, &ctx);
3163 break;
3164
3165 case ACT_HTTP_SET_HDR:
3166 case ACT_HTTP_ADD_HDR: {
3167 struct buffer *replace;
3168 struct ist n, v;
3169
3170 replace = alloc_trash_chunk();
3171 if (!replace) {
3172 rule_ret = HTTP_RULE_RES_BADREQ;
3173 goto end;
3174 }
3175
3176 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3177 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3178 v = ist2(replace->area, replace->data);
3179
3180 if (rule->action == ACT_HTTP_SET_HDR) {
3181 /* remove all occurrences of the header */
3182 ctx.blk = NULL;
3183 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3184 http_remove_header(htx, &ctx);
3185 }
3186
3187 if (!http_add_header(htx, n, v)) {
3188 static unsigned char rate_limit = 0;
3189
3190 if ((rate_limit++ & 255) == 0) {
3191 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);
3192 }
3193
3194 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3195 if (sess->fe != s->be)
3196 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3197 if (sess->listener->counters)
3198 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3199 if (objt_server(s->target))
3200 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3201 }
3202 free_trash_chunk(replace);
3203 break;
3204 }
3205
3206 case ACT_HTTP_DEL_ACL:
3207 case ACT_HTTP_DEL_MAP: {
3208 struct pat_ref *ref;
3209 struct buffer *key;
3210
3211 /* collect reference */
3212 ref = pat_ref_lookup(rule->arg.map.ref);
3213 if (!ref)
3214 continue;
3215
3216 /* allocate key */
3217 key = alloc_trash_chunk();
3218 if (!key) {
3219 rule_ret = HTTP_RULE_RES_BADREQ;
3220 goto end;
3221 }
3222
3223 /* collect key */
3224 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3225 key->area[key->data] = '\0';
3226
3227 /* perform update */
3228 /* returned code: 1=ok, 0=ko */
3229 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3230 pat_ref_delete(ref, key->area);
3231 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3232
3233 free_trash_chunk(key);
3234 break;
3235 }
3236
3237 case ACT_HTTP_ADD_ACL: {
3238 struct pat_ref *ref;
3239 struct buffer *key;
3240
3241 /* collect reference */
3242 ref = pat_ref_lookup(rule->arg.map.ref);
3243 if (!ref)
3244 continue;
3245
3246 /* allocate key */
3247 key = alloc_trash_chunk();
3248 if (!key) {
3249 rule_ret = HTTP_RULE_RES_BADREQ;
3250 goto end;
3251 }
3252
3253 /* collect key */
3254 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3255 key->area[key->data] = '\0';
3256
3257 /* perform update */
3258 /* check if the entry already exists */
3259 if (pat_ref_find_elt(ref, key->area) == NULL)
3260 pat_ref_add(ref, key->area, NULL, NULL);
3261
3262 free_trash_chunk(key);
3263 break;
3264 }
3265
3266 case ACT_HTTP_SET_MAP: {
3267 struct pat_ref *ref;
3268 struct buffer *key, *value;
3269
3270 /* collect reference */
3271 ref = pat_ref_lookup(rule->arg.map.ref);
3272 if (!ref)
3273 continue;
3274
3275 /* allocate key */
3276 key = alloc_trash_chunk();
3277 if (!key) {
3278 rule_ret = HTTP_RULE_RES_BADREQ;
3279 goto end;
3280 }
3281
3282 /* allocate value */
3283 value = alloc_trash_chunk();
3284 if (!value) {
3285 free_trash_chunk(key);
3286 rule_ret = HTTP_RULE_RES_BADREQ;
3287 goto end;
3288 }
3289
3290 /* collect key */
3291 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3292 key->area[key->data] = '\0';
3293
3294 /* collect value */
3295 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3296 value->area[value->data] = '\0';
3297
3298 /* perform update */
3299 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3300 if (pat_ref_find_elt(ref, key->area) != NULL)
3301 /* update entry if it exists */
3302 pat_ref_set(ref, key->area, value->area, NULL);
3303 else
3304 /* insert a new entry */
3305 pat_ref_add(ref, key->area, value->area, NULL);
3306 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3307 free_trash_chunk(key);
3308 free_trash_chunk(value);
3309 break;
3310 }
3311
3312 case ACT_HTTP_REDIR:
3313 rule_ret = HTTP_RULE_RES_DONE;
3314 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3315 rule_ret = HTTP_RULE_RES_BADREQ;
3316 goto end;
3317
3318 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3319 /* Note: only the first valid tracking parameter of each
3320 * applies.
3321 */
3322 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3323 struct stktable *t;
3324 struct stksess *ts;
3325 struct stktable_key *key;
3326 void *ptr;
3327
3328 t = rule->arg.trk_ctr.table.t;
3329 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3330 rule->arg.trk_ctr.expr, NULL);
3331
3332 if (key && (ts = stktable_get_entry(t, key))) {
3333 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3334
3335 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3336
3337 /* let's count a new HTTP request as it's the first time we do it */
3338 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3339 if (ptr)
3340 stktable_data_cast(ptr, http_req_cnt)++;
3341
3342 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3343 if (ptr)
3344 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3345 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3346
3347 /* When the client triggers a 4xx from the server, it's most often due
3348 * to a missing object or permission. These events should be tracked
3349 * because if they happen often, it may indicate a brute force or a
3350 * vulnerability scan. Normally this is done when receiving the response
3351 * but here we're tracking after this ought to have been done so we have
3352 * to do it on purpose.
3353 */
3354 if ((unsigned)(txn->status - 400) < 100) {
3355 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3356 if (ptr)
3357 stktable_data_cast(ptr, http_err_cnt)++;
3358
3359 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3360 if (ptr)
3361 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3362 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3363 }
3364
3365 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3366
3367 /* If data was modified, we need to touch to re-schedule sync */
3368 stktable_touch_local(t, ts, 0);
3369
3370 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3371 if (sess->fe != s->be)
3372 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3373 }
3374 }
3375 break;
3376
3377 case ACT_CUSTOM:
3378 if ((s->req.flags & CF_READ_ERROR) ||
3379 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3380 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3381 (px->options & PR_O_ABRT_CLOSE)))
3382 act_flags |= ACT_FLAG_FINAL;
3383
3384 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3385 case ACT_RET_ERR:
3386 case ACT_RET_CONT:
3387 break;
3388 case ACT_RET_STOP:
3389 rule_ret = HTTP_RULE_RES_STOP;
3390 goto end;
3391 case ACT_RET_YIELD:
3392 s->current_rule = rule;
3393 rule_ret = HTTP_RULE_RES_YIELD;
3394 goto end;
3395 }
3396 break;
3397
3398 /* other flags exists, but normaly, they never be matched. */
3399 default:
3400 break;
3401 }
3402 }
3403
3404 end:
3405 /* we reached the end of the rules, nothing to report */
3406 return rule_ret;
3407}
3408
Christopher Faulet33640082018-10-24 11:53:01 +02003409/* Iterate the same filter through all request headers.
3410 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3411 * Since it can manage the switch to another backend, it updates the per-proxy
3412 * DENY stats.
3413 */
3414static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3415{
3416 struct http_txn *txn = s->txn;
3417 struct htx *htx;
3418 struct buffer *hdr = get_trash_chunk();
3419 int32_t pos;
3420
3421 htx = htx_from_buf(&req->buf);
3422
3423 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3424 struct htx_blk *blk = htx_get_blk(htx, pos);
3425 enum htx_blk_type type;
3426 struct ist n, v;
3427
3428 next_hdr:
3429 type = htx_get_blk_type(blk);
3430 if (type == HTX_BLK_EOH)
3431 break;
3432 if (type != HTX_BLK_HDR)
3433 continue;
3434
3435 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3436 return 1;
3437 else if (unlikely(txn->flags & TX_CLALLOW) &&
3438 (exp->action == ACT_ALLOW ||
3439 exp->action == ACT_DENY ||
3440 exp->action == ACT_TARPIT))
3441 return 0;
3442
3443 n = htx_get_blk_name(htx, blk);
3444 v = htx_get_blk_value(htx, blk);
3445
3446 chunk_memcat(hdr, n.ptr, n.len);
3447 hdr->area[hdr->data++] = ':';
3448 hdr->area[hdr->data++] = ' ';
3449 chunk_memcat(hdr, v.ptr, v.len);
3450
3451 /* Now we have one header in <hdr> */
3452
3453 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3454 struct http_hdr_ctx ctx;
3455 int len;
3456
3457 switch (exp->action) {
3458 case ACT_ALLOW:
3459 txn->flags |= TX_CLALLOW;
3460 goto end;
3461
3462 case ACT_DENY:
3463 txn->flags |= TX_CLDENY;
3464 goto end;
3465
3466 case ACT_TARPIT:
3467 txn->flags |= TX_CLTARPIT;
3468 goto end;
3469
3470 case ACT_REPLACE:
3471 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3472 if (len < 0)
3473 return -1;
3474
3475 http_parse_header(ist2(trash.area, len), &n, &v);
3476 ctx.blk = blk;
3477 ctx.value = v;
3478 if (!http_replace_header(htx, &ctx, n, v))
3479 return -1;
3480 if (!ctx.blk)
3481 goto end;
3482 pos = htx_get_blk_pos(htx, blk);
3483 break;
3484
3485 case ACT_REMOVE:
3486 ctx.blk = blk;
3487 ctx.value = v;
3488 if (!http_remove_header(htx, &ctx))
3489 return -1;
3490 if (!ctx.blk)
3491 goto end;
3492 pos = htx_get_blk_pos(htx, blk);
3493 goto next_hdr;
3494
3495 }
3496 }
3497 }
3498 end:
3499 return 0;
3500}
3501
3502/* Apply the filter to the request line.
3503 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3504 * or -1 if a replacement resulted in an invalid request line.
3505 * Since it can manage the switch to another backend, it updates the per-proxy
3506 * DENY stats.
3507 */
3508static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3509{
3510 struct http_txn *txn = s->txn;
3511 struct htx *htx;
3512 struct buffer *reqline = get_trash_chunk();
3513 int done;
3514
3515 htx = htx_from_buf(&req->buf);
3516
3517 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3518 return 1;
3519 else if (unlikely(txn->flags & TX_CLALLOW) &&
3520 (exp->action == ACT_ALLOW ||
3521 exp->action == ACT_DENY ||
3522 exp->action == ACT_TARPIT))
3523 return 0;
3524 else if (exp->action == ACT_REMOVE)
3525 return 0;
3526
3527 done = 0;
3528
3529 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3530
3531 /* Now we have the request line between cur_ptr and cur_end */
3532 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
3533 union h1_sl sl;
3534 int len;
3535
3536 switch (exp->action) {
3537 case ACT_ALLOW:
3538 txn->flags |= TX_CLALLOW;
3539 done = 1;
3540 break;
3541
3542 case ACT_DENY:
3543 txn->flags |= TX_CLDENY;
3544 done = 1;
3545 break;
3546
3547 case ACT_TARPIT:
3548 txn->flags |= TX_CLTARPIT;
3549 done = 1;
3550 break;
3551
3552 case ACT_REPLACE:
3553 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3554 if (len < 0)
3555 return -1;
3556
3557 http_parse_stline(ist2(trash.area, len),
3558 &sl.rq.m, &sl.rq.u, &sl.rq.v);
3559 sl.rq.meth = find_http_meth(sl.rq.m.ptr, sl.rq.m.len);
3560
3561 if (!http_replace_reqline(htx, sl))
3562 return -1;
3563 done = 1;
3564 break;
3565 }
3566 }
3567 return done;
3568}
3569
3570/*
3571 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3572 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3573 * unparsable request. Since it can manage the switch to another backend, it
3574 * updates the per-proxy DENY stats.
3575 */
3576static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3577{
3578 struct session *sess = s->sess;
3579 struct http_txn *txn = s->txn;
3580 struct hdr_exp *exp;
3581
3582 for (exp = px->req_exp; exp; exp = exp->next) {
3583 int ret;
3584
3585 /*
3586 * The interleaving of transformations and verdicts
3587 * makes it difficult to decide to continue or stop
3588 * the evaluation.
3589 */
3590
3591 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3592 break;
3593
3594 if ((txn->flags & TX_CLALLOW) &&
3595 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3596 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3597 continue;
3598
3599 /* if this filter had a condition, evaluate it now and skip to
3600 * next filter if the condition does not match.
3601 */
3602 if (exp->cond) {
3603 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3604 ret = acl_pass(ret);
3605 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3606 ret = !ret;
3607
3608 if (!ret)
3609 continue;
3610 }
3611
3612 /* Apply the filter to the request line. */
3613 ret = htx_apply_filter_to_req_line(s, req, exp);
3614 if (unlikely(ret < 0))
3615 return -1;
3616
3617 if (likely(ret == 0)) {
3618 /* The filter did not match the request, it can be
3619 * iterated through all headers.
3620 */
3621 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3622 return -1;
3623 }
3624 }
3625 return 0;
3626}
3627
3628/* Iterate the same filter through all response headers contained in <res>.
3629 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3630 */
3631static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3632{
3633 struct http_txn *txn = s->txn;
3634 struct htx *htx;
3635 struct buffer *hdr = get_trash_chunk();
3636 int32_t pos;
3637
3638 htx = htx_from_buf(&res->buf);
3639
3640 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3641 struct htx_blk *blk = htx_get_blk(htx, pos);
3642 enum htx_blk_type type;
3643 struct ist n, v;
3644
3645 next_hdr:
3646 type = htx_get_blk_type(blk);
3647 if (type == HTX_BLK_EOH)
3648 break;
3649 if (type != HTX_BLK_HDR)
3650 continue;
3651
3652 if (unlikely(txn->flags & TX_SVDENY))
3653 return 1;
3654 else if (unlikely(txn->flags & TX_SVALLOW) &&
3655 (exp->action == ACT_ALLOW ||
3656 exp->action == ACT_DENY))
3657 return 0;
3658
3659 n = htx_get_blk_name(htx, blk);
3660 v = htx_get_blk_value(htx, blk);
3661
3662 chunk_memcat(hdr, n.ptr, n.len);
3663 hdr->area[hdr->data++] = ':';
3664 hdr->area[hdr->data++] = ' ';
3665 chunk_memcat(hdr, v.ptr, v.len);
3666
3667 /* Now we have one header in <hdr> */
3668
3669 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3670 struct http_hdr_ctx ctx;
3671 int len;
3672
3673 switch (exp->action) {
3674 case ACT_ALLOW:
3675 txn->flags |= TX_SVALLOW;
3676 goto end;
3677 break;
3678
3679 case ACT_DENY:
3680 txn->flags |= TX_SVDENY;
3681 goto end;
3682 break;
3683
3684 case ACT_REPLACE:
3685 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3686 if (len < 0)
3687 return -1;
3688
3689 http_parse_header(ist2(trash.area, len), &n, &v);
3690 ctx.blk = blk;
3691 ctx.value = v;
3692 if (!http_replace_header(htx, &ctx, n, v))
3693 return -1;
3694 if (!ctx.blk)
3695 goto end;
3696 pos = htx_get_blk_pos(htx, blk);
3697 break;
3698
3699 case ACT_REMOVE:
3700 ctx.blk = blk;
3701 ctx.value = v;
3702 if (!http_remove_header(htx, &ctx))
3703 return -1;
3704 if (!ctx.blk)
3705 goto end;
3706 pos = htx_get_blk_pos(htx, blk);
3707 goto next_hdr;
3708 }
3709 }
3710
3711 }
3712 end:
3713 return 0;
3714}
3715
3716/* Apply the filter to the status line in the response buffer <res>.
3717 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3718 * or -1 if a replacement resulted in an invalid status line.
3719 */
3720static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3721{
3722 struct http_txn *txn = s->txn;
3723 struct htx *htx;
3724 struct buffer *resline = get_trash_chunk();
3725 int done;
3726
3727 htx = htx_from_buf(&res->buf);
3728
3729 if (unlikely(txn->flags & TX_SVDENY))
3730 return 1;
3731 else if (unlikely(txn->flags & TX_SVALLOW) &&
3732 (exp->action == ACT_ALLOW ||
3733 exp->action == ACT_DENY))
3734 return 0;
3735 else if (exp->action == ACT_REMOVE)
3736 return 0;
3737
3738 done = 0;
3739 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3740
3741 /* Now we have the status line between cur_ptr and cur_end */
3742 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
3743 union h1_sl sl;
3744 int len;
3745
3746 switch (exp->action) {
3747 case ACT_ALLOW:
3748 txn->flags |= TX_SVALLOW;
3749 done = 1;
3750 break;
3751
3752 case ACT_DENY:
3753 txn->flags |= TX_SVDENY;
3754 done = 1;
3755 break;
3756
3757 case ACT_REPLACE:
3758 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3759 if (len < 0)
3760 return -1;
3761
3762 http_parse_stline(ist2(trash.area, len),
3763 &sl.st.v, &sl.st.c, &sl.st.r);
3764 sl.st.status = strl2ui(sl.st.c.ptr, sl.st.c.len);
3765
3766 if (!http_replace_resline(htx, sl))
3767 return -1;
3768
3769 done = 1;
3770 return 1;
3771 }
3772 }
3773 return done;
3774}
3775
3776/*
3777 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3778 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3779 * unparsable response.
3780 */
3781static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3782{
3783 struct session *sess = s->sess;
3784 struct http_txn *txn = s->txn;
3785 struct hdr_exp *exp;
3786
3787 for (exp = px->rsp_exp; exp; exp = exp->next) {
3788 int ret;
3789
3790 /*
3791 * The interleaving of transformations and verdicts
3792 * makes it difficult to decide to continue or stop
3793 * the evaluation.
3794 */
3795
3796 if (txn->flags & TX_SVDENY)
3797 break;
3798
3799 if ((txn->flags & TX_SVALLOW) &&
3800 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3801 exp->action == ACT_PASS)) {
3802 exp = exp->next;
3803 continue;
3804 }
3805
3806 /* if this filter had a condition, evaluate it now and skip to
3807 * next filter if the condition does not match.
3808 */
3809 if (exp->cond) {
3810 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3811 ret = acl_pass(ret);
3812 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3813 ret = !ret;
3814 if (!ret)
3815 continue;
3816 }
3817
3818 /* Apply the filter to the status line. */
3819 ret = htx_apply_filter_to_sts_line(s, res, exp);
3820 if (unlikely(ret < 0))
3821 return -1;
3822
3823 if (likely(ret == 0)) {
3824 /* The filter did not match the response, it can be
3825 * iterated through all headers.
3826 */
3827 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3828 return -1;
3829 }
3830 }
3831 return 0;
3832}
3833
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003834/*
3835 * Manage client-side cookie. It can impact performance by about 2% so it is
3836 * desirable to call it only when needed. This code is quite complex because
3837 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3838 * highly recommended not to touch this part without a good reason !
3839 */
3840static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3841{
3842 struct session *sess = s->sess;
3843 struct http_txn *txn = s->txn;
3844 struct htx *htx;
3845 struct http_hdr_ctx ctx;
3846 char *hdr_beg, *hdr_end, *del_from;
3847 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3848 int preserve_hdr;
3849
3850 htx = htx_from_buf(&req->buf);
3851 ctx.blk = NULL;
3852 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3853 del_from = NULL; /* nothing to be deleted */
3854 preserve_hdr = 0; /* assume we may kill the whole header */
3855
3856 /* Now look for cookies. Conforming to RFC2109, we have to support
3857 * attributes whose name begin with a '$', and associate them with
3858 * the right cookie, if we want to delete this cookie.
3859 * So there are 3 cases for each cookie read :
3860 * 1) it's a special attribute, beginning with a '$' : ignore it.
3861 * 2) it's a server id cookie that we *MAY* want to delete : save
3862 * some pointers on it (last semi-colon, beginning of cookie...)
3863 * 3) it's an application cookie : we *MAY* have to delete a previous
3864 * "special" cookie.
3865 * At the end of loop, if a "special" cookie remains, we may have to
3866 * remove it. If no application cookie persists in the header, we
3867 * *MUST* delete it.
3868 *
3869 * Note: RFC2965 is unclear about the processing of spaces around
3870 * the equal sign in the ATTR=VALUE form. A careful inspection of
3871 * the RFC explicitly allows spaces before it, and not within the
3872 * tokens (attrs or values). An inspection of RFC2109 allows that
3873 * too but section 10.1.3 lets one think that spaces may be allowed
3874 * after the equal sign too, resulting in some (rare) buggy
3875 * implementations trying to do that. So let's do what servers do.
3876 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3877 * allowed quoted strings in values, with any possible character
3878 * after a backslash, including control chars and delimitors, which
3879 * causes parsing to become ambiguous. Browsers also allow spaces
3880 * within values even without quotes.
3881 *
3882 * We have to keep multiple pointers in order to support cookie
3883 * removal at the beginning, middle or end of header without
3884 * corrupting the header. All of these headers are valid :
3885 *
3886 * hdr_beg hdr_end
3887 * | |
3888 * v |
3889 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3890 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3891 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3892 * | | | | | | |
3893 * | | | | | | |
3894 * | | | | | | +--> next
3895 * | | | | | +----> val_end
3896 * | | | | +-----------> val_beg
3897 * | | | +--------------> equal
3898 * | | +----------------> att_end
3899 * | +---------------------> att_beg
3900 * +--------------------------> prev
3901 *
3902 */
3903 hdr_beg = ctx.value.ptr;
3904 hdr_end = hdr_beg + ctx.value.len;
3905 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3906 /* Iterate through all cookies on this line */
3907
3908 /* find att_beg */
3909 att_beg = prev;
3910 if (prev > hdr_beg)
3911 att_beg++;
3912
3913 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3914 att_beg++;
3915
3916 /* find att_end : this is the first character after the last non
3917 * space before the equal. It may be equal to hdr_end.
3918 */
3919 equal = att_end = att_beg;
3920 while (equal < hdr_end) {
3921 if (*equal == '=' || *equal == ',' || *equal == ';')
3922 break;
3923 if (HTTP_IS_SPHT(*equal++))
3924 continue;
3925 att_end = equal;
3926 }
3927
3928 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3929 * is between <att_beg> and <equal>, both may be identical.
3930 */
3931 /* look for end of cookie if there is an equal sign */
3932 if (equal < hdr_end && *equal == '=') {
3933 /* look for the beginning of the value */
3934 val_beg = equal + 1;
3935 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3936 val_beg++;
3937
3938 /* find the end of the value, respecting quotes */
3939 next = http_find_cookie_value_end(val_beg, hdr_end);
3940
3941 /* make val_end point to the first white space or delimitor after the value */
3942 val_end = next;
3943 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3944 val_end--;
3945 }
3946 else
3947 val_beg = val_end = next = equal;
3948
3949 /* We have nothing to do with attributes beginning with
3950 * '$'. However, they will automatically be removed if a
3951 * header before them is removed, since they're supposed
3952 * to be linked together.
3953 */
3954 if (*att_beg == '$')
3955 continue;
3956
3957 /* Ignore cookies with no equal sign */
3958 if (equal == next) {
3959 /* This is not our cookie, so we must preserve it. But if we already
3960 * scheduled another cookie for removal, we cannot remove the
3961 * complete header, but we can remove the previous block itself.
3962 */
3963 preserve_hdr = 1;
3964 if (del_from != NULL) {
3965 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3966 val_end += delta;
3967 next += delta;
3968 hdr_end += delta;
3969 prev = del_from;
3970 del_from = NULL;
3971 }
3972 continue;
3973 }
3974
3975 /* if there are spaces around the equal sign, we need to
3976 * strip them otherwise we'll get trouble for cookie captures,
3977 * or even for rewrites. Since this happens extremely rarely,
3978 * it does not hurt performance.
3979 */
3980 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3981 int stripped_before = 0;
3982 int stripped_after = 0;
3983
3984 if (att_end != equal) {
3985 memmove(att_end, equal, hdr_end - equal);
3986 stripped_before = (att_end - equal);
3987 equal += stripped_before;
3988 val_beg += stripped_before;
3989 }
3990
3991 if (val_beg > equal + 1) {
3992 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3993 stripped_after = (equal + 1) - val_beg;
3994 val_beg += stripped_after;
3995 stripped_before += stripped_after;
3996 }
3997
3998 val_end += stripped_before;
3999 next += stripped_before;
4000 hdr_end += stripped_before;
4001 }
4002 /* now everything is as on the diagram above */
4003
4004 /* First, let's see if we want to capture this cookie. We check
4005 * that we don't already have a client side cookie, because we
4006 * can only capture one. Also as an optimisation, we ignore
4007 * cookies shorter than the declared name.
4008 */
4009 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4010 (val_end - att_beg >= sess->fe->capture_namelen) &&
4011 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4012 int log_len = val_end - att_beg;
4013
4014 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4015 ha_alert("HTTP logging : out of memory.\n");
4016 } else {
4017 if (log_len > sess->fe->capture_len)
4018 log_len = sess->fe->capture_len;
4019 memcpy(txn->cli_cookie, att_beg, log_len);
4020 txn->cli_cookie[log_len] = 0;
4021 }
4022 }
4023
4024 /* Persistence cookies in passive, rewrite or insert mode have the
4025 * following form :
4026 *
4027 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4028 *
4029 * For cookies in prefix mode, the form is :
4030 *
4031 * Cookie: NAME=SRV~VALUE
4032 */
4033 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4034 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4035 struct server *srv = s->be->srv;
4036 char *delim;
4037
4038 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4039 * have the server ID between val_beg and delim, and the original cookie between
4040 * delim+1 and val_end. Otherwise, delim==val_end :
4041 *
4042 * hdr_beg
4043 * |
4044 * v
4045 * NAME=SRV; # in all but prefix modes
4046 * NAME=SRV~OPAQUE ; # in prefix mode
4047 * || || | |+-> next
4048 * || || | +--> val_end
4049 * || || +---------> delim
4050 * || |+------------> val_beg
4051 * || +-------------> att_end = equal
4052 * |+-----------------> att_beg
4053 * +------------------> prev
4054 *
4055 */
4056 if (s->be->ck_opts & PR_CK_PFX) {
4057 for (delim = val_beg; delim < val_end; delim++)
4058 if (*delim == COOKIE_DELIM)
4059 break;
4060 }
4061 else {
4062 char *vbar1;
4063 delim = val_end;
4064 /* Now check if the cookie contains a date field, which would
4065 * appear after a vertical bar ('|') just after the server name
4066 * and before the delimiter.
4067 */
4068 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4069 if (vbar1) {
4070 /* OK, so left of the bar is the server's cookie and
4071 * right is the last seen date. It is a base64 encoded
4072 * 30-bit value representing the UNIX date since the
4073 * epoch in 4-second quantities.
4074 */
4075 int val;
4076 delim = vbar1++;
4077 if (val_end - vbar1 >= 5) {
4078 val = b64tos30(vbar1);
4079 if (val > 0)
4080 txn->cookie_last_date = val << 2;
4081 }
4082 /* look for a second vertical bar */
4083 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4084 if (vbar1 && (val_end - vbar1 > 5)) {
4085 val = b64tos30(vbar1 + 1);
4086 if (val > 0)
4087 txn->cookie_first_date = val << 2;
4088 }
4089 }
4090 }
4091
4092 /* if the cookie has an expiration date and the proxy wants to check
4093 * it, then we do that now. We first check if the cookie is too old,
4094 * then only if it has expired. We detect strict overflow because the
4095 * time resolution here is not great (4 seconds). Cookies with dates
4096 * in the future are ignored if their offset is beyond one day. This
4097 * allows an admin to fix timezone issues without expiring everyone
4098 * and at the same time avoids keeping unwanted side effects for too
4099 * long.
4100 */
4101 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4102 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4103 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4104 txn->flags &= ~TX_CK_MASK;
4105 txn->flags |= TX_CK_OLD;
4106 delim = val_beg; // let's pretend we have not found the cookie
4107 txn->cookie_first_date = 0;
4108 txn->cookie_last_date = 0;
4109 }
4110 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4111 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4112 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4113 txn->flags &= ~TX_CK_MASK;
4114 txn->flags |= TX_CK_EXPIRED;
4115 delim = val_beg; // let's pretend we have not found the cookie
4116 txn->cookie_first_date = 0;
4117 txn->cookie_last_date = 0;
4118 }
4119
4120 /* Here, we'll look for the first running server which supports the cookie.
4121 * This allows to share a same cookie between several servers, for example
4122 * to dedicate backup servers to specific servers only.
4123 * However, to prevent clients from sticking to cookie-less backup server
4124 * when they have incidentely learned an empty cookie, we simply ignore
4125 * empty cookies and mark them as invalid.
4126 * The same behaviour is applied when persistence must be ignored.
4127 */
4128 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4129 srv = NULL;
4130
4131 while (srv) {
4132 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4133 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4134 if ((srv->cur_state != SRV_ST_STOPPED) ||
4135 (s->be->options & PR_O_PERSIST) ||
4136 (s->flags & SF_FORCE_PRST)) {
4137 /* we found the server and we can use it */
4138 txn->flags &= ~TX_CK_MASK;
4139 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4140 s->flags |= SF_DIRECT | SF_ASSIGNED;
4141 s->target = &srv->obj_type;
4142 break;
4143 } else {
4144 /* we found a server, but it's down,
4145 * mark it as such and go on in case
4146 * another one is available.
4147 */
4148 txn->flags &= ~TX_CK_MASK;
4149 txn->flags |= TX_CK_DOWN;
4150 }
4151 }
4152 srv = srv->next;
4153 }
4154
4155 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4156 /* no server matched this cookie or we deliberately skipped it */
4157 txn->flags &= ~TX_CK_MASK;
4158 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4159 txn->flags |= TX_CK_UNUSED;
4160 else
4161 txn->flags |= TX_CK_INVALID;
4162 }
4163
4164 /* depending on the cookie mode, we may have to either :
4165 * - delete the complete cookie if we're in insert+indirect mode, so that
4166 * the server never sees it ;
4167 * - remove the server id from the cookie value, and tag the cookie as an
4168 * application cookie so that it does not get accidentely removed later,
4169 * if we're in cookie prefix mode
4170 */
4171 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4172 int delta; /* negative */
4173
4174 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4175 delta = val_beg - (delim + 1);
4176 val_end += delta;
4177 next += delta;
4178 hdr_end += delta;
4179 del_from = NULL;
4180 preserve_hdr = 1; /* we want to keep this cookie */
4181 }
4182 else if (del_from == NULL &&
4183 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4184 del_from = prev;
4185 }
4186 }
4187 else {
4188 /* This is not our cookie, so we must preserve it. But if we already
4189 * scheduled another cookie for removal, we cannot remove the
4190 * complete header, but we can remove the previous block itself.
4191 */
4192 preserve_hdr = 1;
4193
4194 if (del_from != NULL) {
4195 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4196 if (att_beg >= del_from)
4197 att_beg += delta;
4198 if (att_end >= del_from)
4199 att_end += delta;
4200 val_beg += delta;
4201 val_end += delta;
4202 next += delta;
4203 hdr_end += delta;
4204 prev = del_from;
4205 del_from = NULL;
4206 }
4207 }
4208
4209 /* continue with next cookie on this header line */
4210 att_beg = next;
4211 } /* for each cookie */
4212
4213
4214 /* There are no more cookies on this line.
4215 * We may still have one (or several) marked for deletion at the
4216 * end of the line. We must do this now in two ways :
4217 * - if some cookies must be preserved, we only delete from the
4218 * mark to the end of line ;
4219 * - if nothing needs to be preserved, simply delete the whole header
4220 */
4221 if (del_from) {
4222 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4223 }
4224 if ((hdr_end - hdr_beg) != ctx.value.len) {
4225 if (hdr_beg != hdr_end) {
4226 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4227 htx->data -= (hdr_end - ctx.value.ptr);
4228 }
4229 else
4230 http_remove_header(htx, &ctx);
4231 }
4232 } /* for each "Cookie header */
4233}
4234
4235/*
4236 * Manage server-side cookies. It can impact performance by about 2% so it is
4237 * desirable to call it only when needed. This function is also used when we
4238 * just need to know if there is a cookie (eg: for check-cache).
4239 */
4240static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4241{
4242 struct session *sess = s->sess;
4243 struct http_txn *txn = s->txn;
4244 struct htx *htx;
4245 struct http_hdr_ctx ctx;
4246 struct server *srv;
4247 char *hdr_beg, *hdr_end;
4248 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4249 int is_cookie2;
4250
4251 htx = htx_from_buf(&res->buf);
4252
4253 ctx.blk = NULL;
4254 while (1) {
4255 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4256 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4257 break;
4258 is_cookie2 = 1;
4259 }
4260
4261 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4262 * <prev> points to the colon.
4263 */
4264 txn->flags |= TX_SCK_PRESENT;
4265
4266 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4267 * check-cache is enabled) and we are not interested in checking
4268 * them. Warning, the cookie capture is declared in the frontend.
4269 */
4270 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4271 break;
4272
4273 /* OK so now we know we have to process this response cookie.
4274 * The format of the Set-Cookie header is slightly different
4275 * from the format of the Cookie header in that it does not
4276 * support the comma as a cookie delimiter (thus the header
4277 * cannot be folded) because the Expires attribute described in
4278 * the original Netscape's spec may contain an unquoted date
4279 * with a comma inside. We have to live with this because
4280 * many browsers don't support Max-Age and some browsers don't
4281 * support quoted strings. However the Set-Cookie2 header is
4282 * clean.
4283 *
4284 * We have to keep multiple pointers in order to support cookie
4285 * removal at the beginning, middle or end of header without
4286 * corrupting the header (in case of set-cookie2). A special
4287 * pointer, <scav> points to the beginning of the set-cookie-av
4288 * fields after the first semi-colon. The <next> pointer points
4289 * either to the end of line (set-cookie) or next unquoted comma
4290 * (set-cookie2). All of these headers are valid :
4291 *
4292 * hdr_beg hdr_end
4293 * | |
4294 * v |
4295 * NAME1 = VALUE 1 ; Secure; Path="/" |
4296 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4297 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4298 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4299 * | | | | | | | |
4300 * | | | | | | | +-> next
4301 * | | | | | | +------------> scav
4302 * | | | | | +--------------> val_end
4303 * | | | | +--------------------> val_beg
4304 * | | | +----------------------> equal
4305 * | | +------------------------> att_end
4306 * | +----------------------------> att_beg
4307 * +------------------------------> prev
4308 * -------------------------------> hdr_beg
4309 */
4310 hdr_beg = ctx.value.ptr;
4311 hdr_end = hdr_beg + ctx.value.len;
4312 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4313
4314 /* Iterate through all cookies on this line */
4315
4316 /* find att_beg */
4317 att_beg = prev;
4318 if (prev > hdr_beg)
4319 att_beg++;
4320
4321 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4322 att_beg++;
4323
4324 /* find att_end : this is the first character after the last non
4325 * space before the equal. It may be equal to hdr_end.
4326 */
4327 equal = att_end = att_beg;
4328
4329 while (equal < hdr_end) {
4330 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4331 break;
4332 if (HTTP_IS_SPHT(*equal++))
4333 continue;
4334 att_end = equal;
4335 }
4336
4337 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4338 * is between <att_beg> and <equal>, both may be identical.
4339 */
4340
4341 /* look for end of cookie if there is an equal sign */
4342 if (equal < hdr_end && *equal == '=') {
4343 /* look for the beginning of the value */
4344 val_beg = equal + 1;
4345 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4346 val_beg++;
4347
4348 /* find the end of the value, respecting quotes */
4349 next = http_find_cookie_value_end(val_beg, hdr_end);
4350
4351 /* make val_end point to the first white space or delimitor after the value */
4352 val_end = next;
4353 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4354 val_end--;
4355 }
4356 else {
4357 /* <equal> points to next comma, semi-colon or EOL */
4358 val_beg = val_end = next = equal;
4359 }
4360
4361 if (next < hdr_end) {
4362 /* Set-Cookie2 supports multiple cookies, and <next> points to
4363 * a colon or semi-colon before the end. So skip all attr-value
4364 * pairs and look for the next comma. For Set-Cookie, since
4365 * commas are permitted in values, skip to the end.
4366 */
4367 if (is_cookie2)
4368 next = http_find_hdr_value_end(next, hdr_end);
4369 else
4370 next = hdr_end;
4371 }
4372
4373 /* Now everything is as on the diagram above */
4374
4375 /* Ignore cookies with no equal sign */
4376 if (equal == val_end)
4377 continue;
4378
4379 /* If there are spaces around the equal sign, we need to
4380 * strip them otherwise we'll get trouble for cookie captures,
4381 * or even for rewrites. Since this happens extremely rarely,
4382 * it does not hurt performance.
4383 */
4384 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4385 int stripped_before = 0;
4386 int stripped_after = 0;
4387
4388 if (att_end != equal) {
4389 memmove(att_end, equal, hdr_end - equal);
4390 stripped_before = (att_end - equal);
4391 equal += stripped_before;
4392 val_beg += stripped_before;
4393 }
4394
4395 if (val_beg > equal + 1) {
4396 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4397 stripped_after = (equal + 1) - val_beg;
4398 val_beg += stripped_after;
4399 stripped_before += stripped_after;
4400 }
4401
4402 val_end += stripped_before;
4403 next += stripped_before;
4404 hdr_end += stripped_before;
4405
4406 ctx.value.len = hdr_end - hdr_beg;
4407 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4408 htx->data -= (hdr_end - ctx.value.ptr);
4409 }
4410
4411 /* First, let's see if we want to capture this cookie. We check
4412 * that we don't already have a server side cookie, because we
4413 * can only capture one. Also as an optimisation, we ignore
4414 * cookies shorter than the declared name.
4415 */
4416 if (sess->fe->capture_name != NULL &&
4417 txn->srv_cookie == NULL &&
4418 (val_end - att_beg >= sess->fe->capture_namelen) &&
4419 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4420 int log_len = val_end - att_beg;
4421 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4422 ha_alert("HTTP logging : out of memory.\n");
4423 }
4424 else {
4425 if (log_len > sess->fe->capture_len)
4426 log_len = sess->fe->capture_len;
4427 memcpy(txn->srv_cookie, att_beg, log_len);
4428 txn->srv_cookie[log_len] = 0;
4429 }
4430 }
4431
4432 srv = objt_server(s->target);
4433 /* now check if we need to process it for persistence */
4434 if (!(s->flags & SF_IGNORE_PRST) &&
4435 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4436 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4437 /* assume passive cookie by default */
4438 txn->flags &= ~TX_SCK_MASK;
4439 txn->flags |= TX_SCK_FOUND;
4440
4441 /* If the cookie is in insert mode on a known server, we'll delete
4442 * this occurrence because we'll insert another one later.
4443 * We'll delete it too if the "indirect" option is set and we're in
4444 * a direct access.
4445 */
4446 if (s->be->ck_opts & PR_CK_PSV) {
4447 /* The "preserve" flag was set, we don't want to touch the
4448 * server's cookie.
4449 */
4450 }
4451 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4452 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4453 /* this cookie must be deleted */
4454 if (prev == hdr_beg && next == hdr_end) {
4455 /* whole header */
4456 http_remove_header(htx, &ctx);
4457 /* note: while both invalid now, <next> and <hdr_end>
4458 * are still equal, so the for() will stop as expected.
4459 */
4460 } else {
4461 /* just remove the value */
4462 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4463 next = prev;
4464 hdr_end += delta;
4465 }
4466 txn->flags &= ~TX_SCK_MASK;
4467 txn->flags |= TX_SCK_DELETED;
4468 /* and go on with next cookie */
4469 }
4470 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4471 /* replace bytes val_beg->val_end with the cookie name associated
4472 * with this server since we know it.
4473 */
4474 int sliding, delta;
4475
4476 ctx.value = ist2(val_beg, val_end - val_beg);
4477 ctx.lws_before = ctx.lws_after = 0;
4478 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4479 delta = srv->cklen - (val_end - val_beg);
4480 sliding = (ctx.value.ptr - val_beg);
4481 hdr_beg += sliding;
4482 val_beg += sliding;
4483 next += sliding + delta;
4484 hdr_end += sliding + delta;
4485
4486 txn->flags &= ~TX_SCK_MASK;
4487 txn->flags |= TX_SCK_REPLACED;
4488 }
4489 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4490 /* insert the cookie name associated with this server
4491 * before existing cookie, and insert a delimiter between them..
4492 */
4493 int sliding, delta;
4494 ctx.value = ist2(val_beg, 0);
4495 ctx.lws_before = ctx.lws_after = 0;
4496 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4497 delta = srv->cklen + 1;
4498 sliding = (ctx.value.ptr - val_beg);
4499 hdr_beg += sliding;
4500 val_beg += sliding;
4501 next += sliding + delta;
4502 hdr_end += sliding + delta;
4503
4504 val_beg[srv->cklen] = COOKIE_DELIM;
4505 txn->flags &= ~TX_SCK_MASK;
4506 txn->flags |= TX_SCK_REPLACED;
4507 }
4508 }
4509 /* that's done for this cookie, check the next one on the same
4510 * line when next != hdr_end (only if is_cookie2).
4511 */
4512 }
4513 }
4514}
4515
Christopher Faulet25a02f62018-10-24 12:00:25 +02004516/*
4517 * Parses the Cache-Control and Pragma request header fields to determine if
4518 * the request may be served from the cache and/or if it is cacheable. Updates
4519 * s->txn->flags.
4520 */
4521void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4522{
4523 struct http_txn *txn = s->txn;
4524 struct htx *htx;
4525 int32_t pos;
4526 int pragma_found, cc_found, i;
4527
4528 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4529 return; /* nothing more to do here */
4530
4531 htx = htx_from_buf(&req->buf);
4532 pragma_found = cc_found = 0;
4533 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4534 struct htx_blk *blk = htx_get_blk(htx, pos);
4535 enum htx_blk_type type = htx_get_blk_type(blk);
4536 struct ist n, v;
4537
4538 if (type == HTX_BLK_EOH)
4539 break;
4540 if (type != HTX_BLK_HDR)
4541 continue;
4542
4543 n = htx_get_blk_name(htx, blk);
4544 v = htx_get_blk_value(htx, blk);
4545
4546 if (isteqi(n, ist("Pragma"))) {
4547 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4548 pragma_found = 1;
4549 continue;
4550 }
4551 }
4552
4553 /* Don't use the cache and don't try to store if we found the
4554 * Authorization header */
4555 if (isteqi(n, ist("Authorization"))) {
4556 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4557 txn->flags |= TX_CACHE_IGNORE;
4558 continue;
4559 }
4560
4561 if (!isteqi(n, ist("Cache-control")))
4562 continue;
4563
4564 /* OK, right now we know we have a cache-control header */
4565 cc_found = 1;
4566 if (!v.len) /* no info */
4567 continue;
4568
4569 i = 0;
4570 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4571 !isspace((unsigned char)*(v.ptr+i)))
4572 i++;
4573
4574 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4575 * values after max-age, max-stale nor min-fresh, we simply don't
4576 * use the cache when they're specified.
4577 */
4578 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4579 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4580 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4581 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4582 txn->flags |= TX_CACHE_IGNORE;
4583 continue;
4584 }
4585
4586 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4587 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4588 continue;
4589 }
4590 }
4591
4592 /* RFC7234#5.4:
4593 * When the Cache-Control header field is also present and
4594 * understood in a request, Pragma is ignored.
4595 * When the Cache-Control header field is not present in a
4596 * request, caches MUST consider the no-cache request
4597 * pragma-directive as having the same effect as if
4598 * "Cache-Control: no-cache" were present.
4599 */
4600 if (!cc_found && pragma_found)
4601 txn->flags |= TX_CACHE_IGNORE;
4602}
4603
4604/*
4605 * Check if response is cacheable or not. Updates s->txn->flags.
4606 */
4607void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4608{
4609 struct http_txn *txn = s->txn;
4610 struct htx *htx;
4611 int32_t pos;
4612 int i;
4613
4614 if (txn->status < 200) {
4615 /* do not try to cache interim responses! */
4616 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4617 return;
4618 }
4619
4620 htx = htx_from_buf(&res->buf);
4621 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4622 struct htx_blk *blk = htx_get_blk(htx, pos);
4623 enum htx_blk_type type = htx_get_blk_type(blk);
4624 struct ist n, v;
4625
4626 if (type == HTX_BLK_EOH)
4627 break;
4628 if (type != HTX_BLK_HDR)
4629 continue;
4630
4631 n = htx_get_blk_name(htx, blk);
4632 v = htx_get_blk_value(htx, blk);
4633
4634 if (isteqi(n, ist("Pragma"))) {
4635 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4636 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4637 return;
4638 }
4639 }
4640
4641 if (!isteqi(n, ist("Cache-control")))
4642 continue;
4643
4644 /* OK, right now we know we have a cache-control header */
4645 if (!v.len) /* no info */
4646 continue;
4647
4648 i = 0;
4649 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4650 !isspace((unsigned char)*(v.ptr+i)))
4651 i++;
4652
4653 /* we have a complete value between v.ptr and (v.ptr+i) */
4654 if (i < v.len && *(v.ptr + i) == '=') {
4655 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4656 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4657 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4658 continue;
4659 }
4660
4661 /* we have something of the form no-cache="set-cookie" */
4662 if ((v.len >= 21) &&
4663 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4664 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4665 txn->flags &= ~TX_CACHE_COOK;
4666 continue;
4667 }
4668
4669 /* OK, so we know that either p2 points to the end of string or to a comma */
4670 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4671 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4672 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4673 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4674 return;
4675 }
4676
4677 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4678 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4679 continue;
4680 }
4681 }
4682}
4683
Christopher Faulet64159df2018-10-24 21:15:35 +02004684/* send a server's name with an outgoing request over an established connection.
4685 * Note: this function is designed to be called once the request has been
4686 * scheduled for being forwarded. This is the reason why the number of forwarded
4687 * bytes have to be adjusted.
4688 */
4689int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4690{
4691 struct htx *htx;
4692 struct http_hdr_ctx ctx;
4693 struct ist hdr;
4694 uint32_t data;
4695
4696 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
4697 htx = htx_from_buf(&s->req.buf);
4698 data = htx->data;
4699
4700 ctx.blk = NULL;
4701 while (http_find_header(htx, hdr, &ctx, 1))
4702 http_remove_header(htx, &ctx);
4703 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4704
4705 if (co_data(&s->req)) {
4706 if (data >= htx->data)
4707 c_rew(&s->req, data - htx->data);
4708 else
4709 c_adv(&s->req, htx->data - data);
4710 }
4711 return 0;
4712}
4713
Christopher Faulet377c5a52018-10-24 21:21:30 +02004714/*
4715 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4716 * for the current backend.
4717 *
4718 * It is assumed that the request is either a HEAD, GET, or POST and that the
4719 * uri_auth field is valid.
4720 *
4721 * Returns 1 if stats should be provided, otherwise 0.
4722 */
4723static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4724{
4725 struct uri_auth *uri_auth = backend->uri_auth;
4726 struct htx *htx;
4727 struct ist uri;
4728 union h1_sl sl;
4729
4730 if (!uri_auth)
4731 return 0;
4732
4733 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4734 return 0;
4735
4736 htx = htx_from_buf(&s->req.buf);
4737 sl = http_find_stline(htx);
4738 uri = sl.rq.u;
4739
4740 /* check URI size */
4741 if (uri_auth->uri_len > uri.len)
4742 return 0;
4743
4744 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4745 return 0;
4746
4747 return 1;
4748}
4749
4750/* This function prepares an applet to handle the stats. It can deal with the
4751 * "100-continue" expectation, check that admin rules are met for POST requests,
4752 * and program a response message if something was unexpected. It cannot fail
4753 * and always relies on the stats applet to complete the job. It does not touch
4754 * analysers nor counters, which are left to the caller. It does not touch
4755 * s->target which is supposed to already point to the stats applet. The caller
4756 * is expected to have already assigned an appctx to the stream.
4757 */
4758static int htx_handle_stats(struct stream *s, struct channel *req)
4759{
4760 struct stats_admin_rule *stats_admin_rule;
4761 struct stream_interface *si = &s->si[1];
4762 struct session *sess = s->sess;
4763 struct http_txn *txn = s->txn;
4764 struct http_msg *msg = &txn->req;
4765 struct uri_auth *uri_auth = s->be->uri_auth;
4766 const char *h, *lookup, *end;
4767 struct appctx *appctx;
4768 struct htx *htx;
4769 union h1_sl sl;
4770
4771 appctx = si_appctx(si);
4772 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4773 appctx->st1 = appctx->st2 = 0;
4774 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4775 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4776 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4777 appctx->ctx.stats.flags |= STAT_CHUNKED;
4778
4779 htx = htx_from_buf(&req->buf);
4780 sl = http_find_stline(htx);
4781 lookup = sl.rq.u.ptr + uri_auth->uri_len;
4782 end = sl.rq.u.ptr + sl.rq.u.len;
4783
4784 for (h = lookup; h <= end - 3; h++) {
4785 if (memcmp(h, ";up", 3) == 0) {
4786 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4787 break;
4788 }
4789 }
4790
4791 if (uri_auth->refresh) {
4792 for (h = lookup; h <= end - 10; h++) {
4793 if (memcmp(h, ";norefresh", 10) == 0) {
4794 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4795 break;
4796 }
4797 }
4798 }
4799
4800 for (h = lookup; h <= end - 4; h++) {
4801 if (memcmp(h, ";csv", 4) == 0) {
4802 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4803 break;
4804 }
4805 }
4806
4807 for (h = lookup; h <= end - 6; h++) {
4808 if (memcmp(h, ";typed", 6) == 0) {
4809 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4810 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4811 break;
4812 }
4813 }
4814
4815 for (h = lookup; h <= end - 8; h++) {
4816 if (memcmp(h, ";st=", 4) == 0) {
4817 int i;
4818 h += 4;
4819 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4820 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4821 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4822 appctx->ctx.stats.st_code = i;
4823 break;
4824 }
4825 }
4826 break;
4827 }
4828 }
4829
4830 appctx->ctx.stats.scope_str = 0;
4831 appctx->ctx.stats.scope_len = 0;
4832 for (h = lookup; h <= end - 8; h++) {
4833 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4834 int itx = 0;
4835 const char *h2;
4836 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4837 const char *err;
4838
4839 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4840 h2 = h;
4841 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4842 while (h <= end) {
4843 if (*h == ';' || *h == '&' || *h == ' ')
4844 break;
4845 itx++;
4846 h++;
4847 }
4848
4849 if (itx > STAT_SCOPE_TXT_MAXLEN)
4850 itx = STAT_SCOPE_TXT_MAXLEN;
4851 appctx->ctx.stats.scope_len = itx;
4852
4853 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4854 memcpy(scope_txt, h2, itx);
4855 scope_txt[itx] = '\0';
4856 err = invalid_char(scope_txt);
4857 if (err) {
4858 /* bad char in search text => clear scope */
4859 appctx->ctx.stats.scope_str = 0;
4860 appctx->ctx.stats.scope_len = 0;
4861 }
4862 break;
4863 }
4864 }
4865
4866 /* now check whether we have some admin rules for this request */
4867 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4868 int ret = 1;
4869
4870 if (stats_admin_rule->cond) {
4871 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4872 ret = acl_pass(ret);
4873 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4874 ret = !ret;
4875 }
4876
4877 if (ret) {
4878 /* no rule, or the rule matches */
4879 appctx->ctx.stats.flags |= STAT_ADMIN;
4880 break;
4881 }
4882 }
4883
4884 /* Was the status page requested with a POST ? */
4885 if (unlikely(txn->meth == HTTP_METH_POST)) {
4886 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4887 /* we'll need the request body, possibly after sending 100-continue */
4888 if (msg->msg_state < HTTP_MSG_DATA)
4889 req->analysers |= AN_REQ_HTTP_BODY;
4890 appctx->st0 = STAT_HTTP_POST;
4891 }
4892 else {
4893 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4894 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4895 appctx->st0 = STAT_HTTP_LAST;
4896 }
4897 }
4898 else {
4899 /* So it was another method (GET/HEAD) */
4900 appctx->st0 = STAT_HTTP_HEAD;
4901 }
4902
4903 s->task->nice = -32; /* small boost for HTTP statistics */
4904 return 1;
4905}
4906
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004907void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4908{
4909 struct http_txn *txn = s->txn;
4910 struct htx *htx;
4911 struct server *srv;
4912 union h1_sl sl;
4913 struct ist path;
4914
4915 /* 1: create the response header */
4916 if (!chunk_memcat(&trash, HTTP_302, strlen(HTTP_302)))
4917 return;
4918
4919 /* 2: add the server's prefix */
4920 /* special prefix "/" means don't change URL */
4921 srv = __objt_server(s->target);
4922 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4923 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4924 return;
4925 }
4926
4927 /* 3: add the request Path */
4928 htx = htx_from_buf(&s->req.buf);
4929 sl = http_find_stline(htx);
4930 path = http_get_path(sl.rq.u);
4931 if (!path.ptr)
4932 return;
4933
4934 if (!chunk_memcat(&trash, path.ptr, path.len))
4935 return;
4936
4937 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4938 if (!chunk_memcat(&trash, "\r\nProxy-Connection: close\r\n\r\n", 29))
4939 return;
4940 }
4941 else {
4942 if (!chunk_memcat(&trash, "\r\nConnection: close\r\n\r\n", 23))
4943 return;
4944 }
4945
4946 /* prepare to return without error. */
4947 si_shutr(si);
4948 si_shutw(si);
4949 si->err_type = SI_ET_NONE;
4950 si->state = SI_ST_CLO;
4951
4952 /* send the message */
4953 txn->status = 302;
4954 htx_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, &trash);
4955
4956 /* FIXME: we should increase a counter of redirects per server and per backend. */
4957 srv_inc_sess_ctr(srv);
4958 srv_set_sess_last(srv);
4959}
4960
Christopher Fauletf2824e62018-10-01 12:12:37 +02004961/* This function terminates the request because it was completly analyzed or
4962 * because an error was triggered during the body forwarding.
4963 */
4964static void htx_end_request(struct stream *s)
4965{
4966 struct channel *chn = &s->req;
4967 struct http_txn *txn = s->txn;
4968
4969 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4970 now_ms, __FUNCTION__, s,
4971 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4972 s->req.analysers, s->res.analysers);
4973
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004974 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4975 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004976 channel_abort(chn);
4977 channel_truncate(chn);
4978 goto end;
4979 }
4980
4981 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4982 return;
4983
4984 if (txn->req.msg_state == HTTP_MSG_DONE) {
4985 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4986 /* The server has not finished to respond, so we
4987 * don't want to move in order not to upset it.
4988 */
4989 return;
4990 }
4991
4992 /* No need to read anymore, the request was completely parsed.
4993 * We can shut the read side unless we want to abort_on_close,
4994 * or we have a POST request. The issue with POST requests is
4995 * that some browsers still send a CRLF after the request, and
4996 * this CRLF must be read so that it does not remain in the kernel
4997 * buffers, otherwise a close could cause an RST on some systems
4998 * (eg: Linux).
4999 */
5000 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5001 txn->meth != HTTP_METH_POST)
5002 channel_dont_read(chn);
5003
5004 /* if the server closes the connection, we want to immediately react
5005 * and close the socket to save packets and syscalls.
5006 */
5007 s->si[1].flags |= SI_FL_NOHALF;
5008
5009 /* In any case we've finished parsing the request so we must
5010 * disable Nagle when sending data because 1) we're not going
5011 * to shut this side, and 2) the server is waiting for us to
5012 * send pending data.
5013 */
5014 chn->flags |= CF_NEVER_WAIT;
5015
5016 /* When we get here, it means that both the request and the
5017 * response have finished receiving. Depending on the connection
5018 * mode, we'll have to wait for the last bytes to leave in either
5019 * direction, and sometimes for a close to be effective.
5020 */
5021 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5022 /* Tunnel mode will not have any analyser so it needs to
5023 * poll for reads.
5024 */
5025 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005026 if (b_data(&chn->buf))
5027 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005028 txn->req.msg_state = HTTP_MSG_TUNNEL;
5029 }
5030 else {
5031 /* we're not expecting any new data to come for this
5032 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005033 *
5034 * However, there is an exception if the response
5035 * length is undefined. In this case, we need to wait
5036 * the close from the server. The response will be
5037 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005038 */
5039 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5040 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005041 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005042
5043 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5044 channel_shutr_now(chn);
5045 channel_shutw_now(chn);
5046 }
5047 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005048 goto check_channel_flags;
5049 }
5050
5051 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5052 http_msg_closing:
5053 /* nothing else to forward, just waiting for the output buffer
5054 * to be empty and for the shutw_now to take effect.
5055 */
5056 if (channel_is_empty(chn)) {
5057 txn->req.msg_state = HTTP_MSG_CLOSED;
5058 goto http_msg_closed;
5059 }
5060 else if (chn->flags & CF_SHUTW) {
5061 txn->req.err_state = txn->req.msg_state;
5062 txn->req.msg_state = HTTP_MSG_ERROR;
5063 goto end;
5064 }
5065 return;
5066 }
5067
5068 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5069 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005070 /* if we don't know whether the server will close, we need to hard close */
5071 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5072 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005073 /* see above in MSG_DONE why we only do this in these states */
5074 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5075 channel_dont_read(chn);
5076 goto end;
5077 }
5078
5079 check_channel_flags:
5080 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5081 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5082 /* if we've just closed an output, let's switch */
5083 txn->req.msg_state = HTTP_MSG_CLOSING;
5084 goto http_msg_closing;
5085 }
5086
5087 end:
5088 chn->analysers &= AN_REQ_FLT_END;
5089 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5090 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5091 channel_auto_close(chn);
5092 channel_auto_read(chn);
5093}
5094
5095
5096/* This function terminates the response because it was completly analyzed or
5097 * because an error was triggered during the body forwarding.
5098 */
5099static void htx_end_response(struct stream *s)
5100{
5101 struct channel *chn = &s->res;
5102 struct http_txn *txn = s->txn;
5103
5104 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5105 now_ms, __FUNCTION__, s,
5106 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5107 s->req.analysers, s->res.analysers);
5108
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005109 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5110 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005111 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005112 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005113 goto end;
5114 }
5115
5116 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5117 return;
5118
5119 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5120 /* In theory, we don't need to read anymore, but we must
5121 * still monitor the server connection for a possible close
5122 * while the request is being uploaded, so we don't disable
5123 * reading.
5124 */
5125 /* channel_dont_read(chn); */
5126
5127 if (txn->req.msg_state < HTTP_MSG_DONE) {
5128 /* The client seems to still be sending data, probably
5129 * because we got an error response during an upload.
5130 * We have the choice of either breaking the connection
5131 * or letting it pass through. Let's do the later.
5132 */
5133 return;
5134 }
5135
5136 /* When we get here, it means that both the request and the
5137 * response have finished receiving. Depending on the connection
5138 * mode, we'll have to wait for the last bytes to leave in either
5139 * direction, and sometimes for a close to be effective.
5140 */
5141 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5142 channel_auto_read(chn);
5143 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005144 if (b_data(&chn->buf))
5145 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005146 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5147 }
5148 else {
5149 /* we're not expecting any new data to come for this
5150 * transaction, so we can close it.
5151 */
5152 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5153 channel_shutr_now(chn);
5154 channel_shutw_now(chn);
5155 }
5156 }
5157 goto check_channel_flags;
5158 }
5159
5160 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5161 http_msg_closing:
5162 /* nothing else to forward, just waiting for the output buffer
5163 * to be empty and for the shutw_now to take effect.
5164 */
5165 if (channel_is_empty(chn)) {
5166 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5167 goto http_msg_closed;
5168 }
5169 else if (chn->flags & CF_SHUTW) {
5170 txn->rsp.err_state = txn->rsp.msg_state;
5171 txn->rsp.msg_state = HTTP_MSG_ERROR;
5172 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5173 if (objt_server(s->target))
5174 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5175 goto end;
5176 }
5177 return;
5178 }
5179
5180 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5181 http_msg_closed:
5182 /* drop any pending data */
5183 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005184 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005185 goto end;
5186 }
5187
5188 check_channel_flags:
5189 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5190 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5191 /* if we've just closed an output, let's switch */
5192 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5193 goto http_msg_closing;
5194 }
5195
5196 end:
5197 chn->analysers &= AN_RES_FLT_END;
5198 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5199 chn->analysers |= AN_RES_FLT_XFER_DATA;
5200 channel_auto_close(chn);
5201 channel_auto_read(chn);
5202}
5203
Christopher Faulet0f226952018-10-22 09:29:56 +02005204void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5205 int finst, const struct buffer *msg)
5206{
5207 channel_auto_read(si_oc(si));
5208 channel_abort(si_oc(si));
5209 channel_auto_close(si_oc(si));
5210 channel_erase(si_oc(si));
5211 channel_auto_close(si_ic(si));
5212 channel_auto_read(si_ic(si));
5213 if (msg) {
5214 struct channel *chn = si_ic(si);
5215 struct htx *htx;
5216
5217 htx = htx_from_buf(&chn->buf);
5218 htx_add_oob(htx, ist2(msg->area, msg->data));
5219 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5220 b_set_data(&chn->buf, b_size(&chn->buf));
5221 c_adv(chn, htx->data);
5222 chn->total += htx->data;
5223 }
5224 if (!(s->flags & SF_ERR_MASK))
5225 s->flags |= err;
5226 if (!(s->flags & SF_FINST_MASK))
5227 s->flags |= finst;
5228}
5229
5230void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5231{
5232 channel_auto_read(&s->req);
5233 channel_abort(&s->req);
5234 channel_auto_close(&s->req);
5235 channel_erase(&s->req);
5236 channel_truncate(&s->res);
5237
5238 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
5239 if (msg) {
5240 struct channel *chn = &s->res;
5241 struct htx *htx;
5242
5243 htx = htx_from_buf(&chn->buf);
5244 htx_add_oob(htx, ist2(msg->area, msg->data));
5245 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5246 b_set_data(&chn->buf, b_size(&chn->buf));
5247 c_adv(chn, htx->data);
5248 chn->total += htx->data;
5249 }
5250
5251 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5252 channel_auto_read(&s->res);
5253 channel_auto_close(&s->res);
5254 channel_shutr_now(&s->res);
5255}
5256
5257/*
5258 * Capture headers from message <htx> according to header list <cap_hdr>, and
5259 * fill the <cap> pointers appropriately.
5260 */
5261static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5262{
5263 struct cap_hdr *h;
5264 int32_t pos;
5265
5266 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5267 struct htx_blk *blk = htx_get_blk(htx, pos);
5268 enum htx_blk_type type = htx_get_blk_type(blk);
5269 struct ist n, v;
5270
5271 if (type == HTX_BLK_EOH)
5272 break;
5273 if (type != HTX_BLK_HDR)
5274 continue;
5275
5276 n = htx_get_blk_name(htx, blk);
5277
5278 for (h = cap_hdr; h; h = h->next) {
5279 if (h->namelen && (h->namelen == n.len) &&
5280 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5281 if (cap[h->index] == NULL)
5282 cap[h->index] =
5283 pool_alloc(h->pool);
5284
5285 if (cap[h->index] == NULL) {
5286 ha_alert("HTTP capture : out of memory.\n");
5287 break;
5288 }
5289
5290 v = htx_get_blk_value(htx, blk);
5291 if (v.len > h->len)
5292 v.len = h->len;
5293
5294 memcpy(cap[h->index], v.ptr, v.len);
5295 cap[h->index][v.len]=0;
5296 }
5297 }
5298 }
5299}
5300
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005301/* Delete a value in a header between delimiters <from> and <next>. The header
5302 * itself is delimited by <start> and <end> pointers. The number of characters
5303 * displaced is returned, and the pointer to the first delimiter is updated if
5304 * required. The function tries as much as possible to respect the following
5305 * principles :
5306 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5307 * in which case <next> is simply removed
5308 * - set exactly one space character after the new first delimiter, unless there
5309 * are not enough characters in the block being moved to do so.
5310 * - remove unneeded spaces before the previous delimiter and after the new
5311 * one.
5312 *
5313 * It is the caller's responsibility to ensure that :
5314 * - <from> points to a valid delimiter or <start> ;
5315 * - <next> points to a valid delimiter or <end> ;
5316 * - there are non-space chars before <from>.
5317 */
5318static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5319{
5320 char *prev = *from;
5321
5322 if (prev == start) {
5323 /* We're removing the first value. eat the semicolon, if <next>
5324 * is lower than <end> */
5325 if (next < end)
5326 next++;
5327
5328 while (next < end && HTTP_IS_SPHT(*next))
5329 next++;
5330 }
5331 else {
5332 /* Remove useless spaces before the old delimiter. */
5333 while (HTTP_IS_SPHT(*(prev-1)))
5334 prev--;
5335 *from = prev;
5336
5337 /* copy the delimiter and if possible a space if we're
5338 * not at the end of the line.
5339 */
5340 if (next < end) {
5341 *prev++ = *next++;
5342 if (prev + 1 < next)
5343 *prev++ = ' ';
5344 while (next < end && HTTP_IS_SPHT(*next))
5345 next++;
5346 }
5347 }
5348 memmove(prev, next, end - next);
5349 return (prev - next);
5350}
5351
Christopher Faulet0f226952018-10-22 09:29:56 +02005352
5353/* Formats the start line of the request (without CRLF) and puts it in <str> and
5354 * return the written lenght. The line can be truncated if it exceeds <len>.
5355 */
5356static size_t htx_fmt_req_line(const union h1_sl sl, char *str, size_t len)
5357{
5358 struct ist dst = ist2(str, 0);
5359
5360 if (istcat(&dst, sl.rq.m, len) == -1)
5361 goto end;
5362 if (dst.len + 1 > len)
5363 goto end;
5364 dst.ptr[dst.len++] = ' ';
5365
5366 if (istcat(&dst, sl.rq.u, len) == -1)
5367 goto end;
5368 if (dst.len + 1 > len)
5369 goto end;
5370 dst.ptr[dst.len++] = ' ';
5371
5372 istcat(&dst, sl.rq.v, len);
5373 end:
5374 return dst.len;
5375}
5376
Christopher Fauletf0523542018-10-24 11:06:58 +02005377/* Formats the start line of the response (without CRLF) and puts it in <str> and
5378 * return the written lenght. The line can be truncated if it exceeds <len>.
5379 */
5380static size_t htx_fmt_res_line(const union h1_sl sl, char *str, size_t len)
5381{
5382 struct ist dst = ist2(str, 0);
5383
5384 if (istcat(&dst, sl.st.v, len) == -1)
5385 goto end;
5386 if (dst.len + 1 > len)
5387 goto end;
5388 dst.ptr[dst.len++] = ' ';
5389
5390 if (istcat(&dst, sl.st.c, len) == -1)
5391 goto end;
5392 if (dst.len + 1 > len)
5393 goto end;
5394 dst.ptr[dst.len++] = ' ';
5395
5396 istcat(&dst, sl.st.r, len);
5397 end:
5398 return dst.len;
5399}
5400
5401
Christopher Faulet0f226952018-10-22 09:29:56 +02005402/*
5403 * Print a debug line with a start line.
5404 */
5405static void htx_debug_stline(const char *dir, struct stream *s, const union h1_sl sl)
5406{
5407 struct session *sess = strm_sess(s);
5408 int max;
5409
5410 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5411 dir,
5412 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5413 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5414
5415 max = sl.rq.m.len;
5416 UBOUND(max, trash.size - trash.data - 3);
5417 chunk_memcat(&trash, sl.rq.m.ptr, max);
5418 trash.area[trash.data++] = ' ';
5419
5420 max = sl.rq.u.len;
5421 UBOUND(max, trash.size - trash.data - 2);
5422 chunk_memcat(&trash, sl.rq.u.ptr, max);
5423 trash.area[trash.data++] = ' ';
5424
5425 max = sl.rq.v.len;
5426 UBOUND(max, trash.size - trash.data - 1);
5427 chunk_memcat(&trash, sl.rq.v.ptr, max);
5428 trash.area[trash.data++] = '\n';
5429
5430 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5431}
5432
5433/*
5434 * Print a debug line with a header.
5435 */
5436static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5437{
5438 struct session *sess = strm_sess(s);
5439 int max;
5440
5441 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5442 dir,
5443 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5444 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5445
5446 max = n.len;
5447 UBOUND(max, trash.size - trash.data - 3);
5448 chunk_memcat(&trash, n.ptr, max);
5449 trash.area[trash.data++] = ':';
5450 trash.area[trash.data++] = ' ';
5451
5452 max = v.len;
5453 UBOUND(max, trash.size - trash.data - 1);
5454 chunk_memcat(&trash, v.ptr, max);
5455 trash.area[trash.data++] = '\n';
5456
5457 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5458}
5459
5460
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005461__attribute__((constructor))
5462static void __htx_protocol_init(void)
5463{
5464}
5465
5466
5467/*
5468 * Local variables:
5469 * c-indent-level: 8
5470 * c-basic-offset: 8
5471 * End:
5472 */