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