blob: 3232d0a2ef2836835aa5f5872a09c4f2b3eb9afe [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);
Christopher Faulet12c51e22018-11-28 15:59:42 +010064static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm);
Christopher Faulet23a3c792018-11-28 10:01:23 +010065
Christopher Faulete0768eb2018-10-03 16:38:02 +020066/* This stream analyser waits for a complete HTTP request. It returns 1 if the
67 * processing can continue on next analysers, or zero if it either needs more
68 * data or wants to immediately abort the request (eg: timeout, error, ...). It
69 * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req.analysers
70 * when it has nothing left to do, and may remove any analyser when it wants to
71 * abort.
72 */
73int htx_wait_for_request(struct stream *s, struct channel *req, int an_bit)
74{
Christopher Faulet9768c262018-10-22 09:34:31 +020075
Christopher Faulete0768eb2018-10-03 16:38:02 +020076 /*
Christopher Faulet9768c262018-10-22 09:34:31 +020077 * We will analyze a complete HTTP request to check the its syntax.
Christopher Faulete0768eb2018-10-03 16:38:02 +020078 *
Christopher Faulet9768c262018-10-22 09:34:31 +020079 * Once the start line and all headers are received, we may perform a
80 * capture of the error (if any), and we will set a few fields. We also
81 * check for monitor-uri, logging and finally headers capture.
Christopher Faulete0768eb2018-10-03 16:38:02 +020082 */
Christopher Faulete0768eb2018-10-03 16:38:02 +020083 struct session *sess = s->sess;
84 struct http_txn *txn = s->txn;
85 struct http_msg *msg = &txn->req;
Christopher Faulet9768c262018-10-22 09:34:31 +020086 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +010087 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +020088
89 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
90 now_ms, __FUNCTION__,
91 s,
92 req,
93 req->rex, req->wex,
94 req->flags,
95 ci_data(req),
96 req->analysers);
97
Christopher Faulet27ba2dc2018-12-05 11:53:24 +010098 htx = htxbuf(&req->buf);
Christopher Faulet9768c262018-10-22 09:34:31 +020099
Christopher Faulete0768eb2018-10-03 16:38:02 +0200100 /* we're speaking HTTP here, so let's speak HTTP to the client */
101 s->srv_error = http_return_srv_error;
102
103 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100104 if (c_data(req) && s->logs.t_idle == -1) {
105 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
106
107 s->logs.t_idle = ((csinfo)
108 ? csinfo->t_idle
109 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
110 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200111
Christopher Faulete0768eb2018-10-03 16:38:02 +0200112 /*
113 * Now we quickly check if we have found a full valid request.
114 * If not so, we check the FD and buffer states before leaving.
115 * A full request is indicated by the fact that we have seen
116 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
117 * requests are checked first. When waiting for a second request
118 * on a keep-alive stream, if we encounter and error, close, t/o,
119 * we note the error in the stream flags but don't set any state.
120 * Since the error will be noted there, it will not be counted by
121 * process_stream() as a frontend error.
122 * Last, we may increase some tracked counters' http request errors on
123 * the cases that are deliberately the client's fault. For instance,
124 * a timeout or connection reset is not counted as an error. However
125 * a bad request is.
126 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200127 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100128 /*
129 * First catch invalid request
130 */
131 if (htx->flags & HTX_FL_PARSING_ERROR) {
132 stream_inc_http_req_ctr(s);
133 stream_inc_http_err_ctr(s);
134 proxy_inc_fe_req_ctr(sess->fe);
135 goto return_bad_req;
136 }
137
Christopher Faulet9768c262018-10-22 09:34:31 +0200138 /* 1: have we encountered a read error ? */
139 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200140 if (!(s->flags & SF_ERR_MASK))
141 s->flags |= SF_ERR_CLICL;
142
143 if (txn->flags & TX_WAIT_NEXT_RQ)
144 goto failed_keep_alive;
145
146 if (sess->fe->options & PR_O_IGNORE_PRB)
147 goto failed_keep_alive;
148
Christopher Faulet9768c262018-10-22 09:34:31 +0200149 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 stream_inc_http_req_ctr(s);
151 proxy_inc_fe_req_ctr(sess->fe);
152 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
153 if (sess->listener->counters)
154 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
155
Christopher Faulet9768c262018-10-22 09:34:31 +0200156 txn->status = 400;
157 msg->err_state = msg->msg_state;
158 msg->msg_state = HTTP_MSG_ERROR;
159 htx_reply_and_close(s, txn->status, NULL);
160 req->analysers &= AN_REQ_FLT_END;
161
Christopher Faulete0768eb2018-10-03 16:38:02 +0200162 if (!(s->flags & SF_FINST_MASK))
163 s->flags |= SF_FINST_R;
164 return 0;
165 }
166
Christopher Faulet9768c262018-10-22 09:34:31 +0200167 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200168 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
169 if (!(s->flags & SF_ERR_MASK))
170 s->flags |= SF_ERR_CLITO;
171
172 if (txn->flags & TX_WAIT_NEXT_RQ)
173 goto failed_keep_alive;
174
175 if (sess->fe->options & PR_O_IGNORE_PRB)
176 goto failed_keep_alive;
177
Christopher Faulet9768c262018-10-22 09:34:31 +0200178 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200179 stream_inc_http_req_ctr(s);
180 proxy_inc_fe_req_ctr(sess->fe);
181 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
182 if (sess->listener->counters)
183 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
184
Christopher Faulet9768c262018-10-22 09:34:31 +0200185 txn->status = 408;
186 msg->err_state = msg->msg_state;
187 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100188 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200189 req->analysers &= AN_REQ_FLT_END;
190
Christopher Faulete0768eb2018-10-03 16:38:02 +0200191 if (!(s->flags & SF_FINST_MASK))
192 s->flags |= SF_FINST_R;
193 return 0;
194 }
195
Christopher Faulet9768c262018-10-22 09:34:31 +0200196 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200197 else if (req->flags & CF_SHUTR) {
198 if (!(s->flags & SF_ERR_MASK))
199 s->flags |= SF_ERR_CLICL;
200
201 if (txn->flags & TX_WAIT_NEXT_RQ)
202 goto failed_keep_alive;
203
204 if (sess->fe->options & PR_O_IGNORE_PRB)
205 goto failed_keep_alive;
206
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 stream_inc_http_err_ctr(s);
208 stream_inc_http_req_ctr(s);
209 proxy_inc_fe_req_ctr(sess->fe);
210 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
211 if (sess->listener->counters)
212 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
213
Christopher Faulet9768c262018-10-22 09:34:31 +0200214 txn->status = 400;
215 msg->err_state = msg->msg_state;
216 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100217 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200218 req->analysers &= AN_REQ_FLT_END;
219
Christopher Faulete0768eb2018-10-03 16:38:02 +0200220 if (!(s->flags & SF_FINST_MASK))
221 s->flags |= SF_FINST_R;
222 return 0;
223 }
224
225 channel_dont_connect(req);
226 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
227 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
228#ifdef TCP_QUICKACK
Christopher Faulet9768c262018-10-22 09:34:31 +0200229 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
231 /* We need more data, we have to re-enable quick-ack in case we
232 * previously disabled it, otherwise we might cause the client
233 * to delay next data.
234 */
235 setsockopt(__objt_conn(sess->origin)->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
236 }
237#endif
Christopher Faulet47365272018-10-31 17:40:50 +0100238 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200239 /* If the client starts to talk, let's fall back to
240 * request timeout processing.
241 */
242 txn->flags &= ~TX_WAIT_NEXT_RQ;
243 req->analyse_exp = TICK_ETERNITY;
244 }
245
246 /* just set the request timeout once at the beginning of the request */
247 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
250 else
251 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
252 }
253
254 /* we're not ready yet */
255 return 0;
256
257 failed_keep_alive:
258 /* Here we process low-level errors for keep-alive requests. In
259 * short, if the request is not the first one and it experiences
260 * a timeout, read error or shutdown, we just silently close so
261 * that the client can try again.
262 */
263 txn->status = 0;
264 msg->msg_state = HTTP_MSG_RQBEFORE;
265 req->analysers &= AN_REQ_FLT_END;
266 s->logs.logwait = 0;
267 s->logs.level = 0;
268 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200269 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200270 return 0;
271 }
272
Christopher Faulet9768c262018-10-22 09:34:31 +0200273 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200274 stream_inc_http_req_ctr(s);
275 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
276
Christopher Faulet9768c262018-10-22 09:34:31 +0200277 /* kill the pending keep-alive timeout */
278 txn->flags &= ~TX_WAIT_NEXT_RQ;
279 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280
Christopher Faulet03599112018-11-27 11:21:21 +0100281 sl = http_find_stline(htx);
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 /* 0: we might have to print this header in debug mode */
284 if (unlikely((global.mode & MODE_DEBUG) &&
285 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
286 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200287
Christopher Faulet03599112018-11-27 11:21:21 +0100288 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200289
290 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
291 struct htx_blk *blk = htx_get_blk(htx, pos);
292 enum htx_blk_type type = htx_get_blk_type(blk);
293
294 if (type == HTX_BLK_EOH)
295 break;
296 if (type != HTX_BLK_HDR)
297 continue;
298
299 htx_debug_hdr("clihdr", s,
300 htx_get_blk_name(htx, blk),
301 htx_get_blk_value(htx, blk));
302 }
303 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200304
305 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100306 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100308 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100309 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200310 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100311 msg->flags |= HTTP_MSGF_XFER_LEN;
312 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100313 if (sl->flags & HTX_SL_F_BODYLESS)
314 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200315
316 /* we can make use of server redirect on GET and HEAD */
317 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
318 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100319 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200320 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200321 goto return_bad_req;
322 }
323
324 /*
325 * 2: check if the URI matches the monitor_uri.
326 * We have to do this for every request which gets in, because
327 * the monitor-uri is defined by the frontend.
328 */
329 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100330 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 /*
332 * We have found the monitor URI
333 */
334 struct acl_cond *cond;
335
336 s->flags |= SF_MONITOR;
337 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
338
339 /* Check if we want to fail this monitor request or not */
340 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
341 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
342
343 ret = acl_pass(ret);
344 if (cond->pol == ACL_COND_UNLESS)
345 ret = !ret;
346
347 if (ret) {
348 /* we fail this request, let's return 503 service unavail */
349 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100350 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200351 if (!(s->flags & SF_ERR_MASK))
352 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
353 goto return_prx_cond;
354 }
355 }
356
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800357 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200358 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100359 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200360 if (!(s->flags & SF_ERR_MASK))
361 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
362 goto return_prx_cond;
363 }
364
365 /*
366 * 3: Maybe we have to copy the original REQURI for the logs ?
367 * Note: we cannot log anymore if the request has been
368 * classified as invalid.
369 */
370 if (unlikely(s->logs.logwait & LW_REQ)) {
371 /* we have a complete HTTP request that we must log */
372 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200373 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200374
Christopher Faulet9768c262018-10-22 09:34:31 +0200375 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
376 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377
378 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
379 s->do_log(s);
380 } else {
381 ha_alert("HTTP logging : out of memory.\n");
382 }
383 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulete0768eb2018-10-03 16:38:02 +0200385 /* if the frontend has "option http-use-proxy-header", we'll check if
386 * we have what looks like a proxied connection instead of a connection,
387 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
388 * Note that this is *not* RFC-compliant, however browsers and proxies
389 * happen to do that despite being non-standard :-(
390 * We consider that a request not beginning with either '/' or '*' is
391 * a proxied connection, which covers both "scheme://location" and
392 * CONNECT ip:port.
393 */
394 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100395 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200396 txn->flags |= TX_USE_PX_CONN;
397
Christopher Faulete0768eb2018-10-03 16:38:02 +0200398 /* 5: we may need to capture headers */
399 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200400 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200401
402 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
403 * only change if both the request and the config reference something else.
404 * Option httpclose by itself sets tunnel mode where headers are mangled.
405 * However, if another mode is set, it will affect it (eg: server-close/
406 * keep-alive + httpclose = close). Note that we avoid to redo the same work
407 * if FE and BE have the same settings (common). The method consists in
408 * checking if options changed between the two calls (implying that either
409 * one is non-null, or one of them is non-null and we are there for the first
410 * time.
411 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200412 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200413 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200414
415 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200416 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417 req->analysers |= AN_REQ_HTTP_BODY;
418
419 /*
420 * RFC7234#4:
421 * A cache MUST write through requests with methods
422 * that are unsafe (Section 4.2.1 of [RFC7231]) to
423 * the origin server; i.e., a cache is not allowed
424 * to generate a reply to such a request before
425 * having forwarded the request and having received
426 * a corresponding response.
427 *
428 * RFC7231#4.2.1:
429 * Of the request methods defined by this
430 * specification, the GET, HEAD, OPTIONS, and TRACE
431 * methods are defined to be safe.
432 */
433 if (likely(txn->meth == HTTP_METH_GET ||
434 txn->meth == HTTP_METH_HEAD ||
435 txn->meth == HTTP_METH_OPTIONS ||
436 txn->meth == HTTP_METH_TRACE))
437 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
438
439 /* end of job, return OK */
440 req->analysers &= ~an_bit;
441 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200442
Christopher Faulete0768eb2018-10-03 16:38:02 +0200443 return 1;
444
445 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200446 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200447 txn->req.err_state = txn->req.msg_state;
448 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100449 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200450 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
451 if (sess->listener->counters)
452 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
453
454 return_prx_cond:
455 if (!(s->flags & SF_ERR_MASK))
456 s->flags |= SF_ERR_PRXCOND;
457 if (!(s->flags & SF_FINST_MASK))
458 s->flags |= SF_FINST_R;
459
460 req->analysers &= AN_REQ_FLT_END;
461 req->analyse_exp = TICK_ETERNITY;
462 return 0;
463}
464
465
466/* This stream analyser runs all HTTP request processing which is common to
467 * frontends and backends, which means blocking ACLs, filters, connection-close,
468 * reqadd, stats and redirects. This is performed for the designated proxy.
469 * It returns 1 if the processing can continue on next analysers, or zero if it
470 * either needs more data or wants to immediately abort the request (eg: deny,
471 * error, ...).
472 */
473int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
474{
475 struct session *sess = s->sess;
476 struct http_txn *txn = s->txn;
477 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200478 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200479 struct redirect_rule *rule;
480 struct cond_wordlist *wl;
481 enum rule_result verdict;
482 int deny_status = HTTP_ERR_403;
483 struct connection *conn = objt_conn(sess->origin);
484
485 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
486 /* we need more data */
487 goto return_prx_yield;
488 }
489
490 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
491 now_ms, __FUNCTION__,
492 s,
493 req,
494 req->rex, req->wex,
495 req->flags,
496 ci_data(req),
497 req->analysers);
498
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100499 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200500
Christopher Faulete0768eb2018-10-03 16:38:02 +0200501 /* just in case we have some per-backend tracking */
502 stream_inc_be_http_req_ctr(s);
503
504 /* evaluate http-request rules */
505 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200506 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200507
508 switch (verdict) {
509 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
510 goto return_prx_yield;
511
512 case HTTP_RULE_RES_CONT:
513 case HTTP_RULE_RES_STOP: /* nothing to do */
514 break;
515
516 case HTTP_RULE_RES_DENY: /* deny or tarpit */
517 if (txn->flags & TX_CLTARPIT)
518 goto tarpit;
519 goto deny;
520
521 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
522 goto return_prx_cond;
523
524 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
525 goto done;
526
527 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
528 goto return_bad_req;
529 }
530 }
531
532 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
533 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200534 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200535
Christopher Fauletff2759f2018-10-24 11:13:16 +0200536 ctx.blk = NULL;
537 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
538 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200539 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200540 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200541 }
542
543 /* OK at this stage, we know that the request was accepted according to
544 * the http-request rules, we can check for the stats. Note that the
545 * URI is detected *before* the req* rules in order not to be affected
546 * by a possible reqrep, while they are processed *after* so that a
547 * reqdeny can still block them. This clearly needs to change in 1.6!
548 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200549 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 s->target = &http_stats_applet.obj_type;
551 if (unlikely(!stream_int_register_handler(&s->si[1], objt_applet(s->target)))) {
552 txn->status = 500;
553 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100554 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555
556 if (!(s->flags & SF_ERR_MASK))
557 s->flags |= SF_ERR_RESOURCE;
558 goto return_prx_cond;
559 }
560
561 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200562 htx_handle_stats(s, req);
563 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200564 /* not all actions implemented: deny, allow, auth */
565
566 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
567 goto deny;
568
569 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
570 goto return_prx_cond;
571 }
572
573 /* evaluate the req* rules except reqadd */
574 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200575 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200576 goto return_bad_req;
577
578 if (txn->flags & TX_CLDENY)
579 goto deny;
580
581 if (txn->flags & TX_CLTARPIT) {
582 deny_status = HTTP_ERR_500;
583 goto tarpit;
584 }
585 }
586
587 /* add request headers from the rule sets in the same order */
588 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200589 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200590 if (wl->cond) {
591 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
592 ret = acl_pass(ret);
593 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
594 ret = !ret;
595 if (!ret)
596 continue;
597 }
598
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
600 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200601 goto return_bad_req;
602 }
603
Christopher Faulete0768eb2018-10-03 16:38:02 +0200604 /* Proceed with the stats now. */
605 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
606 unlikely(objt_applet(s->target) == &http_cache_applet)) {
Christopher Fauletef779222018-10-31 08:47:01 +0100607
608 if (unlikely(objt_applet(s->target) == &http_cache_applet)) {
609 // TODO: Disabled for now, waiting to be adapted for HTX implementation
610 goto deny;
611 }
Christopher Fauletff2759f2018-10-24 11:13:16 +0200612
Christopher Faulete0768eb2018-10-03 16:38:02 +0200613 /* process the stats request now */
614 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
615 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
616
617 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
618 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
619 if (!(s->flags & SF_FINST_MASK))
620 s->flags |= SF_FINST_R;
621
622 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
623 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
624 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
625 req->analysers |= AN_REQ_HTTP_XFER_BODY;
626 goto done;
627 }
628
629 /* check whether we have some ACLs set to redirect this request */
630 list_for_each_entry(rule, &px->redirect_rules, list) {
631 if (rule->cond) {
632 int ret;
633
634 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
635 ret = acl_pass(ret);
636 if (rule->cond->pol == ACL_COND_UNLESS)
637 ret = !ret;
638 if (!ret)
639 continue;
640 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200641 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200642 goto return_bad_req;
643 goto done;
644 }
645
646 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
647 * If this happens, then the data will not come immediately, so we must
648 * send all what we have without waiting. Note that due to the small gain
649 * in waiting for the body of the request, it's easier to simply put the
650 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
651 * itself once used.
652 */
653 req->flags |= CF_SEND_DONTWAIT;
654
655 done: /* done with this analyser, continue with next ones that the calling
656 * points will have set, if any.
657 */
658 req->analyse_exp = TICK_ETERNITY;
659 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
660 req->analysers &= ~an_bit;
661 return 1;
662
663 tarpit:
664 /* Allow cookie logging
665 */
666 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200667 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200668
669 /* When a connection is tarpitted, we use the tarpit timeout,
670 * which may be the same as the connect timeout if unspecified.
671 * If unset, then set it to zero because we really want it to
672 * eventually expire. We build the tarpit as an analyser.
673 */
674 channel_erase(&s->req);
675
676 /* wipe the request out so that we can drop the connection early
677 * if the client closes first.
678 */
679 channel_dont_connect(req);
680
681 txn->status = http_err_codes[deny_status];
682
683 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
684 req->analysers |= AN_REQ_HTTP_TARPIT;
685 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
686 if (!req->analyse_exp)
687 req->analyse_exp = tick_add(now_ms, 0);
688 stream_inc_http_err_ctr(s);
689 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
690 if (sess->fe != s->be)
691 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
692 if (sess->listener->counters)
693 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
694 goto done_without_exp;
695
696 deny: /* this request was blocked (denied) */
697
698 /* Allow cookie logging
699 */
700 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200701 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200702
703 txn->flags |= TX_CLDENY;
704 txn->status = http_err_codes[deny_status];
705 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100706 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200707 stream_inc_http_err_ctr(s);
708 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
709 if (sess->fe != s->be)
710 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
711 if (sess->listener->counters)
712 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
713 goto return_prx_cond;
714
715 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200716 txn->req.err_state = txn->req.msg_state;
717 txn->req.msg_state = HTTP_MSG_ERROR;
718 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100719 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720
721 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
722 if (sess->listener->counters)
723 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
724
725 return_prx_cond:
726 if (!(s->flags & SF_ERR_MASK))
727 s->flags |= SF_ERR_PRXCOND;
728 if (!(s->flags & SF_FINST_MASK))
729 s->flags |= SF_FINST_R;
730
731 req->analysers &= AN_REQ_FLT_END;
732 req->analyse_exp = TICK_ETERNITY;
733 return 0;
734
735 return_prx_yield:
736 channel_dont_connect(req);
737 return 0;
738}
739
740/* This function performs all the processing enabled for the current request.
741 * It returns 1 if the processing can continue on next analysers, or zero if it
742 * needs more data, encounters an error, or wants to immediately abort the
743 * request. It relies on buffers flags, and updates s->req.analysers.
744 */
745int htx_process_request(struct stream *s, struct channel *req, int an_bit)
746{
747 struct session *sess = s->sess;
748 struct http_txn *txn = s->txn;
749 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200750 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200751 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
752
753 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
754 /* we need more data */
755 channel_dont_connect(req);
756 return 0;
757 }
758
759 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
760 now_ms, __FUNCTION__,
761 s,
762 req,
763 req->rex, req->wex,
764 req->flags,
765 ci_data(req),
766 req->analysers);
767
768 /*
769 * Right now, we know that we have processed the entire headers
770 * and that unwanted requests have been filtered out. We can do
771 * whatever we want with the remaining request. Also, now we
772 * may have separate values for ->fe, ->be.
773 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100774 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200775
776 /*
777 * If HTTP PROXY is set we simply get remote server address parsing
778 * incoming request. Note that this requires that a connection is
779 * allocated on the server side.
780 */
781 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
782 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100783 struct htx_sl *sl;
784 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200785
786 /* Note that for now we don't reuse existing proxy connections */
787 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
788 txn->req.err_state = txn->req.msg_state;
789 txn->req.msg_state = HTTP_MSG_ERROR;
790 txn->status = 500;
791 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100792 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200793
794 if (!(s->flags & SF_ERR_MASK))
795 s->flags |= SF_ERR_RESOURCE;
796 if (!(s->flags & SF_FINST_MASK))
797 s->flags |= SF_FINST_R;
798
799 return 0;
800 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200801 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100802 uri = htx_sl_req_uri(sl);
803 path = http_get_path(uri);
804 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200805 goto return_bad_req;
806
807 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200808 * uri.ptr and path.ptr (excluded). If it was not found, we need
809 * to replace from all the uri by a single "/".
810 *
811 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100812 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200813 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200814 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100815 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200816 }
817
818 /*
819 * 7: Now we can work with the cookies.
820 * Note that doing so might move headers in the request, but
821 * the fields will stay coherent and the URI will not move.
822 * This should only be performed in the backend.
823 */
824 if (s->be->cookie_name || sess->fe->capture_name)
825 manage_client_side_cookies(s, req);
826
827 /* add unique-id if "header-unique-id" is specified */
828
829 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
830 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
831 goto return_bad_req;
832 s->unique_id[0] = '\0';
833 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
834 }
835
836 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200837 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
838 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
839
840 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200841 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200842 }
843
844 /*
845 * 9: add X-Forwarded-For if either the frontend or the backend
846 * asks for it.
847 */
848 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200849 struct http_hdr_ctx ctx = { .blk = NULL };
850 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
851 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
852
Christopher Faulete0768eb2018-10-03 16:38:02 +0200853 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200854 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200855 /* The header is set to be added only if none is present
856 * and we found it, so don't do anything.
857 */
858 }
859 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
860 /* Add an X-Forwarded-For header unless the source IP is
861 * in the 'except' network range.
862 */
863 if ((!sess->fe->except_mask.s_addr ||
864 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
865 != sess->fe->except_net.s_addr) &&
866 (!s->be->except_mask.s_addr ||
867 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
868 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200869 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200870
871 /* Note: we rely on the backend to get the header name to be used for
872 * x-forwarded-for, because the header is really meant for the backends.
873 * However, if the backend did not specify any option, we have to rely
874 * on the frontend's header name.
875 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200876 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
877 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200878 goto return_bad_req;
879 }
880 }
881 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
882 /* FIXME: for the sake of completeness, we should also support
883 * 'except' here, although it is mostly useless in this case.
884 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200885 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200886
Christopher Faulete0768eb2018-10-03 16:38:02 +0200887 inet_ntop(AF_INET6,
888 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
889 pn, sizeof(pn));
890
891 /* Note: we rely on the backend to get the header name to be used for
892 * x-forwarded-for, because the header is really meant for the backends.
893 * However, if the backend did not specify any option, we have to rely
894 * on the frontend's header name.
895 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200896 chunk_printf(&trash, "%s", pn);
897 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200898 goto return_bad_req;
899 }
900 }
901
902 /*
903 * 10: add X-Original-To if either the frontend or the backend
904 * asks for it.
905 */
906 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
907
908 /* FIXME: don't know if IPv6 can handle that case too. */
909 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
910 /* Add an X-Original-To header unless the destination IP is
911 * in the 'except' network range.
912 */
913 conn_get_to_addr(cli_conn);
914
915 if (cli_conn->addr.to.ss_family == AF_INET &&
916 ((!sess->fe->except_mask_to.s_addr ||
917 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
918 != sess->fe->except_to.s_addr) &&
919 (!s->be->except_mask_to.s_addr ||
920 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
921 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200922 struct ist hdr;
923 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200924
925 /* Note: we rely on the backend to get the header name to be used for
926 * x-original-to, because the header is really meant for the backends.
927 * However, if the backend did not specify any option, we have to rely
928 * on the frontend's header name.
929 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200930 if (s->be->orgto_hdr_len)
931 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
932 else
933 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200935 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
936 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200937 goto return_bad_req;
938 }
939 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200940 }
941
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 /* If we have no server assigned yet and we're balancing on url_param
943 * with a POST request, we may be interested in checking the body for
944 * that parameter. This will be done in another analyser.
945 */
946 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200947 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200948 channel_dont_connect(req);
949 req->analysers |= AN_REQ_HTTP_BODY;
950 }
951
952 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
953 req->analysers |= AN_REQ_HTTP_XFER_BODY;
954#ifdef TCP_QUICKACK
955 /* We expect some data from the client. Unless we know for sure
956 * we already have a full request, we have to re-enable quick-ack
957 * in case we previously disabled it, otherwise we might cause
958 * the client to delay further data.
959 */
960 if ((sess->listener->options & LI_O_NOQUICKACK) &&
961 cli_conn && conn_ctrl_ready(cli_conn) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200962 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200963 setsockopt(cli_conn->handle.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
964#endif
965
966 /*************************************************************
967 * OK, that's finished for the headers. We have done what we *
968 * could. Let's switch to the DATA state. *
969 ************************************************************/
970 req->analyse_exp = TICK_ETERNITY;
971 req->analysers &= ~an_bit;
972
973 s->logs.tv_request = now;
974 /* OK let's go on with the BODY now */
975 return 1;
976
977 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200978 txn->req.err_state = txn->req.msg_state;
979 txn->req.msg_state = HTTP_MSG_ERROR;
980 txn->status = 400;
981 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100982 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200983
984 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
985 if (sess->listener->counters)
986 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
987
988 if (!(s->flags & SF_ERR_MASK))
989 s->flags |= SF_ERR_PRXCOND;
990 if (!(s->flags & SF_FINST_MASK))
991 s->flags |= SF_FINST_R;
992 return 0;
993}
994
995/* This function is an analyser which processes the HTTP tarpit. It always
996 * returns zero, at the beginning because it prevents any other processing
997 * from occurring, and at the end because it terminates the request.
998 */
999int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1000{
1001 struct http_txn *txn = s->txn;
1002
1003 /* This connection is being tarpitted. The CLIENT side has
1004 * already set the connect expiration date to the right
1005 * timeout. We just have to check that the client is still
1006 * there and that the timeout has not expired.
1007 */
1008 channel_dont_connect(req);
1009 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1010 !tick_is_expired(req->analyse_exp, now_ms))
1011 return 0;
1012
1013 /* We will set the queue timer to the time spent, just for
1014 * logging purposes. We fake a 500 server error, so that the
1015 * attacker will not suspect his connection has been tarpitted.
1016 * It will not cause trouble to the logs because we can exclude
1017 * the tarpitted connections by filtering on the 'PT' status flags.
1018 */
1019 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1020
1021 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001022 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001023
1024 req->analysers &= AN_REQ_FLT_END;
1025 req->analyse_exp = TICK_ETERNITY;
1026
1027 if (!(s->flags & SF_ERR_MASK))
1028 s->flags |= SF_ERR_PRXCOND;
1029 if (!(s->flags & SF_FINST_MASK))
1030 s->flags |= SF_FINST_T;
1031 return 0;
1032}
1033
1034/* This function is an analyser which waits for the HTTP request body. It waits
1035 * for either the buffer to be full, or the full advertised contents to have
1036 * reached the buffer. It must only be called after the standard HTTP request
1037 * processing has occurred, because it expects the request to be parsed and will
1038 * look for the Expect header. It may send a 100-Continue interim response. It
1039 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1040 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1041 * needs to read more data, or 1 once it has completed its analysis.
1042 */
1043int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1044{
1045 struct session *sess = s->sess;
1046 struct http_txn *txn = s->txn;
1047 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001048 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001049
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001050
1051 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1052 now_ms, __FUNCTION__,
1053 s,
1054 req,
1055 req->rex, req->wex,
1056 req->flags,
1057 ci_data(req),
1058 req->analysers);
1059
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001060 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001061
1062 if (msg->msg_state < HTTP_MSG_BODY)
1063 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001064
Christopher Faulete0768eb2018-10-03 16:38:02 +02001065 /* We have to parse the HTTP request body to find any required data.
1066 * "balance url_param check_post" should have been the only way to get
1067 * into this. We were brought here after HTTP header analysis, so all
1068 * related structures are ready.
1069 */
1070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 if (msg->msg_state < HTTP_MSG_DATA) {
1072 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1073 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001075 if (msg->flags & HTTP_MSGF_VER_11) {
1076 struct ist hdr = { .ptr = "Expect", .len = 6 };
1077 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001078
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001079 ctx.blk = NULL;
1080 /* Expect is allowed in 1.1, look for it */
1081 if (http_find_header(htx, hdr, &ctx, 0) &&
1082 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001083 if (htx_reply_100_continue(s) == -1)
1084 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 http_remove_header(htx, &ctx);
1086 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001088 }
1089
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001090 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001091
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001092 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1093 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001094 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1096 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001097 goto http_end;
1098
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001099 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001100 if (htx->flags & HTX_FL_PARSING_ERROR)
1101 goto return_bad_req;
1102
Christopher Faulete0768eb2018-10-03 16:38:02 +02001103 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1104 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001105 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001106
1107 if (!(s->flags & SF_ERR_MASK))
1108 s->flags |= SF_ERR_CLITO;
1109 if (!(s->flags & SF_FINST_MASK))
1110 s->flags |= SF_FINST_D;
1111 goto return_err_msg;
1112 }
1113
1114 /* we get here if we need to wait for more data */
1115 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1116 /* Not enough data. We'll re-use the http-request
1117 * timeout here. Ideally, we should set the timeout
1118 * relative to the accept() date. We just set the
1119 * request timeout once at the beginning of the
1120 * request.
1121 */
1122 channel_dont_connect(req);
1123 if (!tick_isset(req->analyse_exp))
1124 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1125 return 0;
1126 }
1127
1128 http_end:
1129 /* The situation will not evolve, so let's give up on the analysis. */
1130 s->logs.tv_request = now; /* update the request timer to reflect full request */
1131 req->analysers &= ~an_bit;
1132 req->analyse_exp = TICK_ETERNITY;
1133 return 1;
1134
1135 return_bad_req: /* let's centralize all bad requests */
1136 txn->req.err_state = txn->req.msg_state;
1137 txn->req.msg_state = HTTP_MSG_ERROR;
1138 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001139 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001140
1141 if (!(s->flags & SF_ERR_MASK))
1142 s->flags |= SF_ERR_PRXCOND;
1143 if (!(s->flags & SF_FINST_MASK))
1144 s->flags |= SF_FINST_R;
1145
1146 return_err_msg:
1147 req->analysers &= AN_REQ_FLT_END;
1148 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1149 if (sess->listener->counters)
1150 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1151 return 0;
1152}
1153
1154/* This function is an analyser which forwards request body (including chunk
1155 * sizes if any). It is called as soon as we must forward, even if we forward
1156 * zero byte. The only situation where it must not be called is when we're in
1157 * tunnel mode and we want to forward till the close. It's used both to forward
1158 * remaining data and to resync after end of body. It expects the msg_state to
1159 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1160 * read more data, or 1 once we can go on with next request or end the stream.
1161 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1162 * bytes of pending data + the headers if not already done.
1163 */
1164int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1165{
1166 struct session *sess = s->sess;
1167 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001168 struct http_msg *msg = &txn->req;
1169 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001170 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001171
1172 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1173 now_ms, __FUNCTION__,
1174 s,
1175 req,
1176 req->rex, req->wex,
1177 req->flags,
1178 ci_data(req),
1179 req->analysers);
1180
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001181 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001182
1183 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1184 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1185 /* Output closed while we were sending data. We must abort and
1186 * wake the other side up.
1187 */
1188 msg->err_state = msg->msg_state;
1189 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001190 htx_end_request(s);
1191 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001192 return 1;
1193 }
1194
1195 /* Note that we don't have to send 100-continue back because we don't
1196 * need the data to complete our job, and it's up to the server to
1197 * decide whether to return 100, 417 or anything else in return of
1198 * an "Expect: 100-continue" header.
1199 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001200 if (msg->msg_state == HTTP_MSG_BODY)
1201 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001202
1203 /* Some post-connect processing might want us to refrain from starting to
1204 * forward data. Currently, the only reason for this is "balance url_param"
1205 * whichs need to parse/process the request after we've enabled forwarding.
1206 */
1207 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1208 if (!(s->res.flags & CF_READ_ATTACHED)) {
1209 channel_auto_connect(req);
1210 req->flags |= CF_WAKE_CONNECT;
1211 channel_dont_close(req); /* don't fail on early shutr */
1212 goto waiting;
1213 }
1214 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1215 }
1216
1217 /* in most states, we should abort in case of early close */
1218 channel_auto_close(req);
1219
1220 if (req->to_forward) {
1221 /* We can't process the buffer's contents yet */
1222 req->flags |= CF_WAKE_WRITE;
1223 goto missing_data_or_waiting;
1224 }
1225
Christopher Faulet9768c262018-10-22 09:34:31 +02001226 if (msg->msg_state >= HTTP_MSG_DONE)
1227 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 /* Forward input data. We get it by removing all outgoing data not
1229 * forwarded yet from HTX data size. If there are some data filters, we
1230 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001231 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001232 if (HAS_REQ_DATA_FILTERS(s)) {
1233 ret = flt_http_payload(s, msg, htx->data);
1234 if (ret < 0)
1235 goto return_bad_req;
1236 c_adv(req, ret);
1237 if (htx->data != co_data(req) || htx->extra)
1238 goto missing_data_or_waiting;
1239 }
1240 else {
1241 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001242
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001243 /* To let the function channel_forward work as expected we must update
1244 * the channel's buffer to pretend there is no more input data. The
1245 * right length is then restored. We must do that, because when an HTX
1246 * message is stored into a buffer, it appears as full.
1247 */
1248 b_set_data(&req->buf, co_data(req));
1249 if (msg->flags & HTTP_MSGF_XFER_LEN)
1250 htx->extra -= channel_forward(req, htx->extra);
1251 b_set_data(&req->buf, b_size(&req->buf));
1252 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001253
Christopher Faulet9768c262018-10-22 09:34:31 +02001254 /* Check if the end-of-message is reached and if so, switch the message
1255 * in HTTP_MSG_DONE state.
1256 */
1257 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1258 goto missing_data_or_waiting;
1259
1260 msg->msg_state = HTTP_MSG_DONE;
1261
1262 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001263 /* other states, DONE...TUNNEL */
1264 /* we don't want to forward closes on DONE except in tunnel mode. */
1265 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1266 channel_dont_close(req);
1267
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001268 if (HAS_REQ_DATA_FILTERS(s)) {
1269 ret = flt_http_end(s, msg);
1270 if (ret <= 0) {
1271 if (!ret)
1272 goto missing_data_or_waiting;
1273 goto return_bad_req;
1274 }
1275 }
1276
Christopher Fauletf2824e62018-10-01 12:12:37 +02001277 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001278 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001279 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1281 if (req->flags & CF_SHUTW) {
1282 /* request errors are most likely due to the
1283 * server aborting the transfer. */
1284 goto aborted_xfer;
1285 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001286 goto return_bad_req;
1287 }
1288 return 1;
1289 }
1290
1291 /* If "option abortonclose" is set on the backend, we want to monitor
1292 * the client's connection and forward any shutdown notification to the
1293 * server, which will decide whether to close or to go on processing the
1294 * request. We only do that in tunnel mode, and not in other modes since
1295 * it can be abused to exhaust source ports. */
1296 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1297 channel_auto_read(req);
1298 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1299 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1300 s->si[1].flags |= SI_FL_NOLINGER;
1301 channel_auto_close(req);
1302 }
1303 else if (s->txn->meth == HTTP_METH_POST) {
1304 /* POST requests may require to read extra CRLF sent by broken
1305 * browsers and which could cause an RST to be sent upon close
1306 * on some systems (eg: Linux). */
1307 channel_auto_read(req);
1308 }
1309 return 0;
1310
1311 missing_data_or_waiting:
1312 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001313 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001314 if (!(s->flags & SF_ERR_MASK))
1315 s->flags |= SF_ERR_CLICL;
1316 if (!(s->flags & SF_FINST_MASK)) {
1317 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1318 s->flags |= SF_FINST_H;
1319 else
1320 s->flags |= SF_FINST_D;
1321 }
1322
1323 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1324 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1325 if (objt_server(s->target))
1326 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1327
1328 goto return_bad_req_stats_ok;
1329 }
1330
1331 waiting:
1332 /* waiting for the last bits to leave the buffer */
1333 if (req->flags & CF_SHUTW)
1334 goto aborted_xfer;
1335
Christopher Faulet47365272018-10-31 17:40:50 +01001336 if (htx->flags & HTX_FL_PARSING_ERROR)
1337 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001338
Christopher Faulete0768eb2018-10-03 16:38:02 +02001339 /* When TE: chunked is used, we need to get there again to parse remaining
1340 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1341 * And when content-length is used, we never want to let the possible
1342 * shutdown be forwarded to the other side, as the state machine will
1343 * take care of it once the client responds. It's also important to
1344 * prevent TIME_WAITs from accumulating on the backend side, and for
1345 * HTTP/2 where the last frame comes with a shutdown.
1346 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001347 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001348 channel_dont_close(req);
1349
1350 /* We know that more data are expected, but we couldn't send more that
1351 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1352 * system knows it must not set a PUSH on this first part. Interactive
1353 * modes are already handled by the stream sock layer. We must not do
1354 * this in content-length mode because it could present the MSG_MORE
1355 * flag with the last block of forwarded data, which would cause an
1356 * additional delay to be observed by the receiver.
1357 */
1358 if (msg->flags & HTTP_MSGF_TE_CHNK)
1359 req->flags |= CF_EXPECT_MORE;
1360
1361 return 0;
1362
1363 return_bad_req: /* let's centralize all bad requests */
1364 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1365 if (sess->listener->counters)
1366 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1367
1368 return_bad_req_stats_ok:
1369 txn->req.err_state = txn->req.msg_state;
1370 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001371 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001373 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 } else {
1375 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001376 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377 }
1378 req->analysers &= AN_REQ_FLT_END;
1379 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1380
1381 if (!(s->flags & SF_ERR_MASK))
1382 s->flags |= SF_ERR_PRXCOND;
1383 if (!(s->flags & SF_FINST_MASK)) {
1384 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1385 s->flags |= SF_FINST_H;
1386 else
1387 s->flags |= SF_FINST_D;
1388 }
1389 return 0;
1390
1391 aborted_xfer:
1392 txn->req.err_state = txn->req.msg_state;
1393 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001394 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001395 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001396 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001397 } else {
1398 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001399 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001400 }
1401 req->analysers &= AN_REQ_FLT_END;
1402 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1403
1404 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1405 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1406 if (objt_server(s->target))
1407 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1408
1409 if (!(s->flags & SF_ERR_MASK))
1410 s->flags |= SF_ERR_SRVCL;
1411 if (!(s->flags & SF_FINST_MASK)) {
1412 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1413 s->flags |= SF_FINST_H;
1414 else
1415 s->flags |= SF_FINST_D;
1416 }
1417 return 0;
1418}
1419
1420/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1421 * processing can continue on next analysers, or zero if it either needs more
1422 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1423 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1424 * when it has nothing left to do, and may remove any analyser when it wants to
1425 * abort.
1426 */
1427int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1428{
Christopher Faulet9768c262018-10-22 09:34:31 +02001429 /*
1430 * We will analyze a complete HTTP response to check the its syntax.
1431 *
1432 * Once the start line and all headers are received, we may perform a
1433 * capture of the error (if any), and we will set a few fields. We also
1434 * logging and finally headers capture.
1435 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001436 struct session *sess = s->sess;
1437 struct http_txn *txn = s->txn;
1438 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001439 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001440 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001441 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001442 int n;
1443
1444 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1445 now_ms, __FUNCTION__,
1446 s,
1447 rep,
1448 rep->rex, rep->wex,
1449 rep->flags,
1450 ci_data(rep),
1451 rep->analysers);
1452
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001453 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001454
1455 /*
1456 * Now we quickly check if we have found a full valid response.
1457 * If not so, we check the FD and buffer states before leaving.
1458 * A full response is indicated by the fact that we have seen
1459 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1460 * responses are checked first.
1461 *
1462 * Depending on whether the client is still there or not, we
1463 * may send an error response back or not. Note that normally
1464 * we should only check for HTTP status there, and check I/O
1465 * errors somewhere else.
1466 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001467 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001468 /*
1469 * First catch invalid response
1470 */
1471 if (htx->flags & HTX_FL_PARSING_ERROR)
1472 goto return_bad_res;
1473
Christopher Faulet9768c262018-10-22 09:34:31 +02001474 /* 1: have we encountered a read error ? */
1475 if (rep->flags & CF_READ_ERROR) {
1476 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001477 goto abort_keep_alive;
1478
1479 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1480 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001481 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1482 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483 }
1484
Christopher Faulete0768eb2018-10-03 16:38:02 +02001485 rep->analysers &= AN_RES_FLT_END;
1486 txn->status = 502;
1487
1488 /* Check to see if the server refused the early data.
1489 * If so, just send a 425
1490 */
1491 if (objt_cs(s->si[1].end)) {
1492 struct connection *conn = objt_cs(s->si[1].end)->conn;
1493
1494 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1495 txn->status = 425;
1496 }
1497
1498 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001499 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500
1501 if (!(s->flags & SF_ERR_MASK))
1502 s->flags |= SF_ERR_SRVCL;
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 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1511 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001512 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1513 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001514 }
1515
Christopher Faulete0768eb2018-10-03 16:38:02 +02001516 rep->analysers &= AN_RES_FLT_END;
1517 txn->status = 504;
1518 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001519 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520
1521 if (!(s->flags & SF_ERR_MASK))
1522 s->flags |= SF_ERR_SRVTO;
1523 if (!(s->flags & SF_FINST_MASK))
1524 s->flags |= SF_FINST_H;
1525 return 0;
1526 }
1527
Christopher Faulet9768c262018-10-22 09:34:31 +02001528 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1530 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1531 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1532 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001533 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534
1535 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001536 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001537 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001538
1539 if (!(s->flags & SF_ERR_MASK))
1540 s->flags |= SF_ERR_CLICL;
1541 if (!(s->flags & SF_FINST_MASK))
1542 s->flags |= SF_FINST_H;
1543
1544 /* process_stream() will take care of the error */
1545 return 0;
1546 }
1547
Christopher Faulet9768c262018-10-22 09:34:31 +02001548 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001550 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001551 goto abort_keep_alive;
1552
1553 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1554 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001555 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1556 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 }
1558
Christopher Faulete0768eb2018-10-03 16:38:02 +02001559 rep->analysers &= AN_RES_FLT_END;
1560 txn->status = 502;
1561 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001562 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563
1564 if (!(s->flags & SF_ERR_MASK))
1565 s->flags |= SF_ERR_SRVCL;
1566 if (!(s->flags & SF_FINST_MASK))
1567 s->flags |= SF_FINST_H;
1568 return 0;
1569 }
1570
Christopher Faulet9768c262018-10-22 09:34:31 +02001571 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001572 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001573 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001574 goto abort_keep_alive;
1575
1576 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1577 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001578
1579 if (!(s->flags & SF_ERR_MASK))
1580 s->flags |= SF_ERR_CLICL;
1581 if (!(s->flags & SF_FINST_MASK))
1582 s->flags |= SF_FINST_H;
1583
1584 /* process_stream() will take care of the error */
1585 return 0;
1586 }
1587
1588 channel_dont_close(rep);
1589 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1590 return 0;
1591 }
1592
1593 /* More interesting part now : we know that we have a complete
1594 * response which at least looks like HTTP. We have an indicator
1595 * of each header's length, so we can parse them quickly.
1596 */
1597
Christopher Faulet9768c262018-10-22 09:34:31 +02001598 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001599 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001600
Christopher Faulet9768c262018-10-22 09:34:31 +02001601 /* 0: we might have to print this header in debug mode */
1602 if (unlikely((global.mode & MODE_DEBUG) &&
1603 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1604 int32_t pos;
1605
Christopher Faulet03599112018-11-27 11:21:21 +01001606 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001607
1608 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1609 struct htx_blk *blk = htx_get_blk(htx, pos);
1610 enum htx_blk_type type = htx_get_blk_type(blk);
1611
1612 if (type == HTX_BLK_EOH)
1613 break;
1614 if (type != HTX_BLK_HDR)
1615 continue;
1616
1617 htx_debug_hdr("srvhdr", s,
1618 htx_get_blk_name(htx, blk),
1619 htx_get_blk_value(htx, blk));
1620 }
1621 }
1622
Christopher Faulet03599112018-11-27 11:21:21 +01001623 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001624 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001625 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001626 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001627 if (sl->flags & HTX_SL_F_XFER_LEN) {
1628 msg->flags |= HTTP_MSGF_XFER_LEN;
1629 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001630 if (sl->flags & HTX_SL_F_BODYLESS)
1631 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001632 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001633
1634 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001635 if (n < 1 || n > 5)
1636 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001637
Christopher Faulete0768eb2018-10-03 16:38:02 +02001638 /* when the client triggers a 4xx from the server, it's most often due
1639 * to a missing object or permission. These events should be tracked
1640 * because if they happen often, it may indicate a brute force or a
1641 * vulnerability scan.
1642 */
1643 if (n == 4)
1644 stream_inc_http_err_ctr(s);
1645
1646 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001647 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648
Christopher Faulete0768eb2018-10-03 16:38:02 +02001649 /* Adjust server's health based on status code. Note: status codes 501
1650 * and 505 are triggered on demand by client request, so we must not
1651 * count them as server failures.
1652 */
1653 if (objt_server(s->target)) {
1654 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001655 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001656 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001657 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001658 }
1659
1660 /*
1661 * We may be facing a 100-continue response, or any other informational
1662 * 1xx response which is non-final, in which case this is not the right
1663 * response, and we're waiting for the next one. Let's allow this response
1664 * to go to the client and wait for the next one. There's an exception for
1665 * 101 which is used later in the code to switch protocols.
1666 */
1667 if (txn->status < 200 &&
1668 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001669 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001670 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001671 msg->msg_state = HTTP_MSG_RPBEFORE;
1672 txn->status = 0;
1673 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001674 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001675 }
1676
1677 /*
1678 * 2: check for cacheability.
1679 */
1680
1681 switch (txn->status) {
1682 case 200:
1683 case 203:
1684 case 204:
1685 case 206:
1686 case 300:
1687 case 301:
1688 case 404:
1689 case 405:
1690 case 410:
1691 case 414:
1692 case 501:
1693 break;
1694 default:
1695 /* RFC7231#6.1:
1696 * Responses with status codes that are defined as
1697 * cacheable by default (e.g., 200, 203, 204, 206,
1698 * 300, 301, 404, 405, 410, 414, and 501 in this
1699 * specification) can be reused by a cache with
1700 * heuristic expiration unless otherwise indicated
1701 * by the method definition or explicit cache
1702 * controls [RFC7234]; all other status codes are
1703 * not cacheable by default.
1704 */
1705 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1706 break;
1707 }
1708
1709 /*
1710 * 3: we may need to capture headers
1711 */
1712 s->logs.logwait &= ~LW_RESP;
1713 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001714 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001715
Christopher Faulet9768c262018-10-22 09:34:31 +02001716 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001717 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1718 txn->status == 101)) {
1719 /* Either we've established an explicit tunnel, or we're
1720 * switching the protocol. In both cases, we're very unlikely
1721 * to understand the next protocols. We have to switch to tunnel
1722 * mode, so that we transfer the request and responses then let
1723 * this protocol pass unmodified. When we later implement specific
1724 * parsers for such protocols, we'll want to check the Upgrade
1725 * header which contains information about that protocol for
1726 * responses with status 101 (eg: see RFC2817 about TLS).
1727 */
1728 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001729 }
1730
Christopher Faulet61608322018-11-23 16:23:45 +01001731 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1732 * 407 (Proxy-Authenticate) responses and set the connection to private
1733 */
1734 srv_conn = cs_conn(objt_cs(s->si[1].end));
1735 if (srv_conn) {
1736 struct ist hdr;
1737 struct http_hdr_ctx ctx;
1738
1739 if (txn->status == 401)
1740 hdr = ist("WWW-Authenticate");
1741 else if (txn->status == 407)
1742 hdr = ist("Proxy-Authenticate");
1743 else
1744 goto end;
1745
1746 ctx.blk = NULL;
1747 while (http_find_header(htx, hdr, &ctx, 0)) {
1748 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1749 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1750 srv_conn->flags |= CO_FL_PRIVATE;
1751 }
1752 }
1753
1754 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001755 /* we want to have the response time before we start processing it */
1756 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1757
1758 /* end of job, return OK */
1759 rep->analysers &= ~an_bit;
1760 rep->analyse_exp = TICK_ETERNITY;
1761 channel_auto_close(rep);
1762 return 1;
1763
Christopher Faulet47365272018-10-31 17:40:50 +01001764 return_bad_res:
1765 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1766 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001767 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1768 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001769 }
1770 txn->status = 502;
1771 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001772 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001773 rep->analysers &= AN_RES_FLT_END;
1774
1775 if (!(s->flags & SF_ERR_MASK))
1776 s->flags |= SF_ERR_PRXCOND;
1777 if (!(s->flags & SF_FINST_MASK))
1778 s->flags |= SF_FINST_H;
1779 return 0;
1780
Christopher Faulete0768eb2018-10-03 16:38:02 +02001781 abort_keep_alive:
1782 /* A keep-alive request to the server failed on a network error.
1783 * The client is required to retry. We need to close without returning
1784 * any other information so that the client retries.
1785 */
1786 txn->status = 0;
1787 rep->analysers &= AN_RES_FLT_END;
1788 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001789 s->logs.logwait = 0;
1790 s->logs.level = 0;
1791 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001792 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001793 return 0;
1794}
1795
1796/* This function performs all the processing enabled for the current response.
1797 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1798 * and updates s->res.analysers. It might make sense to explode it into several
1799 * other functions. It works like process_request (see indications above).
1800 */
1801int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1802{
1803 struct session *sess = s->sess;
1804 struct http_txn *txn = s->txn;
1805 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001806 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001807 struct proxy *cur_proxy;
1808 struct cond_wordlist *wl;
1809 enum rule_result ret = HTTP_RULE_RES_CONT;
1810
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001811 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1812 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001813
Christopher Faulete0768eb2018-10-03 16:38:02 +02001814 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1815 now_ms, __FUNCTION__,
1816 s,
1817 rep,
1818 rep->rex, rep->wex,
1819 rep->flags,
1820 ci_data(rep),
1821 rep->analysers);
1822
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001823 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001824
1825 /* The stats applet needs to adjust the Connection header but we don't
1826 * apply any filter there.
1827 */
1828 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1829 rep->analysers &= ~an_bit;
1830 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001831 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001832 }
1833
1834 /*
1835 * We will have to evaluate the filters.
1836 * As opposed to version 1.2, now they will be evaluated in the
1837 * filters order and not in the header order. This means that
1838 * each filter has to be validated among all headers.
1839 *
1840 * Filters are tried with ->be first, then with ->fe if it is
1841 * different from ->be.
1842 *
1843 * Maybe we are in resume condiion. In this case I choose the
1844 * "struct proxy" which contains the rule list matching the resume
1845 * pointer. If none of theses "struct proxy" match, I initialise
1846 * the process with the first one.
1847 *
1848 * In fact, I check only correspondance betwwen the current list
1849 * pointer and the ->fe rule list. If it doesn't match, I initialize
1850 * the loop with the ->be.
1851 */
1852 if (s->current_rule_list == &sess->fe->http_res_rules)
1853 cur_proxy = sess->fe;
1854 else
1855 cur_proxy = s->be;
1856 while (1) {
1857 struct proxy *rule_set = cur_proxy;
1858
1859 /* evaluate http-response rules */
1860 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001861 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001862
1863 if (ret == HTTP_RULE_RES_BADREQ)
1864 goto return_srv_prx_502;
1865
1866 if (ret == HTTP_RULE_RES_DONE) {
1867 rep->analysers &= ~an_bit;
1868 rep->analyse_exp = TICK_ETERNITY;
1869 return 1;
1870 }
1871 }
1872
1873 /* we need to be called again. */
1874 if (ret == HTTP_RULE_RES_YIELD) {
1875 channel_dont_close(rep);
1876 return 0;
1877 }
1878
1879 /* try headers filters */
1880 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001881 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1882 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001883 }
1884
1885 /* has the response been denied ? */
1886 if (txn->flags & TX_SVDENY) {
1887 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001888 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001889
1890 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1891 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1892 if (sess->listener->counters)
1893 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001894 goto return_srv_prx_502;
1895 }
1896
1897 /* add response headers from the rule sets in the same order */
1898 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001899 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001900 if (txn->status < 200 && txn->status != 101)
1901 break;
1902 if (wl->cond) {
1903 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1904 ret = acl_pass(ret);
1905 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1906 ret = !ret;
1907 if (!ret)
1908 continue;
1909 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001910
1911 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1912 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001913 goto return_bad_resp;
1914 }
1915
1916 /* check whether we're already working on the frontend */
1917 if (cur_proxy == sess->fe)
1918 break;
1919 cur_proxy = sess->fe;
1920 }
1921
1922 /* After this point, this anayzer can't return yield, so we can
1923 * remove the bit corresponding to this analyzer from the list.
1924 *
1925 * Note that the intermediate returns and goto found previously
1926 * reset the analyzers.
1927 */
1928 rep->analysers &= ~an_bit;
1929 rep->analyse_exp = TICK_ETERNITY;
1930
1931 /* OK that's all we can do for 1xx responses */
1932 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001933 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001934
1935 /*
1936 * Now check for a server cookie.
1937 */
1938 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001939 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001940
1941 /*
1942 * Check for cache-control or pragma headers if required.
1943 */
1944 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1945 check_response_for_cacheability(s, rep);
1946
1947 /*
1948 * Add server cookie in the response if needed
1949 */
1950 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1951 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1952 (!(s->flags & SF_DIRECT) ||
1953 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1954 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1955 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1956 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1957 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1958 !(s->flags & SF_IGNORE_PRST)) {
1959 /* the server is known, it's not the one the client requested, or the
1960 * cookie's last seen date needs to be refreshed. We have to
1961 * insert a set-cookie here, except if we want to insert only on POST
1962 * requests and this one isn't. Note that servers which don't have cookies
1963 * (eg: some backup servers) will return a full cookie removal request.
1964 */
1965 if (!objt_server(s->target)->cookie) {
1966 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001967 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001968 s->be->cookie_name);
1969 }
1970 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001971 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001972
1973 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1974 /* emit last_date, which is mandatory */
1975 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1976 s30tob64((date.tv_sec+3) >> 2,
1977 trash.area + trash.data);
1978 trash.data += 5;
1979
1980 if (s->be->cookie_maxlife) {
1981 /* emit first_date, which is either the original one or
1982 * the current date.
1983 */
1984 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1985 s30tob64(txn->cookie_first_date ?
1986 txn->cookie_first_date >> 2 :
1987 (date.tv_sec+3) >> 2,
1988 trash.area + trash.data);
1989 trash.data += 5;
1990 }
1991 }
1992 chunk_appendf(&trash, "; path=/");
1993 }
1994
1995 if (s->be->cookie_domain)
1996 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1997
1998 if (s->be->ck_opts & PR_CK_HTTPONLY)
1999 chunk_appendf(&trash, "; HttpOnly");
2000
2001 if (s->be->ck_opts & PR_CK_SECURE)
2002 chunk_appendf(&trash, "; Secure");
2003
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002004 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002005 goto return_bad_resp;
2006
2007 txn->flags &= ~TX_SCK_MASK;
2008 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2009 /* the server did not change, only the date was updated */
2010 txn->flags |= TX_SCK_UPDATED;
2011 else
2012 txn->flags |= TX_SCK_INSERTED;
2013
2014 /* Here, we will tell an eventual cache on the client side that we don't
2015 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2016 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2017 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2018 */
2019 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2020
2021 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2022
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002023 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002024 goto return_bad_resp;
2025 }
2026 }
2027
2028 /*
2029 * Check if result will be cacheable with a cookie.
2030 * We'll block the response if security checks have caught
2031 * nasty things such as a cacheable cookie.
2032 */
2033 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2034 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2035 (s->be->options & PR_O_CHK_CACHE)) {
2036 /* we're in presence of a cacheable response containing
2037 * a set-cookie header. We'll block it as requested by
2038 * the 'checkcache' option, and send an alert.
2039 */
2040 if (objt_server(s->target))
2041 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2042
2043 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2044 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2045 if (sess->listener->counters)
2046 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2047
2048 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2049 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2050 send_log(s->be, LOG_ALERT,
2051 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2052 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2053 goto return_srv_prx_502;
2054 }
2055
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002056 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002057 /* Always enter in the body analyzer */
2058 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2059 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2060
2061 /* if the user wants to log as soon as possible, without counting
2062 * bytes from the server, then this is the right moment. We have
2063 * to temporarily assign bytes_out to log what we currently have.
2064 */
2065 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2066 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002067 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002068 s->do_log(s);
2069 s->logs.bytes_out = 0;
2070 }
2071 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002072
2073 return_bad_resp:
2074 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002075 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2076 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002077 }
2078 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2079
2080 return_srv_prx_502:
2081 rep->analysers &= AN_RES_FLT_END;
2082 txn->status = 502;
2083 s->logs.t_data = -1; /* was not a valid response */
2084 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002085 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002086 if (!(s->flags & SF_ERR_MASK))
2087 s->flags |= SF_ERR_PRXCOND;
2088 if (!(s->flags & SF_FINST_MASK))
2089 s->flags |= SF_FINST_H;
2090 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002091}
2092
2093/* This function is an analyser which forwards response body (including chunk
2094 * sizes if any). It is called as soon as we must forward, even if we forward
2095 * zero byte. The only situation where it must not be called is when we're in
2096 * tunnel mode and we want to forward till the close. It's used both to forward
2097 * remaining data and to resync after end of body. It expects the msg_state to
2098 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2099 * read more data, or 1 once we can go on with next request or end the stream.
2100 *
2101 * It is capable of compressing response data both in content-length mode and
2102 * in chunked mode. The state machines follows different flows depending on
2103 * whether content-length and chunked modes are used, since there are no
2104 * trailers in content-length :
2105 *
2106 * chk-mode cl-mode
2107 * ,----- BODY -----.
2108 * / \
2109 * V size > 0 V chk-mode
2110 * .--> SIZE -------------> DATA -------------> CRLF
2111 * | | size == 0 | last byte |
2112 * | v final crlf v inspected |
2113 * | TRAILERS -----------> DONE |
2114 * | |
2115 * `----------------------------------------------'
2116 *
2117 * Compression only happens in the DATA state, and must be flushed in final
2118 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2119 * is performed at once on final states for all bytes parsed, or when leaving
2120 * on missing data.
2121 */
2122int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2123{
2124 struct session *sess = s->sess;
2125 struct http_txn *txn = s->txn;
2126 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002127 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002128 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002129
2130 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2131 now_ms, __FUNCTION__,
2132 s,
2133 res,
2134 res->rex, res->wex,
2135 res->flags,
2136 ci_data(res),
2137 res->analysers);
2138
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002139 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002140
2141 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002142 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002143 /* Output closed while we were sending data. We must abort and
2144 * wake the other side up.
2145 */
2146 msg->err_state = msg->msg_state;
2147 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002148 htx_end_response(s);
2149 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002150 return 1;
2151 }
2152
Christopher Faulet9768c262018-10-22 09:34:31 +02002153 if (msg->msg_state == HTTP_MSG_BODY)
2154 msg->msg_state = HTTP_MSG_DATA;
2155
Christopher Faulete0768eb2018-10-03 16:38:02 +02002156 /* in most states, we should abort in case of early close */
2157 channel_auto_close(res);
2158
Christopher Faulete0768eb2018-10-03 16:38:02 +02002159 if (res->to_forward) {
2160 /* We can't process the buffer's contents yet */
2161 res->flags |= CF_WAKE_WRITE;
2162 goto missing_data_or_waiting;
2163 }
2164
Christopher Faulet9768c262018-10-22 09:34:31 +02002165 if (msg->msg_state >= HTTP_MSG_DONE)
2166 goto done;
2167
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002168 /* Forward input data. We get it by removing all outgoing data not
2169 * forwarded yet from HTX data size. If there are some data filters, we
2170 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002171 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002172 if (HAS_RSP_DATA_FILTERS(s)) {
2173 ret = flt_http_payload(s, msg, htx->data);
2174 if (ret < 0)
2175 goto return_bad_res;
2176 c_adv(res, ret);
2177 if (htx->data != co_data(res) || htx->extra)
2178 goto missing_data_or_waiting;
2179 }
2180 else {
2181 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002182
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002183 /* To let the function channel_forward work as expected we must update
2184 * the channel's buffer to pretend there is no more input data. The
2185 * right length is then restored. We must do that, because when an HTX
2186 * message is stored into a buffer, it appears as full.
2187 */
2188 b_set_data(&res->buf, co_data(res));
2189 if (msg->flags & HTTP_MSGF_XFER_LEN)
2190 htx->extra -= channel_forward(res, htx->extra);
2191 b_set_data(&res->buf, b_size(&res->buf));
2192 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002193
2194 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2195 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002196 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002197 msg->msg_state = HTTP_MSG_TUNNEL;
2198 goto done;
2199 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 }
2201
Christopher Faulet9768c262018-10-22 09:34:31 +02002202 /* Check if the end-of-message is reached and if so, switch the message
2203 * in HTTP_MSG_DONE state.
2204 */
2205 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2206 goto missing_data_or_waiting;
2207
2208 msg->msg_state = HTTP_MSG_DONE;
2209
2210 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002211 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002212 channel_dont_close(res);
2213
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002214 if (HAS_RSP_DATA_FILTERS(s)) {
2215 ret = flt_http_end(s, msg);
2216 if (ret <= 0) {
2217 if (!ret)
2218 goto missing_data_or_waiting;
2219 goto return_bad_res;
2220 }
2221 }
2222
Christopher Fauletf2824e62018-10-01 12:12:37 +02002223 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002224 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002225 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2227 if (res->flags & CF_SHUTW) {
2228 /* response errors are most likely due to the
2229 * client aborting the transfer. */
2230 goto aborted_xfer;
2231 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 goto return_bad_res;
2233 }
2234 return 1;
2235 }
2236 return 0;
2237
2238 missing_data_or_waiting:
2239 if (res->flags & CF_SHUTW)
2240 goto aborted_xfer;
2241
Christopher Faulet47365272018-10-31 17:40:50 +01002242 if (htx->flags & HTX_FL_PARSING_ERROR)
2243 goto return_bad_res;
2244
Christopher Faulete0768eb2018-10-03 16:38:02 +02002245 /* stop waiting for data if the input is closed before the end. If the
2246 * client side was already closed, it means that the client has aborted,
2247 * so we don't want to count this as a server abort. Otherwise it's a
2248 * server abort.
2249 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002250 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002251 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2252 goto aborted_xfer;
2253 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002254 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002255 if (!(s->flags & SF_ERR_MASK))
2256 s->flags |= SF_ERR_SRVCL;
2257 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2258 if (objt_server(s->target))
2259 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2260 goto return_bad_res_stats_ok;
2261 }
2262 }
2263
Christopher Faulete0768eb2018-10-03 16:38:02 +02002264 /* When TE: chunked is used, we need to get there again to parse
2265 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002266 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2267 * are filters registered on the stream, we don't want to forward a
2268 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002269 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002270 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002271 channel_dont_close(res);
2272
2273 /* We know that more data are expected, but we couldn't send more that
2274 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2275 * system knows it must not set a PUSH on this first part. Interactive
2276 * modes are already handled by the stream sock layer. We must not do
2277 * this in content-length mode because it could present the MSG_MORE
2278 * flag with the last block of forwarded data, which would cause an
2279 * additional delay to be observed by the receiver.
2280 */
2281 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2282 res->flags |= CF_EXPECT_MORE;
2283
2284 /* the stream handler will take care of timeouts and errors */
2285 return 0;
2286
2287 return_bad_res: /* let's centralize all bad responses */
2288 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2289 if (objt_server(s->target))
2290 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2291
2292 return_bad_res_stats_ok:
2293 txn->rsp.err_state = txn->rsp.msg_state;
2294 txn->rsp.msg_state = HTTP_MSG_ERROR;
2295 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002296 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002297 res->analysers &= AN_RES_FLT_END;
2298 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2299 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002300 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301
2302 if (!(s->flags & SF_ERR_MASK))
2303 s->flags |= SF_ERR_PRXCOND;
2304 if (!(s->flags & SF_FINST_MASK))
2305 s->flags |= SF_FINST_D;
2306 return 0;
2307
2308 aborted_xfer:
2309 txn->rsp.err_state = txn->rsp.msg_state;
2310 txn->rsp.msg_state = HTTP_MSG_ERROR;
2311 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002312 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002313 res->analysers &= AN_RES_FLT_END;
2314 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2315
2316 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2317 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2318 if (objt_server(s->target))
2319 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2320
2321 if (!(s->flags & SF_ERR_MASK))
2322 s->flags |= SF_ERR_CLICL;
2323 if (!(s->flags & SF_FINST_MASK))
2324 s->flags |= SF_FINST_D;
2325 return 0;
2326}
2327
Christopher Faulet0f226952018-10-22 09:29:56 +02002328void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002329{
2330 struct proxy *fe = strm_fe(s);
2331 int tmp = TX_CON_WANT_CLO;
2332
2333 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2334 tmp = TX_CON_WANT_TUN;
2335
2336 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002337 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338}
2339
2340/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002341 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002342 * as too large a request to build a valid response.
2343 */
2344int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2345{
Christopher Faulet99daf282018-11-28 22:58:13 +01002346 struct channel *req = &s->req;
2347 struct channel *res = &s->res;
2348 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002349 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002350 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002351 struct ist status, reason, location;
2352 unsigned int flags;
2353 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002354
2355 chunk = alloc_trash_chunk();
2356 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358
Christopher Faulet99daf282018-11-28 22:58:13 +01002359 /*
2360 * Create the location
2361 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002362 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002364 case REDIRECT_TYPE_SCHEME: {
2365 struct http_hdr_ctx ctx;
2366 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002367
Christopher Faulet99daf282018-11-28 22:58:13 +01002368 host = ist("");
2369 ctx.blk = NULL;
2370 if (http_find_header(htx, ist("Host"), &ctx, 0))
2371 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002372
Christopher Faulet99daf282018-11-28 22:58:13 +01002373 sl = http_find_stline(htx);
2374 path = http_get_path(htx_sl_req_uri(sl));
2375 /* build message using path */
2376 if (path.ptr) {
2377 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2378 int qs = 0;
2379 while (qs < path.len) {
2380 if (*(path.ptr + qs) == '?') {
2381 path.len = qs;
2382 break;
2383 }
2384 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002385 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002386 }
2387 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 else
2389 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 if (rule->rdr_str) { /* this is an old "redirect" rule */
2392 /* add scheme */
2393 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2394 goto fail;
2395 }
2396 else {
2397 /* add scheme with executing log format */
2398 chunk->data += build_logline(s, chunk->area + chunk->data,
2399 chunk->size - chunk->data,
2400 &rule->rdr_fmt);
2401 }
2402 /* add "://" + host + path */
2403 if (!chunk_memcat(chunk, "://", 3) ||
2404 !chunk_memcat(chunk, host.ptr, host.len) ||
2405 !chunk_memcat(chunk, path.ptr, path.len))
2406 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407
Christopher Faulet99daf282018-11-28 22:58:13 +01002408 /* append a slash at the end of the location if needed and missing */
2409 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2410 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2411 if (chunk->data + 1 >= chunk->size)
2412 goto fail;
2413 chunk->area[chunk->data++] = '/';
2414 }
2415 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002416 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002417
Christopher Faulet99daf282018-11-28 22:58:13 +01002418 case REDIRECT_TYPE_PREFIX: {
2419 struct ist path;
2420
2421 sl = http_find_stline(htx);
2422 path = http_get_path(htx_sl_req_uri(sl));
2423 /* build message using path */
2424 if (path.ptr) {
2425 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2426 int qs = 0;
2427 while (qs < path.len) {
2428 if (*(path.ptr + qs) == '?') {
2429 path.len = qs;
2430 break;
2431 }
2432 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002433 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002434 }
2435 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 else
2437 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002438
Christopher Faulet99daf282018-11-28 22:58:13 +01002439 if (rule->rdr_str) { /* this is an old "redirect" rule */
2440 /* add prefix. Note that if prefix == "/", we don't want to
2441 * add anything, otherwise it makes it hard for the user to
2442 * configure a self-redirection.
2443 */
2444 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2445 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2446 goto fail;
2447 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002449 else {
2450 /* add prefix with executing log format */
2451 chunk->data += build_logline(s, chunk->area + chunk->data,
2452 chunk->size - chunk->data,
2453 &rule->rdr_fmt);
2454 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002455
Christopher Faulet99daf282018-11-28 22:58:13 +01002456 /* add path */
2457 if (!chunk_memcat(chunk, path.ptr, path.len))
2458 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002459
Christopher Faulet99daf282018-11-28 22:58:13 +01002460 /* append a slash at the end of the location if needed and missing */
2461 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2462 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2463 if (chunk->data + 1 >= chunk->size)
2464 goto fail;
2465 chunk->area[chunk->data++] = '/';
2466 }
2467 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002468 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002469 case REDIRECT_TYPE_LOCATION:
2470 default:
2471 if (rule->rdr_str) { /* this is an old "redirect" rule */
2472 /* add location */
2473 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2474 goto fail;
2475 }
2476 else {
2477 /* add location with executing log format */
2478 chunk->data += build_logline(s, chunk->area + chunk->data,
2479 chunk->size - chunk->data,
2480 &rule->rdr_fmt);
2481 }
2482 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002483 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002484 location = ist2(chunk->area, chunk->data);
2485
2486 /*
2487 * Create the 30x response
2488 */
2489 switch (rule->code) {
2490 case 308:
2491 status = ist("308");
2492 reason = ist("Permanent Redirect");
2493 break;
2494 case 307:
2495 status = ist("307");
2496 reason = ist("Temporary Redirect");
2497 break;
2498 case 303:
2499 status = ist("303");
2500 reason = ist("See Other");
2501 break;
2502 case 301:
2503 status = ist("301");
2504 reason = ist("Moved Permanently");
2505 break;
2506 case 302:
2507 default:
2508 status = ist("302");
2509 reason = ist("Found");
2510 break;
2511 }
2512
2513 htx = htx_from_buf(&res->buf);
2514 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2515 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2516 if (!sl)
2517 goto fail;
2518 sl->info.res.status = rule->code;
2519 s->txn->status = rule->code;
2520
2521 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2522 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2523 !htx_add_header(htx, ist("Location"), location))
2524 goto fail;
2525
2526 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2527 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2528 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002529 }
2530
2531 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2533 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002534 }
2535
Christopher Faulet99daf282018-11-28 22:58:13 +01002536 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2537 goto fail;
2538
Christopher Fauletf2824e62018-10-01 12:12:37 +02002539 /* let's log the request time */
2540 s->logs.tv_request = now;
2541
Christopher Faulet99daf282018-11-28 22:58:13 +01002542 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002543 c_adv(res, data);
2544 res->total += data;
2545
2546 channel_auto_read(req);
2547 channel_abort(req);
2548 channel_auto_close(req);
2549 channel_erase(req);
2550
2551 res->wex = tick_add_ifset(now_ms, res->wto);
2552 channel_auto_read(res);
2553 channel_auto_close(res);
2554 channel_shutr_now(res);
2555
2556 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002557
2558 if (!(s->flags & SF_ERR_MASK))
2559 s->flags |= SF_ERR_LOCAL;
2560 if (!(s->flags & SF_FINST_MASK))
2561 s->flags |= SF_FINST_R;
2562
Christopher Faulet99daf282018-11-28 22:58:13 +01002563 free_trash_chunk(chunk);
2564 return 1;
2565
2566 fail:
2567 /* If an error occurred, remove the incomplete HTTP response from the
2568 * buffer */
2569 channel_truncate(res);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002570 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002571 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002572}
2573
Christopher Faulet72333522018-10-24 11:25:02 +02002574int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2575 struct ist name, const char *str, struct my_regex *re, int action)
2576{
2577 struct http_hdr_ctx ctx;
2578 struct buffer *output = get_trash_chunk();
2579
2580 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2581 ctx.blk = NULL;
2582 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2583 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2584 continue;
2585
2586 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2587 if (output->data == -1)
2588 return -1;
2589 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2590 return -1;
2591 }
2592 return 0;
2593}
2594
2595static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2596 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2597{
2598 struct buffer *replace;
2599 int ret = -1;
2600
2601 replace = alloc_trash_chunk();
2602 if (!replace)
2603 goto leave;
2604
2605 replace->data = build_logline(s, replace->area, replace->size, fmt);
2606 if (replace->data >= replace->size - 1)
2607 goto leave;
2608
2609 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2610
2611 leave:
2612 free_trash_chunk(replace);
2613 return ret;
2614}
2615
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002616
2617/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2618 * on success and -1 on error. The response channel is updated accordingly.
2619 */
2620static int htx_reply_103_early_hints(struct channel *res)
2621{
2622 struct htx *htx = htx_from_buf(&res->buf);
2623 size_t data;
2624
2625 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2626 /* If an error occurred during an Early-hint rule,
2627 * remove the incomplete HTTP 103 response from the
2628 * buffer */
2629 channel_truncate(res);
2630 return -1;
2631 }
2632
2633 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002634 c_adv(res, data);
2635 res->total += data;
2636 return 0;
2637}
2638
Christopher Faulet6eb92892018-11-15 16:39:29 +01002639/*
2640 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2641 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 * If <early_hints> is 0, it is starts a new response by adding the start
2643 * line. If an error occurred -1 is returned. On success 0 is returned. The
2644 * channel is not updated here. It must be done calling the function
2645 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002646 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002647static int htx_add_early_hint_header(struct stream *s, int early_hints, const struct ist name, struct list *fmt)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002648{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002649 struct channel *res = &s->res;
2650 struct htx *htx = htx_from_buf(&res->buf);
2651 struct buffer *value = alloc_trash_chunk();
2652
Christopher Faulet6eb92892018-11-15 16:39:29 +01002653 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 struct htx_sl *sl;
2655 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2656 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2657
2658 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2659 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2660 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002661 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002663 }
2664
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2666 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667 goto fail;
2668
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002669 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002671
2672 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002673 /* If an error occurred during an Early-hint rule, remove the incomplete
2674 * HTTP 103 response from the buffer */
2675 channel_truncate(res);
2676 free_trash_chunk(value);
2677 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002678}
2679
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002680/* This function executes one of the set-{method,path,query,uri} actions. It
2681 * takes the string from the variable 'replace' with length 'len', then modifies
2682 * the relevant part of the request line accordingly. Then it updates various
2683 * pointers to the next elements which were moved, and the total buffer length.
2684 * It finds the action to be performed in p[2], previously filled by function
2685 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2686 * error, though this can be revisited when this code is finally exploited.
2687 *
2688 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2689 * query string and 3 to replace uri.
2690 *
2691 * In query string case, the mark question '?' must be set at the start of the
2692 * string by the caller, event if the replacement query string is empty.
2693 */
2694int htx_req_replace_stline(int action, const char *replace, int len,
2695 struct proxy *px, struct stream *s)
2696{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002697 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002698
2699 switch (action) {
2700 case 0: // method
2701 if (!http_replace_req_meth(htx, ist2(replace, len)))
2702 return -1;
2703 break;
2704
2705 case 1: // path
2706 if (!http_replace_req_path(htx, ist2(replace, len)))
2707 return -1;
2708 break;
2709
2710 case 2: // query
2711 if (!http_replace_req_query(htx, ist2(replace, len)))
2712 return -1;
2713 break;
2714
2715 case 3: // uri
2716 if (!http_replace_req_uri(htx, ist2(replace, len)))
2717 return -1;
2718 break;
2719
2720 default:
2721 return -1;
2722 }
2723 return 0;
2724}
2725
2726/* This function replace the HTTP status code and the associated message. The
2727 * variable <status> contains the new status code. This function never fails.
2728 */
2729void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2730{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002731 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002732 char *res;
2733
2734 chunk_reset(&trash);
2735 res = ultoa_o(status, trash.area, trash.size);
2736 trash.data = res - trash.area;
2737
2738 /* Do we have a custom reason format string? */
2739 if (reason == NULL)
2740 reason = http_get_reason(status);
2741
2742 if (!http_replace_res_status(htx, ist2(trash.area, trash.data)))
2743 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2744}
2745
Christopher Faulet3e964192018-10-24 11:39:23 +02002746/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2747 * transaction <txn>. Returns the verdict of the first rule that prevents
2748 * further processing of the request (auth, deny, ...), and defaults to
2749 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2750 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2751 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2752 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2753 * status.
2754 */
2755static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2756 struct stream *s, int *deny_status)
2757{
2758 struct session *sess = strm_sess(s);
2759 struct http_txn *txn = s->txn;
2760 struct htx *htx;
2761 struct connection *cli_conn;
2762 struct act_rule *rule;
2763 struct http_hdr_ctx ctx;
2764 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002765 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2766 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002767 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002768
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002769 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002770
2771 /* If "the current_rule_list" match the executed rule list, we are in
2772 * resume condition. If a resume is needed it is always in the action
2773 * and never in the ACL or converters. In this case, we initialise the
2774 * current rule, and go to the action execution point.
2775 */
2776 if (s->current_rule) {
2777 rule = s->current_rule;
2778 s->current_rule = NULL;
2779 if (s->current_rule_list == rules)
2780 goto resume_execution;
2781 }
2782 s->current_rule_list = rules;
2783
2784 list_for_each_entry(rule, rules, list) {
2785 /* check optional condition */
2786 if (rule->cond) {
2787 int ret;
2788
2789 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2790 ret = acl_pass(ret);
2791
2792 if (rule->cond->pol == ACL_COND_UNLESS)
2793 ret = !ret;
2794
2795 if (!ret) /* condition not matched */
2796 continue;
2797 }
2798
2799 act_flags |= ACT_FLAG_FIRST;
2800 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002801 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2802 early_hints = 0;
2803 if (htx_reply_103_early_hints(&s->res) == -1) {
2804 rule_ret = HTTP_RULE_RES_BADREQ;
2805 goto end;
2806 }
2807 }
2808
Christopher Faulet3e964192018-10-24 11:39:23 +02002809 switch (rule->action) {
2810 case ACT_ACTION_ALLOW:
2811 rule_ret = HTTP_RULE_RES_STOP;
2812 goto end;
2813
2814 case ACT_ACTION_DENY:
2815 if (deny_status)
2816 *deny_status = rule->deny_status;
2817 rule_ret = HTTP_RULE_RES_DENY;
2818 goto end;
2819
2820 case ACT_HTTP_REQ_TARPIT:
2821 txn->flags |= TX_CLTARPIT;
2822 if (deny_status)
2823 *deny_status = rule->deny_status;
2824 rule_ret = HTTP_RULE_RES_DENY;
2825 goto end;
2826
2827 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 /* Auth might be performed on regular http-req rules as well as on stats */
2829 auth_realm = rule->arg.auth.realm;
2830 if (!auth_realm) {
2831 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2832 auth_realm = STATS_DEFAULT_REALM;
2833 else
2834 auth_realm = px->id;
2835 }
2836 /* send 401/407 depending on whether we use a proxy or not. We still
2837 * count one error, because normal browsing won't significantly
2838 * increase the counter but brute force attempts will.
2839 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002840 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002841 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2842 rule_ret = HTTP_RULE_RES_BADREQ;
2843 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002844 goto end;
2845
2846 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002847 rule_ret = HTTP_RULE_RES_DONE;
2848 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2849 rule_ret = HTTP_RULE_RES_BADREQ;
2850 goto end;
2851
2852 case ACT_HTTP_SET_NICE:
2853 s->task->nice = rule->arg.nice;
2854 break;
2855
2856 case ACT_HTTP_SET_TOS:
2857 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2858 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
2859 break;
2860
2861 case ACT_HTTP_SET_MARK:
2862#ifdef SO_MARK
2863 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
2864 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
2865#endif
2866 break;
2867
2868 case ACT_HTTP_SET_LOGL:
2869 s->logs.level = rule->arg.loglevel;
2870 break;
2871
2872 case ACT_HTTP_REPLACE_HDR:
2873 case ACT_HTTP_REPLACE_VAL:
2874 if (htx_transform_header(s, &s->req, htx,
2875 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2876 &rule->arg.hdr_add.fmt,
2877 &rule->arg.hdr_add.re, rule->action)) {
2878 rule_ret = HTTP_RULE_RES_BADREQ;
2879 goto end;
2880 }
2881 break;
2882
2883 case ACT_HTTP_DEL_HDR:
2884 /* remove all occurrences of the header */
2885 ctx.blk = NULL;
2886 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2887 http_remove_header(htx, &ctx);
2888 break;
2889
2890 case ACT_HTTP_SET_HDR:
2891 case ACT_HTTP_ADD_HDR: {
2892 /* The scope of the trash buffer must be limited to this function. The
2893 * build_logline() function can execute a lot of other function which
2894 * can use the trash buffer. So for limiting the scope of this global
2895 * buffer, we build first the header value using build_logline, and
2896 * after we store the header name.
2897 */
2898 struct buffer *replace;
2899 struct ist n, v;
2900
2901 replace = alloc_trash_chunk();
2902 if (!replace) {
2903 rule_ret = HTTP_RULE_RES_BADREQ;
2904 goto end;
2905 }
2906
2907 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2908 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2909 v = ist2(replace->area, replace->data);
2910
2911 if (rule->action == ACT_HTTP_SET_HDR) {
2912 /* remove all occurrences of the header */
2913 ctx.blk = NULL;
2914 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2915 http_remove_header(htx, &ctx);
2916 }
2917
2918 if (!http_add_header(htx, n, v)) {
2919 static unsigned char rate_limit = 0;
2920
2921 if ((rate_limit++ & 255) == 0) {
2922 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);
2923 }
2924
2925 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2926 if (sess->fe != s->be)
2927 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2928 if (sess->listener->counters)
2929 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2930 }
2931 free_trash_chunk(replace);
2932 break;
2933 }
2934
2935 case ACT_HTTP_DEL_ACL:
2936 case ACT_HTTP_DEL_MAP: {
2937 struct pat_ref *ref;
2938 struct buffer *key;
2939
2940 /* collect reference */
2941 ref = pat_ref_lookup(rule->arg.map.ref);
2942 if (!ref)
2943 continue;
2944
2945 /* allocate key */
2946 key = alloc_trash_chunk();
2947 if (!key) {
2948 rule_ret = HTTP_RULE_RES_BADREQ;
2949 goto end;
2950 }
2951
2952 /* collect key */
2953 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2954 key->area[key->data] = '\0';
2955
2956 /* perform update */
2957 /* returned code: 1=ok, 0=ko */
2958 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2959 pat_ref_delete(ref, key->area);
2960 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2961
2962 free_trash_chunk(key);
2963 break;
2964 }
2965
2966 case ACT_HTTP_ADD_ACL: {
2967 struct pat_ref *ref;
2968 struct buffer *key;
2969
2970 /* collect reference */
2971 ref = pat_ref_lookup(rule->arg.map.ref);
2972 if (!ref)
2973 continue;
2974
2975 /* allocate key */
2976 key = alloc_trash_chunk();
2977 if (!key) {
2978 rule_ret = HTTP_RULE_RES_BADREQ;
2979 goto end;
2980 }
2981
2982 /* collect key */
2983 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2984 key->area[key->data] = '\0';
2985
2986 /* perform update */
2987 /* add entry only if it does not already exist */
2988 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2989 if (pat_ref_find_elt(ref, key->area) == NULL)
2990 pat_ref_add(ref, key->area, NULL, NULL);
2991 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2992
2993 free_trash_chunk(key);
2994 break;
2995 }
2996
2997 case ACT_HTTP_SET_MAP: {
2998 struct pat_ref *ref;
2999 struct buffer *key, *value;
3000
3001 /* collect reference */
3002 ref = pat_ref_lookup(rule->arg.map.ref);
3003 if (!ref)
3004 continue;
3005
3006 /* allocate key */
3007 key = alloc_trash_chunk();
3008 if (!key) {
3009 rule_ret = HTTP_RULE_RES_BADREQ;
3010 goto end;
3011 }
3012
3013 /* allocate value */
3014 value = alloc_trash_chunk();
3015 if (!value) {
3016 free_trash_chunk(key);
3017 rule_ret = HTTP_RULE_RES_BADREQ;
3018 goto end;
3019 }
3020
3021 /* collect key */
3022 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3023 key->area[key->data] = '\0';
3024
3025 /* collect value */
3026 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3027 value->area[value->data] = '\0';
3028
3029 /* perform update */
3030 if (pat_ref_find_elt(ref, key->area) != NULL)
3031 /* update entry if it exists */
3032 pat_ref_set(ref, key->area, value->area, NULL);
3033 else
3034 /* insert a new entry */
3035 pat_ref_add(ref, key->area, value->area, NULL);
3036
3037 free_trash_chunk(key);
3038 free_trash_chunk(value);
3039 break;
3040 }
3041
3042 case ACT_HTTP_EARLY_HINT:
3043 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3044 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003045 early_hints = htx_add_early_hint_header(s, early_hints,
3046 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003047 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003048 if (early_hints == -1) {
3049 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003050 goto end;
3051 }
3052 break;
3053
3054 case ACT_CUSTOM:
3055 if ((s->req.flags & CF_READ_ERROR) ||
3056 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3057 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3058 (px->options & PR_O_ABRT_CLOSE)))
3059 act_flags |= ACT_FLAG_FINAL;
3060
3061 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3062 case ACT_RET_ERR:
3063 case ACT_RET_CONT:
3064 break;
3065 case ACT_RET_STOP:
3066 rule_ret = HTTP_RULE_RES_DONE;
3067 goto end;
3068 case ACT_RET_YIELD:
3069 s->current_rule = rule;
3070 rule_ret = HTTP_RULE_RES_YIELD;
3071 goto end;
3072 }
3073 break;
3074
3075 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3076 /* Note: only the first valid tracking parameter of each
3077 * applies.
3078 */
3079
3080 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3081 struct stktable *t;
3082 struct stksess *ts;
3083 struct stktable_key *key;
3084 void *ptr1, *ptr2;
3085
3086 t = rule->arg.trk_ctr.table.t;
3087 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3088 rule->arg.trk_ctr.expr, NULL);
3089
3090 if (key && (ts = stktable_get_entry(t, key))) {
3091 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3092
3093 /* let's count a new HTTP request as it's the first time we do it */
3094 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3095 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3096 if (ptr1 || ptr2) {
3097 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3098
3099 if (ptr1)
3100 stktable_data_cast(ptr1, http_req_cnt)++;
3101
3102 if (ptr2)
3103 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3104 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3105
3106 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3107
3108 /* If data was modified, we need to touch to re-schedule sync */
3109 stktable_touch_local(t, ts, 0);
3110 }
3111
3112 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3113 if (sess->fe != s->be)
3114 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3115 }
3116 }
3117 break;
3118
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003119 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003120 default:
3121 break;
3122 }
3123 }
3124
3125 end:
3126 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003127 if (htx_reply_103_early_hints(&s->res) == -1)
3128 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003129 }
3130
3131 /* we reached the end of the rules, nothing to report */
3132 return rule_ret;
3133}
3134
3135/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3136 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3137 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3138 * is returned, the process can continue the evaluation of next rule list. If
3139 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3140 * is returned, it means the operation could not be processed and a server error
3141 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3142 * deny rule. If *YIELD is returned, the caller must call again the function
3143 * with the same context.
3144 */
3145static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3146 struct stream *s)
3147{
3148 struct session *sess = strm_sess(s);
3149 struct http_txn *txn = s->txn;
3150 struct htx *htx;
3151 struct connection *cli_conn;
3152 struct act_rule *rule;
3153 struct http_hdr_ctx ctx;
3154 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3155 int act_flags = 0;
3156
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003157 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003158
3159 /* If "the current_rule_list" match the executed rule list, we are in
3160 * resume condition. If a resume is needed it is always in the action
3161 * and never in the ACL or converters. In this case, we initialise the
3162 * current rule, and go to the action execution point.
3163 */
3164 if (s->current_rule) {
3165 rule = s->current_rule;
3166 s->current_rule = NULL;
3167 if (s->current_rule_list == rules)
3168 goto resume_execution;
3169 }
3170 s->current_rule_list = rules;
3171
3172 list_for_each_entry(rule, rules, list) {
3173 /* check optional condition */
3174 if (rule->cond) {
3175 int ret;
3176
3177 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3178 ret = acl_pass(ret);
3179
3180 if (rule->cond->pol == ACL_COND_UNLESS)
3181 ret = !ret;
3182
3183 if (!ret) /* condition not matched */
3184 continue;
3185 }
3186
3187 act_flags |= ACT_FLAG_FIRST;
3188resume_execution:
3189 switch (rule->action) {
3190 case ACT_ACTION_ALLOW:
3191 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3192 goto end;
3193
3194 case ACT_ACTION_DENY:
3195 txn->flags |= TX_SVDENY;
3196 rule_ret = HTTP_RULE_RES_STOP;
3197 goto end;
3198
3199 case ACT_HTTP_SET_NICE:
3200 s->task->nice = rule->arg.nice;
3201 break;
3202
3203 case ACT_HTTP_SET_TOS:
3204 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3205 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, rule->arg.tos);
3206 break;
3207
3208 case ACT_HTTP_SET_MARK:
3209#ifdef SO_MARK
3210 if ((cli_conn = objt_conn(sess->origin)) && conn_ctrl_ready(cli_conn))
3211 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark));
3212#endif
3213 break;
3214
3215 case ACT_HTTP_SET_LOGL:
3216 s->logs.level = rule->arg.loglevel;
3217 break;
3218
3219 case ACT_HTTP_REPLACE_HDR:
3220 case ACT_HTTP_REPLACE_VAL:
3221 if (htx_transform_header(s, &s->res, htx,
3222 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3223 &rule->arg.hdr_add.fmt,
3224 &rule->arg.hdr_add.re, rule->action)) {
3225 rule_ret = HTTP_RULE_RES_BADREQ;
3226 goto end;
3227 }
3228 break;
3229
3230 case ACT_HTTP_DEL_HDR:
3231 /* remove all occurrences of the header */
3232 ctx.blk = NULL;
3233 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3234 http_remove_header(htx, &ctx);
3235 break;
3236
3237 case ACT_HTTP_SET_HDR:
3238 case ACT_HTTP_ADD_HDR: {
3239 struct buffer *replace;
3240 struct ist n, v;
3241
3242 replace = alloc_trash_chunk();
3243 if (!replace) {
3244 rule_ret = HTTP_RULE_RES_BADREQ;
3245 goto end;
3246 }
3247
3248 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3249 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3250 v = ist2(replace->area, replace->data);
3251
3252 if (rule->action == ACT_HTTP_SET_HDR) {
3253 /* remove all occurrences of the header */
3254 ctx.blk = NULL;
3255 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3256 http_remove_header(htx, &ctx);
3257 }
3258
3259 if (!http_add_header(htx, n, v)) {
3260 static unsigned char rate_limit = 0;
3261
3262 if ((rate_limit++ & 255) == 0) {
3263 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);
3264 }
3265
3266 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3267 if (sess->fe != s->be)
3268 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3269 if (sess->listener->counters)
3270 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3271 if (objt_server(s->target))
3272 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3273 }
3274 free_trash_chunk(replace);
3275 break;
3276 }
3277
3278 case ACT_HTTP_DEL_ACL:
3279 case ACT_HTTP_DEL_MAP: {
3280 struct pat_ref *ref;
3281 struct buffer *key;
3282
3283 /* collect reference */
3284 ref = pat_ref_lookup(rule->arg.map.ref);
3285 if (!ref)
3286 continue;
3287
3288 /* allocate key */
3289 key = alloc_trash_chunk();
3290 if (!key) {
3291 rule_ret = HTTP_RULE_RES_BADREQ;
3292 goto end;
3293 }
3294
3295 /* collect key */
3296 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3297 key->area[key->data] = '\0';
3298
3299 /* perform update */
3300 /* returned code: 1=ok, 0=ko */
3301 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3302 pat_ref_delete(ref, key->area);
3303 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3304
3305 free_trash_chunk(key);
3306 break;
3307 }
3308
3309 case ACT_HTTP_ADD_ACL: {
3310 struct pat_ref *ref;
3311 struct buffer *key;
3312
3313 /* collect reference */
3314 ref = pat_ref_lookup(rule->arg.map.ref);
3315 if (!ref)
3316 continue;
3317
3318 /* allocate key */
3319 key = alloc_trash_chunk();
3320 if (!key) {
3321 rule_ret = HTTP_RULE_RES_BADREQ;
3322 goto end;
3323 }
3324
3325 /* collect key */
3326 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3327 key->area[key->data] = '\0';
3328
3329 /* perform update */
3330 /* check if the entry already exists */
3331 if (pat_ref_find_elt(ref, key->area) == NULL)
3332 pat_ref_add(ref, key->area, NULL, NULL);
3333
3334 free_trash_chunk(key);
3335 break;
3336 }
3337
3338 case ACT_HTTP_SET_MAP: {
3339 struct pat_ref *ref;
3340 struct buffer *key, *value;
3341
3342 /* collect reference */
3343 ref = pat_ref_lookup(rule->arg.map.ref);
3344 if (!ref)
3345 continue;
3346
3347 /* allocate key */
3348 key = alloc_trash_chunk();
3349 if (!key) {
3350 rule_ret = HTTP_RULE_RES_BADREQ;
3351 goto end;
3352 }
3353
3354 /* allocate value */
3355 value = alloc_trash_chunk();
3356 if (!value) {
3357 free_trash_chunk(key);
3358 rule_ret = HTTP_RULE_RES_BADREQ;
3359 goto end;
3360 }
3361
3362 /* collect key */
3363 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3364 key->area[key->data] = '\0';
3365
3366 /* collect value */
3367 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3368 value->area[value->data] = '\0';
3369
3370 /* perform update */
3371 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3372 if (pat_ref_find_elt(ref, key->area) != NULL)
3373 /* update entry if it exists */
3374 pat_ref_set(ref, key->area, value->area, NULL);
3375 else
3376 /* insert a new entry */
3377 pat_ref_add(ref, key->area, value->area, NULL);
3378 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3379 free_trash_chunk(key);
3380 free_trash_chunk(value);
3381 break;
3382 }
3383
3384 case ACT_HTTP_REDIR:
3385 rule_ret = HTTP_RULE_RES_DONE;
3386 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3387 rule_ret = HTTP_RULE_RES_BADREQ;
3388 goto end;
3389
3390 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3391 /* Note: only the first valid tracking parameter of each
3392 * applies.
3393 */
3394 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3395 struct stktable *t;
3396 struct stksess *ts;
3397 struct stktable_key *key;
3398 void *ptr;
3399
3400 t = rule->arg.trk_ctr.table.t;
3401 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3402 rule->arg.trk_ctr.expr, NULL);
3403
3404 if (key && (ts = stktable_get_entry(t, key))) {
3405 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3406
3407 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3408
3409 /* let's count a new HTTP request as it's the first time we do it */
3410 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3411 if (ptr)
3412 stktable_data_cast(ptr, http_req_cnt)++;
3413
3414 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3415 if (ptr)
3416 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3417 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3418
3419 /* When the client triggers a 4xx from the server, it's most often due
3420 * to a missing object or permission. These events should be tracked
3421 * because if they happen often, it may indicate a brute force or a
3422 * vulnerability scan. Normally this is done when receiving the response
3423 * but here we're tracking after this ought to have been done so we have
3424 * to do it on purpose.
3425 */
3426 if ((unsigned)(txn->status - 400) < 100) {
3427 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3428 if (ptr)
3429 stktable_data_cast(ptr, http_err_cnt)++;
3430
3431 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3432 if (ptr)
3433 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3434 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3435 }
3436
3437 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3438
3439 /* If data was modified, we need to touch to re-schedule sync */
3440 stktable_touch_local(t, ts, 0);
3441
3442 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3443 if (sess->fe != s->be)
3444 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3445 }
3446 }
3447 break;
3448
3449 case ACT_CUSTOM:
3450 if ((s->req.flags & CF_READ_ERROR) ||
3451 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3452 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3453 (px->options & PR_O_ABRT_CLOSE)))
3454 act_flags |= ACT_FLAG_FINAL;
3455
3456 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3457 case ACT_RET_ERR:
3458 case ACT_RET_CONT:
3459 break;
3460 case ACT_RET_STOP:
3461 rule_ret = HTTP_RULE_RES_STOP;
3462 goto end;
3463 case ACT_RET_YIELD:
3464 s->current_rule = rule;
3465 rule_ret = HTTP_RULE_RES_YIELD;
3466 goto end;
3467 }
3468 break;
3469
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003470 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003471 default:
3472 break;
3473 }
3474 }
3475
3476 end:
3477 /* we reached the end of the rules, nothing to report */
3478 return rule_ret;
3479}
3480
Christopher Faulet33640082018-10-24 11:53:01 +02003481/* Iterate the same filter through all request headers.
3482 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3483 * Since it can manage the switch to another backend, it updates the per-proxy
3484 * DENY stats.
3485 */
3486static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3487{
3488 struct http_txn *txn = s->txn;
3489 struct htx *htx;
3490 struct buffer *hdr = get_trash_chunk();
3491 int32_t pos;
3492
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003493 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003494
3495 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3496 struct htx_blk *blk = htx_get_blk(htx, pos);
3497 enum htx_blk_type type;
3498 struct ist n, v;
3499
3500 next_hdr:
3501 type = htx_get_blk_type(blk);
3502 if (type == HTX_BLK_EOH)
3503 break;
3504 if (type != HTX_BLK_HDR)
3505 continue;
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
3515 n = htx_get_blk_name(htx, blk);
3516 v = htx_get_blk_value(htx, blk);
3517
3518 chunk_memcat(hdr, n.ptr, n.len);
3519 hdr->area[hdr->data++] = ':';
3520 hdr->area[hdr->data++] = ' ';
3521 chunk_memcat(hdr, v.ptr, v.len);
3522
3523 /* Now we have one header in <hdr> */
3524
3525 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3526 struct http_hdr_ctx ctx;
3527 int len;
3528
3529 switch (exp->action) {
3530 case ACT_ALLOW:
3531 txn->flags |= TX_CLALLOW;
3532 goto end;
3533
3534 case ACT_DENY:
3535 txn->flags |= TX_CLDENY;
3536 goto end;
3537
3538 case ACT_TARPIT:
3539 txn->flags |= TX_CLTARPIT;
3540 goto end;
3541
3542 case ACT_REPLACE:
3543 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3544 if (len < 0)
3545 return -1;
3546
3547 http_parse_header(ist2(trash.area, len), &n, &v);
3548 ctx.blk = blk;
3549 ctx.value = v;
3550 if (!http_replace_header(htx, &ctx, n, v))
3551 return -1;
3552 if (!ctx.blk)
3553 goto end;
3554 pos = htx_get_blk_pos(htx, blk);
3555 break;
3556
3557 case ACT_REMOVE:
3558 ctx.blk = blk;
3559 ctx.value = v;
3560 if (!http_remove_header(htx, &ctx))
3561 return -1;
3562 if (!ctx.blk)
3563 goto end;
3564 pos = htx_get_blk_pos(htx, blk);
3565 goto next_hdr;
3566
3567 }
3568 }
3569 }
3570 end:
3571 return 0;
3572}
3573
3574/* Apply the filter to the request line.
3575 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3576 * or -1 if a replacement resulted in an invalid request line.
3577 * Since it can manage the switch to another backend, it updates the per-proxy
3578 * DENY stats.
3579 */
3580static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3581{
3582 struct http_txn *txn = s->txn;
3583 struct htx *htx;
3584 struct buffer *reqline = get_trash_chunk();
3585 int done;
3586
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003587 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003588
3589 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3590 return 1;
3591 else if (unlikely(txn->flags & TX_CLALLOW) &&
3592 (exp->action == ACT_ALLOW ||
3593 exp->action == ACT_DENY ||
3594 exp->action == ACT_TARPIT))
3595 return 0;
3596 else if (exp->action == ACT_REMOVE)
3597 return 0;
3598
3599 done = 0;
3600
3601 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3602
3603 /* Now we have the request line between cur_ptr and cur_end */
3604 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003605 struct htx_sl *sl = http_find_stline(htx);
3606 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003607 int len;
3608
3609 switch (exp->action) {
3610 case ACT_ALLOW:
3611 txn->flags |= TX_CLALLOW;
3612 done = 1;
3613 break;
3614
3615 case ACT_DENY:
3616 txn->flags |= TX_CLDENY;
3617 done = 1;
3618 break;
3619
3620 case ACT_TARPIT:
3621 txn->flags |= TX_CLTARPIT;
3622 done = 1;
3623 break;
3624
3625 case ACT_REPLACE:
3626 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3627 if (len < 0)
3628 return -1;
3629
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003630 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3631 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3632 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003633 return -1;
3634 done = 1;
3635 break;
3636 }
3637 }
3638 return done;
3639}
3640
3641/*
3642 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3643 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3644 * unparsable request. Since it can manage the switch to another backend, it
3645 * updates the per-proxy DENY stats.
3646 */
3647static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3648{
3649 struct session *sess = s->sess;
3650 struct http_txn *txn = s->txn;
3651 struct hdr_exp *exp;
3652
3653 for (exp = px->req_exp; exp; exp = exp->next) {
3654 int ret;
3655
3656 /*
3657 * The interleaving of transformations and verdicts
3658 * makes it difficult to decide to continue or stop
3659 * the evaluation.
3660 */
3661
3662 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3663 break;
3664
3665 if ((txn->flags & TX_CLALLOW) &&
3666 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3667 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3668 continue;
3669
3670 /* if this filter had a condition, evaluate it now and skip to
3671 * next filter if the condition does not match.
3672 */
3673 if (exp->cond) {
3674 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3675 ret = acl_pass(ret);
3676 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3677 ret = !ret;
3678
3679 if (!ret)
3680 continue;
3681 }
3682
3683 /* Apply the filter to the request line. */
3684 ret = htx_apply_filter_to_req_line(s, req, exp);
3685 if (unlikely(ret < 0))
3686 return -1;
3687
3688 if (likely(ret == 0)) {
3689 /* The filter did not match the request, it can be
3690 * iterated through all headers.
3691 */
3692 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3693 return -1;
3694 }
3695 }
3696 return 0;
3697}
3698
3699/* Iterate the same filter through all response headers contained in <res>.
3700 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3701 */
3702static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3703{
3704 struct http_txn *txn = s->txn;
3705 struct htx *htx;
3706 struct buffer *hdr = get_trash_chunk();
3707 int32_t pos;
3708
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003709 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003710
3711 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3712 struct htx_blk *blk = htx_get_blk(htx, pos);
3713 enum htx_blk_type type;
3714 struct ist n, v;
3715
3716 next_hdr:
3717 type = htx_get_blk_type(blk);
3718 if (type == HTX_BLK_EOH)
3719 break;
3720 if (type != HTX_BLK_HDR)
3721 continue;
3722
3723 if (unlikely(txn->flags & TX_SVDENY))
3724 return 1;
3725 else if (unlikely(txn->flags & TX_SVALLOW) &&
3726 (exp->action == ACT_ALLOW ||
3727 exp->action == ACT_DENY))
3728 return 0;
3729
3730 n = htx_get_blk_name(htx, blk);
3731 v = htx_get_blk_value(htx, blk);
3732
3733 chunk_memcat(hdr, n.ptr, n.len);
3734 hdr->area[hdr->data++] = ':';
3735 hdr->area[hdr->data++] = ' ';
3736 chunk_memcat(hdr, v.ptr, v.len);
3737
3738 /* Now we have one header in <hdr> */
3739
3740 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3741 struct http_hdr_ctx ctx;
3742 int len;
3743
3744 switch (exp->action) {
3745 case ACT_ALLOW:
3746 txn->flags |= TX_SVALLOW;
3747 goto end;
3748 break;
3749
3750 case ACT_DENY:
3751 txn->flags |= TX_SVDENY;
3752 goto end;
3753 break;
3754
3755 case ACT_REPLACE:
3756 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3757 if (len < 0)
3758 return -1;
3759
3760 http_parse_header(ist2(trash.area, len), &n, &v);
3761 ctx.blk = blk;
3762 ctx.value = v;
3763 if (!http_replace_header(htx, &ctx, n, v))
3764 return -1;
3765 if (!ctx.blk)
3766 goto end;
3767 pos = htx_get_blk_pos(htx, blk);
3768 break;
3769
3770 case ACT_REMOVE:
3771 ctx.blk = blk;
3772 ctx.value = v;
3773 if (!http_remove_header(htx, &ctx))
3774 return -1;
3775 if (!ctx.blk)
3776 goto end;
3777 pos = htx_get_blk_pos(htx, blk);
3778 goto next_hdr;
3779 }
3780 }
3781
3782 }
3783 end:
3784 return 0;
3785}
3786
3787/* Apply the filter to the status line in the response buffer <res>.
3788 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3789 * or -1 if a replacement resulted in an invalid status line.
3790 */
3791static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3792{
3793 struct http_txn *txn = s->txn;
3794 struct htx *htx;
3795 struct buffer *resline = get_trash_chunk();
3796 int done;
3797
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003798 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003799
3800 if (unlikely(txn->flags & TX_SVDENY))
3801 return 1;
3802 else if (unlikely(txn->flags & TX_SVALLOW) &&
3803 (exp->action == ACT_ALLOW ||
3804 exp->action == ACT_DENY))
3805 return 0;
3806 else if (exp->action == ACT_REMOVE)
3807 return 0;
3808
3809 done = 0;
3810 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3811
3812 /* Now we have the status line between cur_ptr and cur_end */
3813 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003814 struct htx_sl *sl = http_find_stline(htx);
3815 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003816 int len;
3817
3818 switch (exp->action) {
3819 case ACT_ALLOW:
3820 txn->flags |= TX_SVALLOW;
3821 done = 1;
3822 break;
3823
3824 case ACT_DENY:
3825 txn->flags |= TX_SVDENY;
3826 done = 1;
3827 break;
3828
3829 case ACT_REPLACE:
3830 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3831 if (len < 0)
3832 return -1;
3833
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003834 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3835 sl->info.res.status = strl2ui(code.ptr, code.len);
3836 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003837 return -1;
3838
3839 done = 1;
3840 return 1;
3841 }
3842 }
3843 return done;
3844}
3845
3846/*
3847 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3848 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3849 * unparsable response.
3850 */
3851static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3852{
3853 struct session *sess = s->sess;
3854 struct http_txn *txn = s->txn;
3855 struct hdr_exp *exp;
3856
3857 for (exp = px->rsp_exp; exp; exp = exp->next) {
3858 int ret;
3859
3860 /*
3861 * The interleaving of transformations and verdicts
3862 * makes it difficult to decide to continue or stop
3863 * the evaluation.
3864 */
3865
3866 if (txn->flags & TX_SVDENY)
3867 break;
3868
3869 if ((txn->flags & TX_SVALLOW) &&
3870 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3871 exp->action == ACT_PASS)) {
3872 exp = exp->next;
3873 continue;
3874 }
3875
3876 /* if this filter had a condition, evaluate it now and skip to
3877 * next filter if the condition does not match.
3878 */
3879 if (exp->cond) {
3880 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3881 ret = acl_pass(ret);
3882 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3883 ret = !ret;
3884 if (!ret)
3885 continue;
3886 }
3887
3888 /* Apply the filter to the status line. */
3889 ret = htx_apply_filter_to_sts_line(s, res, exp);
3890 if (unlikely(ret < 0))
3891 return -1;
3892
3893 if (likely(ret == 0)) {
3894 /* The filter did not match the response, it can be
3895 * iterated through all headers.
3896 */
3897 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3898 return -1;
3899 }
3900 }
3901 return 0;
3902}
3903
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003904/*
3905 * Manage client-side cookie. It can impact performance by about 2% so it is
3906 * desirable to call it only when needed. This code is quite complex because
3907 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3908 * highly recommended not to touch this part without a good reason !
3909 */
3910static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3911{
3912 struct session *sess = s->sess;
3913 struct http_txn *txn = s->txn;
3914 struct htx *htx;
3915 struct http_hdr_ctx ctx;
3916 char *hdr_beg, *hdr_end, *del_from;
3917 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3918 int preserve_hdr;
3919
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003920 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003921 ctx.blk = NULL;
3922 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3923 del_from = NULL; /* nothing to be deleted */
3924 preserve_hdr = 0; /* assume we may kill the whole header */
3925
3926 /* Now look for cookies. Conforming to RFC2109, we have to support
3927 * attributes whose name begin with a '$', and associate them with
3928 * the right cookie, if we want to delete this cookie.
3929 * So there are 3 cases for each cookie read :
3930 * 1) it's a special attribute, beginning with a '$' : ignore it.
3931 * 2) it's a server id cookie that we *MAY* want to delete : save
3932 * some pointers on it (last semi-colon, beginning of cookie...)
3933 * 3) it's an application cookie : we *MAY* have to delete a previous
3934 * "special" cookie.
3935 * At the end of loop, if a "special" cookie remains, we may have to
3936 * remove it. If no application cookie persists in the header, we
3937 * *MUST* delete it.
3938 *
3939 * Note: RFC2965 is unclear about the processing of spaces around
3940 * the equal sign in the ATTR=VALUE form. A careful inspection of
3941 * the RFC explicitly allows spaces before it, and not within the
3942 * tokens (attrs or values). An inspection of RFC2109 allows that
3943 * too but section 10.1.3 lets one think that spaces may be allowed
3944 * after the equal sign too, resulting in some (rare) buggy
3945 * implementations trying to do that. So let's do what servers do.
3946 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3947 * allowed quoted strings in values, with any possible character
3948 * after a backslash, including control chars and delimitors, which
3949 * causes parsing to become ambiguous. Browsers also allow spaces
3950 * within values even without quotes.
3951 *
3952 * We have to keep multiple pointers in order to support cookie
3953 * removal at the beginning, middle or end of header without
3954 * corrupting the header. All of these headers are valid :
3955 *
3956 * hdr_beg hdr_end
3957 * | |
3958 * v |
3959 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3960 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3961 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3962 * | | | | | | |
3963 * | | | | | | |
3964 * | | | | | | +--> next
3965 * | | | | | +----> val_end
3966 * | | | | +-----------> val_beg
3967 * | | | +--------------> equal
3968 * | | +----------------> att_end
3969 * | +---------------------> att_beg
3970 * +--------------------------> prev
3971 *
3972 */
3973 hdr_beg = ctx.value.ptr;
3974 hdr_end = hdr_beg + ctx.value.len;
3975 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3976 /* Iterate through all cookies on this line */
3977
3978 /* find att_beg */
3979 att_beg = prev;
3980 if (prev > hdr_beg)
3981 att_beg++;
3982
3983 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3984 att_beg++;
3985
3986 /* find att_end : this is the first character after the last non
3987 * space before the equal. It may be equal to hdr_end.
3988 */
3989 equal = att_end = att_beg;
3990 while (equal < hdr_end) {
3991 if (*equal == '=' || *equal == ',' || *equal == ';')
3992 break;
3993 if (HTTP_IS_SPHT(*equal++))
3994 continue;
3995 att_end = equal;
3996 }
3997
3998 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3999 * is between <att_beg> and <equal>, both may be identical.
4000 */
4001 /* look for end of cookie if there is an equal sign */
4002 if (equal < hdr_end && *equal == '=') {
4003 /* look for the beginning of the value */
4004 val_beg = equal + 1;
4005 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4006 val_beg++;
4007
4008 /* find the end of the value, respecting quotes */
4009 next = http_find_cookie_value_end(val_beg, hdr_end);
4010
4011 /* make val_end point to the first white space or delimitor after the value */
4012 val_end = next;
4013 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4014 val_end--;
4015 }
4016 else
4017 val_beg = val_end = next = equal;
4018
4019 /* We have nothing to do with attributes beginning with
4020 * '$'. However, they will automatically be removed if a
4021 * header before them is removed, since they're supposed
4022 * to be linked together.
4023 */
4024 if (*att_beg == '$')
4025 continue;
4026
4027 /* Ignore cookies with no equal sign */
4028 if (equal == next) {
4029 /* This is not our cookie, so we must preserve it. But if we already
4030 * scheduled another cookie for removal, we cannot remove the
4031 * complete header, but we can remove the previous block itself.
4032 */
4033 preserve_hdr = 1;
4034 if (del_from != NULL) {
4035 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4036 val_end += delta;
4037 next += delta;
4038 hdr_end += delta;
4039 prev = del_from;
4040 del_from = NULL;
4041 }
4042 continue;
4043 }
4044
4045 /* if there are spaces around the equal sign, we need to
4046 * strip them otherwise we'll get trouble for cookie captures,
4047 * or even for rewrites. Since this happens extremely rarely,
4048 * it does not hurt performance.
4049 */
4050 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4051 int stripped_before = 0;
4052 int stripped_after = 0;
4053
4054 if (att_end != equal) {
4055 memmove(att_end, equal, hdr_end - equal);
4056 stripped_before = (att_end - equal);
4057 equal += stripped_before;
4058 val_beg += stripped_before;
4059 }
4060
4061 if (val_beg > equal + 1) {
4062 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4063 stripped_after = (equal + 1) - val_beg;
4064 val_beg += stripped_after;
4065 stripped_before += stripped_after;
4066 }
4067
4068 val_end += stripped_before;
4069 next += stripped_before;
4070 hdr_end += stripped_before;
4071 }
4072 /* now everything is as on the diagram above */
4073
4074 /* First, let's see if we want to capture this cookie. We check
4075 * that we don't already have a client side cookie, because we
4076 * can only capture one. Also as an optimisation, we ignore
4077 * cookies shorter than the declared name.
4078 */
4079 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4080 (val_end - att_beg >= sess->fe->capture_namelen) &&
4081 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4082 int log_len = val_end - att_beg;
4083
4084 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4085 ha_alert("HTTP logging : out of memory.\n");
4086 } else {
4087 if (log_len > sess->fe->capture_len)
4088 log_len = sess->fe->capture_len;
4089 memcpy(txn->cli_cookie, att_beg, log_len);
4090 txn->cli_cookie[log_len] = 0;
4091 }
4092 }
4093
4094 /* Persistence cookies in passive, rewrite or insert mode have the
4095 * following form :
4096 *
4097 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4098 *
4099 * For cookies in prefix mode, the form is :
4100 *
4101 * Cookie: NAME=SRV~VALUE
4102 */
4103 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4104 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4105 struct server *srv = s->be->srv;
4106 char *delim;
4107
4108 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4109 * have the server ID between val_beg and delim, and the original cookie between
4110 * delim+1 and val_end. Otherwise, delim==val_end :
4111 *
4112 * hdr_beg
4113 * |
4114 * v
4115 * NAME=SRV; # in all but prefix modes
4116 * NAME=SRV~OPAQUE ; # in prefix mode
4117 * || || | |+-> next
4118 * || || | +--> val_end
4119 * || || +---------> delim
4120 * || |+------------> val_beg
4121 * || +-------------> att_end = equal
4122 * |+-----------------> att_beg
4123 * +------------------> prev
4124 *
4125 */
4126 if (s->be->ck_opts & PR_CK_PFX) {
4127 for (delim = val_beg; delim < val_end; delim++)
4128 if (*delim == COOKIE_DELIM)
4129 break;
4130 }
4131 else {
4132 char *vbar1;
4133 delim = val_end;
4134 /* Now check if the cookie contains a date field, which would
4135 * appear after a vertical bar ('|') just after the server name
4136 * and before the delimiter.
4137 */
4138 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4139 if (vbar1) {
4140 /* OK, so left of the bar is the server's cookie and
4141 * right is the last seen date. It is a base64 encoded
4142 * 30-bit value representing the UNIX date since the
4143 * epoch in 4-second quantities.
4144 */
4145 int val;
4146 delim = vbar1++;
4147 if (val_end - vbar1 >= 5) {
4148 val = b64tos30(vbar1);
4149 if (val > 0)
4150 txn->cookie_last_date = val << 2;
4151 }
4152 /* look for a second vertical bar */
4153 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4154 if (vbar1 && (val_end - vbar1 > 5)) {
4155 val = b64tos30(vbar1 + 1);
4156 if (val > 0)
4157 txn->cookie_first_date = val << 2;
4158 }
4159 }
4160 }
4161
4162 /* if the cookie has an expiration date and the proxy wants to check
4163 * it, then we do that now. We first check if the cookie is too old,
4164 * then only if it has expired. We detect strict overflow because the
4165 * time resolution here is not great (4 seconds). Cookies with dates
4166 * in the future are ignored if their offset is beyond one day. This
4167 * allows an admin to fix timezone issues without expiring everyone
4168 * and at the same time avoids keeping unwanted side effects for too
4169 * long.
4170 */
4171 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4172 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4173 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4174 txn->flags &= ~TX_CK_MASK;
4175 txn->flags |= TX_CK_OLD;
4176 delim = val_beg; // let's pretend we have not found the cookie
4177 txn->cookie_first_date = 0;
4178 txn->cookie_last_date = 0;
4179 }
4180 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4181 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4182 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4183 txn->flags &= ~TX_CK_MASK;
4184 txn->flags |= TX_CK_EXPIRED;
4185 delim = val_beg; // let's pretend we have not found the cookie
4186 txn->cookie_first_date = 0;
4187 txn->cookie_last_date = 0;
4188 }
4189
4190 /* Here, we'll look for the first running server which supports the cookie.
4191 * This allows to share a same cookie between several servers, for example
4192 * to dedicate backup servers to specific servers only.
4193 * However, to prevent clients from sticking to cookie-less backup server
4194 * when they have incidentely learned an empty cookie, we simply ignore
4195 * empty cookies and mark them as invalid.
4196 * The same behaviour is applied when persistence must be ignored.
4197 */
4198 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4199 srv = NULL;
4200
4201 while (srv) {
4202 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4203 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4204 if ((srv->cur_state != SRV_ST_STOPPED) ||
4205 (s->be->options & PR_O_PERSIST) ||
4206 (s->flags & SF_FORCE_PRST)) {
4207 /* we found the server and we can use it */
4208 txn->flags &= ~TX_CK_MASK;
4209 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4210 s->flags |= SF_DIRECT | SF_ASSIGNED;
4211 s->target = &srv->obj_type;
4212 break;
4213 } else {
4214 /* we found a server, but it's down,
4215 * mark it as such and go on in case
4216 * another one is available.
4217 */
4218 txn->flags &= ~TX_CK_MASK;
4219 txn->flags |= TX_CK_DOWN;
4220 }
4221 }
4222 srv = srv->next;
4223 }
4224
4225 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4226 /* no server matched this cookie or we deliberately skipped it */
4227 txn->flags &= ~TX_CK_MASK;
4228 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4229 txn->flags |= TX_CK_UNUSED;
4230 else
4231 txn->flags |= TX_CK_INVALID;
4232 }
4233
4234 /* depending on the cookie mode, we may have to either :
4235 * - delete the complete cookie if we're in insert+indirect mode, so that
4236 * the server never sees it ;
4237 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004238 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004239 * if we're in cookie prefix mode
4240 */
4241 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4242 int delta; /* negative */
4243
4244 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4245 delta = val_beg - (delim + 1);
4246 val_end += delta;
4247 next += delta;
4248 hdr_end += delta;
4249 del_from = NULL;
4250 preserve_hdr = 1; /* we want to keep this cookie */
4251 }
4252 else if (del_from == NULL &&
4253 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4254 del_from = prev;
4255 }
4256 }
4257 else {
4258 /* This is not our cookie, so we must preserve it. But if we already
4259 * scheduled another cookie for removal, we cannot remove the
4260 * complete header, but we can remove the previous block itself.
4261 */
4262 preserve_hdr = 1;
4263
4264 if (del_from != NULL) {
4265 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4266 if (att_beg >= del_from)
4267 att_beg += delta;
4268 if (att_end >= del_from)
4269 att_end += delta;
4270 val_beg += delta;
4271 val_end += delta;
4272 next += delta;
4273 hdr_end += delta;
4274 prev = del_from;
4275 del_from = NULL;
4276 }
4277 }
4278
4279 /* continue with next cookie on this header line */
4280 att_beg = next;
4281 } /* for each cookie */
4282
4283
4284 /* There are no more cookies on this line.
4285 * We may still have one (or several) marked for deletion at the
4286 * end of the line. We must do this now in two ways :
4287 * - if some cookies must be preserved, we only delete from the
4288 * mark to the end of line ;
4289 * - if nothing needs to be preserved, simply delete the whole header
4290 */
4291 if (del_from) {
4292 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4293 }
4294 if ((hdr_end - hdr_beg) != ctx.value.len) {
4295 if (hdr_beg != hdr_end) {
4296 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4297 htx->data -= (hdr_end - ctx.value.ptr);
4298 }
4299 else
4300 http_remove_header(htx, &ctx);
4301 }
4302 } /* for each "Cookie header */
4303}
4304
4305/*
4306 * Manage server-side cookies. It can impact performance by about 2% so it is
4307 * desirable to call it only when needed. This function is also used when we
4308 * just need to know if there is a cookie (eg: for check-cache).
4309 */
4310static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4311{
4312 struct session *sess = s->sess;
4313 struct http_txn *txn = s->txn;
4314 struct htx *htx;
4315 struct http_hdr_ctx ctx;
4316 struct server *srv;
4317 char *hdr_beg, *hdr_end;
4318 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4319 int is_cookie2;
4320
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004321 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004322
4323 ctx.blk = NULL;
4324 while (1) {
4325 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4326 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4327 break;
4328 is_cookie2 = 1;
4329 }
4330
4331 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4332 * <prev> points to the colon.
4333 */
4334 txn->flags |= TX_SCK_PRESENT;
4335
4336 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4337 * check-cache is enabled) and we are not interested in checking
4338 * them. Warning, the cookie capture is declared in the frontend.
4339 */
4340 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4341 break;
4342
4343 /* OK so now we know we have to process this response cookie.
4344 * The format of the Set-Cookie header is slightly different
4345 * from the format of the Cookie header in that it does not
4346 * support the comma as a cookie delimiter (thus the header
4347 * cannot be folded) because the Expires attribute described in
4348 * the original Netscape's spec may contain an unquoted date
4349 * with a comma inside. We have to live with this because
4350 * many browsers don't support Max-Age and some browsers don't
4351 * support quoted strings. However the Set-Cookie2 header is
4352 * clean.
4353 *
4354 * We have to keep multiple pointers in order to support cookie
4355 * removal at the beginning, middle or end of header without
4356 * corrupting the header (in case of set-cookie2). A special
4357 * pointer, <scav> points to the beginning of the set-cookie-av
4358 * fields after the first semi-colon. The <next> pointer points
4359 * either to the end of line (set-cookie) or next unquoted comma
4360 * (set-cookie2). All of these headers are valid :
4361 *
4362 * hdr_beg hdr_end
4363 * | |
4364 * v |
4365 * NAME1 = VALUE 1 ; Secure; Path="/" |
4366 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4367 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4368 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4369 * | | | | | | | |
4370 * | | | | | | | +-> next
4371 * | | | | | | +------------> scav
4372 * | | | | | +--------------> val_end
4373 * | | | | +--------------------> val_beg
4374 * | | | +----------------------> equal
4375 * | | +------------------------> att_end
4376 * | +----------------------------> att_beg
4377 * +------------------------------> prev
4378 * -------------------------------> hdr_beg
4379 */
4380 hdr_beg = ctx.value.ptr;
4381 hdr_end = hdr_beg + ctx.value.len;
4382 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4383
4384 /* Iterate through all cookies on this line */
4385
4386 /* find att_beg */
4387 att_beg = prev;
4388 if (prev > hdr_beg)
4389 att_beg++;
4390
4391 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4392 att_beg++;
4393
4394 /* find att_end : this is the first character after the last non
4395 * space before the equal. It may be equal to hdr_end.
4396 */
4397 equal = att_end = att_beg;
4398
4399 while (equal < hdr_end) {
4400 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4401 break;
4402 if (HTTP_IS_SPHT(*equal++))
4403 continue;
4404 att_end = equal;
4405 }
4406
4407 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4408 * is between <att_beg> and <equal>, both may be identical.
4409 */
4410
4411 /* look for end of cookie if there is an equal sign */
4412 if (equal < hdr_end && *equal == '=') {
4413 /* look for the beginning of the value */
4414 val_beg = equal + 1;
4415 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4416 val_beg++;
4417
4418 /* find the end of the value, respecting quotes */
4419 next = http_find_cookie_value_end(val_beg, hdr_end);
4420
4421 /* make val_end point to the first white space or delimitor after the value */
4422 val_end = next;
4423 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4424 val_end--;
4425 }
4426 else {
4427 /* <equal> points to next comma, semi-colon or EOL */
4428 val_beg = val_end = next = equal;
4429 }
4430
4431 if (next < hdr_end) {
4432 /* Set-Cookie2 supports multiple cookies, and <next> points to
4433 * a colon or semi-colon before the end. So skip all attr-value
4434 * pairs and look for the next comma. For Set-Cookie, since
4435 * commas are permitted in values, skip to the end.
4436 */
4437 if (is_cookie2)
4438 next = http_find_hdr_value_end(next, hdr_end);
4439 else
4440 next = hdr_end;
4441 }
4442
4443 /* Now everything is as on the diagram above */
4444
4445 /* Ignore cookies with no equal sign */
4446 if (equal == val_end)
4447 continue;
4448
4449 /* If there are spaces around the equal sign, we need to
4450 * strip them otherwise we'll get trouble for cookie captures,
4451 * or even for rewrites. Since this happens extremely rarely,
4452 * it does not hurt performance.
4453 */
4454 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4455 int stripped_before = 0;
4456 int stripped_after = 0;
4457
4458 if (att_end != equal) {
4459 memmove(att_end, equal, hdr_end - equal);
4460 stripped_before = (att_end - equal);
4461 equal += stripped_before;
4462 val_beg += stripped_before;
4463 }
4464
4465 if (val_beg > equal + 1) {
4466 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4467 stripped_after = (equal + 1) - val_beg;
4468 val_beg += stripped_after;
4469 stripped_before += stripped_after;
4470 }
4471
4472 val_end += stripped_before;
4473 next += stripped_before;
4474 hdr_end += stripped_before;
4475
4476 ctx.value.len = hdr_end - hdr_beg;
4477 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4478 htx->data -= (hdr_end - ctx.value.ptr);
4479 }
4480
4481 /* First, let's see if we want to capture this cookie. We check
4482 * that we don't already have a server side cookie, because we
4483 * can only capture one. Also as an optimisation, we ignore
4484 * cookies shorter than the declared name.
4485 */
4486 if (sess->fe->capture_name != NULL &&
4487 txn->srv_cookie == NULL &&
4488 (val_end - att_beg >= sess->fe->capture_namelen) &&
4489 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4490 int log_len = val_end - att_beg;
4491 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4492 ha_alert("HTTP logging : out of memory.\n");
4493 }
4494 else {
4495 if (log_len > sess->fe->capture_len)
4496 log_len = sess->fe->capture_len;
4497 memcpy(txn->srv_cookie, att_beg, log_len);
4498 txn->srv_cookie[log_len] = 0;
4499 }
4500 }
4501
4502 srv = objt_server(s->target);
4503 /* now check if we need to process it for persistence */
4504 if (!(s->flags & SF_IGNORE_PRST) &&
4505 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4506 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4507 /* assume passive cookie by default */
4508 txn->flags &= ~TX_SCK_MASK;
4509 txn->flags |= TX_SCK_FOUND;
4510
4511 /* If the cookie is in insert mode on a known server, we'll delete
4512 * this occurrence because we'll insert another one later.
4513 * We'll delete it too if the "indirect" option is set and we're in
4514 * a direct access.
4515 */
4516 if (s->be->ck_opts & PR_CK_PSV) {
4517 /* The "preserve" flag was set, we don't want to touch the
4518 * server's cookie.
4519 */
4520 }
4521 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4522 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4523 /* this cookie must be deleted */
4524 if (prev == hdr_beg && next == hdr_end) {
4525 /* whole header */
4526 http_remove_header(htx, &ctx);
4527 /* note: while both invalid now, <next> and <hdr_end>
4528 * are still equal, so the for() will stop as expected.
4529 */
4530 } else {
4531 /* just remove the value */
4532 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4533 next = prev;
4534 hdr_end += delta;
4535 }
4536 txn->flags &= ~TX_SCK_MASK;
4537 txn->flags |= TX_SCK_DELETED;
4538 /* and go on with next cookie */
4539 }
4540 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4541 /* replace bytes val_beg->val_end with the cookie name associated
4542 * with this server since we know it.
4543 */
4544 int sliding, delta;
4545
4546 ctx.value = ist2(val_beg, val_end - val_beg);
4547 ctx.lws_before = ctx.lws_after = 0;
4548 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4549 delta = srv->cklen - (val_end - val_beg);
4550 sliding = (ctx.value.ptr - val_beg);
4551 hdr_beg += sliding;
4552 val_beg += sliding;
4553 next += sliding + delta;
4554 hdr_end += sliding + delta;
4555
4556 txn->flags &= ~TX_SCK_MASK;
4557 txn->flags |= TX_SCK_REPLACED;
4558 }
4559 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4560 /* insert the cookie name associated with this server
4561 * before existing cookie, and insert a delimiter between them..
4562 */
4563 int sliding, delta;
4564 ctx.value = ist2(val_beg, 0);
4565 ctx.lws_before = ctx.lws_after = 0;
4566 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4567 delta = srv->cklen + 1;
4568 sliding = (ctx.value.ptr - val_beg);
4569 hdr_beg += sliding;
4570 val_beg += sliding;
4571 next += sliding + delta;
4572 hdr_end += sliding + delta;
4573
4574 val_beg[srv->cklen] = COOKIE_DELIM;
4575 txn->flags &= ~TX_SCK_MASK;
4576 txn->flags |= TX_SCK_REPLACED;
4577 }
4578 }
4579 /* that's done for this cookie, check the next one on the same
4580 * line when next != hdr_end (only if is_cookie2).
4581 */
4582 }
4583 }
4584}
4585
Christopher Faulet25a02f62018-10-24 12:00:25 +02004586/*
4587 * Parses the Cache-Control and Pragma request header fields to determine if
4588 * the request may be served from the cache and/or if it is cacheable. Updates
4589 * s->txn->flags.
4590 */
4591void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4592{
4593 struct http_txn *txn = s->txn;
4594 struct htx *htx;
4595 int32_t pos;
4596 int pragma_found, cc_found, i;
4597
4598 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4599 return; /* nothing more to do here */
4600
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004601 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004602 pragma_found = cc_found = 0;
4603 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4604 struct htx_blk *blk = htx_get_blk(htx, pos);
4605 enum htx_blk_type type = htx_get_blk_type(blk);
4606 struct ist n, v;
4607
4608 if (type == HTX_BLK_EOH)
4609 break;
4610 if (type != HTX_BLK_HDR)
4611 continue;
4612
4613 n = htx_get_blk_name(htx, blk);
4614 v = htx_get_blk_value(htx, blk);
4615
4616 if (isteqi(n, ist("Pragma"))) {
4617 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4618 pragma_found = 1;
4619 continue;
4620 }
4621 }
4622
4623 /* Don't use the cache and don't try to store if we found the
4624 * Authorization header */
4625 if (isteqi(n, ist("Authorization"))) {
4626 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4627 txn->flags |= TX_CACHE_IGNORE;
4628 continue;
4629 }
4630
4631 if (!isteqi(n, ist("Cache-control")))
4632 continue;
4633
4634 /* OK, right now we know we have a cache-control header */
4635 cc_found = 1;
4636 if (!v.len) /* no info */
4637 continue;
4638
4639 i = 0;
4640 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4641 !isspace((unsigned char)*(v.ptr+i)))
4642 i++;
4643
4644 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4645 * values after max-age, max-stale nor min-fresh, we simply don't
4646 * use the cache when they're specified.
4647 */
4648 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4649 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4650 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4651 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4652 txn->flags |= TX_CACHE_IGNORE;
4653 continue;
4654 }
4655
4656 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4657 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4658 continue;
4659 }
4660 }
4661
4662 /* RFC7234#5.4:
4663 * When the Cache-Control header field is also present and
4664 * understood in a request, Pragma is ignored.
4665 * When the Cache-Control header field is not present in a
4666 * request, caches MUST consider the no-cache request
4667 * pragma-directive as having the same effect as if
4668 * "Cache-Control: no-cache" were present.
4669 */
4670 if (!cc_found && pragma_found)
4671 txn->flags |= TX_CACHE_IGNORE;
4672}
4673
4674/*
4675 * Check if response is cacheable or not. Updates s->txn->flags.
4676 */
4677void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4678{
4679 struct http_txn *txn = s->txn;
4680 struct htx *htx;
4681 int32_t pos;
4682 int i;
4683
4684 if (txn->status < 200) {
4685 /* do not try to cache interim responses! */
4686 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4687 return;
4688 }
4689
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004690 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004691 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4692 struct htx_blk *blk = htx_get_blk(htx, pos);
4693 enum htx_blk_type type = htx_get_blk_type(blk);
4694 struct ist n, v;
4695
4696 if (type == HTX_BLK_EOH)
4697 break;
4698 if (type != HTX_BLK_HDR)
4699 continue;
4700
4701 n = htx_get_blk_name(htx, blk);
4702 v = htx_get_blk_value(htx, blk);
4703
4704 if (isteqi(n, ist("Pragma"))) {
4705 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4706 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4707 return;
4708 }
4709 }
4710
4711 if (!isteqi(n, ist("Cache-control")))
4712 continue;
4713
4714 /* OK, right now we know we have a cache-control header */
4715 if (!v.len) /* no info */
4716 continue;
4717
4718 i = 0;
4719 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4720 !isspace((unsigned char)*(v.ptr+i)))
4721 i++;
4722
4723 /* we have a complete value between v.ptr and (v.ptr+i) */
4724 if (i < v.len && *(v.ptr + i) == '=') {
4725 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4726 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4727 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4728 continue;
4729 }
4730
4731 /* we have something of the form no-cache="set-cookie" */
4732 if ((v.len >= 21) &&
4733 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4734 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4735 txn->flags &= ~TX_CACHE_COOK;
4736 continue;
4737 }
4738
4739 /* OK, so we know that either p2 points to the end of string or to a comma */
4740 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4741 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4742 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4743 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4744 return;
4745 }
4746
4747 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4748 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4749 continue;
4750 }
4751 }
4752}
4753
Christopher Faulet64159df2018-10-24 21:15:35 +02004754/* send a server's name with an outgoing request over an established connection.
4755 * Note: this function is designed to be called once the request has been
4756 * scheduled for being forwarded. This is the reason why the number of forwarded
4757 * bytes have to be adjusted.
4758 */
4759int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4760{
4761 struct htx *htx;
4762 struct http_hdr_ctx ctx;
4763 struct ist hdr;
4764 uint32_t data;
4765
4766 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004767 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004768 data = htx->data;
4769
4770 ctx.blk = NULL;
4771 while (http_find_header(htx, hdr, &ctx, 1))
4772 http_remove_header(htx, &ctx);
4773 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4774
4775 if (co_data(&s->req)) {
4776 if (data >= htx->data)
4777 c_rew(&s->req, data - htx->data);
4778 else
4779 c_adv(&s->req, htx->data - data);
4780 }
4781 return 0;
4782}
4783
Christopher Faulet377c5a52018-10-24 21:21:30 +02004784/*
4785 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4786 * for the current backend.
4787 *
4788 * It is assumed that the request is either a HEAD, GET, or POST and that the
4789 * uri_auth field is valid.
4790 *
4791 * Returns 1 if stats should be provided, otherwise 0.
4792 */
4793static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4794{
4795 struct uri_auth *uri_auth = backend->uri_auth;
4796 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004797 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004798 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004799
4800 if (!uri_auth)
4801 return 0;
4802
4803 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4804 return 0;
4805
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004806 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004807 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004808 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004809
4810 /* check URI size */
4811 if (uri_auth->uri_len > uri.len)
4812 return 0;
4813
4814 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4815 return 0;
4816
4817 return 1;
4818}
4819
4820/* This function prepares an applet to handle the stats. It can deal with the
4821 * "100-continue" expectation, check that admin rules are met for POST requests,
4822 * and program a response message if something was unexpected. It cannot fail
4823 * and always relies on the stats applet to complete the job. It does not touch
4824 * analysers nor counters, which are left to the caller. It does not touch
4825 * s->target which is supposed to already point to the stats applet. The caller
4826 * is expected to have already assigned an appctx to the stream.
4827 */
4828static int htx_handle_stats(struct stream *s, struct channel *req)
4829{
4830 struct stats_admin_rule *stats_admin_rule;
4831 struct stream_interface *si = &s->si[1];
4832 struct session *sess = s->sess;
4833 struct http_txn *txn = s->txn;
4834 struct http_msg *msg = &txn->req;
4835 struct uri_auth *uri_auth = s->be->uri_auth;
4836 const char *h, *lookup, *end;
4837 struct appctx *appctx;
4838 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004839 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004840
4841 appctx = si_appctx(si);
4842 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4843 appctx->st1 = appctx->st2 = 0;
4844 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4845 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4846 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4847 appctx->ctx.stats.flags |= STAT_CHUNKED;
4848
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004849 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004850 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004851 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4852 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004853
4854 for (h = lookup; h <= end - 3; h++) {
4855 if (memcmp(h, ";up", 3) == 0) {
4856 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4857 break;
4858 }
4859 }
4860
4861 if (uri_auth->refresh) {
4862 for (h = lookup; h <= end - 10; h++) {
4863 if (memcmp(h, ";norefresh", 10) == 0) {
4864 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4865 break;
4866 }
4867 }
4868 }
4869
4870 for (h = lookup; h <= end - 4; h++) {
4871 if (memcmp(h, ";csv", 4) == 0) {
4872 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4873 break;
4874 }
4875 }
4876
4877 for (h = lookup; h <= end - 6; h++) {
4878 if (memcmp(h, ";typed", 6) == 0) {
4879 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4880 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4881 break;
4882 }
4883 }
4884
4885 for (h = lookup; h <= end - 8; h++) {
4886 if (memcmp(h, ";st=", 4) == 0) {
4887 int i;
4888 h += 4;
4889 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4890 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4891 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4892 appctx->ctx.stats.st_code = i;
4893 break;
4894 }
4895 }
4896 break;
4897 }
4898 }
4899
4900 appctx->ctx.stats.scope_str = 0;
4901 appctx->ctx.stats.scope_len = 0;
4902 for (h = lookup; h <= end - 8; h++) {
4903 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4904 int itx = 0;
4905 const char *h2;
4906 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4907 const char *err;
4908
4909 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4910 h2 = h;
4911 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4912 while (h <= end) {
4913 if (*h == ';' || *h == '&' || *h == ' ')
4914 break;
4915 itx++;
4916 h++;
4917 }
4918
4919 if (itx > STAT_SCOPE_TXT_MAXLEN)
4920 itx = STAT_SCOPE_TXT_MAXLEN;
4921 appctx->ctx.stats.scope_len = itx;
4922
4923 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4924 memcpy(scope_txt, h2, itx);
4925 scope_txt[itx] = '\0';
4926 err = invalid_char(scope_txt);
4927 if (err) {
4928 /* bad char in search text => clear scope */
4929 appctx->ctx.stats.scope_str = 0;
4930 appctx->ctx.stats.scope_len = 0;
4931 }
4932 break;
4933 }
4934 }
4935
4936 /* now check whether we have some admin rules for this request */
4937 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4938 int ret = 1;
4939
4940 if (stats_admin_rule->cond) {
4941 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4942 ret = acl_pass(ret);
4943 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4944 ret = !ret;
4945 }
4946
4947 if (ret) {
4948 /* no rule, or the rule matches */
4949 appctx->ctx.stats.flags |= STAT_ADMIN;
4950 break;
4951 }
4952 }
4953
4954 /* Was the status page requested with a POST ? */
4955 if (unlikely(txn->meth == HTTP_METH_POST)) {
4956 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4957 /* we'll need the request body, possibly after sending 100-continue */
4958 if (msg->msg_state < HTTP_MSG_DATA)
4959 req->analysers |= AN_REQ_HTTP_BODY;
4960 appctx->st0 = STAT_HTTP_POST;
4961 }
4962 else {
4963 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4964 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4965 appctx->st0 = STAT_HTTP_LAST;
4966 }
4967 }
4968 else {
4969 /* So it was another method (GET/HEAD) */
4970 appctx->st0 = STAT_HTTP_HEAD;
4971 }
4972
4973 s->task->nice = -32; /* small boost for HTTP statistics */
4974 return 1;
4975}
4976
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004977void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4978{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004979 struct channel *req = &s->req;
4980 struct channel *res = &s->res;
4981 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004982 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004983 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004984 struct ist path, location;
4985 unsigned int flags;
4986 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004987
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004988 /*
4989 * Create the location
4990 */
4991 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004992
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004993 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004994 /* special prefix "/" means don't change URL */
4995 srv = __objt_server(s->target);
4996 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4997 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4998 return;
4999 }
5000
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01005002 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005003 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005004 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005005 if (!path.ptr)
5006 return;
5007
5008 if (!chunk_memcat(&trash, path.ptr, path.len))
5009 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005010 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /*
5013 * Create the 302 respone
5014 */
5015 htx = htx_from_buf(&res->buf);
5016 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5017 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5018 ist("HTTP/1.1"), ist("302"), ist("Found"));
5019 if (!sl)
5020 goto fail;
5021 sl->info.res.status = 302;
5022 s->txn->status = 302;
5023
5024 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5025 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5026 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5027 !htx_add_header(htx, ist("Location"), location))
5028 goto fail;
5029
5030 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5031 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005032
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005033 /*
5034 * Send the message
5035 */
5036 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005037 c_adv(res, data);
5038 res->total += data;
5039
5040 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005041 si_shutr(si);
5042 si_shutw(si);
5043 si->err_type = SI_ET_NONE;
5044 si->state = SI_ST_CLO;
5045
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005046 channel_auto_read(req);
5047 channel_abort(req);
5048 channel_auto_close(req);
5049 channel_erase(req);
5050 channel_auto_read(res);
5051 channel_auto_close(res);
5052
5053 if (!(s->flags & SF_ERR_MASK))
5054 s->flags |= SF_ERR_LOCAL;
5055 if (!(s->flags & SF_FINST_MASK))
5056 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005057
5058 /* FIXME: we should increase a counter of redirects per server and per backend. */
5059 srv_inc_sess_ctr(srv);
5060 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005061 return;
5062
5063 fail:
5064 /* If an error occurred, remove the incomplete HTTP response from the
5065 * buffer */
5066 channel_truncate(res);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005067}
5068
Christopher Fauletf2824e62018-10-01 12:12:37 +02005069/* This function terminates the request because it was completly analyzed or
5070 * because an error was triggered during the body forwarding.
5071 */
5072static void htx_end_request(struct stream *s)
5073{
5074 struct channel *chn = &s->req;
5075 struct http_txn *txn = s->txn;
5076
5077 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5078 now_ms, __FUNCTION__, s,
5079 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5080 s->req.analysers, s->res.analysers);
5081
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005082 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5083 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005084 channel_abort(chn);
5085 channel_truncate(chn);
5086 goto end;
5087 }
5088
5089 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5090 return;
5091
5092 if (txn->req.msg_state == HTTP_MSG_DONE) {
5093 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5094 /* The server has not finished to respond, so we
5095 * don't want to move in order not to upset it.
5096 */
5097 return;
5098 }
5099
5100 /* No need to read anymore, the request was completely parsed.
5101 * We can shut the read side unless we want to abort_on_close,
5102 * or we have a POST request. The issue with POST requests is
5103 * that some browsers still send a CRLF after the request, and
5104 * this CRLF must be read so that it does not remain in the kernel
5105 * buffers, otherwise a close could cause an RST on some systems
5106 * (eg: Linux).
5107 */
5108 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5109 txn->meth != HTTP_METH_POST)
5110 channel_dont_read(chn);
5111
5112 /* if the server closes the connection, we want to immediately react
5113 * and close the socket to save packets and syscalls.
5114 */
5115 s->si[1].flags |= SI_FL_NOHALF;
5116
5117 /* In any case we've finished parsing the request so we must
5118 * disable Nagle when sending data because 1) we're not going
5119 * to shut this side, and 2) the server is waiting for us to
5120 * send pending data.
5121 */
5122 chn->flags |= CF_NEVER_WAIT;
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 /* Tunnel mode will not have any analyser so it needs to
5131 * poll for reads.
5132 */
5133 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005134 if (b_data(&chn->buf))
5135 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005136 txn->req.msg_state = HTTP_MSG_TUNNEL;
5137 }
5138 else {
5139 /* we're not expecting any new data to come for this
5140 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005141 *
5142 * However, there is an exception if the response
5143 * length is undefined. In this case, we need to wait
5144 * the close from the server. The response will be
5145 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005146 */
5147 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5148 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005149 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005150
5151 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5152 channel_shutr_now(chn);
5153 channel_shutw_now(chn);
5154 }
5155 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005156 goto check_channel_flags;
5157 }
5158
5159 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5160 http_msg_closing:
5161 /* nothing else to forward, just waiting for the output buffer
5162 * to be empty and for the shutw_now to take effect.
5163 */
5164 if (channel_is_empty(chn)) {
5165 txn->req.msg_state = HTTP_MSG_CLOSED;
5166 goto http_msg_closed;
5167 }
5168 else if (chn->flags & CF_SHUTW) {
5169 txn->req.err_state = txn->req.msg_state;
5170 txn->req.msg_state = HTTP_MSG_ERROR;
5171 goto end;
5172 }
5173 return;
5174 }
5175
5176 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5177 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005178 /* if we don't know whether the server will close, we need to hard close */
5179 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5180 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005181 /* see above in MSG_DONE why we only do this in these states */
5182 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5183 channel_dont_read(chn);
5184 goto end;
5185 }
5186
5187 check_channel_flags:
5188 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5189 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5190 /* if we've just closed an output, let's switch */
5191 txn->req.msg_state = HTTP_MSG_CLOSING;
5192 goto http_msg_closing;
5193 }
5194
5195 end:
5196 chn->analysers &= AN_REQ_FLT_END;
5197 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5198 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5199 channel_auto_close(chn);
5200 channel_auto_read(chn);
5201}
5202
5203
5204/* This function terminates the response because it was completly analyzed or
5205 * because an error was triggered during the body forwarding.
5206 */
5207static void htx_end_response(struct stream *s)
5208{
5209 struct channel *chn = &s->res;
5210 struct http_txn *txn = s->txn;
5211
5212 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5213 now_ms, __FUNCTION__, s,
5214 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5215 s->req.analysers, s->res.analysers);
5216
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005217 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5218 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf3d48052018-12-04 16:23:54 +01005219 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005220 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005221 goto end;
5222 }
5223
5224 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5225 return;
5226
5227 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5228 /* In theory, we don't need to read anymore, but we must
5229 * still monitor the server connection for a possible close
5230 * while the request is being uploaded, so we don't disable
5231 * reading.
5232 */
5233 /* channel_dont_read(chn); */
5234
5235 if (txn->req.msg_state < HTTP_MSG_DONE) {
5236 /* The client seems to still be sending data, probably
5237 * because we got an error response during an upload.
5238 * We have the choice of either breaking the connection
5239 * or letting it pass through. Let's do the later.
5240 */
5241 return;
5242 }
5243
5244 /* When we get here, it means that both the request and the
5245 * response have finished receiving. Depending on the connection
5246 * mode, we'll have to wait for the last bytes to leave in either
5247 * direction, and sometimes for a close to be effective.
5248 */
5249 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5250 channel_auto_read(chn);
5251 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005252 if (b_data(&chn->buf))
5253 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005254 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5255 }
5256 else {
5257 /* we're not expecting any new data to come for this
5258 * transaction, so we can close it.
5259 */
5260 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5261 channel_shutr_now(chn);
5262 channel_shutw_now(chn);
5263 }
5264 }
5265 goto check_channel_flags;
5266 }
5267
5268 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5269 http_msg_closing:
5270 /* nothing else to forward, just waiting for the output buffer
5271 * to be empty and for the shutw_now to take effect.
5272 */
5273 if (channel_is_empty(chn)) {
5274 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5275 goto http_msg_closed;
5276 }
5277 else if (chn->flags & CF_SHUTW) {
5278 txn->rsp.err_state = txn->rsp.msg_state;
5279 txn->rsp.msg_state = HTTP_MSG_ERROR;
5280 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5281 if (objt_server(s->target))
5282 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5283 goto end;
5284 }
5285 return;
5286 }
5287
5288 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5289 http_msg_closed:
5290 /* drop any pending data */
Christopher Fauletf3d48052018-12-04 16:23:54 +01005291 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005292 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005293 goto end;
5294 }
5295
5296 check_channel_flags:
5297 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5298 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5299 /* if we've just closed an output, let's switch */
5300 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5301 goto http_msg_closing;
5302 }
5303
5304 end:
5305 chn->analysers &= AN_RES_FLT_END;
5306 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5307 chn->analysers |= AN_RES_FLT_XFER_DATA;
5308 channel_auto_close(chn);
5309 channel_auto_read(chn);
5310}
5311
Christopher Faulet0f226952018-10-22 09:29:56 +02005312void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5313 int finst, const struct buffer *msg)
5314{
5315 channel_auto_read(si_oc(si));
5316 channel_abort(si_oc(si));
5317 channel_auto_close(si_oc(si));
5318 channel_erase(si_oc(si));
5319 channel_auto_close(si_ic(si));
5320 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005321
5322 /* <msg> is an HTX structure. So we copy it in the response's
5323 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005324 if (msg) {
5325 struct channel *chn = si_ic(si);
5326 struct htx *htx;
5327
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005328 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005329 chn->buf.data = msg->data;
5330 memcpy(chn->buf.area, msg->area, msg->data);
5331 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005332 c_adv(chn, htx->data);
5333 chn->total += htx->data;
5334 }
5335 if (!(s->flags & SF_ERR_MASK))
5336 s->flags |= err;
5337 if (!(s->flags & SF_FINST_MASK))
5338 s->flags |= finst;
5339}
5340
5341void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5342{
5343 channel_auto_read(&s->req);
5344 channel_abort(&s->req);
5345 channel_auto_close(&s->req);
5346 channel_erase(&s->req);
5347 channel_truncate(&s->res);
5348
5349 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005350
5351 /* <msg> is an HTX structure. So we copy it in the response's
5352 * channel */
5353 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005354 if (msg) {
5355 struct channel *chn = &s->res;
5356 struct htx *htx;
5357
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005358 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005359 chn->buf.data = msg->data;
5360 memcpy(chn->buf.area, msg->area, msg->data);
5361 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005362 c_adv(chn, htx->data);
5363 chn->total += htx->data;
5364 }
5365
5366 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5367 channel_auto_read(&s->res);
5368 channel_auto_close(&s->res);
5369 channel_shutr_now(&s->res);
5370}
5371
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005372struct buffer *htx_error_message(struct stream *s)
5373{
5374 const int msgnum = http_get_status_idx(s->txn->status);
5375
5376 if (s->be->errmsg[msgnum].area)
5377 return &s->be->errmsg[msgnum];
5378 else if (strm_fe(s)->errmsg[msgnum].area)
5379 return &strm_fe(s)->errmsg[msgnum];
5380 else
5381 return &htx_err_chunks[msgnum];
5382}
5383
5384
Christopher Faulet23a3c792018-11-28 10:01:23 +01005385/* Send a 100-Continue response to the client. It returns 0 on success and -1
5386 * on error. The response channel is updated accordingly.
5387 */
5388static int htx_reply_100_continue(struct stream *s)
5389{
5390 struct channel *res = &s->res;
5391 struct htx *htx = htx_from_buf(&res->buf);
5392 struct htx_sl *sl;
5393 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5394 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5395 size_t data;
5396
5397 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5398 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5399 if (!sl)
5400 goto fail;
5401 sl->info.res.status = 100;
5402
5403 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5404 goto fail;
5405
5406 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005407 c_adv(res, data);
5408 res->total += data;
5409 return 0;
5410
5411 fail:
5412 /* If an error occurred, remove the incomplete HTTP response from the
5413 * buffer */
5414 channel_truncate(res);
5415 return -1;
5416}
5417
Christopher Faulet12c51e22018-11-28 15:59:42 +01005418
5419/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5420 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5421 * error. The response channel is updated accordingly.
5422 */
5423static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5424{
5425 struct channel *res = &s->res;
5426 struct htx *htx = htx_from_buf(&res->buf);
5427 struct htx_sl *sl;
5428 struct ist code, body;
5429 int status;
5430 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5431 size_t data;
5432
5433 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5434 status = 401;
5435 code = ist("401");
5436 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5437 "You need a valid user and password to access this content.\n"
5438 "</body></html>\n");
5439 }
5440 else {
5441 status = 407;
5442 code = ist("407");
5443 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5444 "You need a valid user and password to access this content.\n"
5445 "</body></html>\n");
5446 }
5447
5448 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5449 ist("HTTP/1.1"), code, ist("Unauthorized"));
5450 if (!sl)
5451 goto fail;
5452 sl->info.res.status = status;
5453 s->txn->status = status;
5454
5455 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5456 goto fail;
5457
5458 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5459 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5460 !htx_add_header(htx, ist("Content-Type"), ist("text/html")) ||
5461 !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
5462 goto fail;
5463
5464 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5465 goto fail;
5466
5467 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005468 c_adv(res, data);
5469 res->total += data;
5470
5471 channel_auto_read(&s->req);
5472 channel_abort(&s->req);
5473 channel_auto_close(&s->req);
5474 channel_erase(&s->req);
5475
5476 res->wex = tick_add_ifset(now_ms, res->wto);
5477 channel_auto_read(res);
5478 channel_auto_close(res);
5479 channel_shutr_now(res);
5480 return 0;
5481
5482 fail:
5483 /* If an error occurred, remove the incomplete HTTP response from the
5484 * buffer */
5485 channel_truncate(res);
5486 return -1;
5487}
5488
Christopher Faulet0f226952018-10-22 09:29:56 +02005489/*
5490 * Capture headers from message <htx> according to header list <cap_hdr>, and
5491 * fill the <cap> pointers appropriately.
5492 */
5493static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5494{
5495 struct cap_hdr *h;
5496 int32_t pos;
5497
5498 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5499 struct htx_blk *blk = htx_get_blk(htx, pos);
5500 enum htx_blk_type type = htx_get_blk_type(blk);
5501 struct ist n, v;
5502
5503 if (type == HTX_BLK_EOH)
5504 break;
5505 if (type != HTX_BLK_HDR)
5506 continue;
5507
5508 n = htx_get_blk_name(htx, blk);
5509
5510 for (h = cap_hdr; h; h = h->next) {
5511 if (h->namelen && (h->namelen == n.len) &&
5512 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5513 if (cap[h->index] == NULL)
5514 cap[h->index] =
5515 pool_alloc(h->pool);
5516
5517 if (cap[h->index] == NULL) {
5518 ha_alert("HTTP capture : out of memory.\n");
5519 break;
5520 }
5521
5522 v = htx_get_blk_value(htx, blk);
5523 if (v.len > h->len)
5524 v.len = h->len;
5525
5526 memcpy(cap[h->index], v.ptr, v.len);
5527 cap[h->index][v.len]=0;
5528 }
5529 }
5530 }
5531}
5532
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005533/* Delete a value in a header between delimiters <from> and <next>. The header
5534 * itself is delimited by <start> and <end> pointers. The number of characters
5535 * displaced is returned, and the pointer to the first delimiter is updated if
5536 * required. The function tries as much as possible to respect the following
5537 * principles :
5538 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5539 * in which case <next> is simply removed
5540 * - set exactly one space character after the new first delimiter, unless there
5541 * are not enough characters in the block being moved to do so.
5542 * - remove unneeded spaces before the previous delimiter and after the new
5543 * one.
5544 *
5545 * It is the caller's responsibility to ensure that :
5546 * - <from> points to a valid delimiter or <start> ;
5547 * - <next> points to a valid delimiter or <end> ;
5548 * - there are non-space chars before <from>.
5549 */
5550static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5551{
5552 char *prev = *from;
5553
5554 if (prev == start) {
5555 /* We're removing the first value. eat the semicolon, if <next>
5556 * is lower than <end> */
5557 if (next < end)
5558 next++;
5559
5560 while (next < end && HTTP_IS_SPHT(*next))
5561 next++;
5562 }
5563 else {
5564 /* Remove useless spaces before the old delimiter. */
5565 while (HTTP_IS_SPHT(*(prev-1)))
5566 prev--;
5567 *from = prev;
5568
5569 /* copy the delimiter and if possible a space if we're
5570 * not at the end of the line.
5571 */
5572 if (next < end) {
5573 *prev++ = *next++;
5574 if (prev + 1 < next)
5575 *prev++ = ' ';
5576 while (next < end && HTTP_IS_SPHT(*next))
5577 next++;
5578 }
5579 }
5580 memmove(prev, next, end - next);
5581 return (prev - next);
5582}
5583
Christopher Faulet0f226952018-10-22 09:29:56 +02005584
5585/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005586 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005587 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005588static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005589{
5590 struct ist dst = ist2(str, 0);
5591
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005592 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005593 goto end;
5594 if (dst.len + 1 > len)
5595 goto end;
5596 dst.ptr[dst.len++] = ' ';
5597
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005598 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005599 goto end;
5600 if (dst.len + 1 > len)
5601 goto end;
5602 dst.ptr[dst.len++] = ' ';
5603
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005604 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005605 end:
5606 return dst.len;
5607}
5608
Christopher Fauletf0523542018-10-24 11:06:58 +02005609/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005610 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005611 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005612static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005613{
5614 struct ist dst = ist2(str, 0);
5615
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005616 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005617 goto end;
5618 if (dst.len + 1 > len)
5619 goto end;
5620 dst.ptr[dst.len++] = ' ';
5621
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005622 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005623 goto end;
5624 if (dst.len + 1 > len)
5625 goto end;
5626 dst.ptr[dst.len++] = ' ';
5627
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005628 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005629 end:
5630 return dst.len;
5631}
5632
5633
Christopher Faulet0f226952018-10-22 09:29:56 +02005634/*
5635 * Print a debug line with a start line.
5636 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005638{
5639 struct session *sess = strm_sess(s);
5640 int max;
5641
5642 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5643 dir,
5644 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5645 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5646
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005647 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005648 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005649 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005650 trash.area[trash.data++] = ' ';
5651
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005652 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005654 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005655 trash.area[trash.data++] = ' ';
5656
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005657 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005658 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005659 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005660 trash.area[trash.data++] = '\n';
5661
5662 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5663}
5664
5665/*
5666 * Print a debug line with a header.
5667 */
5668static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5669{
5670 struct session *sess = strm_sess(s);
5671 int max;
5672
5673 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5674 dir,
5675 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5676 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5677
5678 max = n.len;
5679 UBOUND(max, trash.size - trash.data - 3);
5680 chunk_memcat(&trash, n.ptr, max);
5681 trash.area[trash.data++] = ':';
5682 trash.area[trash.data++] = ' ';
5683
5684 max = v.len;
5685 UBOUND(max, trash.size - trash.data - 1);
5686 chunk_memcat(&trash, v.ptr, max);
5687 trash.area[trash.data++] = '\n';
5688
5689 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5690}
5691
5692
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005693__attribute__((constructor))
5694static void __htx_protocol_init(void)
5695{
5696}
5697
5698
5699/*
5700 * Local variables:
5701 * c-indent-level: 8
5702 * c-basic-offset: 8
5703 * End:
5704 */