blob: 026580036d8c8996d902016674d9f574a0428681 [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 Fauletf1ba18d2018-11-26 21:37:08 +010046static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len);
47static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len);
48static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl);
Christopher Faulet0f226952018-10-22 09:29:56 +020049static 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 Faulet23a3c792018-11-28 10:01:23 +010063static int htx_reply_100_continue(struct stream *s);
64
Christopher Faulete0768eb2018-10-03 16:38:02 +020065/* This stream analyser waits for a complete HTTP request. It returns 1 if the
66 * processing can continue on next analysers, or zero if it either needs more
67 * data or wants to immediately abort the request (eg: timeout, error, ...). It
68 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
69 * when it has nothing left to do, and may remove any analyser when it wants to
70 * abort.
71 */
72int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
73{
Christopher Faulet9768c262018-10-22 09:34:31 +020074
Christopher Faulete0768eb2018-10-03 16:38:02 +020075 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020076 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020077 *
Christopher Faulet9768c262018-10-22 09:34:31 +020078 * Once the start line and all headers are received, we may perform a
79 * capture of the error (if any), and we will set a few fields. We also
80 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020081 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 struct session *sess = s->sess;
83 struct http_txn *txn = s->txn;
84 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020085 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010086 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020087
88 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
89 now_ms, __FUNCTION__,
90 s,
91 req,
92 req->rex, req->wex,
93 req->flags,
94 ci_data(req),
95 req->analysers);
96
Christopher Faulet9768c262018-10-22 09:34:31 +020097 htx = htx_from_buf(&req->buf);
98
Christopher Faulete0768eb2018-10-03 16:38:02 +020099 /* we're speaking HTTP here, so let's speak HTTP to the client */
100 s->srv_error = http_return_srv_error;
101
102 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100103 if (c_data(req) && s->logs.t_idle == -1) {
104 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
105
106 s->logs.t_idle = ((csinfo)
107 ? csinfo->t_idle
108 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
109 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200110
Christopher Faulete0768eb2018-10-03 16:38:02 +0200111 /*
112 * Now we quickly check if we have found a full valid request.
113 * If not so, we check the FD and buffer states before leaving.
114 * A full request is indicated by the fact that we have seen
115 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
116 * requests are checked first. When waiting for a second request
117 * on a keep-alive stream, if we encounter and error, close, t/o,
118 * we note the error in the stream flags but don't set any state.
119 * Since the error will be noted there, it will not be counted by
120 * process_stream() as a frontend error.
121 * Last, we may increase some tracked counters' http request errors on
122 * the cases that are deliberately the client's fault. For instance,
123 * a timeout or connection reset is not counted as an error. However
124 * a bad request is.
125 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200126 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100127 /*
128 * First catch invalid request
129 */
130 if (htx->flags & HTX_FL_PARSING_ERROR) {
131 stream_inc_http_req_ctr(s);
132 stream_inc_http_err_ctr(s);
133 proxy_inc_fe_req_ctr(sess->fe);
134 goto return_bad_req;
135 }
136
Christopher Faulet9768c262018-10-22 09:34:31 +0200137 /* 1: have we encountered a read error ? */
138 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200139 if (!(s->flags & SF_ERR_MASK))
140 s->flags |= SF_ERR_CLICL;
141
142 if (txn->flags & TX_WAIT_NEXT_RQ)
143 goto failed_keep_alive;
144
145 if (sess->fe->options & PR_O_IGNORE_PRB)
146 goto failed_keep_alive;
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200149 stream_inc_http_req_ctr(s);
150 proxy_inc_fe_req_ctr(sess->fe);
151 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
152 if (sess->listener->counters)
153 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
154
Christopher Faulet9768c262018-10-22 09:34:31 +0200155 txn->status = 400;
156 msg->err_state = msg->msg_state;
157 msg->msg_state = HTTP_MSG_ERROR;
158 htx_reply_and_close(s, txn->status, NULL);
159 req->analysers &= AN_REQ_FLT_END;
160
Christopher Faulete0768eb2018-10-03 16:38:02 +0200161 if (!(s->flags & SF_FINST_MASK))
162 s->flags |= SF_FINST_R;
163 return 0;
164 }
165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200167 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
168 if (!(s->flags & SF_ERR_MASK))
169 s->flags |= SF_ERR_CLITO;
170
171 if (txn->flags & TX_WAIT_NEXT_RQ)
172 goto failed_keep_alive;
173
174 if (sess->fe->options & PR_O_IGNORE_PRB)
175 goto failed_keep_alive;
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 stream_inc_http_req_ctr(s);
179 proxy_inc_fe_req_ctr(sess->fe);
180 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
181 if (sess->listener->counters)
182 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
183
Christopher Faulet9768c262018-10-22 09:34:31 +0200184 txn->status = 408;
185 msg->err_state = msg->msg_state;
186 msg->msg_state = HTTP_MSG_ERROR;
187 htx_reply_and_close(s, txn->status, http_error_message(s));
188 req->analysers &= AN_REQ_FLT_END;
189
Christopher Faulete0768eb2018-10-03 16:38:02 +0200190 if (!(s->flags & SF_FINST_MASK))
191 s->flags |= SF_FINST_R;
192 return 0;
193 }
194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200196 else if (req->flags & CF_SHUTR) {
197 if (!(s->flags & SF_ERR_MASK))
198 s->flags |= SF_ERR_CLICL;
199
200 if (txn->flags & TX_WAIT_NEXT_RQ)
201 goto failed_keep_alive;
202
203 if (sess->fe->options & PR_O_IGNORE_PRB)
204 goto failed_keep_alive;
205
Christopher Faulete0768eb2018-10-03 16:38:02 +0200206 stream_inc_http_err_ctr(s);
207 stream_inc_http_req_ctr(s);
208 proxy_inc_fe_req_ctr(sess->fe);
209 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
210 if (sess->listener->counters)
211 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
212
Christopher Faulet9768c262018-10-22 09:34:31 +0200213 txn->status = 400;
214 msg->err_state = msg->msg_state;
215 msg->msg_state = HTTP_MSG_ERROR;
216 htx_reply_and_close(s, txn->status, http_error_message(s));
217 req->analysers &= AN_REQ_FLT_END;
218
Christopher Faulete0768eb2018-10-03 16:38:02 +0200219 if (!(s->flags & SF_FINST_MASK))
220 s->flags |= SF_FINST_R;
221 return 0;
222 }
223
224 channel_dont_connect(req);
225 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
226 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
227#ifdef TCP_QUICKACK
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200229 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
230 /* We need more data, we have to re-enable quick-ack in case we
231 * previously disabled it, otherwise we might cause the client
232 * to delay next data.
233 */
234 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
235 }
236#endif
Christopher Faulet47365272018-10-31 17:40:50 +0100237 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200238 /* If the client starts to talk, let's fall back to
239 * request timeout processing.
240 */
241 txn->flags &= ~TX_WAIT_NEXT_RQ;
242 req->analyse_exp = TICK_ETERNITY;
243 }
244
245 /* just set the request timeout once at the beginning of the request */
246 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100247 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200248 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
249 else
250 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
251 }
252
253 /* we're not ready yet */
254 return 0;
255
256 failed_keep_alive:
257 /* Here we process low-level errors for keep-alive requests. In
258 * short, if the request is not the first one and it experiences
259 * a timeout, read error or shutdown, we just silently close so
260 * that the client can try again.
261 */
262 txn->status = 0;
263 msg->msg_state = HTTP_MSG_RQBEFORE;
264 req->analysers &= AN_REQ_FLT_END;
265 s->logs.logwait = 0;
266 s->logs.level = 0;
267 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200268 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200269 return 0;
270 }
271
Christopher Faulet9768c262018-10-22 09:34:31 +0200272 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200273 stream_inc_http_req_ctr(s);
274 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
275
Christopher Faulet9768c262018-10-22 09:34:31 +0200276 /* kill the pending keep-alive timeout */
277 txn->flags &= ~TX_WAIT_NEXT_RQ;
278 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200279
Christopher Faulet03599112018-11-27 11:21:21 +0100280 sl = http_find_stline(htx);
281
Christopher Faulet9768c262018-10-22 09:34:31 +0200282 /* 0: we might have to print this header in debug mode */
283 if (unlikely((global.mode & MODE_DEBUG) &&
284 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
285 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200286
Christopher Faulet03599112018-11-27 11:21:21 +0100287 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200288
289 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
290 struct htx_blk *blk = htx_get_blk(htx, pos);
291 enum htx_blk_type type = htx_get_blk_type(blk);
292
293 if (type == HTX_BLK_EOH)
294 break;
295 if (type != HTX_BLK_HDR)
296 continue;
297
298 htx_debug_hdr("clihdr", s,
299 htx_get_blk_name(htx, blk),
300 htx_get_blk_value(htx, blk));
301 }
302 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200303
304 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100305 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200306 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100307 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100308 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200309 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100310 msg->flags |= HTTP_MSGF_XFER_LEN;
311 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100312 if (sl->flags & HTX_SL_F_BODYLESS)
313 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /* we can make use of server redirect on GET and HEAD */
316 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
317 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200319 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 goto return_bad_req;
321 }
322
323 /*
324 * 2: check if the URI matches the monitor_uri.
325 * We have to do this for every request which gets in, because
326 * the monitor-uri is defined by the frontend.
327 */
328 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /*
331 * We have found the monitor URI
332 */
333 struct acl_cond *cond;
334
335 s->flags |= SF_MONITOR;
336 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
337
338 /* Check if we want to fail this monitor request or not */
339 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
340 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
341
342 ret = acl_pass(ret);
343 if (cond->pol == ACL_COND_UNLESS)
344 ret = !ret;
345
346 if (ret) {
347 /* we fail this request, let's return 503 service unavail */
348 txn->status = 503;
Christopher Faulet9768c262018-10-22 09:34:31 +0200349 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200350 if (!(s->flags & SF_ERR_MASK))
351 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
352 goto return_prx_cond;
353 }
354 }
355
356 /* nothing to fail, let's reply normaly */
357 txn->status = 200;
Christopher Faulet9768c262018-10-22 09:34:31 +0200358 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200359 if (!(s->flags & SF_ERR_MASK))
360 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
361 goto return_prx_cond;
362 }
363
364 /*
365 * 3: Maybe we have to copy the original REQURI for the logs ?
366 * Note: we cannot log anymore if the request has been
367 * classified as invalid.
368 */
369 if (unlikely(s->logs.logwait & LW_REQ)) {
370 /* we have a complete HTTP request that we must log */
371 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200372 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200373
Christopher Faulet9768c262018-10-22 09:34:31 +0200374 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
375 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200376
377 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
378 s->do_log(s);
379 } else {
380 ha_alert("HTTP logging : out of memory.\n");
381 }
382 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200383
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384 /* if the frontend has "option http-use-proxy-header", we'll check if
385 * we have what looks like a proxied connection instead of a connection,
386 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
387 * Note that this is *not* RFC-compliant, however browsers and proxies
388 * happen to do that despite being non-standard :-(
389 * We consider that a request not beginning with either '/' or '*' is
390 * a proxied connection, which covers both "scheme://location" and
391 * CONNECT ip:port.
392 */
393 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100394 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 txn->flags |= TX_USE_PX_CONN;
396
Christopher Faulete0768eb2018-10-03 16:38:02 +0200397 /* 5: we may need to capture headers */
398 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200399 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200400
401 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
402 * only change if both the request and the config reference something else.
403 * Option httpclose by itself sets tunnel mode where headers are mangled.
404 * However, if another mode is set, it will affect it (eg: server-close/
405 * keep-alive + httpclose = close). Note that we avoid to redo the same work
406 * if FE and BE have the same settings (common). The method consists in
407 * checking if options changed between the two calls (implying that either
408 * one is non-null, or one of them is non-null and we are there for the first
409 * time.
410 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200411 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200412 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200413
414 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200415 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200416 req->analysers |= AN_REQ_HTTP_BODY;
417
418 /*
419 * RFC7234#4:
420 * A cache MUST write through requests with methods
421 * that are unsafe (Section 4.2.1 of [RFC7231]) to
422 * the origin server; i.e., a cache is not allowed
423 * to generate a reply to such a request before
424 * having forwarded the request and having received
425 * a corresponding response.
426 *
427 * RFC7231#4.2.1:
428 * Of the request methods defined by this
429 * specification, the GET, HEAD, OPTIONS, and TRACE
430 * methods are defined to be safe.
431 */
432 if (likely(txn->meth == HTTP_METH_GET ||
433 txn->meth == HTTP_METH_HEAD ||
434 txn->meth == HTTP_METH_OPTIONS ||
435 txn->meth == HTTP_METH_TRACE))
436 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
437
438 /* end of job, return OK */
439 req->analysers &= ~an_bit;
440 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200441
Christopher Faulete0768eb2018-10-03 16:38:02 +0200442 return 1;
443
444 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200445 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200446 txn->req.err_state = txn->req.msg_state;
447 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +0200448 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200449 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
450 if (sess->listener->counters)
451 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
452
453 return_prx_cond:
454 if (!(s->flags & SF_ERR_MASK))
455 s->flags |= SF_ERR_PRXCOND;
456 if (!(s->flags & SF_FINST_MASK))
457 s->flags |= SF_FINST_R;
458
459 req->analysers &= AN_REQ_FLT_END;
460 req->analyse_exp = TICK_ETERNITY;
461 return 0;
462}
463
464
465/* This stream analyser runs all HTTP request processing which is common to
466 * frontends and backends, which means blocking ACLs, filters, connection-close,
467 * reqadd, stats and redirects. This is performed for the designated proxy.
468 * It returns 1 if the processing can continue on next analysers, or zero if it
469 * either needs more data or wants to immediately abort the request (eg: deny,
470 * error, ...).
471 */
472int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
473{
474 struct session *sess = s->sess;
475 struct http_txn *txn = s->txn;
476 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200477 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200478 struct redirect_rule *rule;
479 struct cond_wordlist *wl;
480 enum rule_result verdict;
481 int deny_status = HTTP_ERR_403;
482 struct connection *conn = objt_conn(sess->origin);
483
484 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
485 /* we need more data */
486 goto return_prx_yield;
487 }
488
489 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
490 now_ms, __FUNCTION__,
491 s,
492 req,
493 req->rex, req->wex,
494 req->flags,
495 ci_data(req),
496 req->analysers);
497
Christopher Fauletff2759f2018-10-24 11:13:16 +0200498 htx = htx_from_buf(&req->buf);
499
Christopher Faulete0768eb2018-10-03 16:38:02 +0200500 /* just in case we have some per-backend tracking */
501 stream_inc_be_http_req_ctr(s);
502
503 /* evaluate http-request rules */
504 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200505 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200506
507 switch (verdict) {
508 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
509 goto return_prx_yield;
510
511 case HTTP_RULE_RES_CONT:
512 case HTTP_RULE_RES_STOP: /* nothing to do */
513 break;
514
515 case HTTP_RULE_RES_DENY: /* deny or tarpit */
516 if (txn->flags & TX_CLTARPIT)
517 goto tarpit;
518 goto deny;
519
520 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
521 goto return_prx_cond;
522
523 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
524 goto done;
525
526 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
527 goto return_bad_req;
528 }
529 }
530
531 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
532 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200533 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200534
Christopher Fauletff2759f2018-10-24 11:13:16 +0200535 ctx.blk = NULL;
536 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
537 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200538 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200539 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 }
541
542 /* OK at this stage, we know that the request was accepted according to
543 * the http-request rules, we can check for the stats. Note that the
544 * URI is detected *before* the req* rules in order not to be affected
545 * by a possible reqrep, while they are processed *after* so that a
546 * reqdeny can still block them. This clearly needs to change in 1.6!
547 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200548 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 s->target = &http_stats_applet.obj_type;
550 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
551 txn->status = 500;
552 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200553 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200554
555 if (!(s->flags & SF_ERR_MASK))
556 s->flags |= SF_ERR_RESOURCE;
557 goto return_prx_cond;
558 }
559
560 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200561 htx_handle_stats(s, req);
562 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200563 /* not all actions implemented: deny, allow, auth */
564
565 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
566 goto deny;
567
568 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
569 goto return_prx_cond;
570 }
571
572 /* evaluate the req* rules except reqadd */
573 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200574 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200575 goto return_bad_req;
576
577 if (txn->flags & TX_CLDENY)
578 goto deny;
579
580 if (txn->flags & TX_CLTARPIT) {
581 deny_status = HTTP_ERR_500;
582 goto tarpit;
583 }
584 }
585
586 /* add request headers from the rule sets in the same order */
587 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200588 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200589 if (wl->cond) {
590 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
591 ret = acl_pass(ret);
592 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
593 ret = !ret;
594 if (!ret)
595 continue;
596 }
597
Christopher Fauletff2759f2018-10-24 11:13:16 +0200598 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
599 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 goto return_bad_req;
601 }
602
Christopher Faulete0768eb2018-10-03 16:38:02 +0200603 /* Proceed with the stats now. */
604 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
605 unlikely(objt_applet(s->target) == &http_cache_applet)) {
Christopher Fauletef779222018-10-31 08:47:01 +0100606
607 if (unlikely(objt_applet(s->target) == &http_cache_applet)) {
608 // TODO: Disabled for now, waiting to be adapted for HTX implementation
609 goto deny;
610 }
Christopher Fauletff2759f2018-10-24 11:13:16 +0200611
Christopher Faulete0768eb2018-10-03 16:38:02 +0200612 /* process the stats request now */
613 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
614 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
615
616 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
617 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
618 if (!(s->flags & SF_FINST_MASK))
619 s->flags |= SF_FINST_R;
620
621 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
622 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
623 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
624 req->analysers |= AN_REQ_HTTP_XFER_BODY;
625 goto done;
626 }
627
628 /* check whether we have some ACLs set to redirect this request */
629 list_for_each_entry(rule, &px->redirect_rules, list) {
630 if (rule->cond) {
631 int ret;
632
633 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
634 ret = acl_pass(ret);
635 if (rule->cond->pol == ACL_COND_UNLESS)
636 ret = !ret;
637 if (!ret)
638 continue;
639 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200640 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200641 goto return_bad_req;
642 goto done;
643 }
644
645 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
646 * If this happens, then the data will not come immediately, so we must
647 * send all what we have without waiting. Note that due to the small gain
648 * in waiting for the body of the request, it's easier to simply put the
649 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
650 * itself once used.
651 */
652 req->flags |= CF_SEND_DONTWAIT;
653
654 done: /* done with this analyser, continue with next ones that the calling
655 * points will have set, if any.
656 */
657 req->analyse_exp = TICK_ETERNITY;
658 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
659 req->analysers &= ~an_bit;
660 return 1;
661
662 tarpit:
663 /* Allow cookie logging
664 */
665 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200666 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200667
668 /* When a connection is tarpitted, we use the tarpit timeout,
669 * which may be the same as the connect timeout if unspecified.
670 * If unset, then set it to zero because we really want it to
671 * eventually expire. We build the tarpit as an analyser.
672 */
673 channel_erase(&s->req);
674
675 /* wipe the request out so that we can drop the connection early
676 * if the client closes first.
677 */
678 channel_dont_connect(req);
679
680 txn->status = http_err_codes[deny_status];
681
682 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
683 req->analysers |= AN_REQ_HTTP_TARPIT;
684 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
685 if (!req->analyse_exp)
686 req->analyse_exp = tick_add(now_ms, 0);
687 stream_inc_http_err_ctr(s);
688 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
689 if (sess->fe != s->be)
690 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
691 if (sess->listener->counters)
692 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
693 goto done_without_exp;
694
695 deny: /* this request was blocked (denied) */
696
697 /* Allow cookie logging
698 */
699 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200700 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701
702 txn->flags |= TX_CLDENY;
703 txn->status = http_err_codes[deny_status];
704 s->logs.tv_request = now;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200705 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200706 stream_inc_http_err_ctr(s);
707 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
708 if (sess->fe != s->be)
709 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
710 if (sess->listener->counters)
711 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
712 goto return_prx_cond;
713
714 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 txn->req.err_state = txn->req.msg_state;
716 txn->req.msg_state = HTTP_MSG_ERROR;
717 txn->status = 400;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200718 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200719
720 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
721 if (sess->listener->counters)
722 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
723
724 return_prx_cond:
725 if (!(s->flags & SF_ERR_MASK))
726 s->flags |= SF_ERR_PRXCOND;
727 if (!(s->flags & SF_FINST_MASK))
728 s->flags |= SF_FINST_R;
729
730 req->analysers &= AN_REQ_FLT_END;
731 req->analyse_exp = TICK_ETERNITY;
732 return 0;
733
734 return_prx_yield:
735 channel_dont_connect(req);
736 return 0;
737}
738
739/* This function performs all the processing enabled for the current request.
740 * It returns 1 if the processing can continue on next analysers, or zero if it
741 * needs more data, encounters an error, or wants to immediately abort the
742 * request. It relies on buffers flags, and updates s->req.analysers.
743 */
744int htx_process_request(struct stream *s, struct channel *req, int an_bit)
745{
746 struct session *sess = s->sess;
747 struct http_txn *txn = s->txn;
748 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200749 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200750 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
751
752 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
753 /* we need more data */
754 channel_dont_connect(req);
755 return 0;
756 }
757
758 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
759 now_ms, __FUNCTION__,
760 s,
761 req,
762 req->rex, req->wex,
763 req->flags,
764 ci_data(req),
765 req->analysers);
766
767 /*
768 * Right now, we know that we have processed the entire headers
769 * and that unwanted requests have been filtered out. We can do
770 * whatever we want with the remaining request. Also, now we
771 * may have separate values for ->fe, ->be.
772 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200773 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200774
775 /*
776 * If HTTP PROXY is set we simply get remote server address parsing
777 * incoming request. Note that this requires that a connection is
778 * allocated on the server side.
779 */
780 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
781 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100782 struct htx_sl *sl;
783 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200784
785 /* Note that for now we don't reuse existing proxy connections */
786 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
787 txn->req.err_state = txn->req.msg_state;
788 txn->req.msg_state = HTTP_MSG_ERROR;
789 txn->status = 500;
790 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200791 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200792
793 if (!(s->flags & SF_ERR_MASK))
794 s->flags |= SF_ERR_RESOURCE;
795 if (!(s->flags & SF_FINST_MASK))
796 s->flags |= SF_FINST_R;
797
798 return 0;
799 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200800 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100801 uri = htx_sl_req_uri(sl);
802 path = http_get_path(uri);
803 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200804 goto return_bad_req;
805
806 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200807 * uri.ptr and path.ptr (excluded). If it was not found, we need
808 * to replace from all the uri by a single "/".
809 *
810 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100811 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200812 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100814 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
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)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001082 if (htx_reply_100_continue(s) == -1)
1083 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001084 http_remove_header(htx, &ctx);
1085 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087 }
1088
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001089 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1092 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001094 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1095 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 goto http_end;
1097
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001098 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001099 if (htx->flags & HTX_FL_PARSING_ERROR)
1100 goto return_bad_req;
1101
Christopher Faulete0768eb2018-10-03 16:38:02 +02001102 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1103 txn->status = 408;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001104 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001105
1106 if (!(s->flags & SF_ERR_MASK))
1107 s->flags |= SF_ERR_CLITO;
1108 if (!(s->flags & SF_FINST_MASK))
1109 s->flags |= SF_FINST_D;
1110 goto return_err_msg;
1111 }
1112
1113 /* we get here if we need to wait for more data */
1114 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1115 /* Not enough data. We'll re-use the http-request
1116 * timeout here. Ideally, we should set the timeout
1117 * relative to the accept() date. We just set the
1118 * request timeout once at the beginning of the
1119 * request.
1120 */
1121 channel_dont_connect(req);
1122 if (!tick_isset(req->analyse_exp))
1123 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1124 return 0;
1125 }
1126
1127 http_end:
1128 /* The situation will not evolve, so let's give up on the analysis. */
1129 s->logs.tv_request = now; /* update the request timer to reflect full request */
1130 req->analysers &= ~an_bit;
1131 req->analyse_exp = TICK_ETERNITY;
1132 return 1;
1133
1134 return_bad_req: /* let's centralize all bad requests */
1135 txn->req.err_state = txn->req.msg_state;
1136 txn->req.msg_state = HTTP_MSG_ERROR;
1137 txn->status = 400;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001138 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001139
1140 if (!(s->flags & SF_ERR_MASK))
1141 s->flags |= SF_ERR_PRXCOND;
1142 if (!(s->flags & SF_FINST_MASK))
1143 s->flags |= SF_FINST_R;
1144
1145 return_err_msg:
1146 req->analysers &= AN_REQ_FLT_END;
1147 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1148 if (sess->listener->counters)
1149 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1150 return 0;
1151}
1152
1153/* This function is an analyser which forwards request body (including chunk
1154 * sizes if any). It is called as soon as we must forward, even if we forward
1155 * zero byte. The only situation where it must not be called is when we're in
1156 * tunnel mode and we want to forward till the close. It's used both to forward
1157 * remaining data and to resync after end of body. It expects the msg_state to
1158 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1159 * read more data, or 1 once we can go on with next request or end the stream.
1160 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1161 * bytes of pending data + the headers if not already done.
1162 */
1163int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1164{
1165 struct session *sess = s->sess;
1166 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001167 struct http_msg *msg = &txn->req;
1168 struct htx *htx;
1169 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001170
1171 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1172 now_ms, __FUNCTION__,
1173 s,
1174 req,
1175 req->rex, req->wex,
1176 req->flags,
1177 ci_data(req),
1178 req->analysers);
1179
Christopher Faulet9768c262018-10-22 09:34:31 +02001180 htx = htx_from_buf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001181
1182 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1183 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1184 /* Output closed while we were sending data. We must abort and
1185 * wake the other side up.
1186 */
1187 msg->err_state = msg->msg_state;
1188 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001189 htx_end_request(s);
1190 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001191 return 1;
1192 }
1193
1194 /* Note that we don't have to send 100-continue back because we don't
1195 * need the data to complete our job, and it's up to the server to
1196 * decide whether to return 100, 417 or anything else in return of
1197 * an "Expect: 100-continue" header.
1198 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001199 if (msg->msg_state == HTTP_MSG_BODY)
1200 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001201
1202 /* Some post-connect processing might want us to refrain from starting to
1203 * forward data. Currently, the only reason for this is "balance url_param"
1204 * whichs need to parse/process the request after we've enabled forwarding.
1205 */
1206 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1207 if (!(s->res.flags & CF_READ_ATTACHED)) {
1208 channel_auto_connect(req);
1209 req->flags |= CF_WAKE_CONNECT;
1210 channel_dont_close(req); /* don't fail on early shutr */
1211 goto waiting;
1212 }
1213 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1214 }
1215
1216 /* in most states, we should abort in case of early close */
1217 channel_auto_close(req);
1218
1219 if (req->to_forward) {
1220 /* We can't process the buffer's contents yet */
1221 req->flags |= CF_WAKE_WRITE;
1222 goto missing_data_or_waiting;
1223 }
1224
Christopher Faulet9768c262018-10-22 09:34:31 +02001225 if (msg->msg_state >= HTTP_MSG_DONE)
1226 goto done;
1227
1228 /* Forward all input data. We get it by removing all outgoing data not
1229 * forwarded yet from HTX data size.
1230 */
1231 c_adv(req, htx->data - co_data(req));
1232
1233 /* To let the function channel_forward work as expected we must update
1234 * the channel's buffer to pretend there is no more input data. The
1235 * right length is then restored. We must do that, because when an HTX
1236 * message is stored into a buffer, it appears as full.
1237 */
1238 b_set_data(&req->buf, co_data(req));
Christopher Faulet03599112018-11-27 11:21:21 +01001239 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulet9768c262018-10-22 09:34:31 +02001240 htx->extra -= channel_forward(req, htx->extra);
1241 b_set_data(&req->buf, b_size(&req->buf));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001242
Christopher Faulet9768c262018-10-22 09:34:31 +02001243 /* Check if the end-of-message is reached and if so, switch the message
1244 * in HTTP_MSG_DONE state.
1245 */
1246 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1247 goto missing_data_or_waiting;
1248
1249 msg->msg_state = HTTP_MSG_DONE;
1250
1251 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001252 /* other states, DONE...TUNNEL */
1253 /* we don't want to forward closes on DONE except in tunnel mode. */
1254 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1255 channel_dont_close(req);
1256
Christopher Fauletf2824e62018-10-01 12:12:37 +02001257 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001258 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001259 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001260 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1261 if (req->flags & CF_SHUTW) {
1262 /* request errors are most likely due to the
1263 * server aborting the transfer. */
1264 goto aborted_xfer;
1265 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001266 goto return_bad_req;
1267 }
1268 return 1;
1269 }
1270
1271 /* If "option abortonclose" is set on the backend, we want to monitor
1272 * the client's connection and forward any shutdown notification to the
1273 * server, which will decide whether to close or to go on processing the
1274 * request. We only do that in tunnel mode, and not in other modes since
1275 * it can be abused to exhaust source ports. */
1276 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1277 channel_auto_read(req);
1278 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1279 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1280 s->si[1].flags |= SI_FL_NOLINGER;
1281 channel_auto_close(req);
1282 }
1283 else if (s->txn->meth == HTTP_METH_POST) {
1284 /* POST requests may require to read extra CRLF sent by broken
1285 * browsers and which could cause an RST to be sent upon close
1286 * on some systems (eg: Linux). */
1287 channel_auto_read(req);
1288 }
1289 return 0;
1290
1291 missing_data_or_waiting:
1292 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001293 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001294 if (!(s->flags & SF_ERR_MASK))
1295 s->flags |= SF_ERR_CLICL;
1296 if (!(s->flags & SF_FINST_MASK)) {
1297 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1298 s->flags |= SF_FINST_H;
1299 else
1300 s->flags |= SF_FINST_D;
1301 }
1302
1303 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1304 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1305 if (objt_server(s->target))
1306 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1307
1308 goto return_bad_req_stats_ok;
1309 }
1310
1311 waiting:
1312 /* waiting for the last bits to leave the buffer */
1313 if (req->flags & CF_SHUTW)
1314 goto aborted_xfer;
1315
Christopher Faulet47365272018-10-31 17:40:50 +01001316 if (htx->flags & HTX_FL_PARSING_ERROR)
1317 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001318
Christopher Faulete0768eb2018-10-03 16:38:02 +02001319 /* When TE: chunked is used, we need to get there again to parse remaining
1320 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1321 * And when content-length is used, we never want to let the possible
1322 * shutdown be forwarded to the other side, as the state machine will
1323 * take care of it once the client responds. It's also important to
1324 * prevent TIME_WAITs from accumulating on the backend side, and for
1325 * HTTP/2 where the last frame comes with a shutdown.
1326 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001327 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001328 channel_dont_close(req);
1329
1330 /* We know that more data are expected, but we couldn't send more that
1331 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1332 * system knows it must not set a PUSH on this first part. Interactive
1333 * modes are already handled by the stream sock layer. We must not do
1334 * this in content-length mode because it could present the MSG_MORE
1335 * flag with the last block of forwarded data, which would cause an
1336 * additional delay to be observed by the receiver.
1337 */
1338 if (msg->flags & HTTP_MSGF_TE_CHNK)
1339 req->flags |= CF_EXPECT_MORE;
1340
1341 return 0;
1342
1343 return_bad_req: /* let's centralize all bad requests */
1344 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1345 if (sess->listener->counters)
1346 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1347
1348 return_bad_req_stats_ok:
1349 txn->req.err_state = txn->req.msg_state;
1350 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001351 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001352 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001353 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001354 } else {
1355 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001356 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001357 }
1358 req->analysers &= AN_REQ_FLT_END;
1359 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1360
1361 if (!(s->flags & SF_ERR_MASK))
1362 s->flags |= SF_ERR_PRXCOND;
1363 if (!(s->flags & SF_FINST_MASK)) {
1364 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1365 s->flags |= SF_FINST_H;
1366 else
1367 s->flags |= SF_FINST_D;
1368 }
1369 return 0;
1370
1371 aborted_xfer:
1372 txn->req.err_state = txn->req.msg_state;
1373 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001374 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001375 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001376 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 } else {
1378 txn->status = 502;
Christopher Faulet9768c262018-10-22 09:34:31 +02001379 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001380 }
1381 req->analysers &= AN_REQ_FLT_END;
1382 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1383
1384 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1385 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1386 if (objt_server(s->target))
1387 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1388
1389 if (!(s->flags & SF_ERR_MASK))
1390 s->flags |= SF_ERR_SRVCL;
1391 if (!(s->flags & SF_FINST_MASK)) {
1392 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1393 s->flags |= SF_FINST_H;
1394 else
1395 s->flags |= SF_FINST_D;
1396 }
1397 return 0;
1398}
1399
1400/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1401 * processing can continue on next analysers, or zero if it either needs more
1402 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1403 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1404 * when it has nothing left to do, and may remove any analyser when it wants to
1405 * abort.
1406 */
1407int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1408{
Christopher Faulet9768c262018-10-22 09:34:31 +02001409 /*
1410 * We will analyze a complete HTTP response to check the its syntax.
1411 *
1412 * Once the start line and all headers are received, we may perform a
1413 * capture of the error (if any), and we will set a few fields. We also
1414 * logging and finally headers capture.
1415 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001416 struct session *sess = s->sess;
1417 struct http_txn *txn = s->txn;
1418 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001419 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001420 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001421 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001422 int n;
1423
1424 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1425 now_ms, __FUNCTION__,
1426 s,
1427 rep,
1428 rep->rex, rep->wex,
1429 rep->flags,
1430 ci_data(rep),
1431 rep->analysers);
1432
Christopher Faulet9768c262018-10-22 09:34:31 +02001433 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001434
1435 /*
1436 * Now we quickly check if we have found a full valid response.
1437 * If not so, we check the FD and buffer states before leaving.
1438 * A full response is indicated by the fact that we have seen
1439 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1440 * responses are checked first.
1441 *
1442 * Depending on whether the client is still there or not, we
1443 * may send an error response back or not. Note that normally
1444 * we should only check for HTTP status there, and check I/O
1445 * errors somewhere else.
1446 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001447 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001448 /*
1449 * First catch invalid response
1450 */
1451 if (htx->flags & HTX_FL_PARSING_ERROR)
1452 goto return_bad_res;
1453
Christopher Faulet9768c262018-10-22 09:34:31 +02001454 /* 1: have we encountered a read error ? */
1455 if (rep->flags & CF_READ_ERROR) {
1456 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001457 goto abort_keep_alive;
1458
1459 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1460 if (objt_server(s->target)) {
1461 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1462 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
1463 }
1464
Christopher Faulete0768eb2018-10-03 16:38:02 +02001465 rep->analysers &= AN_RES_FLT_END;
1466 txn->status = 502;
1467
1468 /* Check to see if the server refused the early data.
1469 * If so, just send a 425
1470 */
1471 if (objt_cs(s->si[1].end)) {
1472 struct connection *conn = objt_cs(s->si[1].end)->conn;
1473
1474 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1475 txn->status = 425;
1476 }
1477
1478 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001479 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001480
1481 if (!(s->flags & SF_ERR_MASK))
1482 s->flags |= SF_ERR_SRVCL;
1483 if (!(s->flags & SF_FINST_MASK))
1484 s->flags |= SF_FINST_H;
1485 return 0;
1486 }
1487
Christopher Faulet9768c262018-10-22 09:34:31 +02001488 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001489 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001490 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1491 if (objt_server(s->target)) {
1492 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1493 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
1494 }
1495
Christopher Faulete0768eb2018-10-03 16:38:02 +02001496 rep->analysers &= AN_RES_FLT_END;
1497 txn->status = 504;
1498 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001499 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500
1501 if (!(s->flags & SF_ERR_MASK))
1502 s->flags |= SF_ERR_SRVTO;
1503 if (!(s->flags & SF_FINST_MASK))
1504 s->flags |= SF_FINST_H;
1505 return 0;
1506 }
1507
Christopher Faulet9768c262018-10-22 09:34:31 +02001508 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1510 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1511 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1512 if (objt_server(s->target))
1513 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1514
1515 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516 txn->status = 400;
Christopher Faulet9768c262018-10-22 09:34:31 +02001517 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001518
1519 if (!(s->flags & SF_ERR_MASK))
1520 s->flags |= SF_ERR_CLICL;
1521 if (!(s->flags & SF_FINST_MASK))
1522 s->flags |= SF_FINST_H;
1523
1524 /* process_stream() will take care of the error */
1525 return 0;
1526 }
1527
Christopher Faulet9768c262018-10-22 09:34:31 +02001528 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001530 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001531 goto abort_keep_alive;
1532
1533 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1534 if (objt_server(s->target)) {
1535 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1536 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
1537 }
1538
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539 rep->analysers &= AN_RES_FLT_END;
1540 txn->status = 502;
1541 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Faulet9768c262018-10-22 09:34:31 +02001542 htx_reply_and_close(s, txn->status, http_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001543
1544 if (!(s->flags & SF_ERR_MASK))
1545 s->flags |= SF_ERR_SRVCL;
1546 if (!(s->flags & SF_FINST_MASK))
1547 s->flags |= SF_FINST_H;
1548 return 0;
1549 }
1550
Christopher Faulet9768c262018-10-22 09:34:31 +02001551 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001552 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001553 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554 goto abort_keep_alive;
1555
1556 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1557 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558
1559 if (!(s->flags & SF_ERR_MASK))
1560 s->flags |= SF_ERR_CLICL;
1561 if (!(s->flags & SF_FINST_MASK))
1562 s->flags |= SF_FINST_H;
1563
1564 /* process_stream() will take care of the error */
1565 return 0;
1566 }
1567
1568 channel_dont_close(rep);
1569 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1570 return 0;
1571 }
1572
1573 /* More interesting part now : we know that we have a complete
1574 * response which at least looks like HTTP. We have an indicator
1575 * of each header's length, so we can parse them quickly.
1576 */
1577
Christopher Faulet9768c262018-10-22 09:34:31 +02001578 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001579 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001580
Christopher Faulet9768c262018-10-22 09:34:31 +02001581 /* 0: we might have to print this header in debug mode */
1582 if (unlikely((global.mode & MODE_DEBUG) &&
1583 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1584 int32_t pos;
1585
Christopher Faulet03599112018-11-27 11:21:21 +01001586 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001587
1588 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1589 struct htx_blk *blk = htx_get_blk(htx, pos);
1590 enum htx_blk_type type = htx_get_blk_type(blk);
1591
1592 if (type == HTX_BLK_EOH)
1593 break;
1594 if (type != HTX_BLK_HDR)
1595 continue;
1596
1597 htx_debug_hdr("srvhdr", s,
1598 htx_get_blk_name(htx, blk),
1599 htx_get_blk_value(htx, blk));
1600 }
1601 }
1602
Christopher Faulet03599112018-11-27 11:21:21 +01001603 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001604 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001605 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001606 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001607 if (sl->flags & HTX_SL_F_XFER_LEN) {
1608 msg->flags |= HTTP_MSGF_XFER_LEN;
1609 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001610 if (sl->flags & HTX_SL_F_BODYLESS)
1611 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001612 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001613
1614 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001615 if (n < 1 || n > 5)
1616 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001617
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618 /* when the client triggers a 4xx from the server, it's most often due
1619 * to a missing object or permission. These events should be tracked
1620 * because if they happen often, it may indicate a brute force or a
1621 * vulnerability scan.
1622 */
1623 if (n == 4)
1624 stream_inc_http_err_ctr(s);
1625
1626 if (objt_server(s->target))
1627 HA_ATOMIC_ADD(&objt_server(s->target)->counters.p.http.rsp[n], 1);
1628
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 /* Adjust server's health based on status code. Note: status codes 501
1630 * and 505 are triggered on demand by client request, so we must not
1631 * count them as server failures.
1632 */
1633 if (objt_server(s->target)) {
1634 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
1635 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK);
1636 else
1637 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS);
1638 }
1639
1640 /*
1641 * We may be facing a 100-continue response, or any other informational
1642 * 1xx response which is non-final, in which case this is not the right
1643 * response, and we're waiting for the next one. Let's allow this response
1644 * to go to the client and wait for the next one. There's an exception for
1645 * 101 which is used later in the code to switch protocols.
1646 */
1647 if (txn->status < 200 &&
1648 (txn->status == 100 || txn->status >= 102)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001649 //FLT_STRM_CB(s, flt_htx_reset(s, http, htx));
1650 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001651 msg->msg_state = HTTP_MSG_RPBEFORE;
1652 txn->status = 0;
1653 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001654 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001655 }
1656
1657 /*
1658 * 2: check for cacheability.
1659 */
1660
1661 switch (txn->status) {
1662 case 200:
1663 case 203:
1664 case 204:
1665 case 206:
1666 case 300:
1667 case 301:
1668 case 404:
1669 case 405:
1670 case 410:
1671 case 414:
1672 case 501:
1673 break;
1674 default:
1675 /* RFC7231#6.1:
1676 * Responses with status codes that are defined as
1677 * cacheable by default (e.g., 200, 203, 204, 206,
1678 * 300, 301, 404, 405, 410, 414, and 501 in this
1679 * specification) can be reused by a cache with
1680 * heuristic expiration unless otherwise indicated
1681 * by the method definition or explicit cache
1682 * controls [RFC7234]; all other status codes are
1683 * not cacheable by default.
1684 */
1685 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1686 break;
1687 }
1688
1689 /*
1690 * 3: we may need to capture headers
1691 */
1692 s->logs.logwait &= ~LW_RESP;
1693 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001694 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001695
Christopher Faulet9768c262018-10-22 09:34:31 +02001696 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001697 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1698 txn->status == 101)) {
1699 /* Either we've established an explicit tunnel, or we're
1700 * switching the protocol. In both cases, we're very unlikely
1701 * to understand the next protocols. We have to switch to tunnel
1702 * mode, so that we transfer the request and responses then let
1703 * this protocol pass unmodified. When we later implement specific
1704 * parsers for such protocols, we'll want to check the Upgrade
1705 * header which contains information about that protocol for
1706 * responses with status 101 (eg: see RFC2817 about TLS).
1707 */
1708 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001709 }
1710
Christopher Faulet61608322018-11-23 16:23:45 +01001711 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1712 * 407 (Proxy-Authenticate) responses and set the connection to private
1713 */
1714 srv_conn = cs_conn(objt_cs(s->si[1].end));
1715 if (srv_conn) {
1716 struct ist hdr;
1717 struct http_hdr_ctx ctx;
1718
1719 if (txn->status == 401)
1720 hdr = ist("WWW-Authenticate");
1721 else if (txn->status == 407)
1722 hdr = ist("Proxy-Authenticate");
1723 else
1724 goto end;
1725
1726 ctx.blk = NULL;
1727 while (http_find_header(htx, hdr, &ctx, 0)) {
1728 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1729 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1730 srv_conn->flags |= CO_FL_PRIVATE;
1731 }
1732 }
1733
1734 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001735 /* we want to have the response time before we start processing it */
1736 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1737
1738 /* end of job, return OK */
1739 rep->analysers &= ~an_bit;
1740 rep->analyse_exp = TICK_ETERNITY;
1741 channel_auto_close(rep);
1742 return 1;
1743
Christopher Faulet47365272018-10-31 17:40:50 +01001744 return_bad_res:
1745 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1746 if (objt_server(s->target)) {
1747 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
1748 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
1749 }
1750 txn->status = 502;
1751 s->si[1].flags |= SI_FL_NOLINGER;
1752 htx_reply_and_close(s, txn->status, http_error_message(s));
1753 rep->analysers &= AN_RES_FLT_END;
1754
1755 if (!(s->flags & SF_ERR_MASK))
1756 s->flags |= SF_ERR_PRXCOND;
1757 if (!(s->flags & SF_FINST_MASK))
1758 s->flags |= SF_FINST_H;
1759 return 0;
1760
Christopher Faulete0768eb2018-10-03 16:38:02 +02001761 abort_keep_alive:
1762 /* A keep-alive request to the server failed on a network error.
1763 * The client is required to retry. We need to close without returning
1764 * any other information so that the client retries.
1765 */
1766 txn->status = 0;
1767 rep->analysers &= AN_RES_FLT_END;
1768 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001769 s->logs.logwait = 0;
1770 s->logs.level = 0;
1771 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001772 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001773 return 0;
1774}
1775
1776/* This function performs all the processing enabled for the current response.
1777 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1778 * and updates s->res.analysers. It might make sense to explode it into several
1779 * other functions. It works like process_request (see indications above).
1780 */
1781int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1782{
1783 struct session *sess = s->sess;
1784 struct http_txn *txn = s->txn;
1785 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001786 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001787 struct proxy *cur_proxy;
1788 struct cond_wordlist *wl;
1789 enum rule_result ret = HTTP_RULE_RES_CONT;
1790
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001791 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1792 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001793
Christopher Faulete0768eb2018-10-03 16:38:02 +02001794 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1795 now_ms, __FUNCTION__,
1796 s,
1797 rep,
1798 rep->rex, rep->wex,
1799 rep->flags,
1800 ci_data(rep),
1801 rep->analysers);
1802
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001803 htx = htx_from_buf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804
1805 /* The stats applet needs to adjust the Connection header but we don't
1806 * apply any filter there.
1807 */
1808 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1809 rep->analysers &= ~an_bit;
1810 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001811 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001812 }
1813
1814 /*
1815 * We will have to evaluate the filters.
1816 * As opposed to version 1.2, now they will be evaluated in the
1817 * filters order and not in the header order. This means that
1818 * each filter has to be validated among all headers.
1819 *
1820 * Filters are tried with ->be first, then with ->fe if it is
1821 * different from ->be.
1822 *
1823 * Maybe we are in resume condiion. In this case I choose the
1824 * "struct proxy" which contains the rule list matching the resume
1825 * pointer. If none of theses "struct proxy" match, I initialise
1826 * the process with the first one.
1827 *
1828 * In fact, I check only correspondance betwwen the current list
1829 * pointer and the ->fe rule list. If it doesn't match, I initialize
1830 * the loop with the ->be.
1831 */
1832 if (s->current_rule_list == &sess->fe->http_res_rules)
1833 cur_proxy = sess->fe;
1834 else
1835 cur_proxy = s->be;
1836 while (1) {
1837 struct proxy *rule_set = cur_proxy;
1838
1839 /* evaluate http-response rules */
1840 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001841 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001842
1843 if (ret == HTTP_RULE_RES_BADREQ)
1844 goto return_srv_prx_502;
1845
1846 if (ret == HTTP_RULE_RES_DONE) {
1847 rep->analysers &= ~an_bit;
1848 rep->analyse_exp = TICK_ETERNITY;
1849 return 1;
1850 }
1851 }
1852
1853 /* we need to be called again. */
1854 if (ret == HTTP_RULE_RES_YIELD) {
1855 channel_dont_close(rep);
1856 return 0;
1857 }
1858
1859 /* try headers filters */
1860 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001861 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1862 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001863 }
1864
1865 /* has the response been denied ? */
1866 if (txn->flags & TX_SVDENY) {
1867 if (objt_server(s->target))
1868 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
1869
1870 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1871 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1872 if (sess->listener->counters)
1873 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001874 goto return_srv_prx_502;
1875 }
1876
1877 /* add response headers from the rule sets in the same order */
1878 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001879 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001880 if (txn->status < 200 && txn->status != 101)
1881 break;
1882 if (wl->cond) {
1883 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1884 ret = acl_pass(ret);
1885 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1886 ret = !ret;
1887 if (!ret)
1888 continue;
1889 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001890
1891 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1892 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001893 goto return_bad_resp;
1894 }
1895
1896 /* check whether we're already working on the frontend */
1897 if (cur_proxy == sess->fe)
1898 break;
1899 cur_proxy = sess->fe;
1900 }
1901
1902 /* After this point, this anayzer can't return yield, so we can
1903 * remove the bit corresponding to this analyzer from the list.
1904 *
1905 * Note that the intermediate returns and goto found previously
1906 * reset the analyzers.
1907 */
1908 rep->analysers &= ~an_bit;
1909 rep->analyse_exp = TICK_ETERNITY;
1910
1911 /* OK that's all we can do for 1xx responses */
1912 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001913 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001914
1915 /*
1916 * Now check for a server cookie.
1917 */
1918 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001919 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001920
1921 /*
1922 * Check for cache-control or pragma headers if required.
1923 */
1924 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1925 check_response_for_cacheability(s, rep);
1926
1927 /*
1928 * Add server cookie in the response if needed
1929 */
1930 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1931 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1932 (!(s->flags & SF_DIRECT) ||
1933 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1934 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1935 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1936 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1937 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1938 !(s->flags & SF_IGNORE_PRST)) {
1939 /* the server is known, it's not the one the client requested, or the
1940 * cookie's last seen date needs to be refreshed. We have to
1941 * insert a set-cookie here, except if we want to insert only on POST
1942 * requests and this one isn't. Note that servers which don't have cookies
1943 * (eg: some backup servers) will return a full cookie removal request.
1944 */
1945 if (!objt_server(s->target)->cookie) {
1946 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001947 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001948 s->be->cookie_name);
1949 }
1950 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001951 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001952
1953 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1954 /* emit last_date, which is mandatory */
1955 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1956 s30tob64((date.tv_sec+3) >> 2,
1957 trash.area + trash.data);
1958 trash.data += 5;
1959
1960 if (s->be->cookie_maxlife) {
1961 /* emit first_date, which is either the original one or
1962 * the current date.
1963 */
1964 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1965 s30tob64(txn->cookie_first_date ?
1966 txn->cookie_first_date >> 2 :
1967 (date.tv_sec+3) >> 2,
1968 trash.area + trash.data);
1969 trash.data += 5;
1970 }
1971 }
1972 chunk_appendf(&trash, "; path=/");
1973 }
1974
1975 if (s->be->cookie_domain)
1976 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1977
1978 if (s->be->ck_opts & PR_CK_HTTPONLY)
1979 chunk_appendf(&trash, "; HttpOnly");
1980
1981 if (s->be->ck_opts & PR_CK_SECURE)
1982 chunk_appendf(&trash, "; Secure");
1983
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001984 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001985 goto return_bad_resp;
1986
1987 txn->flags &= ~TX_SCK_MASK;
1988 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1989 /* the server did not change, only the date was updated */
1990 txn->flags |= TX_SCK_UPDATED;
1991 else
1992 txn->flags |= TX_SCK_INSERTED;
1993
1994 /* Here, we will tell an eventual cache on the client side that we don't
1995 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1996 * Some caches understand the correct form: 'no-cache="set-cookie"', but
1997 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
1998 */
1999 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2000
2001 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2002
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002003 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002004 goto return_bad_resp;
2005 }
2006 }
2007
2008 /*
2009 * Check if result will be cacheable with a cookie.
2010 * We'll block the response if security checks have caught
2011 * nasty things such as a cacheable cookie.
2012 */
2013 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2014 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2015 (s->be->options & PR_O_CHK_CACHE)) {
2016 /* we're in presence of a cacheable response containing
2017 * a set-cookie header. We'll block it as requested by
2018 * the 'checkcache' option, and send an alert.
2019 */
2020 if (objt_server(s->target))
2021 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2022
2023 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2024 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2025 if (sess->listener->counters)
2026 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2027
2028 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2029 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2030 send_log(s->be, LOG_ALERT,
2031 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2032 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2033 goto return_srv_prx_502;
2034 }
2035
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002036 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002037 /* Always enter in the body analyzer */
2038 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2039 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2040
2041 /* if the user wants to log as soon as possible, without counting
2042 * bytes from the server, then this is the right moment. We have
2043 * to temporarily assign bytes_out to log what we currently have.
2044 */
2045 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2046 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002047 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002048 s->do_log(s);
2049 s->logs.bytes_out = 0;
2050 }
2051 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002052
2053 return_bad_resp:
2054 if (objt_server(s->target)) {
2055 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2056 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP);
2057 }
2058 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2059
2060 return_srv_prx_502:
2061 rep->analysers &= AN_RES_FLT_END;
2062 txn->status = 502;
2063 s->logs.t_data = -1; /* was not a valid response */
2064 s->si[1].flags |= SI_FL_NOLINGER;
2065 htx_reply_and_close(s, txn->status, http_error_message(s));
2066 if (!(s->flags & SF_ERR_MASK))
2067 s->flags |= SF_ERR_PRXCOND;
2068 if (!(s->flags & SF_FINST_MASK))
2069 s->flags |= SF_FINST_H;
2070 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002071}
2072
2073/* This function is an analyser which forwards response body (including chunk
2074 * sizes if any). It is called as soon as we must forward, even if we forward
2075 * zero byte. The only situation where it must not be called is when we're in
2076 * tunnel mode and we want to forward till the close. It's used both to forward
2077 * remaining data and to resync after end of body. It expects the msg_state to
2078 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2079 * read more data, or 1 once we can go on with next request or end the stream.
2080 *
2081 * It is capable of compressing response data both in content-length mode and
2082 * in chunked mode. The state machines follows different flows depending on
2083 * whether content-length and chunked modes are used, since there are no
2084 * trailers in content-length :
2085 *
2086 * chk-mode cl-mode
2087 * ,----- BODY -----.
2088 * / \
2089 * V size > 0 V chk-mode
2090 * .--> SIZE -------------> DATA -------------> CRLF
2091 * | | size == 0 | last byte |
2092 * | v final crlf v inspected |
2093 * | TRAILERS -----------> DONE |
2094 * | |
2095 * `----------------------------------------------'
2096 *
2097 * Compression only happens in the DATA state, and must be flushed in final
2098 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2099 * is performed at once on final states for all bytes parsed, or when leaving
2100 * on missing data.
2101 */
2102int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2103{
2104 struct session *sess = s->sess;
2105 struct http_txn *txn = s->txn;
2106 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002107 struct htx *htx;
2108 //int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002109
2110 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2111 now_ms, __FUNCTION__,
2112 s,
2113 res,
2114 res->rex, res->wex,
2115 res->flags,
2116 ci_data(res),
2117 res->analysers);
2118
Christopher Faulet9768c262018-10-22 09:34:31 +02002119 htx = htx_from_buf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120
2121 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002122 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123 /* Output closed while we were sending data. We must abort and
2124 * wake the other side up.
2125 */
2126 msg->err_state = msg->msg_state;
2127 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002128 htx_end_response(s);
2129 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002130 return 1;
2131 }
2132
Christopher Faulet9768c262018-10-22 09:34:31 +02002133 if (msg->msg_state == HTTP_MSG_BODY)
2134 msg->msg_state = HTTP_MSG_DATA;
2135
Christopher Faulete0768eb2018-10-03 16:38:02 +02002136 /* in most states, we should abort in case of early close */
2137 channel_auto_close(res);
2138
Christopher Faulete0768eb2018-10-03 16:38:02 +02002139 if (res->to_forward) {
2140 /* We can't process the buffer's contents yet */
2141 res->flags |= CF_WAKE_WRITE;
2142 goto missing_data_or_waiting;
2143 }
2144
Christopher Faulet9768c262018-10-22 09:34:31 +02002145 if (msg->msg_state >= HTTP_MSG_DONE)
2146 goto done;
2147
2148 /* Forward all input data. We get it by removing all outgoing data not
2149 * forwarded yet from HTX data size.
2150 */
2151 c_adv(res, htx->data - co_data(res));
2152
2153 /* To let the function channel_forward work as expected we must update
2154 * the channel's buffer to pretend there is no more input data. The
2155 * right length is then restored. We must do that, because when an HTX
2156 * message is stored into a buffer, it appears as full.
2157 */
2158 b_set_data(&res->buf, co_data(res));
Christopher Faulet03599112018-11-27 11:21:21 +01002159 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulet9768c262018-10-22 09:34:31 +02002160 htx->extra -= channel_forward(res, htx->extra);
2161 b_set_data(&res->buf, b_size(&res->buf));
2162
2163 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2164 /* The server still sending data that should be filtered */
2165 if (res->flags & CF_SHUTR || !HAS_DATA_FILTERS(s, res)) {
2166 msg->msg_state = HTTP_MSG_TUNNEL;
2167 goto done;
2168 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002169 }
2170
Christopher Faulet9768c262018-10-22 09:34:31 +02002171 /* Check if the end-of-message is reached and if so, switch the message
2172 * in HTTP_MSG_DONE state.
2173 */
2174 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2175 goto missing_data_or_waiting;
2176
2177 msg->msg_state = HTTP_MSG_DONE;
2178
2179 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002180 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002181 channel_dont_close(res);
2182
Christopher Fauletf2824e62018-10-01 12:12:37 +02002183 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002184 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002185 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002186 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2187 if (res->flags & CF_SHUTW) {
2188 /* response errors are most likely due to the
2189 * client aborting the transfer. */
2190 goto aborted_xfer;
2191 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 goto return_bad_res;
2193 }
2194 return 1;
2195 }
2196 return 0;
2197
2198 missing_data_or_waiting:
2199 if (res->flags & CF_SHUTW)
2200 goto aborted_xfer;
2201
Christopher Faulet47365272018-10-31 17:40:50 +01002202 if (htx->flags & HTX_FL_PARSING_ERROR)
2203 goto return_bad_res;
2204
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 /* stop waiting for data if the input is closed before the end. If the
2206 * client side was already closed, it means that the client has aborted,
2207 * so we don't want to count this as a server abort. Otherwise it's a
2208 * server abort.
2209 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002210 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2212 goto aborted_xfer;
2213 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002214 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002215 if (!(s->flags & SF_ERR_MASK))
2216 s->flags |= SF_ERR_SRVCL;
2217 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2218 if (objt_server(s->target))
2219 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2220 goto return_bad_res_stats_ok;
2221 }
2222 }
2223
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 /* When TE: chunked is used, we need to get there again to parse
2225 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002226 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2227 * are filters registered on the stream, we don't want to forward a
2228 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002229 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002230 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_DATA_FILTERS(s, res))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002231 channel_dont_close(res);
2232
2233 /* We know that more data are expected, but we couldn't send more that
2234 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2235 * system knows it must not set a PUSH on this first part. Interactive
2236 * modes are already handled by the stream sock layer. We must not do
2237 * this in content-length mode because it could present the MSG_MORE
2238 * flag with the last block of forwarded data, which would cause an
2239 * additional delay to be observed by the receiver.
2240 */
2241 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2242 res->flags |= CF_EXPECT_MORE;
2243
2244 /* the stream handler will take care of timeouts and errors */
2245 return 0;
2246
2247 return_bad_res: /* let's centralize all bad responses */
2248 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2249 if (objt_server(s->target))
2250 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2251
2252 return_bad_res_stats_ok:
2253 txn->rsp.err_state = txn->rsp.msg_state;
2254 txn->rsp.msg_state = HTTP_MSG_ERROR;
2255 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002256 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002257 res->analysers &= AN_RES_FLT_END;
2258 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2259 if (objt_server(s->target))
2260 health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
2261
2262 if (!(s->flags & SF_ERR_MASK))
2263 s->flags |= SF_ERR_PRXCOND;
2264 if (!(s->flags & SF_FINST_MASK))
2265 s->flags |= SF_FINST_D;
2266 return 0;
2267
2268 aborted_xfer:
2269 txn->rsp.err_state = txn->rsp.msg_state;
2270 txn->rsp.msg_state = HTTP_MSG_ERROR;
2271 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002272 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002273 res->analysers &= AN_RES_FLT_END;
2274 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2275
2276 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2277 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2278 if (objt_server(s->target))
2279 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2280
2281 if (!(s->flags & SF_ERR_MASK))
2282 s->flags |= SF_ERR_CLICL;
2283 if (!(s->flags & SF_FINST_MASK))
2284 s->flags |= SF_FINST_D;
2285 return 0;
2286}
2287
Christopher Faulet0f226952018-10-22 09:29:56 +02002288void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002289{
2290 struct proxy *fe = strm_fe(s);
2291 int tmp = TX_CON_WANT_CLO;
2292
2293 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2294 tmp = TX_CON_WANT_TUN;
2295
2296 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002297 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002298}
2299
2300/* Perform an HTTP redirect based on the information in <rule>. The function
2301 * returns non-zero on success, or zero in case of a, irrecoverable error such
2302 * as too large a request to build a valid response.
2303 */
2304int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2305{
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002306 struct htx *htx = htx_from_buf(&s->req.buf);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002307 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002308 const char *msg_fmt;
2309 struct buffer *chunk;
2310 int ret = 0;
2311
2312 chunk = alloc_trash_chunk();
2313 if (!chunk)
2314 goto leave;
2315
2316 /* build redirect message */
2317 switch(rule->code) {
2318 case 308:
2319 msg_fmt = HTTP_308;
2320 break;
2321 case 307:
2322 msg_fmt = HTTP_307;
2323 break;
2324 case 303:
2325 msg_fmt = HTTP_303;
2326 break;
2327 case 301:
2328 msg_fmt = HTTP_301;
2329 break;
2330 case 302:
2331 default:
2332 msg_fmt = HTTP_302;
2333 break;
2334 }
2335
2336 if (unlikely(!chunk_strcpy(chunk, msg_fmt)))
2337 goto leave;
2338
2339 switch(rule->type) {
2340 case REDIRECT_TYPE_SCHEME: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002341 struct http_hdr_ctx ctx;
2342 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002343
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002344 host = ist("");
2345 ctx.blk = NULL;
2346 if (http_find_header(htx, ist("Host"), &ctx, 0))
2347 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002348
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002349 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002350 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002351 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002352 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002353 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2354 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002355 while (qs < path.len) {
2356 if (*(path.ptr + qs) == '?') {
2357 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358 break;
2359 }
2360 qs++;
2361 }
2362 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002364 else
2365 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002366
2367 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002368 /* add scheme */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002369 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2370 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002371 }
2372 else {
2373 /* add scheme with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002374 chunk->data += build_logline(s, chunk->area + chunk->data,
2375 chunk->size - chunk->data,
2376 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002377 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002378 /* add "://" + host + path */
2379 if (!chunk_memcat(chunk, "://", 3) ||
2380 !chunk_memcat(chunk, host.ptr, host.len) ||
2381 !chunk_memcat(chunk, path.ptr, path.len))
2382 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383
2384 /* append a slash at the end of the location if needed and missing */
2385 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2386 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002387 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002388 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002389 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002391 break;
2392 }
2393 case REDIRECT_TYPE_PREFIX: {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002394 struct ist path;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002396 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002397 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002398 /* build message using path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002399 if (path.ptr) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002400 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2401 int qs = 0;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002402 while (qs < path.len) {
2403 if (*(path.ptr + qs) == '?') {
2404 path.len = qs;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405 break;
2406 }
2407 qs++;
2408 }
2409 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002410 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002411 else
2412 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002413
2414 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002415 /* add prefix. Note that if prefix == "/", we don't want to
2416 * add anything, otherwise it makes it hard for the user to
2417 * configure a self-redirection.
2418 */
2419 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002420 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2421 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422 }
2423 }
2424 else {
2425 /* add prefix with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002426 chunk->data += build_logline(s, chunk->area + chunk->data,
2427 chunk->size - chunk->data,
2428 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002429 }
2430
2431 /* add path */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002432 if (!chunk_memcat(chunk, path.ptr, path.len))
2433 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434
2435 /* append a slash at the end of the location if needed and missing */
2436 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2437 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002438 if (chunk->data + 1 >= chunk->size)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002439 goto leave;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002440 chunk->area[chunk->data++] = '/';
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002442 break;
2443 }
2444 case REDIRECT_TYPE_LOCATION:
2445 default:
2446 if (rule->rdr_str) { /* this is an old "redirect" rule */
Christopher Fauletf2824e62018-10-01 12:12:37 +02002447 /* add location */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002448 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2449 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002450 }
2451 else {
2452 /* add location with executing log format */
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002453 chunk->data += build_logline(s, chunk->area + chunk->data,
2454 chunk->size - chunk->data,
2455 &rule->rdr_fmt);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 }
2457 break;
2458 }
2459
2460 if (rule->cookie_len) {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002461 if (!chunk_memcat(chunk, "\r\nSet-Cookie: ", 14) ||
2462 !chunk_memcat(chunk, rule->cookie_str, rule->cookie_len))
2463 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002464 }
2465
2466 /* add end of headers and the keep-alive/close status. */
2467 txn->status = rule->code;
2468 /* let's log the request time */
2469 s->logs.tv_request = now;
2470
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002471 /* FIXME: close for now, but it could be cool to handle the keep-alive here */
2472 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
2473 if (!chunk_memcat(chunk, "\r\nProxy-Connection: close\r\n\r\n", 29))
2474 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002475 } else {
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002476 if (!chunk_memcat(chunk, "\r\nConnection: close\r\n\r\n", 23))
2477 goto leave;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002478 }
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002479 htx_reply_and_close(s, txn->status, chunk);
2480 s->req.analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002481
2482 if (!(s->flags & SF_ERR_MASK))
2483 s->flags |= SF_ERR_LOCAL;
2484 if (!(s->flags & SF_FINST_MASK))
2485 s->flags |= SF_FINST_R;
2486
2487 ret = 1;
Christopher Faulet80f14bf2018-10-24 11:02:25 +02002488 leave:
Christopher Fauletf2824e62018-10-01 12:12:37 +02002489 free_trash_chunk(chunk);
2490 return ret;
2491}
2492
Christopher Faulet72333522018-10-24 11:25:02 +02002493int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2494 struct ist name, const char *str, struct my_regex *re, int action)
2495{
2496 struct http_hdr_ctx ctx;
2497 struct buffer *output = get_trash_chunk();
2498
2499 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2500 ctx.blk = NULL;
2501 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2502 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2503 continue;
2504
2505 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2506 if (output->data == -1)
2507 return -1;
2508 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2509 return -1;
2510 }
2511 return 0;
2512}
2513
2514static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2515 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2516{
2517 struct buffer *replace;
2518 int ret = -1;
2519
2520 replace = alloc_trash_chunk();
2521 if (!replace)
2522 goto leave;
2523
2524 replace->data = build_logline(s, replace->area, replace->size, fmt);
2525 if (replace->data >= replace->size - 1)
2526 goto leave;
2527
2528 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2529
2530 leave:
2531 free_trash_chunk(replace);
2532 return ret;
2533}
2534
Christopher Faulet6eb92892018-11-15 16:39:29 +01002535/*
2536 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2537 * built according to <fmt> log line format.
2538 * If <early_hints> is NULL, it is allocated and the HTTP 103 response first
2539 * line is inserted before the header. If an error occurred <early_hints> is
2540 * released and NULL is returned. On success the updated buffer is returned.
2541 */
2542static struct buffer *htx_apply_early_hint_rule(struct stream* s, struct buffer *early_hints,
2543 const char* name, unsigned int name_len,
2544 struct list *fmt)
2545{
2546 if (!early_hints) {
2547 early_hints = alloc_trash_chunk();
2548 if (!early_hints)
2549 goto fail;
2550 if (!chunk_memcat(early_hints, HTTP_103.ptr, HTTP_103.len))
2551 goto fail;
2552 }
2553
2554 if (!chunk_memcat(early_hints, name, name_len) || !chunk_memcat(early_hints, ": ", 2))
2555 goto fail;
2556
2557 early_hints->data += build_logline(s, b_tail(early_hints), b_room(early_hints), fmt);
2558 if (!chunk_memcat(early_hints, "\r\n", 2))
2559 goto fail;
2560
2561 return early_hints;
2562
2563 fail:
2564 free_trash_chunk(early_hints);
2565 return NULL;
2566}
2567
2568/* Sends an HTTP 103 response. Before sending it, the last CRLF finishing the
2569 * response is added. If an error occurred or if another response was already
2570 * sent, this function does nothing.
2571 */
2572static void htx_send_early_hints(struct stream *s, struct buffer *early_hints)
2573{
2574 struct channel *chn = s->txn->rsp.chn;
2575 struct htx *htx;
2576
2577 /* If a response was already sent, skip early hints */
2578 if (s->txn->status > 0)
2579 return;
2580
2581 if (!chunk_memcat(early_hints, "\r\n", 2))
2582 return;
2583
2584 htx = htx_from_buf(&chn->buf);
2585 if (!htx_add_oob(htx, ist2(early_hints->area, early_hints->data)))
2586 return;
2587
2588 c_adv(chn, early_hints->data);
2589 chn->total += early_hints->data;
2590}
2591
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002592/* This function executes one of the set-{method,path,query,uri} actions. It
2593 * takes the string from the variable 'replace' with length 'len', then modifies
2594 * the relevant part of the request line accordingly. Then it updates various
2595 * pointers to the next elements which were moved, and the total buffer length.
2596 * It finds the action to be performed in p[2], previously filled by function
2597 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2598 * error, though this can be revisited when this code is finally exploited.
2599 *
2600 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2601 * query string and 3 to replace uri.
2602 *
2603 * In query string case, the mark question '?' must be set at the start of the
2604 * string by the caller, event if the replacement query string is empty.
2605 */
2606int htx_req_replace_stline(int action, const char *replace, int len,
2607 struct proxy *px, struct stream *s)
2608{
2609 struct htx *htx = htx_from_buf(&s->req.buf);
2610
2611 switch (action) {
2612 case 0: // method
2613 if (!http_replace_req_meth(htx, ist2(replace, len)))
2614 return -1;
2615 break;
2616
2617 case 1: // path
2618 if (!http_replace_req_path(htx, ist2(replace, len)))
2619 return -1;
2620 break;
2621
2622 case 2: // query
2623 if (!http_replace_req_query(htx, ist2(replace, len)))
2624 return -1;
2625 break;
2626
2627 case 3: // uri
2628 if (!http_replace_req_uri(htx, ist2(replace, len)))
2629 return -1;
2630 break;
2631
2632 default:
2633 return -1;
2634 }
2635 return 0;
2636}
2637
2638/* This function replace the HTTP status code and the associated message. The
2639 * variable <status> contains the new status code. This function never fails.
2640 */
2641void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2642{
2643 struct htx *htx = htx_from_buf(&s->res.buf);
2644 char *res;
2645
2646 chunk_reset(&trash);
2647 res = ultoa_o(status, trash.area, trash.size);
2648 trash.data = res - trash.area;
2649
2650 /* Do we have a custom reason format string? */
2651 if (reason == NULL)
2652 reason = http_get_reason(status);
2653
2654 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2655 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2656}
2657
Christopher Faulet3e964192018-10-24 11:39:23 +02002658/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2659 * transaction <txn>. Returns the verdict of the first rule that prevents
2660 * further processing of the request (auth, deny, ...), and defaults to
2661 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2662 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2663 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2664 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2665 * status.
2666 */
2667static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2668 struct stream *s, int *deny_status)
2669{
2670 struct session *sess = strm_sess(s);
2671 struct http_txn *txn = s->txn;
2672 struct htx *htx;
2673 struct connection *cli_conn;
2674 struct act_rule *rule;
2675 struct http_hdr_ctx ctx;
2676 const char *auth_realm;
2677 struct buffer *early_hints = NULL;
2678 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2679 int act_flags = 0;
2680
2681 htx = htx_from_buf(&s->req.buf);
2682
2683 /* If "the current_rule_list" match the executed rule list, we are in
2684 * resume condition. If a resume is needed it is always in the action
2685 * and never in the ACL or converters. In this case, we initialise the
2686 * current rule, and go to the action execution point.
2687 */
2688 if (s->current_rule) {
2689 rule = s->current_rule;
2690 s->current_rule = NULL;
2691 if (s->current_rule_list == rules)
2692 goto resume_execution;
2693 }
2694 s->current_rule_list = rules;
2695
2696 list_for_each_entry(rule, rules, list) {
2697 /* check optional condition */
2698 if (rule->cond) {
2699 int ret;
2700
2701 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2702 ret = acl_pass(ret);
2703
2704 if (rule->cond->pol == ACL_COND_UNLESS)
2705 ret = !ret;
2706
2707 if (!ret) /* condition not matched */
2708 continue;
2709 }
2710
2711 act_flags |= ACT_FLAG_FIRST;
2712 resume_execution:
2713 switch (rule->action) {
2714 case ACT_ACTION_ALLOW:
2715 rule_ret = HTTP_RULE_RES_STOP;
2716 goto end;
2717
2718 case ACT_ACTION_DENY:
2719 if (deny_status)
2720 *deny_status = rule->deny_status;
2721 rule_ret = HTTP_RULE_RES_DENY;
2722 goto end;
2723
2724 case ACT_HTTP_REQ_TARPIT:
2725 txn->flags |= TX_CLTARPIT;
2726 if (deny_status)
2727 *deny_status = rule->deny_status;
2728 rule_ret = HTTP_RULE_RES_DENY;
2729 goto end;
2730
2731 case ACT_HTTP_REQ_AUTH:
2732 /* Be sure to sned any pending HTTP 103 response first */
2733 if (early_hints) {
2734 htx_send_early_hints(s, early_hints);
2735 free_trash_chunk(early_hints);
2736 early_hints = NULL;
2737 }
2738 /* Auth might be performed on regular http-req rules as well as on stats */
2739 auth_realm = rule->arg.auth.realm;
2740 if (!auth_realm) {
2741 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2742 auth_realm = STATS_DEFAULT_REALM;
2743 else
2744 auth_realm = px->id;
2745 }
2746 /* send 401/407 depending on whether we use a proxy or not. We still
2747 * count one error, because normal browsing won't significantly
2748 * increase the counter but brute force attempts will.
2749 */
2750 chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm);
2751 txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401;
2752 htx_reply_and_close(s, txn->status, &trash);
2753 stream_inc_http_err_ctr(s);
2754 rule_ret = HTTP_RULE_RES_ABRT;
2755 goto end;
2756
2757 case ACT_HTTP_REDIR:
2758 /* Be sure to sned any pending HTTP 103 response first */
2759 if (early_hints) {
2760 htx_send_early_hints(s, early_hints);
2761 free_trash_chunk(early_hints);
2762 early_hints = NULL;
2763 }
2764 rule_ret = HTTP_RULE_RES_DONE;
2765 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2766 rule_ret = HTTP_RULE_RES_BADREQ;
2767 goto end;
2768
2769 case ACT_HTTP_SET_NICE:
2770 s->task->nice = rule->arg.nice;
2771 break;
2772
2773 case ACT_HTTP_SET_TOS:
2774 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2775 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2776 break;
2777
2778 case ACT_HTTP_SET_MARK:
2779#ifdef SO_MARK
2780 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2781 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2782#endif
2783 break;
2784
2785 case ACT_HTTP_SET_LOGL:
2786 s->logs.level = rule->arg.loglevel;
2787 break;
2788
2789 case ACT_HTTP_REPLACE_HDR:
2790 case ACT_HTTP_REPLACE_VAL:
2791 if (htx_transform_header(s, &s->req, htx,
2792 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2793 &rule->arg.hdr_add.fmt,
2794 &rule->arg.hdr_add.re, rule->action)) {
2795 rule_ret = HTTP_RULE_RES_BADREQ;
2796 goto end;
2797 }
2798 break;
2799
2800 case ACT_HTTP_DEL_HDR:
2801 /* remove all occurrences of the header */
2802 ctx.blk = NULL;
2803 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2804 http_remove_header(htx, &ctx);
2805 break;
2806
2807 case ACT_HTTP_SET_HDR:
2808 case ACT_HTTP_ADD_HDR: {
2809 /* The scope of the trash buffer must be limited to this function. The
2810 * build_logline() function can execute a lot of other function which
2811 * can use the trash buffer. So for limiting the scope of this global
2812 * buffer, we build first the header value using build_logline, and
2813 * after we store the header name.
2814 */
2815 struct buffer *replace;
2816 struct ist n, v;
2817
2818 replace = alloc_trash_chunk();
2819 if (!replace) {
2820 rule_ret = HTTP_RULE_RES_BADREQ;
2821 goto end;
2822 }
2823
2824 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2825 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2826 v = ist2(replace->area, replace->data);
2827
2828 if (rule->action == ACT_HTTP_SET_HDR) {
2829 /* remove all occurrences of the header */
2830 ctx.blk = NULL;
2831 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2832 http_remove_header(htx, &ctx);
2833 }
2834
2835 if (!http_add_header(htx, n, v)) {
2836 static unsigned char rate_limit = 0;
2837
2838 if ((rate_limit++ & 255) == 0) {
2839 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);
2840 }
2841
2842 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2843 if (sess->fe != s->be)
2844 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2845 if (sess->listener->counters)
2846 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2847 }
2848 free_trash_chunk(replace);
2849 break;
2850 }
2851
2852 case ACT_HTTP_DEL_ACL:
2853 case ACT_HTTP_DEL_MAP: {
2854 struct pat_ref *ref;
2855 struct buffer *key;
2856
2857 /* collect reference */
2858 ref = pat_ref_lookup(rule->arg.map.ref);
2859 if (!ref)
2860 continue;
2861
2862 /* allocate key */
2863 key = alloc_trash_chunk();
2864 if (!key) {
2865 rule_ret = HTTP_RULE_RES_BADREQ;
2866 goto end;
2867 }
2868
2869 /* collect key */
2870 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2871 key->area[key->data] = '\0';
2872
2873 /* perform update */
2874 /* returned code: 1=ok, 0=ko */
2875 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2876 pat_ref_delete(ref, key->area);
2877 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2878
2879 free_trash_chunk(key);
2880 break;
2881 }
2882
2883 case ACT_HTTP_ADD_ACL: {
2884 struct pat_ref *ref;
2885 struct buffer *key;
2886
2887 /* collect reference */
2888 ref = pat_ref_lookup(rule->arg.map.ref);
2889 if (!ref)
2890 continue;
2891
2892 /* allocate key */
2893 key = alloc_trash_chunk();
2894 if (!key) {
2895 rule_ret = HTTP_RULE_RES_BADREQ;
2896 goto end;
2897 }
2898
2899 /* collect key */
2900 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2901 key->area[key->data] = '\0';
2902
2903 /* perform update */
2904 /* add entry only if it does not already exist */
2905 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2906 if (pat_ref_find_elt(ref, key->area) == NULL)
2907 pat_ref_add(ref, key->area, NULL, NULL);
2908 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2909
2910 free_trash_chunk(key);
2911 break;
2912 }
2913
2914 case ACT_HTTP_SET_MAP: {
2915 struct pat_ref *ref;
2916 struct buffer *key, *value;
2917
2918 /* collect reference */
2919 ref = pat_ref_lookup(rule->arg.map.ref);
2920 if (!ref)
2921 continue;
2922
2923 /* allocate key */
2924 key = alloc_trash_chunk();
2925 if (!key) {
2926 rule_ret = HTTP_RULE_RES_BADREQ;
2927 goto end;
2928 }
2929
2930 /* allocate value */
2931 value = alloc_trash_chunk();
2932 if (!value) {
2933 free_trash_chunk(key);
2934 rule_ret = HTTP_RULE_RES_BADREQ;
2935 goto end;
2936 }
2937
2938 /* collect key */
2939 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2940 key->area[key->data] = '\0';
2941
2942 /* collect value */
2943 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2944 value->area[value->data] = '\0';
2945
2946 /* perform update */
2947 if (pat_ref_find_elt(ref, key->area) != NULL)
2948 /* update entry if it exists */
2949 pat_ref_set(ref, key->area, value->area, NULL);
2950 else
2951 /* insert a new entry */
2952 pat_ref_add(ref, key->area, value->area, NULL);
2953
2954 free_trash_chunk(key);
2955 free_trash_chunk(value);
2956 break;
2957 }
2958
2959 case ACT_HTTP_EARLY_HINT:
2960 if (!(txn->req.flags & HTTP_MSGF_VER_11))
2961 break;
2962 early_hints = htx_apply_early_hint_rule(s, early_hints,
2963 rule->arg.early_hint.name,
2964 rule->arg.early_hint.name_len,
2965 &rule->arg.early_hint.fmt);
2966 if (!early_hints) {
2967 rule_ret = HTTP_RULE_RES_DONE;
2968 goto end;
2969 }
2970 break;
2971
2972 case ACT_CUSTOM:
2973 if ((s->req.flags & CF_READ_ERROR) ||
2974 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
2975 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
2976 (px->options & PR_O_ABRT_CLOSE)))
2977 act_flags |= ACT_FLAG_FINAL;
2978
2979 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
2980 case ACT_RET_ERR:
2981 case ACT_RET_CONT:
2982 break;
2983 case ACT_RET_STOP:
2984 rule_ret = HTTP_RULE_RES_DONE;
2985 goto end;
2986 case ACT_RET_YIELD:
2987 s->current_rule = rule;
2988 rule_ret = HTTP_RULE_RES_YIELD;
2989 goto end;
2990 }
2991 break;
2992
2993 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
2994 /* Note: only the first valid tracking parameter of each
2995 * applies.
2996 */
2997
2998 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
2999 struct stktable *t;
3000 struct stksess *ts;
3001 struct stktable_key *key;
3002 void *ptr1, *ptr2;
3003
3004 t = rule->arg.trk_ctr.table.t;
3005 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3006 rule->arg.trk_ctr.expr, NULL);
3007
3008 if (key && (ts = stktable_get_entry(t, key))) {
3009 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3010
3011 /* let's count a new HTTP request as it's the first time we do it */
3012 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3013 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3014 if (ptr1 || ptr2) {
3015 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3016
3017 if (ptr1)
3018 stktable_data_cast(ptr1, http_req_cnt)++;
3019
3020 if (ptr2)
3021 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3022 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3023
3024 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3025
3026 /* If data was modified, we need to touch to re-schedule sync */
3027 stktable_touch_local(t, ts, 0);
3028 }
3029
3030 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3031 if (sess->fe != s->be)
3032 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3033 }
3034 }
3035 break;
3036
3037 /* other flags exists, but normaly, they never be matched. */
3038 default:
3039 break;
3040 }
3041 }
3042
3043 end:
3044 if (early_hints) {
3045 htx_send_early_hints(s, early_hints);
3046 free_trash_chunk(early_hints);
3047 }
3048
3049 /* we reached the end of the rules, nothing to report */
3050 return rule_ret;
3051}
3052
3053/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3054 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3055 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3056 * is returned, the process can continue the evaluation of next rule list. If
3057 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3058 * is returned, it means the operation could not be processed and a server error
3059 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3060 * deny rule. If *YIELD is returned, the caller must call again the function
3061 * with the same context.
3062 */
3063static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3064 struct stream *s)
3065{
3066 struct session *sess = strm_sess(s);
3067 struct http_txn *txn = s->txn;
3068 struct htx *htx;
3069 struct connection *cli_conn;
3070 struct act_rule *rule;
3071 struct http_hdr_ctx ctx;
3072 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3073 int act_flags = 0;
3074
3075 htx = htx_from_buf(&s->res.buf);
3076
3077 /* If "the current_rule_list" match the executed rule list, we are in
3078 * resume condition. If a resume is needed it is always in the action
3079 * and never in the ACL or converters. In this case, we initialise the
3080 * current rule, and go to the action execution point.
3081 */
3082 if (s->current_rule) {
3083 rule = s->current_rule;
3084 s->current_rule = NULL;
3085 if (s->current_rule_list == rules)
3086 goto resume_execution;
3087 }
3088 s->current_rule_list = rules;
3089
3090 list_for_each_entry(rule, rules, list) {
3091 /* check optional condition */
3092 if (rule->cond) {
3093 int ret;
3094
3095 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3096 ret = acl_pass(ret);
3097
3098 if (rule->cond->pol == ACL_COND_UNLESS)
3099 ret = !ret;
3100
3101 if (!ret) /* condition not matched */
3102 continue;
3103 }
3104
3105 act_flags |= ACT_FLAG_FIRST;
3106resume_execution:
3107 switch (rule->action) {
3108 case ACT_ACTION_ALLOW:
3109 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3110 goto end;
3111
3112 case ACT_ACTION_DENY:
3113 txn->flags |= TX_SVDENY;
3114 rule_ret = HTTP_RULE_RES_STOP;
3115 goto end;
3116
3117 case ACT_HTTP_SET_NICE:
3118 s->task->nice = rule->arg.nice;
3119 break;
3120
3121 case ACT_HTTP_SET_TOS:
3122 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3123 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3124 break;
3125
3126 case ACT_HTTP_SET_MARK:
3127#ifdef SO_MARK
3128 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3129 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3130#endif
3131 break;
3132
3133 case ACT_HTTP_SET_LOGL:
3134 s->logs.level = rule->arg.loglevel;
3135 break;
3136
3137 case ACT_HTTP_REPLACE_HDR:
3138 case ACT_HTTP_REPLACE_VAL:
3139 if (htx_transform_header(s, &s->res, htx,
3140 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3141 &rule->arg.hdr_add.fmt,
3142 &rule->arg.hdr_add.re, rule->action)) {
3143 rule_ret = HTTP_RULE_RES_BADREQ;
3144 goto end;
3145 }
3146 break;
3147
3148 case ACT_HTTP_DEL_HDR:
3149 /* remove all occurrences of the header */
3150 ctx.blk = NULL;
3151 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3152 http_remove_header(htx, &ctx);
3153 break;
3154
3155 case ACT_HTTP_SET_HDR:
3156 case ACT_HTTP_ADD_HDR: {
3157 struct buffer *replace;
3158 struct ist n, v;
3159
3160 replace = alloc_trash_chunk();
3161 if (!replace) {
3162 rule_ret = HTTP_RULE_RES_BADREQ;
3163 goto end;
3164 }
3165
3166 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3167 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3168 v = ist2(replace->area, replace->data);
3169
3170 if (rule->action == ACT_HTTP_SET_HDR) {
3171 /* remove all occurrences of the header */
3172 ctx.blk = NULL;
3173 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3174 http_remove_header(htx, &ctx);
3175 }
3176
3177 if (!http_add_header(htx, n, v)) {
3178 static unsigned char rate_limit = 0;
3179
3180 if ((rate_limit++ & 255) == 0) {
3181 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);
3182 }
3183
3184 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3185 if (sess->fe != s->be)
3186 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3187 if (sess->listener->counters)
3188 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3189 if (objt_server(s->target))
3190 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3191 }
3192 free_trash_chunk(replace);
3193 break;
3194 }
3195
3196 case ACT_HTTP_DEL_ACL:
3197 case ACT_HTTP_DEL_MAP: {
3198 struct pat_ref *ref;
3199 struct buffer *key;
3200
3201 /* collect reference */
3202 ref = pat_ref_lookup(rule->arg.map.ref);
3203 if (!ref)
3204 continue;
3205
3206 /* allocate key */
3207 key = alloc_trash_chunk();
3208 if (!key) {
3209 rule_ret = HTTP_RULE_RES_BADREQ;
3210 goto end;
3211 }
3212
3213 /* collect key */
3214 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3215 key->area[key->data] = '\0';
3216
3217 /* perform update */
3218 /* returned code: 1=ok, 0=ko */
3219 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3220 pat_ref_delete(ref, key->area);
3221 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3222
3223 free_trash_chunk(key);
3224 break;
3225 }
3226
3227 case ACT_HTTP_ADD_ACL: {
3228 struct pat_ref *ref;
3229 struct buffer *key;
3230
3231 /* collect reference */
3232 ref = pat_ref_lookup(rule->arg.map.ref);
3233 if (!ref)
3234 continue;
3235
3236 /* allocate key */
3237 key = alloc_trash_chunk();
3238 if (!key) {
3239 rule_ret = HTTP_RULE_RES_BADREQ;
3240 goto end;
3241 }
3242
3243 /* collect key */
3244 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3245 key->area[key->data] = '\0';
3246
3247 /* perform update */
3248 /* check if the entry already exists */
3249 if (pat_ref_find_elt(ref, key->area) == NULL)
3250 pat_ref_add(ref, key->area, NULL, NULL);
3251
3252 free_trash_chunk(key);
3253 break;
3254 }
3255
3256 case ACT_HTTP_SET_MAP: {
3257 struct pat_ref *ref;
3258 struct buffer *key, *value;
3259
3260 /* collect reference */
3261 ref = pat_ref_lookup(rule->arg.map.ref);
3262 if (!ref)
3263 continue;
3264
3265 /* allocate key */
3266 key = alloc_trash_chunk();
3267 if (!key) {
3268 rule_ret = HTTP_RULE_RES_BADREQ;
3269 goto end;
3270 }
3271
3272 /* allocate value */
3273 value = alloc_trash_chunk();
3274 if (!value) {
3275 free_trash_chunk(key);
3276 rule_ret = HTTP_RULE_RES_BADREQ;
3277 goto end;
3278 }
3279
3280 /* collect key */
3281 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3282 key->area[key->data] = '\0';
3283
3284 /* collect value */
3285 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3286 value->area[value->data] = '\0';
3287
3288 /* perform update */
3289 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3290 if (pat_ref_find_elt(ref, key->area) != NULL)
3291 /* update entry if it exists */
3292 pat_ref_set(ref, key->area, value->area, NULL);
3293 else
3294 /* insert a new entry */
3295 pat_ref_add(ref, key->area, value->area, NULL);
3296 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3297 free_trash_chunk(key);
3298 free_trash_chunk(value);
3299 break;
3300 }
3301
3302 case ACT_HTTP_REDIR:
3303 rule_ret = HTTP_RULE_RES_DONE;
3304 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3305 rule_ret = HTTP_RULE_RES_BADREQ;
3306 goto end;
3307
3308 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3309 /* Note: only the first valid tracking parameter of each
3310 * applies.
3311 */
3312 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3313 struct stktable *t;
3314 struct stksess *ts;
3315 struct stktable_key *key;
3316 void *ptr;
3317
3318 t = rule->arg.trk_ctr.table.t;
3319 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3320 rule->arg.trk_ctr.expr, NULL);
3321
3322 if (key && (ts = stktable_get_entry(t, key))) {
3323 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3324
3325 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3326
3327 /* let's count a new HTTP request as it's the first time we do it */
3328 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3329 if (ptr)
3330 stktable_data_cast(ptr, http_req_cnt)++;
3331
3332 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3333 if (ptr)
3334 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3335 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3336
3337 /* When the client triggers a 4xx from the server, it's most often due
3338 * to a missing object or permission. These events should be tracked
3339 * because if they happen often, it may indicate a brute force or a
3340 * vulnerability scan. Normally this is done when receiving the response
3341 * but here we're tracking after this ought to have been done so we have
3342 * to do it on purpose.
3343 */
3344 if ((unsigned)(txn->status - 400) < 100) {
3345 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3346 if (ptr)
3347 stktable_data_cast(ptr, http_err_cnt)++;
3348
3349 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3350 if (ptr)
3351 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3352 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3353 }
3354
3355 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3356
3357 /* If data was modified, we need to touch to re-schedule sync */
3358 stktable_touch_local(t, ts, 0);
3359
3360 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3361 if (sess->fe != s->be)
3362 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3363 }
3364 }
3365 break;
3366
3367 case ACT_CUSTOM:
3368 if ((s->req.flags & CF_READ_ERROR) ||
3369 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3370 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3371 (px->options & PR_O_ABRT_CLOSE)))
3372 act_flags |= ACT_FLAG_FINAL;
3373
3374 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3375 case ACT_RET_ERR:
3376 case ACT_RET_CONT:
3377 break;
3378 case ACT_RET_STOP:
3379 rule_ret = HTTP_RULE_RES_STOP;
3380 goto end;
3381 case ACT_RET_YIELD:
3382 s->current_rule = rule;
3383 rule_ret = HTTP_RULE_RES_YIELD;
3384 goto end;
3385 }
3386 break;
3387
3388 /* other flags exists, but normaly, they never be matched. */
3389 default:
3390 break;
3391 }
3392 }
3393
3394 end:
3395 /* we reached the end of the rules, nothing to report */
3396 return rule_ret;
3397}
3398
Christopher Faulet33640082018-10-24 11:53:01 +02003399/* Iterate the same filter through all request headers.
3400 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3401 * Since it can manage the switch to another backend, it updates the per-proxy
3402 * DENY stats.
3403 */
3404static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3405{
3406 struct http_txn *txn = s->txn;
3407 struct htx *htx;
3408 struct buffer *hdr = get_trash_chunk();
3409 int32_t pos;
3410
3411 htx = htx_from_buf(&req->buf);
3412
3413 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3414 struct htx_blk *blk = htx_get_blk(htx, pos);
3415 enum htx_blk_type type;
3416 struct ist n, v;
3417
3418 next_hdr:
3419 type = htx_get_blk_type(blk);
3420 if (type == HTX_BLK_EOH)
3421 break;
3422 if (type != HTX_BLK_HDR)
3423 continue;
3424
3425 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3426 return 1;
3427 else if (unlikely(txn->flags & TX_CLALLOW) &&
3428 (exp->action == ACT_ALLOW ||
3429 exp->action == ACT_DENY ||
3430 exp->action == ACT_TARPIT))
3431 return 0;
3432
3433 n = htx_get_blk_name(htx, blk);
3434 v = htx_get_blk_value(htx, blk);
3435
3436 chunk_memcat(hdr, n.ptr, n.len);
3437 hdr->area[hdr->data++] = ':';
3438 hdr->area[hdr->data++] = ' ';
3439 chunk_memcat(hdr, v.ptr, v.len);
3440
3441 /* Now we have one header in <hdr> */
3442
3443 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3444 struct http_hdr_ctx ctx;
3445 int len;
3446
3447 switch (exp->action) {
3448 case ACT_ALLOW:
3449 txn->flags |= TX_CLALLOW;
3450 goto end;
3451
3452 case ACT_DENY:
3453 txn->flags |= TX_CLDENY;
3454 goto end;
3455
3456 case ACT_TARPIT:
3457 txn->flags |= TX_CLTARPIT;
3458 goto end;
3459
3460 case ACT_REPLACE:
3461 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3462 if (len < 0)
3463 return -1;
3464
3465 http_parse_header(ist2(trash.area, len), &n, &v);
3466 ctx.blk = blk;
3467 ctx.value = v;
3468 if (!http_replace_header(htx, &ctx, n, v))
3469 return -1;
3470 if (!ctx.blk)
3471 goto end;
3472 pos = htx_get_blk_pos(htx, blk);
3473 break;
3474
3475 case ACT_REMOVE:
3476 ctx.blk = blk;
3477 ctx.value = v;
3478 if (!http_remove_header(htx, &ctx))
3479 return -1;
3480 if (!ctx.blk)
3481 goto end;
3482 pos = htx_get_blk_pos(htx, blk);
3483 goto next_hdr;
3484
3485 }
3486 }
3487 }
3488 end:
3489 return 0;
3490}
3491
3492/* Apply the filter to the request line.
3493 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3494 * or -1 if a replacement resulted in an invalid request line.
3495 * Since it can manage the switch to another backend, it updates the per-proxy
3496 * DENY stats.
3497 */
3498static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3499{
3500 struct http_txn *txn = s->txn;
3501 struct htx *htx;
3502 struct buffer *reqline = get_trash_chunk();
3503 int done;
3504
3505 htx = htx_from_buf(&req->buf);
3506
3507 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3508 return 1;
3509 else if (unlikely(txn->flags & TX_CLALLOW) &&
3510 (exp->action == ACT_ALLOW ||
3511 exp->action == ACT_DENY ||
3512 exp->action == ACT_TARPIT))
3513 return 0;
3514 else if (exp->action == ACT_REMOVE)
3515 return 0;
3516
3517 done = 0;
3518
3519 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3520
3521 /* Now we have the request line between cur_ptr and cur_end */
3522 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003523 struct htx_sl *sl = http_find_stline(htx);
3524 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003525 int len;
3526
3527 switch (exp->action) {
3528 case ACT_ALLOW:
3529 txn->flags |= TX_CLALLOW;
3530 done = 1;
3531 break;
3532
3533 case ACT_DENY:
3534 txn->flags |= TX_CLDENY;
3535 done = 1;
3536 break;
3537
3538 case ACT_TARPIT:
3539 txn->flags |= TX_CLTARPIT;
3540 done = 1;
3541 break;
3542
3543 case ACT_REPLACE:
3544 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3545 if (len < 0)
3546 return -1;
3547
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003548 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3549 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3550 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003551 return -1;
3552 done = 1;
3553 break;
3554 }
3555 }
3556 return done;
3557}
3558
3559/*
3560 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3561 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3562 * unparsable request. Since it can manage the switch to another backend, it
3563 * updates the per-proxy DENY stats.
3564 */
3565static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3566{
3567 struct session *sess = s->sess;
3568 struct http_txn *txn = s->txn;
3569 struct hdr_exp *exp;
3570
3571 for (exp = px->req_exp; exp; exp = exp->next) {
3572 int ret;
3573
3574 /*
3575 * The interleaving of transformations and verdicts
3576 * makes it difficult to decide to continue or stop
3577 * the evaluation.
3578 */
3579
3580 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3581 break;
3582
3583 if ((txn->flags & TX_CLALLOW) &&
3584 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3585 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3586 continue;
3587
3588 /* if this filter had a condition, evaluate it now and skip to
3589 * next filter if the condition does not match.
3590 */
3591 if (exp->cond) {
3592 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3593 ret = acl_pass(ret);
3594 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3595 ret = !ret;
3596
3597 if (!ret)
3598 continue;
3599 }
3600
3601 /* Apply the filter to the request line. */
3602 ret = htx_apply_filter_to_req_line(s, req, exp);
3603 if (unlikely(ret < 0))
3604 return -1;
3605
3606 if (likely(ret == 0)) {
3607 /* The filter did not match the request, it can be
3608 * iterated through all headers.
3609 */
3610 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3611 return -1;
3612 }
3613 }
3614 return 0;
3615}
3616
3617/* Iterate the same filter through all response headers contained in <res>.
3618 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3619 */
3620static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3621{
3622 struct http_txn *txn = s->txn;
3623 struct htx *htx;
3624 struct buffer *hdr = get_trash_chunk();
3625 int32_t pos;
3626
3627 htx = htx_from_buf(&res->buf);
3628
3629 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3630 struct htx_blk *blk = htx_get_blk(htx, pos);
3631 enum htx_blk_type type;
3632 struct ist n, v;
3633
3634 next_hdr:
3635 type = htx_get_blk_type(blk);
3636 if (type == HTX_BLK_EOH)
3637 break;
3638 if (type != HTX_BLK_HDR)
3639 continue;
3640
3641 if (unlikely(txn->flags & TX_SVDENY))
3642 return 1;
3643 else if (unlikely(txn->flags & TX_SVALLOW) &&
3644 (exp->action == ACT_ALLOW ||
3645 exp->action == ACT_DENY))
3646 return 0;
3647
3648 n = htx_get_blk_name(htx, blk);
3649 v = htx_get_blk_value(htx, blk);
3650
3651 chunk_memcat(hdr, n.ptr, n.len);
3652 hdr->area[hdr->data++] = ':';
3653 hdr->area[hdr->data++] = ' ';
3654 chunk_memcat(hdr, v.ptr, v.len);
3655
3656 /* Now we have one header in <hdr> */
3657
3658 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3659 struct http_hdr_ctx ctx;
3660 int len;
3661
3662 switch (exp->action) {
3663 case ACT_ALLOW:
3664 txn->flags |= TX_SVALLOW;
3665 goto end;
3666 break;
3667
3668 case ACT_DENY:
3669 txn->flags |= TX_SVDENY;
3670 goto end;
3671 break;
3672
3673 case ACT_REPLACE:
3674 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3675 if (len < 0)
3676 return -1;
3677
3678 http_parse_header(ist2(trash.area, len), &n, &v);
3679 ctx.blk = blk;
3680 ctx.value = v;
3681 if (!http_replace_header(htx, &ctx, n, v))
3682 return -1;
3683 if (!ctx.blk)
3684 goto end;
3685 pos = htx_get_blk_pos(htx, blk);
3686 break;
3687
3688 case ACT_REMOVE:
3689 ctx.blk = blk;
3690 ctx.value = v;
3691 if (!http_remove_header(htx, &ctx))
3692 return -1;
3693 if (!ctx.blk)
3694 goto end;
3695 pos = htx_get_blk_pos(htx, blk);
3696 goto next_hdr;
3697 }
3698 }
3699
3700 }
3701 end:
3702 return 0;
3703}
3704
3705/* Apply the filter to the status line in the response buffer <res>.
3706 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3707 * or -1 if a replacement resulted in an invalid status line.
3708 */
3709static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3710{
3711 struct http_txn *txn = s->txn;
3712 struct htx *htx;
3713 struct buffer *resline = get_trash_chunk();
3714 int done;
3715
3716 htx = htx_from_buf(&res->buf);
3717
3718 if (unlikely(txn->flags & TX_SVDENY))
3719 return 1;
3720 else if (unlikely(txn->flags & TX_SVALLOW) &&
3721 (exp->action == ACT_ALLOW ||
3722 exp->action == ACT_DENY))
3723 return 0;
3724 else if (exp->action == ACT_REMOVE)
3725 return 0;
3726
3727 done = 0;
3728 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3729
3730 /* Now we have the status line between cur_ptr and cur_end */
3731 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003732 struct htx_sl *sl = http_find_stline(htx);
3733 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003734 int len;
3735
3736 switch (exp->action) {
3737 case ACT_ALLOW:
3738 txn->flags |= TX_SVALLOW;
3739 done = 1;
3740 break;
3741
3742 case ACT_DENY:
3743 txn->flags |= TX_SVDENY;
3744 done = 1;
3745 break;
3746
3747 case ACT_REPLACE:
3748 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3749 if (len < 0)
3750 return -1;
3751
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003752 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3753 sl->info.res.status = strl2ui(code.ptr, code.len);
3754 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003755 return -1;
3756
3757 done = 1;
3758 return 1;
3759 }
3760 }
3761 return done;
3762}
3763
3764/*
3765 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3766 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3767 * unparsable response.
3768 */
3769static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3770{
3771 struct session *sess = s->sess;
3772 struct http_txn *txn = s->txn;
3773 struct hdr_exp *exp;
3774
3775 for (exp = px->rsp_exp; exp; exp = exp->next) {
3776 int ret;
3777
3778 /*
3779 * The interleaving of transformations and verdicts
3780 * makes it difficult to decide to continue or stop
3781 * the evaluation.
3782 */
3783
3784 if (txn->flags & TX_SVDENY)
3785 break;
3786
3787 if ((txn->flags & TX_SVALLOW) &&
3788 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3789 exp->action == ACT_PASS)) {
3790 exp = exp->next;
3791 continue;
3792 }
3793
3794 /* if this filter had a condition, evaluate it now and skip to
3795 * next filter if the condition does not match.
3796 */
3797 if (exp->cond) {
3798 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3799 ret = acl_pass(ret);
3800 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3801 ret = !ret;
3802 if (!ret)
3803 continue;
3804 }
3805
3806 /* Apply the filter to the status line. */
3807 ret = htx_apply_filter_to_sts_line(s, res, exp);
3808 if (unlikely(ret < 0))
3809 return -1;
3810
3811 if (likely(ret == 0)) {
3812 /* The filter did not match the response, it can be
3813 * iterated through all headers.
3814 */
3815 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3816 return -1;
3817 }
3818 }
3819 return 0;
3820}
3821
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003822/*
3823 * Manage client-side cookie. It can impact performance by about 2% so it is
3824 * desirable to call it only when needed. This code is quite complex because
3825 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3826 * highly recommended not to touch this part without a good reason !
3827 */
3828static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3829{
3830 struct session *sess = s->sess;
3831 struct http_txn *txn = s->txn;
3832 struct htx *htx;
3833 struct http_hdr_ctx ctx;
3834 char *hdr_beg, *hdr_end, *del_from;
3835 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3836 int preserve_hdr;
3837
3838 htx = htx_from_buf(&req->buf);
3839 ctx.blk = NULL;
3840 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3841 del_from = NULL; /* nothing to be deleted */
3842 preserve_hdr = 0; /* assume we may kill the whole header */
3843
3844 /* Now look for cookies. Conforming to RFC2109, we have to support
3845 * attributes whose name begin with a '$', and associate them with
3846 * the right cookie, if we want to delete this cookie.
3847 * So there are 3 cases for each cookie read :
3848 * 1) it's a special attribute, beginning with a '$' : ignore it.
3849 * 2) it's a server id cookie that we *MAY* want to delete : save
3850 * some pointers on it (last semi-colon, beginning of cookie...)
3851 * 3) it's an application cookie : we *MAY* have to delete a previous
3852 * "special" cookie.
3853 * At the end of loop, if a "special" cookie remains, we may have to
3854 * remove it. If no application cookie persists in the header, we
3855 * *MUST* delete it.
3856 *
3857 * Note: RFC2965 is unclear about the processing of spaces around
3858 * the equal sign in the ATTR=VALUE form. A careful inspection of
3859 * the RFC explicitly allows spaces before it, and not within the
3860 * tokens (attrs or values). An inspection of RFC2109 allows that
3861 * too but section 10.1.3 lets one think that spaces may be allowed
3862 * after the equal sign too, resulting in some (rare) buggy
3863 * implementations trying to do that. So let's do what servers do.
3864 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3865 * allowed quoted strings in values, with any possible character
3866 * after a backslash, including control chars and delimitors, which
3867 * causes parsing to become ambiguous. Browsers also allow spaces
3868 * within values even without quotes.
3869 *
3870 * We have to keep multiple pointers in order to support cookie
3871 * removal at the beginning, middle or end of header without
3872 * corrupting the header. All of these headers are valid :
3873 *
3874 * hdr_beg hdr_end
3875 * | |
3876 * v |
3877 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3878 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3879 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3880 * | | | | | | |
3881 * | | | | | | |
3882 * | | | | | | +--> next
3883 * | | | | | +----> val_end
3884 * | | | | +-----------> val_beg
3885 * | | | +--------------> equal
3886 * | | +----------------> att_end
3887 * | +---------------------> att_beg
3888 * +--------------------------> prev
3889 *
3890 */
3891 hdr_beg = ctx.value.ptr;
3892 hdr_end = hdr_beg + ctx.value.len;
3893 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3894 /* Iterate through all cookies on this line */
3895
3896 /* find att_beg */
3897 att_beg = prev;
3898 if (prev > hdr_beg)
3899 att_beg++;
3900
3901 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3902 att_beg++;
3903
3904 /* find att_end : this is the first character after the last non
3905 * space before the equal. It may be equal to hdr_end.
3906 */
3907 equal = att_end = att_beg;
3908 while (equal < hdr_end) {
3909 if (*equal == '=' || *equal == ',' || *equal == ';')
3910 break;
3911 if (HTTP_IS_SPHT(*equal++))
3912 continue;
3913 att_end = equal;
3914 }
3915
3916 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3917 * is between <att_beg> and <equal>, both may be identical.
3918 */
3919 /* look for end of cookie if there is an equal sign */
3920 if (equal < hdr_end && *equal == '=') {
3921 /* look for the beginning of the value */
3922 val_beg = equal + 1;
3923 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3924 val_beg++;
3925
3926 /* find the end of the value, respecting quotes */
3927 next = http_find_cookie_value_end(val_beg, hdr_end);
3928
3929 /* make val_end point to the first white space or delimitor after the value */
3930 val_end = next;
3931 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3932 val_end--;
3933 }
3934 else
3935 val_beg = val_end = next = equal;
3936
3937 /* We have nothing to do with attributes beginning with
3938 * '$'. However, they will automatically be removed if a
3939 * header before them is removed, since they're supposed
3940 * to be linked together.
3941 */
3942 if (*att_beg == '$')
3943 continue;
3944
3945 /* Ignore cookies with no equal sign */
3946 if (equal == next) {
3947 /* This is not our cookie, so we must preserve it. But if we already
3948 * scheduled another cookie for removal, we cannot remove the
3949 * complete header, but we can remove the previous block itself.
3950 */
3951 preserve_hdr = 1;
3952 if (del_from != NULL) {
3953 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
3954 val_end += delta;
3955 next += delta;
3956 hdr_end += delta;
3957 prev = del_from;
3958 del_from = NULL;
3959 }
3960 continue;
3961 }
3962
3963 /* if there are spaces around the equal sign, we need to
3964 * strip them otherwise we'll get trouble for cookie captures,
3965 * or even for rewrites. Since this happens extremely rarely,
3966 * it does not hurt performance.
3967 */
3968 if (unlikely(att_end != equal || val_beg > equal + 1)) {
3969 int stripped_before = 0;
3970 int stripped_after = 0;
3971
3972 if (att_end != equal) {
3973 memmove(att_end, equal, hdr_end - equal);
3974 stripped_before = (att_end - equal);
3975 equal += stripped_before;
3976 val_beg += stripped_before;
3977 }
3978
3979 if (val_beg > equal + 1) {
3980 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
3981 stripped_after = (equal + 1) - val_beg;
3982 val_beg += stripped_after;
3983 stripped_before += stripped_after;
3984 }
3985
3986 val_end += stripped_before;
3987 next += stripped_before;
3988 hdr_end += stripped_before;
3989 }
3990 /* now everything is as on the diagram above */
3991
3992 /* First, let's see if we want to capture this cookie. We check
3993 * that we don't already have a client side cookie, because we
3994 * can only capture one. Also as an optimisation, we ignore
3995 * cookies shorter than the declared name.
3996 */
3997 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
3998 (val_end - att_beg >= sess->fe->capture_namelen) &&
3999 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4000 int log_len = val_end - att_beg;
4001
4002 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4003 ha_alert("HTTP logging : out of memory.\n");
4004 } else {
4005 if (log_len > sess->fe->capture_len)
4006 log_len = sess->fe->capture_len;
4007 memcpy(txn->cli_cookie, att_beg, log_len);
4008 txn->cli_cookie[log_len] = 0;
4009 }
4010 }
4011
4012 /* Persistence cookies in passive, rewrite or insert mode have the
4013 * following form :
4014 *
4015 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4016 *
4017 * For cookies in prefix mode, the form is :
4018 *
4019 * Cookie: NAME=SRV~VALUE
4020 */
4021 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4022 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4023 struct server *srv = s->be->srv;
4024 char *delim;
4025
4026 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4027 * have the server ID between val_beg and delim, and the original cookie between
4028 * delim+1 and val_end. Otherwise, delim==val_end :
4029 *
4030 * hdr_beg
4031 * |
4032 * v
4033 * NAME=SRV; # in all but prefix modes
4034 * NAME=SRV~OPAQUE ; # in prefix mode
4035 * || || | |+-> next
4036 * || || | +--> val_end
4037 * || || +---------> delim
4038 * || |+------------> val_beg
4039 * || +-------------> att_end = equal
4040 * |+-----------------> att_beg
4041 * +------------------> prev
4042 *
4043 */
4044 if (s->be->ck_opts & PR_CK_PFX) {
4045 for (delim = val_beg; delim < val_end; delim++)
4046 if (*delim == COOKIE_DELIM)
4047 break;
4048 }
4049 else {
4050 char *vbar1;
4051 delim = val_end;
4052 /* Now check if the cookie contains a date field, which would
4053 * appear after a vertical bar ('|') just after the server name
4054 * and before the delimiter.
4055 */
4056 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4057 if (vbar1) {
4058 /* OK, so left of the bar is the server's cookie and
4059 * right is the last seen date. It is a base64 encoded
4060 * 30-bit value representing the UNIX date since the
4061 * epoch in 4-second quantities.
4062 */
4063 int val;
4064 delim = vbar1++;
4065 if (val_end - vbar1 >= 5) {
4066 val = b64tos30(vbar1);
4067 if (val > 0)
4068 txn->cookie_last_date = val << 2;
4069 }
4070 /* look for a second vertical bar */
4071 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4072 if (vbar1 && (val_end - vbar1 > 5)) {
4073 val = b64tos30(vbar1 + 1);
4074 if (val > 0)
4075 txn->cookie_first_date = val << 2;
4076 }
4077 }
4078 }
4079
4080 /* if the cookie has an expiration date and the proxy wants to check
4081 * it, then we do that now. We first check if the cookie is too old,
4082 * then only if it has expired. We detect strict overflow because the
4083 * time resolution here is not great (4 seconds). Cookies with dates
4084 * in the future are ignored if their offset is beyond one day. This
4085 * allows an admin to fix timezone issues without expiring everyone
4086 * and at the same time avoids keeping unwanted side effects for too
4087 * long.
4088 */
4089 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4090 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4091 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4092 txn->flags &= ~TX_CK_MASK;
4093 txn->flags |= TX_CK_OLD;
4094 delim = val_beg; // let's pretend we have not found the cookie
4095 txn->cookie_first_date = 0;
4096 txn->cookie_last_date = 0;
4097 }
4098 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4099 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4100 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4101 txn->flags &= ~TX_CK_MASK;
4102 txn->flags |= TX_CK_EXPIRED;
4103 delim = val_beg; // let's pretend we have not found the cookie
4104 txn->cookie_first_date = 0;
4105 txn->cookie_last_date = 0;
4106 }
4107
4108 /* Here, we'll look for the first running server which supports the cookie.
4109 * This allows to share a same cookie between several servers, for example
4110 * to dedicate backup servers to specific servers only.
4111 * However, to prevent clients from sticking to cookie-less backup server
4112 * when they have incidentely learned an empty cookie, we simply ignore
4113 * empty cookies and mark them as invalid.
4114 * The same behaviour is applied when persistence must be ignored.
4115 */
4116 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4117 srv = NULL;
4118
4119 while (srv) {
4120 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4121 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4122 if ((srv->cur_state != SRV_ST_STOPPED) ||
4123 (s->be->options & PR_O_PERSIST) ||
4124 (s->flags & SF_FORCE_PRST)) {
4125 /* we found the server and we can use it */
4126 txn->flags &= ~TX_CK_MASK;
4127 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4128 s->flags |= SF_DIRECT | SF_ASSIGNED;
4129 s->target = &srv->obj_type;
4130 break;
4131 } else {
4132 /* we found a server, but it's down,
4133 * mark it as such and go on in case
4134 * another one is available.
4135 */
4136 txn->flags &= ~TX_CK_MASK;
4137 txn->flags |= TX_CK_DOWN;
4138 }
4139 }
4140 srv = srv->next;
4141 }
4142
4143 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4144 /* no server matched this cookie or we deliberately skipped it */
4145 txn->flags &= ~TX_CK_MASK;
4146 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4147 txn->flags |= TX_CK_UNUSED;
4148 else
4149 txn->flags |= TX_CK_INVALID;
4150 }
4151
4152 /* depending on the cookie mode, we may have to either :
4153 * - delete the complete cookie if we're in insert+indirect mode, so that
4154 * the server never sees it ;
4155 * - remove the server id from the cookie value, and tag the cookie as an
4156 * application cookie so that it does not get accidentely removed later,
4157 * if we're in cookie prefix mode
4158 */
4159 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4160 int delta; /* negative */
4161
4162 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4163 delta = val_beg - (delim + 1);
4164 val_end += delta;
4165 next += delta;
4166 hdr_end += delta;
4167 del_from = NULL;
4168 preserve_hdr = 1; /* we want to keep this cookie */
4169 }
4170 else if (del_from == NULL &&
4171 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4172 del_from = prev;
4173 }
4174 }
4175 else {
4176 /* This is not our cookie, so we must preserve it. But if we already
4177 * scheduled another cookie for removal, we cannot remove the
4178 * complete header, but we can remove the previous block itself.
4179 */
4180 preserve_hdr = 1;
4181
4182 if (del_from != NULL) {
4183 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4184 if (att_beg >= del_from)
4185 att_beg += delta;
4186 if (att_end >= del_from)
4187 att_end += delta;
4188 val_beg += delta;
4189 val_end += delta;
4190 next += delta;
4191 hdr_end += delta;
4192 prev = del_from;
4193 del_from = NULL;
4194 }
4195 }
4196
4197 /* continue with next cookie on this header line */
4198 att_beg = next;
4199 } /* for each cookie */
4200
4201
4202 /* There are no more cookies on this line.
4203 * We may still have one (or several) marked for deletion at the
4204 * end of the line. We must do this now in two ways :
4205 * - if some cookies must be preserved, we only delete from the
4206 * mark to the end of line ;
4207 * - if nothing needs to be preserved, simply delete the whole header
4208 */
4209 if (del_from) {
4210 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4211 }
4212 if ((hdr_end - hdr_beg) != ctx.value.len) {
4213 if (hdr_beg != hdr_end) {
4214 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4215 htx->data -= (hdr_end - ctx.value.ptr);
4216 }
4217 else
4218 http_remove_header(htx, &ctx);
4219 }
4220 } /* for each "Cookie header */
4221}
4222
4223/*
4224 * Manage server-side cookies. It can impact performance by about 2% so it is
4225 * desirable to call it only when needed. This function is also used when we
4226 * just need to know if there is a cookie (eg: for check-cache).
4227 */
4228static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4229{
4230 struct session *sess = s->sess;
4231 struct http_txn *txn = s->txn;
4232 struct htx *htx;
4233 struct http_hdr_ctx ctx;
4234 struct server *srv;
4235 char *hdr_beg, *hdr_end;
4236 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4237 int is_cookie2;
4238
4239 htx = htx_from_buf(&res->buf);
4240
4241 ctx.blk = NULL;
4242 while (1) {
4243 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4244 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4245 break;
4246 is_cookie2 = 1;
4247 }
4248
4249 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4250 * <prev> points to the colon.
4251 */
4252 txn->flags |= TX_SCK_PRESENT;
4253
4254 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4255 * check-cache is enabled) and we are not interested in checking
4256 * them. Warning, the cookie capture is declared in the frontend.
4257 */
4258 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4259 break;
4260
4261 /* OK so now we know we have to process this response cookie.
4262 * The format of the Set-Cookie header is slightly different
4263 * from the format of the Cookie header in that it does not
4264 * support the comma as a cookie delimiter (thus the header
4265 * cannot be folded) because the Expires attribute described in
4266 * the original Netscape's spec may contain an unquoted date
4267 * with a comma inside. We have to live with this because
4268 * many browsers don't support Max-Age and some browsers don't
4269 * support quoted strings. However the Set-Cookie2 header is
4270 * clean.
4271 *
4272 * We have to keep multiple pointers in order to support cookie
4273 * removal at the beginning, middle or end of header without
4274 * corrupting the header (in case of set-cookie2). A special
4275 * pointer, <scav> points to the beginning of the set-cookie-av
4276 * fields after the first semi-colon. The <next> pointer points
4277 * either to the end of line (set-cookie) or next unquoted comma
4278 * (set-cookie2). All of these headers are valid :
4279 *
4280 * hdr_beg hdr_end
4281 * | |
4282 * v |
4283 * NAME1 = VALUE 1 ; Secure; Path="/" |
4284 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4285 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4286 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4287 * | | | | | | | |
4288 * | | | | | | | +-> next
4289 * | | | | | | +------------> scav
4290 * | | | | | +--------------> val_end
4291 * | | | | +--------------------> val_beg
4292 * | | | +----------------------> equal
4293 * | | +------------------------> att_end
4294 * | +----------------------------> att_beg
4295 * +------------------------------> prev
4296 * -------------------------------> hdr_beg
4297 */
4298 hdr_beg = ctx.value.ptr;
4299 hdr_end = hdr_beg + ctx.value.len;
4300 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4301
4302 /* Iterate through all cookies on this line */
4303
4304 /* find att_beg */
4305 att_beg = prev;
4306 if (prev > hdr_beg)
4307 att_beg++;
4308
4309 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4310 att_beg++;
4311
4312 /* find att_end : this is the first character after the last non
4313 * space before the equal. It may be equal to hdr_end.
4314 */
4315 equal = att_end = att_beg;
4316
4317 while (equal < hdr_end) {
4318 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4319 break;
4320 if (HTTP_IS_SPHT(*equal++))
4321 continue;
4322 att_end = equal;
4323 }
4324
4325 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4326 * is between <att_beg> and <equal>, both may be identical.
4327 */
4328
4329 /* look for end of cookie if there is an equal sign */
4330 if (equal < hdr_end && *equal == '=') {
4331 /* look for the beginning of the value */
4332 val_beg = equal + 1;
4333 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4334 val_beg++;
4335
4336 /* find the end of the value, respecting quotes */
4337 next = http_find_cookie_value_end(val_beg, hdr_end);
4338
4339 /* make val_end point to the first white space or delimitor after the value */
4340 val_end = next;
4341 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4342 val_end--;
4343 }
4344 else {
4345 /* <equal> points to next comma, semi-colon or EOL */
4346 val_beg = val_end = next = equal;
4347 }
4348
4349 if (next < hdr_end) {
4350 /* Set-Cookie2 supports multiple cookies, and <next> points to
4351 * a colon or semi-colon before the end. So skip all attr-value
4352 * pairs and look for the next comma. For Set-Cookie, since
4353 * commas are permitted in values, skip to the end.
4354 */
4355 if (is_cookie2)
4356 next = http_find_hdr_value_end(next, hdr_end);
4357 else
4358 next = hdr_end;
4359 }
4360
4361 /* Now everything is as on the diagram above */
4362
4363 /* Ignore cookies with no equal sign */
4364 if (equal == val_end)
4365 continue;
4366
4367 /* If there are spaces around the equal sign, we need to
4368 * strip them otherwise we'll get trouble for cookie captures,
4369 * or even for rewrites. Since this happens extremely rarely,
4370 * it does not hurt performance.
4371 */
4372 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4373 int stripped_before = 0;
4374 int stripped_after = 0;
4375
4376 if (att_end != equal) {
4377 memmove(att_end, equal, hdr_end - equal);
4378 stripped_before = (att_end - equal);
4379 equal += stripped_before;
4380 val_beg += stripped_before;
4381 }
4382
4383 if (val_beg > equal + 1) {
4384 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4385 stripped_after = (equal + 1) - val_beg;
4386 val_beg += stripped_after;
4387 stripped_before += stripped_after;
4388 }
4389
4390 val_end += stripped_before;
4391 next += stripped_before;
4392 hdr_end += stripped_before;
4393
4394 ctx.value.len = hdr_end - hdr_beg;
4395 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4396 htx->data -= (hdr_end - ctx.value.ptr);
4397 }
4398
4399 /* First, let's see if we want to capture this cookie. We check
4400 * that we don't already have a server side cookie, because we
4401 * can only capture one. Also as an optimisation, we ignore
4402 * cookies shorter than the declared name.
4403 */
4404 if (sess->fe->capture_name != NULL &&
4405 txn->srv_cookie == NULL &&
4406 (val_end - att_beg >= sess->fe->capture_namelen) &&
4407 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4408 int log_len = val_end - att_beg;
4409 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4410 ha_alert("HTTP logging : out of memory.\n");
4411 }
4412 else {
4413 if (log_len > sess->fe->capture_len)
4414 log_len = sess->fe->capture_len;
4415 memcpy(txn->srv_cookie, att_beg, log_len);
4416 txn->srv_cookie[log_len] = 0;
4417 }
4418 }
4419
4420 srv = objt_server(s->target);
4421 /* now check if we need to process it for persistence */
4422 if (!(s->flags & SF_IGNORE_PRST) &&
4423 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4424 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4425 /* assume passive cookie by default */
4426 txn->flags &= ~TX_SCK_MASK;
4427 txn->flags |= TX_SCK_FOUND;
4428
4429 /* If the cookie is in insert mode on a known server, we'll delete
4430 * this occurrence because we'll insert another one later.
4431 * We'll delete it too if the "indirect" option is set and we're in
4432 * a direct access.
4433 */
4434 if (s->be->ck_opts & PR_CK_PSV) {
4435 /* The "preserve" flag was set, we don't want to touch the
4436 * server's cookie.
4437 */
4438 }
4439 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4440 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4441 /* this cookie must be deleted */
4442 if (prev == hdr_beg && next == hdr_end) {
4443 /* whole header */
4444 http_remove_header(htx, &ctx);
4445 /* note: while both invalid now, <next> and <hdr_end>
4446 * are still equal, so the for() will stop as expected.
4447 */
4448 } else {
4449 /* just remove the value */
4450 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4451 next = prev;
4452 hdr_end += delta;
4453 }
4454 txn->flags &= ~TX_SCK_MASK;
4455 txn->flags |= TX_SCK_DELETED;
4456 /* and go on with next cookie */
4457 }
4458 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4459 /* replace bytes val_beg->val_end with the cookie name associated
4460 * with this server since we know it.
4461 */
4462 int sliding, delta;
4463
4464 ctx.value = ist2(val_beg, val_end - val_beg);
4465 ctx.lws_before = ctx.lws_after = 0;
4466 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4467 delta = srv->cklen - (val_end - val_beg);
4468 sliding = (ctx.value.ptr - val_beg);
4469 hdr_beg += sliding;
4470 val_beg += sliding;
4471 next += sliding + delta;
4472 hdr_end += sliding + delta;
4473
4474 txn->flags &= ~TX_SCK_MASK;
4475 txn->flags |= TX_SCK_REPLACED;
4476 }
4477 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4478 /* insert the cookie name associated with this server
4479 * before existing cookie, and insert a delimiter between them..
4480 */
4481 int sliding, delta;
4482 ctx.value = ist2(val_beg, 0);
4483 ctx.lws_before = ctx.lws_after = 0;
4484 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4485 delta = srv->cklen + 1;
4486 sliding = (ctx.value.ptr - val_beg);
4487 hdr_beg += sliding;
4488 val_beg += sliding;
4489 next += sliding + delta;
4490 hdr_end += sliding + delta;
4491
4492 val_beg[srv->cklen] = COOKIE_DELIM;
4493 txn->flags &= ~TX_SCK_MASK;
4494 txn->flags |= TX_SCK_REPLACED;
4495 }
4496 }
4497 /* that's done for this cookie, check the next one on the same
4498 * line when next != hdr_end (only if is_cookie2).
4499 */
4500 }
4501 }
4502}
4503
Christopher Faulet25a02f62018-10-24 12:00:25 +02004504/*
4505 * Parses the Cache-Control and Pragma request header fields to determine if
4506 * the request may be served from the cache and/or if it is cacheable. Updates
4507 * s->txn->flags.
4508 */
4509void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4510{
4511 struct http_txn *txn = s->txn;
4512 struct htx *htx;
4513 int32_t pos;
4514 int pragma_found, cc_found, i;
4515
4516 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4517 return; /* nothing more to do here */
4518
4519 htx = htx_from_buf(&req->buf);
4520 pragma_found = cc_found = 0;
4521 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4522 struct htx_blk *blk = htx_get_blk(htx, pos);
4523 enum htx_blk_type type = htx_get_blk_type(blk);
4524 struct ist n, v;
4525
4526 if (type == HTX_BLK_EOH)
4527 break;
4528 if (type != HTX_BLK_HDR)
4529 continue;
4530
4531 n = htx_get_blk_name(htx, blk);
4532 v = htx_get_blk_value(htx, blk);
4533
4534 if (isteqi(n, ist("Pragma"))) {
4535 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4536 pragma_found = 1;
4537 continue;
4538 }
4539 }
4540
4541 /* Don't use the cache and don't try to store if we found the
4542 * Authorization header */
4543 if (isteqi(n, ist("Authorization"))) {
4544 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4545 txn->flags |= TX_CACHE_IGNORE;
4546 continue;
4547 }
4548
4549 if (!isteqi(n, ist("Cache-control")))
4550 continue;
4551
4552 /* OK, right now we know we have a cache-control header */
4553 cc_found = 1;
4554 if (!v.len) /* no info */
4555 continue;
4556
4557 i = 0;
4558 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4559 !isspace((unsigned char)*(v.ptr+i)))
4560 i++;
4561
4562 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4563 * values after max-age, max-stale nor min-fresh, we simply don't
4564 * use the cache when they're specified.
4565 */
4566 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4567 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4568 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4569 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4570 txn->flags |= TX_CACHE_IGNORE;
4571 continue;
4572 }
4573
4574 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4575 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4576 continue;
4577 }
4578 }
4579
4580 /* RFC7234#5.4:
4581 * When the Cache-Control header field is also present and
4582 * understood in a request, Pragma is ignored.
4583 * When the Cache-Control header field is not present in a
4584 * request, caches MUST consider the no-cache request
4585 * pragma-directive as having the same effect as if
4586 * "Cache-Control: no-cache" were present.
4587 */
4588 if (!cc_found && pragma_found)
4589 txn->flags |= TX_CACHE_IGNORE;
4590}
4591
4592/*
4593 * Check if response is cacheable or not. Updates s->txn->flags.
4594 */
4595void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4596{
4597 struct http_txn *txn = s->txn;
4598 struct htx *htx;
4599 int32_t pos;
4600 int i;
4601
4602 if (txn->status < 200) {
4603 /* do not try to cache interim responses! */
4604 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4605 return;
4606 }
4607
4608 htx = htx_from_buf(&res->buf);
4609 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4610 struct htx_blk *blk = htx_get_blk(htx, pos);
4611 enum htx_blk_type type = htx_get_blk_type(blk);
4612 struct ist n, v;
4613
4614 if (type == HTX_BLK_EOH)
4615 break;
4616 if (type != HTX_BLK_HDR)
4617 continue;
4618
4619 n = htx_get_blk_name(htx, blk);
4620 v = htx_get_blk_value(htx, blk);
4621
4622 if (isteqi(n, ist("Pragma"))) {
4623 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4624 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4625 return;
4626 }
4627 }
4628
4629 if (!isteqi(n, ist("Cache-control")))
4630 continue;
4631
4632 /* OK, right now we know we have a cache-control header */
4633 if (!v.len) /* no info */
4634 continue;
4635
4636 i = 0;
4637 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4638 !isspace((unsigned char)*(v.ptr+i)))
4639 i++;
4640
4641 /* we have a complete value between v.ptr and (v.ptr+i) */
4642 if (i < v.len && *(v.ptr + i) == '=') {
4643 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4644 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4645 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4646 continue;
4647 }
4648
4649 /* we have something of the form no-cache="set-cookie" */
4650 if ((v.len >= 21) &&
4651 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4652 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4653 txn->flags &= ~TX_CACHE_COOK;
4654 continue;
4655 }
4656
4657 /* OK, so we know that either p2 points to the end of string or to a comma */
4658 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4659 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4660 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4661 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4662 return;
4663 }
4664
4665 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4666 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4667 continue;
4668 }
4669 }
4670}
4671
Christopher Faulet64159df2018-10-24 21:15:35 +02004672/* send a server's name with an outgoing request over an established connection.
4673 * Note: this function is designed to be called once the request has been
4674 * scheduled for being forwarded. This is the reason why the number of forwarded
4675 * bytes have to be adjusted.
4676 */
4677int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4678{
4679 struct htx *htx;
4680 struct http_hdr_ctx ctx;
4681 struct ist hdr;
4682 uint32_t data;
4683
4684 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
4685 htx = htx_from_buf(&s->req.buf);
4686 data = htx->data;
4687
4688 ctx.blk = NULL;
4689 while (http_find_header(htx, hdr, &ctx, 1))
4690 http_remove_header(htx, &ctx);
4691 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4692
4693 if (co_data(&s->req)) {
4694 if (data >= htx->data)
4695 c_rew(&s->req, data - htx->data);
4696 else
4697 c_adv(&s->req, htx->data - data);
4698 }
4699 return 0;
4700}
4701
Christopher Faulet377c5a52018-10-24 21:21:30 +02004702/*
4703 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4704 * for the current backend.
4705 *
4706 * It is assumed that the request is either a HEAD, GET, or POST and that the
4707 * uri_auth field is valid.
4708 *
4709 * Returns 1 if stats should be provided, otherwise 0.
4710 */
4711static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4712{
4713 struct uri_auth *uri_auth = backend->uri_auth;
4714 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004715 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004716 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004717
4718 if (!uri_auth)
4719 return 0;
4720
4721 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4722 return 0;
4723
4724 htx = htx_from_buf(&s->req.buf);
4725 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004726 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004727
4728 /* check URI size */
4729 if (uri_auth->uri_len > uri.len)
4730 return 0;
4731
4732 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4733 return 0;
4734
4735 return 1;
4736}
4737
4738/* This function prepares an applet to handle the stats. It can deal with the
4739 * "100-continue" expectation, check that admin rules are met for POST requests,
4740 * and program a response message if something was unexpected. It cannot fail
4741 * and always relies on the stats applet to complete the job. It does not touch
4742 * analysers nor counters, which are left to the caller. It does not touch
4743 * s->target which is supposed to already point to the stats applet. The caller
4744 * is expected to have already assigned an appctx to the stream.
4745 */
4746static int htx_handle_stats(struct stream *s, struct channel *req)
4747{
4748 struct stats_admin_rule *stats_admin_rule;
4749 struct stream_interface *si = &s->si[1];
4750 struct session *sess = s->sess;
4751 struct http_txn *txn = s->txn;
4752 struct http_msg *msg = &txn->req;
4753 struct uri_auth *uri_auth = s->be->uri_auth;
4754 const char *h, *lookup, *end;
4755 struct appctx *appctx;
4756 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004757 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004758
4759 appctx = si_appctx(si);
4760 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4761 appctx->st1 = appctx->st2 = 0;
4762 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4763 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4764 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4765 appctx->ctx.stats.flags |= STAT_CHUNKED;
4766
4767 htx = htx_from_buf(&req->buf);
4768 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004769 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4770 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004771
4772 for (h = lookup; h <= end - 3; h++) {
4773 if (memcmp(h, ";up", 3) == 0) {
4774 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4775 break;
4776 }
4777 }
4778
4779 if (uri_auth->refresh) {
4780 for (h = lookup; h <= end - 10; h++) {
4781 if (memcmp(h, ";norefresh", 10) == 0) {
4782 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4783 break;
4784 }
4785 }
4786 }
4787
4788 for (h = lookup; h <= end - 4; h++) {
4789 if (memcmp(h, ";csv", 4) == 0) {
4790 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4791 break;
4792 }
4793 }
4794
4795 for (h = lookup; h <= end - 6; h++) {
4796 if (memcmp(h, ";typed", 6) == 0) {
4797 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4798 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4799 break;
4800 }
4801 }
4802
4803 for (h = lookup; h <= end - 8; h++) {
4804 if (memcmp(h, ";st=", 4) == 0) {
4805 int i;
4806 h += 4;
4807 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4808 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4809 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4810 appctx->ctx.stats.st_code = i;
4811 break;
4812 }
4813 }
4814 break;
4815 }
4816 }
4817
4818 appctx->ctx.stats.scope_str = 0;
4819 appctx->ctx.stats.scope_len = 0;
4820 for (h = lookup; h <= end - 8; h++) {
4821 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4822 int itx = 0;
4823 const char *h2;
4824 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4825 const char *err;
4826
4827 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4828 h2 = h;
4829 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4830 while (h <= end) {
4831 if (*h == ';' || *h == '&' || *h == ' ')
4832 break;
4833 itx++;
4834 h++;
4835 }
4836
4837 if (itx > STAT_SCOPE_TXT_MAXLEN)
4838 itx = STAT_SCOPE_TXT_MAXLEN;
4839 appctx->ctx.stats.scope_len = itx;
4840
4841 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4842 memcpy(scope_txt, h2, itx);
4843 scope_txt[itx] = '\0';
4844 err = invalid_char(scope_txt);
4845 if (err) {
4846 /* bad char in search text => clear scope */
4847 appctx->ctx.stats.scope_str = 0;
4848 appctx->ctx.stats.scope_len = 0;
4849 }
4850 break;
4851 }
4852 }
4853
4854 /* now check whether we have some admin rules for this request */
4855 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4856 int ret = 1;
4857
4858 if (stats_admin_rule->cond) {
4859 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4860 ret = acl_pass(ret);
4861 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4862 ret = !ret;
4863 }
4864
4865 if (ret) {
4866 /* no rule, or the rule matches */
4867 appctx->ctx.stats.flags |= STAT_ADMIN;
4868 break;
4869 }
4870 }
4871
4872 /* Was the status page requested with a POST ? */
4873 if (unlikely(txn->meth == HTTP_METH_POST)) {
4874 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4875 /* we'll need the request body, possibly after sending 100-continue */
4876 if (msg->msg_state < HTTP_MSG_DATA)
4877 req->analysers |= AN_REQ_HTTP_BODY;
4878 appctx->st0 = STAT_HTTP_POST;
4879 }
4880 else {
4881 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4882 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4883 appctx->st0 = STAT_HTTP_LAST;
4884 }
4885 }
4886 else {
4887 /* So it was another method (GET/HEAD) */
4888 appctx->st0 = STAT_HTTP_HEAD;
4889 }
4890
4891 s->task->nice = -32; /* small boost for HTTP statistics */
4892 return 1;
4893}
4894
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004895void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4896{
4897 struct http_txn *txn = s->txn;
4898 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004899 struct htx_sl *sl;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004900 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004901 struct ist path;
4902
4903 /* 1: create the response header */
4904 if (!chunk_memcat(&trash, HTTP_302, strlen(HTTP_302)))
4905 return;
4906
4907 /* 2: add the server's prefix */
4908 /* special prefix "/" means don't change URL */
4909 srv = __objt_server(s->target);
4910 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4911 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4912 return;
4913 }
4914
4915 /* 3: add the request Path */
4916 htx = htx_from_buf(&s->req.buf);
4917 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004918 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004919 if (!path.ptr)
4920 return;
4921
4922 if (!chunk_memcat(&trash, path.ptr, path.len))
4923 return;
4924
4925 if (unlikely(txn->flags & TX_USE_PX_CONN)) {
4926 if (!chunk_memcat(&trash, "\r\nProxy-Connection: close\r\n\r\n", 29))
4927 return;
4928 }
4929 else {
4930 if (!chunk_memcat(&trash, "\r\nConnection: close\r\n\r\n", 23))
4931 return;
4932 }
4933
4934 /* prepare to return without error. */
4935 si_shutr(si);
4936 si_shutw(si);
4937 si->err_type = SI_ET_NONE;
4938 si->state = SI_ST_CLO;
4939
4940 /* send the message */
4941 txn->status = 302;
4942 htx_server_error(s, si, SF_ERR_LOCAL, SF_FINST_C, &trash);
4943
4944 /* FIXME: we should increase a counter of redirects per server and per backend. */
4945 srv_inc_sess_ctr(srv);
4946 srv_set_sess_last(srv);
4947}
4948
Christopher Fauletf2824e62018-10-01 12:12:37 +02004949/* This function terminates the request because it was completly analyzed or
4950 * because an error was triggered during the body forwarding.
4951 */
4952static void htx_end_request(struct stream *s)
4953{
4954 struct channel *chn = &s->req;
4955 struct http_txn *txn = s->txn;
4956
4957 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
4958 now_ms, __FUNCTION__, s,
4959 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
4960 s->req.analysers, s->res.analysers);
4961
Christopher Fauletb42a8b62018-11-19 21:59:00 +01004962 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
4963 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02004964 channel_abort(chn);
4965 channel_truncate(chn);
4966 goto end;
4967 }
4968
4969 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
4970 return;
4971
4972 if (txn->req.msg_state == HTTP_MSG_DONE) {
4973 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
4974 /* The server has not finished to respond, so we
4975 * don't want to move in order not to upset it.
4976 */
4977 return;
4978 }
4979
4980 /* No need to read anymore, the request was completely parsed.
4981 * We can shut the read side unless we want to abort_on_close,
4982 * or we have a POST request. The issue with POST requests is
4983 * that some browsers still send a CRLF after the request, and
4984 * this CRLF must be read so that it does not remain in the kernel
4985 * buffers, otherwise a close could cause an RST on some systems
4986 * (eg: Linux).
4987 */
4988 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
4989 txn->meth != HTTP_METH_POST)
4990 channel_dont_read(chn);
4991
4992 /* if the server closes the connection, we want to immediately react
4993 * and close the socket to save packets and syscalls.
4994 */
4995 s->si[1].flags |= SI_FL_NOHALF;
4996
4997 /* In any case we've finished parsing the request so we must
4998 * disable Nagle when sending data because 1) we're not going
4999 * to shut this side, and 2) the server is waiting for us to
5000 * send pending data.
5001 */
5002 chn->flags |= CF_NEVER_WAIT;
5003
5004 /* When we get here, it means that both the request and the
5005 * response have finished receiving. Depending on the connection
5006 * mode, we'll have to wait for the last bytes to leave in either
5007 * direction, and sometimes for a close to be effective.
5008 */
5009 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5010 /* Tunnel mode will not have any analyser so it needs to
5011 * poll for reads.
5012 */
5013 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005014 if (b_data(&chn->buf))
5015 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005016 txn->req.msg_state = HTTP_MSG_TUNNEL;
5017 }
5018 else {
5019 /* we're not expecting any new data to come for this
5020 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005021 *
5022 * However, there is an exception if the response
5023 * length is undefined. In this case, we need to wait
5024 * the close from the server. The response will be
5025 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005026 */
5027 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5028 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005029 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005030
5031 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5032 channel_shutr_now(chn);
5033 channel_shutw_now(chn);
5034 }
5035 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005036 goto check_channel_flags;
5037 }
5038
5039 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5040 http_msg_closing:
5041 /* nothing else to forward, just waiting for the output buffer
5042 * to be empty and for the shutw_now to take effect.
5043 */
5044 if (channel_is_empty(chn)) {
5045 txn->req.msg_state = HTTP_MSG_CLOSED;
5046 goto http_msg_closed;
5047 }
5048 else if (chn->flags & CF_SHUTW) {
5049 txn->req.err_state = txn->req.msg_state;
5050 txn->req.msg_state = HTTP_MSG_ERROR;
5051 goto end;
5052 }
5053 return;
5054 }
5055
5056 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5057 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005058 /* if we don't know whether the server will close, we need to hard close */
5059 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5060 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005061 /* see above in MSG_DONE why we only do this in these states */
5062 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5063 channel_dont_read(chn);
5064 goto end;
5065 }
5066
5067 check_channel_flags:
5068 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5069 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5070 /* if we've just closed an output, let's switch */
5071 txn->req.msg_state = HTTP_MSG_CLOSING;
5072 goto http_msg_closing;
5073 }
5074
5075 end:
5076 chn->analysers &= AN_REQ_FLT_END;
5077 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5078 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5079 channel_auto_close(chn);
5080 channel_auto_read(chn);
5081}
5082
5083
5084/* This function terminates the response because it was completly analyzed or
5085 * because an error was triggered during the body forwarding.
5086 */
5087static void htx_end_response(struct stream *s)
5088{
5089 struct channel *chn = &s->res;
5090 struct http_txn *txn = s->txn;
5091
5092 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5093 now_ms, __FUNCTION__, s,
5094 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5095 s->req.analysers, s->res.analysers);
5096
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005097 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5098 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005099 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005100 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005101 goto end;
5102 }
5103
5104 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5105 return;
5106
5107 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5108 /* In theory, we don't need to read anymore, but we must
5109 * still monitor the server connection for a possible close
5110 * while the request is being uploaded, so we don't disable
5111 * reading.
5112 */
5113 /* channel_dont_read(chn); */
5114
5115 if (txn->req.msg_state < HTTP_MSG_DONE) {
5116 /* The client seems to still be sending data, probably
5117 * because we got an error response during an upload.
5118 * We have the choice of either breaking the connection
5119 * or letting it pass through. Let's do the later.
5120 */
5121 return;
5122 }
5123
5124 /* When we get here, it means that both the request and the
5125 * response have finished receiving. Depending on the connection
5126 * mode, we'll have to wait for the last bytes to leave in either
5127 * direction, and sometimes for a close to be effective.
5128 */
5129 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5130 channel_auto_read(chn);
5131 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005132 if (b_data(&chn->buf))
5133 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005134 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5135 }
5136 else {
5137 /* we're not expecting any new data to come for this
5138 * transaction, so we can close it.
5139 */
5140 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5141 channel_shutr_now(chn);
5142 channel_shutw_now(chn);
5143 }
5144 }
5145 goto check_channel_flags;
5146 }
5147
5148 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5149 http_msg_closing:
5150 /* nothing else to forward, just waiting for the output buffer
5151 * to be empty and for the shutw_now to take effect.
5152 */
5153 if (channel_is_empty(chn)) {
5154 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5155 goto http_msg_closed;
5156 }
5157 else if (chn->flags & CF_SHUTW) {
5158 txn->rsp.err_state = txn->rsp.msg_state;
5159 txn->rsp.msg_state = HTTP_MSG_ERROR;
5160 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5161 if (objt_server(s->target))
5162 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5163 goto end;
5164 }
5165 return;
5166 }
5167
5168 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5169 http_msg_closed:
5170 /* drop any pending data */
5171 channel_truncate(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005172 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005173 goto end;
5174 }
5175
5176 check_channel_flags:
5177 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5178 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5179 /* if we've just closed an output, let's switch */
5180 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5181 goto http_msg_closing;
5182 }
5183
5184 end:
5185 chn->analysers &= AN_RES_FLT_END;
5186 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5187 chn->analysers |= AN_RES_FLT_XFER_DATA;
5188 channel_auto_close(chn);
5189 channel_auto_read(chn);
5190}
5191
Christopher Faulet0f226952018-10-22 09:29:56 +02005192void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5193 int finst, const struct buffer *msg)
5194{
5195 channel_auto_read(si_oc(si));
5196 channel_abort(si_oc(si));
5197 channel_auto_close(si_oc(si));
5198 channel_erase(si_oc(si));
5199 channel_auto_close(si_ic(si));
5200 channel_auto_read(si_ic(si));
5201 if (msg) {
5202 struct channel *chn = si_ic(si);
5203 struct htx *htx;
5204
5205 htx = htx_from_buf(&chn->buf);
5206 htx_add_oob(htx, ist2(msg->area, msg->data));
5207 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5208 b_set_data(&chn->buf, b_size(&chn->buf));
5209 c_adv(chn, htx->data);
5210 chn->total += htx->data;
5211 }
5212 if (!(s->flags & SF_ERR_MASK))
5213 s->flags |= err;
5214 if (!(s->flags & SF_FINST_MASK))
5215 s->flags |= finst;
5216}
5217
5218void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5219{
5220 channel_auto_read(&s->req);
5221 channel_abort(&s->req);
5222 channel_auto_close(&s->req);
5223 channel_erase(&s->req);
5224 channel_truncate(&s->res);
5225
5226 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
5227 if (msg) {
5228 struct channel *chn = &s->res;
5229 struct htx *htx;
5230
5231 htx = htx_from_buf(&chn->buf);
5232 htx_add_oob(htx, ist2(msg->area, msg->data));
5233 //FLT_STRM_CB(s, flt_htx_reply(s, s->txn->status, htx));
5234 b_set_data(&chn->buf, b_size(&chn->buf));
5235 c_adv(chn, htx->data);
5236 chn->total += htx->data;
5237 }
5238
5239 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5240 channel_auto_read(&s->res);
5241 channel_auto_close(&s->res);
5242 channel_shutr_now(&s->res);
5243}
5244
Christopher Faulet23a3c792018-11-28 10:01:23 +01005245/* Send a 100-Continue response to the client. It returns 0 on success and -1
5246 * on error. The response channel is updated accordingly.
5247 */
5248static int htx_reply_100_continue(struct stream *s)
5249{
5250 struct channel *res = &s->res;
5251 struct htx *htx = htx_from_buf(&res->buf);
5252 struct htx_sl *sl;
5253 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5254 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5255 size_t data;
5256
5257 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5258 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5259 if (!sl)
5260 goto fail;
5261 sl->info.res.status = 100;
5262
5263 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5264 goto fail;
5265
5266 data = htx->data - co_data(res);
5267 b_set_data(&res->buf, b_size(&res->buf));
5268 c_adv(res, data);
5269 res->total += data;
5270 return 0;
5271
5272 fail:
5273 /* If an error occurred, remove the incomplete HTTP response from the
5274 * buffer */
5275 channel_truncate(res);
5276 return -1;
5277}
5278
Christopher Faulet0f226952018-10-22 09:29:56 +02005279/*
5280 * Capture headers from message <htx> according to header list <cap_hdr>, and
5281 * fill the <cap> pointers appropriately.
5282 */
5283static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5284{
5285 struct cap_hdr *h;
5286 int32_t pos;
5287
5288 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5289 struct htx_blk *blk = htx_get_blk(htx, pos);
5290 enum htx_blk_type type = htx_get_blk_type(blk);
5291 struct ist n, v;
5292
5293 if (type == HTX_BLK_EOH)
5294 break;
5295 if (type != HTX_BLK_HDR)
5296 continue;
5297
5298 n = htx_get_blk_name(htx, blk);
5299
5300 for (h = cap_hdr; h; h = h->next) {
5301 if (h->namelen && (h->namelen == n.len) &&
5302 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5303 if (cap[h->index] == NULL)
5304 cap[h->index] =
5305 pool_alloc(h->pool);
5306
5307 if (cap[h->index] == NULL) {
5308 ha_alert("HTTP capture : out of memory.\n");
5309 break;
5310 }
5311
5312 v = htx_get_blk_value(htx, blk);
5313 if (v.len > h->len)
5314 v.len = h->len;
5315
5316 memcpy(cap[h->index], v.ptr, v.len);
5317 cap[h->index][v.len]=0;
5318 }
5319 }
5320 }
5321}
5322
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005323/* Delete a value in a header between delimiters <from> and <next>. The header
5324 * itself is delimited by <start> and <end> pointers. The number of characters
5325 * displaced is returned, and the pointer to the first delimiter is updated if
5326 * required. The function tries as much as possible to respect the following
5327 * principles :
5328 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5329 * in which case <next> is simply removed
5330 * - set exactly one space character after the new first delimiter, unless there
5331 * are not enough characters in the block being moved to do so.
5332 * - remove unneeded spaces before the previous delimiter and after the new
5333 * one.
5334 *
5335 * It is the caller's responsibility to ensure that :
5336 * - <from> points to a valid delimiter or <start> ;
5337 * - <next> points to a valid delimiter or <end> ;
5338 * - there are non-space chars before <from>.
5339 */
5340static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5341{
5342 char *prev = *from;
5343
5344 if (prev == start) {
5345 /* We're removing the first value. eat the semicolon, if <next>
5346 * is lower than <end> */
5347 if (next < end)
5348 next++;
5349
5350 while (next < end && HTTP_IS_SPHT(*next))
5351 next++;
5352 }
5353 else {
5354 /* Remove useless spaces before the old delimiter. */
5355 while (HTTP_IS_SPHT(*(prev-1)))
5356 prev--;
5357 *from = prev;
5358
5359 /* copy the delimiter and if possible a space if we're
5360 * not at the end of the line.
5361 */
5362 if (next < end) {
5363 *prev++ = *next++;
5364 if (prev + 1 < next)
5365 *prev++ = ' ';
5366 while (next < end && HTTP_IS_SPHT(*next))
5367 next++;
5368 }
5369 }
5370 memmove(prev, next, end - next);
5371 return (prev - next);
5372}
5373
Christopher Faulet0f226952018-10-22 09:29:56 +02005374
5375/* Formats the start line of the request (without CRLF) and puts it in <str> and
5376 * return the written lenght. The line can be truncated if it exceeds <len>.
5377 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005378static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005379{
5380 struct ist dst = ist2(str, 0);
5381
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005382 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005383 goto end;
5384 if (dst.len + 1 > len)
5385 goto end;
5386 dst.ptr[dst.len++] = ' ';
5387
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005388 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005389 goto end;
5390 if (dst.len + 1 > len)
5391 goto end;
5392 dst.ptr[dst.len++] = ' ';
5393
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005394 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005395 end:
5396 return dst.len;
5397}
5398
Christopher Fauletf0523542018-10-24 11:06:58 +02005399/* Formats the start line of the response (without CRLF) and puts it in <str> and
5400 * return the written lenght. The line can be truncated if it exceeds <len>.
5401 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005402static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005403{
5404 struct ist dst = ist2(str, 0);
5405
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005406 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005407 goto end;
5408 if (dst.len + 1 > len)
5409 goto end;
5410 dst.ptr[dst.len++] = ' ';
5411
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005412 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005413 goto end;
5414 if (dst.len + 1 > len)
5415 goto end;
5416 dst.ptr[dst.len++] = ' ';
5417
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005418 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005419 end:
5420 return dst.len;
5421}
5422
5423
Christopher Faulet0f226952018-10-22 09:29:56 +02005424/*
5425 * Print a debug line with a start line.
5426 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005427static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005428{
5429 struct session *sess = strm_sess(s);
5430 int max;
5431
5432 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5433 dir,
5434 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5435 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5436
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005437 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005438 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005439 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005440 trash.area[trash.data++] = ' ';
5441
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005442 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005443 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005444 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005445 trash.area[trash.data++] = ' ';
5446
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005447 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005448 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005449 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005450 trash.area[trash.data++] = '\n';
5451
5452 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5453}
5454
5455/*
5456 * Print a debug line with a header.
5457 */
5458static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5459{
5460 struct session *sess = strm_sess(s);
5461 int max;
5462
5463 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5464 dir,
5465 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5466 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5467
5468 max = n.len;
5469 UBOUND(max, trash.size - trash.data - 3);
5470 chunk_memcat(&trash, n.ptr, max);
5471 trash.area[trash.data++] = ':';
5472 trash.area[trash.data++] = ' ';
5473
5474 max = v.len;
5475 UBOUND(max, trash.size - trash.data - 1);
5476 chunk_memcat(&trash, v.ptr, max);
5477 trash.area[trash.data++] = '\n';
5478
5479 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5480}
5481
5482
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005483__attribute__((constructor))
5484static void __htx_protocol_init(void)
5485{
5486}
5487
5488
5489/*
5490 * Local variables:
5491 * c-indent-level: 8
5492 * c-basic-offset: 8
5493 * End:
5494 */