blob: 86bf38eb9965ec59ad68c5eee8cf64aa45fe366a [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>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010016#include <common/htx.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020017#include <common/uri_auth.h>
18
19#include <types/cache.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020020#include <types/capture.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020021
22#include <proto/acl.h>
Christopher Faulet3e964192018-10-24 11:39:23 +020023#include <proto/action.h>
Christopher Faulete0768eb2018-10-03 16:38:02 +020024#include <proto/channel.h>
25#include <proto/checks.h>
26#include <proto/connection.h>
27#include <proto/filters.h>
28#include <proto/hdr_idx.h>
Christopher Faulet0f226952018-10-22 09:29:56 +020029#include <proto/http_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 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100228
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 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100235 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200236 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100237
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)) {
607 /* process the stats request now */
608 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
609 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
610
611 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
612 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
613 if (!(s->flags & SF_FINST_MASK))
614 s->flags |= SF_FINST_R;
615
616 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
617 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
618 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
619 req->analysers |= AN_REQ_HTTP_XFER_BODY;
620 goto done;
621 }
622
623 /* check whether we have some ACLs set to redirect this request */
624 list_for_each_entry(rule, &px->redirect_rules, list) {
625 if (rule->cond) {
626 int ret;
627
628 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
629 ret = acl_pass(ret);
630 if (rule->cond->pol == ACL_COND_UNLESS)
631 ret = !ret;
632 if (!ret)
633 continue;
634 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200635 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200636 goto return_bad_req;
637 goto done;
638 }
639
640 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
641 * If this happens, then the data will not come immediately, so we must
642 * send all what we have without waiting. Note that due to the small gain
643 * in waiting for the body of the request, it's easier to simply put the
644 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
645 * itself once used.
646 */
647 req->flags |= CF_SEND_DONTWAIT;
648
649 done: /* done with this analyser, continue with next ones that the calling
650 * points will have set, if any.
651 */
652 req->analyse_exp = TICK_ETERNITY;
653 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
654 req->analysers &= ~an_bit;
655 return 1;
656
657 tarpit:
658 /* Allow cookie logging
659 */
660 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200661 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200662
663 /* When a connection is tarpitted, we use the tarpit timeout,
664 * which may be the same as the connect timeout if unspecified.
665 * If unset, then set it to zero because we really want it to
666 * eventually expire. We build the tarpit as an analyser.
667 */
668 channel_erase(&s->req);
669
670 /* wipe the request out so that we can drop the connection early
671 * if the client closes first.
672 */
673 channel_dont_connect(req);
674
675 txn->status = http_err_codes[deny_status];
676
677 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
678 req->analysers |= AN_REQ_HTTP_TARPIT;
679 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
680 if (!req->analyse_exp)
681 req->analyse_exp = tick_add(now_ms, 0);
682 stream_inc_http_err_ctr(s);
683 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
684 if (sess->fe != s->be)
685 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
686 if (sess->listener->counters)
687 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
688 goto done_without_exp;
689
690 deny: /* this request was blocked (denied) */
691
692 /* Allow cookie logging
693 */
694 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200695 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200696
697 txn->flags |= TX_CLDENY;
698 txn->status = http_err_codes[deny_status];
699 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100700 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200701 stream_inc_http_err_ctr(s);
702 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
703 if (sess->fe != s->be)
704 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
705 if (sess->listener->counters)
706 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
707 goto return_prx_cond;
708
709 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200710 txn->req.err_state = txn->req.msg_state;
711 txn->req.msg_state = HTTP_MSG_ERROR;
712 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100713 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200714
715 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
716 if (sess->listener->counters)
717 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
718
719 return_prx_cond:
720 if (!(s->flags & SF_ERR_MASK))
721 s->flags |= SF_ERR_PRXCOND;
722 if (!(s->flags & SF_FINST_MASK))
723 s->flags |= SF_FINST_R;
724
725 req->analysers &= AN_REQ_FLT_END;
726 req->analyse_exp = TICK_ETERNITY;
727 return 0;
728
729 return_prx_yield:
730 channel_dont_connect(req);
731 return 0;
732}
733
734/* This function performs all the processing enabled for the current request.
735 * It returns 1 if the processing can continue on next analysers, or zero if it
736 * needs more data, encounters an error, or wants to immediately abort the
737 * request. It relies on buffers flags, and updates s->req.analysers.
738 */
739int htx_process_request(struct stream *s, struct channel *req, int an_bit)
740{
741 struct session *sess = s->sess;
742 struct http_txn *txn = s->txn;
743 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200744 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200745 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
746
747 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
748 /* we need more data */
749 channel_dont_connect(req);
750 return 0;
751 }
752
753 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
754 now_ms, __FUNCTION__,
755 s,
756 req,
757 req->rex, req->wex,
758 req->flags,
759 ci_data(req),
760 req->analysers);
761
762 /*
763 * Right now, we know that we have processed the entire headers
764 * and that unwanted requests have been filtered out. We can do
765 * whatever we want with the remaining request. Also, now we
766 * may have separate values for ->fe, ->be.
767 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100768 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200769
770 /*
771 * If HTTP PROXY is set we simply get remote server address parsing
772 * incoming request. Note that this requires that a connection is
773 * allocated on the server side.
774 */
775 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
776 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100777 struct htx_sl *sl;
778 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200779
780 /* Note that for now we don't reuse existing proxy connections */
781 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
782 txn->req.err_state = txn->req.msg_state;
783 txn->req.msg_state = HTTP_MSG_ERROR;
784 txn->status = 500;
785 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100786 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200787
788 if (!(s->flags & SF_ERR_MASK))
789 s->flags |= SF_ERR_RESOURCE;
790 if (!(s->flags & SF_FINST_MASK))
791 s->flags |= SF_FINST_R;
792
793 return 0;
794 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200795 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100796 uri = htx_sl_req_uri(sl);
797 path = http_get_path(uri);
798 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200799 goto return_bad_req;
800
801 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200802 * uri.ptr and path.ptr (excluded). If it was not found, we need
803 * to replace from all the uri by a single "/".
804 *
805 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100806 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200807 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200808 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100809 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200810 }
811
812 /*
813 * 7: Now we can work with the cookies.
814 * Note that doing so might move headers in the request, but
815 * the fields will stay coherent and the URI will not move.
816 * This should only be performed in the backend.
817 */
818 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100819 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200820
821 /* add unique-id if "header-unique-id" is specified */
822
823 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
824 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
825 goto return_bad_req;
826 s->unique_id[0] = '\0';
827 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
828 }
829
830 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200831 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
832 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
833
834 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200835 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200836 }
837
838 /*
839 * 9: add X-Forwarded-For if either the frontend or the backend
840 * asks for it.
841 */
842 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200843 struct http_hdr_ctx ctx = { .blk = NULL };
844 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
845 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
846
Christopher Faulete0768eb2018-10-03 16:38:02 +0200847 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200848 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200849 /* The header is set to be added only if none is present
850 * and we found it, so don't do anything.
851 */
852 }
853 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
854 /* Add an X-Forwarded-For header unless the source IP is
855 * in the 'except' network range.
856 */
857 if ((!sess->fe->except_mask.s_addr ||
858 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
859 != sess->fe->except_net.s_addr) &&
860 (!s->be->except_mask.s_addr ||
861 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
862 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200863 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200864
865 /* Note: we rely on the backend to get the header name to be used for
866 * x-forwarded-for, because the header is really meant for the backends.
867 * However, if the backend did not specify any option, we have to rely
868 * on the frontend's header name.
869 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200870 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
871 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200872 goto return_bad_req;
873 }
874 }
875 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
876 /* FIXME: for the sake of completeness, we should also support
877 * 'except' here, although it is mostly useless in this case.
878 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200879 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200880
Christopher Faulete0768eb2018-10-03 16:38:02 +0200881 inet_ntop(AF_INET6,
882 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
883 pn, sizeof(pn));
884
885 /* Note: we rely on the backend to get the header name to be used for
886 * x-forwarded-for, because the header is really meant for the backends.
887 * However, if the backend did not specify any option, we have to rely
888 * on the frontend's header name.
889 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200890 chunk_printf(&trash, "%s", pn);
891 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200892 goto return_bad_req;
893 }
894 }
895
896 /*
897 * 10: add X-Original-To if either the frontend or the backend
898 * asks for it.
899 */
900 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
901
902 /* FIXME: don't know if IPv6 can handle that case too. */
903 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
904 /* Add an X-Original-To header unless the destination IP is
905 * in the 'except' network range.
906 */
907 conn_get_to_addr(cli_conn);
908
909 if (cli_conn->addr.to.ss_family == AF_INET &&
910 ((!sess->fe->except_mask_to.s_addr ||
911 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
912 != sess->fe->except_to.s_addr) &&
913 (!s->be->except_mask_to.s_addr ||
914 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
915 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200916 struct ist hdr;
917 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200918
919 /* Note: we rely on the backend to get the header name to be used for
920 * x-original-to, because the header is really meant for the backends.
921 * However, if the backend did not specify any option, we have to rely
922 * on the frontend's header name.
923 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200924 if (s->be->orgto_hdr_len)
925 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
926 else
927 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200929 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
930 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931 goto return_bad_req;
932 }
933 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 }
935
Christopher Faulete0768eb2018-10-03 16:38:02 +0200936 /* If we have no server assigned yet and we're balancing on url_param
937 * with a POST request, we may be interested in checking the body for
938 * that parameter. This will be done in another analyser.
939 */
940 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200941 s->txn->meth == HTTP_METH_POST && s->be->url_param_name != NULL) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200942 channel_dont_connect(req);
943 req->analysers |= AN_REQ_HTTP_BODY;
944 }
945
946 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
947 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100948
Christopher Faulete0768eb2018-10-03 16:38:02 +0200949 /* We expect some data from the client. Unless we know for sure
950 * we already have a full request, we have to re-enable quick-ack
951 * in case we previously disabled it, otherwise we might cause
952 * the client to delay further data.
953 */
954 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200955 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100956 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200957
958 /*************************************************************
959 * OK, that's finished for the headers. We have done what we *
960 * could. Let's switch to the DATA state. *
961 ************************************************************/
962 req->analyse_exp = TICK_ETERNITY;
963 req->analysers &= ~an_bit;
964
965 s->logs.tv_request = now;
966 /* OK let's go on with the BODY now */
967 return 1;
968
969 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200970 txn->req.err_state = txn->req.msg_state;
971 txn->req.msg_state = HTTP_MSG_ERROR;
972 txn->status = 400;
973 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100974 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200975
976 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
977 if (sess->listener->counters)
978 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
979
980 if (!(s->flags & SF_ERR_MASK))
981 s->flags |= SF_ERR_PRXCOND;
982 if (!(s->flags & SF_FINST_MASK))
983 s->flags |= SF_FINST_R;
984 return 0;
985}
986
987/* This function is an analyser which processes the HTTP tarpit. It always
988 * returns zero, at the beginning because it prevents any other processing
989 * from occurring, and at the end because it terminates the request.
990 */
991int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
992{
993 struct http_txn *txn = s->txn;
994
995 /* This connection is being tarpitted. The CLIENT side has
996 * already set the connect expiration date to the right
997 * timeout. We just have to check that the client is still
998 * there and that the timeout has not expired.
999 */
1000 channel_dont_connect(req);
1001 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1002 !tick_is_expired(req->analyse_exp, now_ms))
1003 return 0;
1004
1005 /* We will set the queue timer to the time spent, just for
1006 * logging purposes. We fake a 500 server error, so that the
1007 * attacker will not suspect his connection has been tarpitted.
1008 * It will not cause trouble to the logs because we can exclude
1009 * the tarpitted connections by filtering on the 'PT' status flags.
1010 */
1011 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1012
1013 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001014 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001015
1016 req->analysers &= AN_REQ_FLT_END;
1017 req->analyse_exp = TICK_ETERNITY;
1018
1019 if (!(s->flags & SF_ERR_MASK))
1020 s->flags |= SF_ERR_PRXCOND;
1021 if (!(s->flags & SF_FINST_MASK))
1022 s->flags |= SF_FINST_T;
1023 return 0;
1024}
1025
1026/* This function is an analyser which waits for the HTTP request body. It waits
1027 * for either the buffer to be full, or the full advertised contents to have
1028 * reached the buffer. It must only be called after the standard HTTP request
1029 * processing has occurred, because it expects the request to be parsed and will
1030 * look for the Expect header. It may send a 100-Continue interim response. It
1031 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1032 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1033 * needs to read more data, or 1 once it has completed its analysis.
1034 */
1035int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1036{
1037 struct session *sess = s->sess;
1038 struct http_txn *txn = s->txn;
1039 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001040 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001041
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001042
1043 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1044 now_ms, __FUNCTION__,
1045 s,
1046 req,
1047 req->rex, req->wex,
1048 req->flags,
1049 ci_data(req),
1050 req->analysers);
1051
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001052 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053
1054 if (msg->msg_state < HTTP_MSG_BODY)
1055 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001056
Christopher Faulete0768eb2018-10-03 16:38:02 +02001057 /* We have to parse the HTTP request body to find any required data.
1058 * "balance url_param check_post" should have been the only way to get
1059 * into this. We were brought here after HTTP header analysis, so all
1060 * related structures are ready.
1061 */
1062
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001063 if (msg->msg_state < HTTP_MSG_DATA) {
1064 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1065 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001066 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001067 if (msg->flags & HTTP_MSGF_VER_11) {
1068 struct ist hdr = { .ptr = "Expect", .len = 6 };
1069 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001070
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 ctx.blk = NULL;
1072 /* Expect is allowed in 1.1, look for it */
1073 if (http_find_header(htx, hdr, &ctx, 0) &&
1074 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001075 if (htx_reply_100_continue(s) == -1)
1076 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001077 http_remove_header(htx, &ctx);
1078 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001079 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 }
1081
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001082 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001084 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1085 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001086 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001087 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1088 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001089 goto http_end;
1090
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001092 if (htx->flags & HTX_FL_PARSING_ERROR)
1093 goto return_bad_req;
1094
Christopher Faulete0768eb2018-10-03 16:38:02 +02001095 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1096 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001097 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001098
1099 if (!(s->flags & SF_ERR_MASK))
1100 s->flags |= SF_ERR_CLITO;
1101 if (!(s->flags & SF_FINST_MASK))
1102 s->flags |= SF_FINST_D;
1103 goto return_err_msg;
1104 }
1105
1106 /* we get here if we need to wait for more data */
1107 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1108 /* Not enough data. We'll re-use the http-request
1109 * timeout here. Ideally, we should set the timeout
1110 * relative to the accept() date. We just set the
1111 * request timeout once at the beginning of the
1112 * request.
1113 */
1114 channel_dont_connect(req);
1115 if (!tick_isset(req->analyse_exp))
1116 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1117 return 0;
1118 }
1119
1120 http_end:
1121 /* The situation will not evolve, so let's give up on the analysis. */
1122 s->logs.tv_request = now; /* update the request timer to reflect full request */
1123 req->analysers &= ~an_bit;
1124 req->analyse_exp = TICK_ETERNITY;
1125 return 1;
1126
1127 return_bad_req: /* let's centralize all bad requests */
1128 txn->req.err_state = txn->req.msg_state;
1129 txn->req.msg_state = HTTP_MSG_ERROR;
1130 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001131 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001132
1133 if (!(s->flags & SF_ERR_MASK))
1134 s->flags |= SF_ERR_PRXCOND;
1135 if (!(s->flags & SF_FINST_MASK))
1136 s->flags |= SF_FINST_R;
1137
1138 return_err_msg:
1139 req->analysers &= AN_REQ_FLT_END;
1140 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1141 if (sess->listener->counters)
1142 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1143 return 0;
1144}
1145
1146/* This function is an analyser which forwards request body (including chunk
1147 * sizes if any). It is called as soon as we must forward, even if we forward
1148 * zero byte. The only situation where it must not be called is when we're in
1149 * tunnel mode and we want to forward till the close. It's used both to forward
1150 * remaining data and to resync after end of body. It expects the msg_state to
1151 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1152 * read more data, or 1 once we can go on with next request or end the stream.
1153 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1154 * bytes of pending data + the headers if not already done.
1155 */
1156int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1157{
1158 struct session *sess = s->sess;
1159 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001160 struct http_msg *msg = &txn->req;
1161 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001162 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001163
1164 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1165 now_ms, __FUNCTION__,
1166 s,
1167 req,
1168 req->rex, req->wex,
1169 req->flags,
1170 ci_data(req),
1171 req->analysers);
1172
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001173 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001174
1175 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1176 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1177 /* Output closed while we were sending data. We must abort and
1178 * wake the other side up.
1179 */
1180 msg->err_state = msg->msg_state;
1181 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001182 htx_end_request(s);
1183 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001184 return 1;
1185 }
1186
1187 /* Note that we don't have to send 100-continue back because we don't
1188 * need the data to complete our job, and it's up to the server to
1189 * decide whether to return 100, 417 or anything else in return of
1190 * an "Expect: 100-continue" header.
1191 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001192 if (msg->msg_state == HTTP_MSG_BODY)
1193 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001194
1195 /* Some post-connect processing might want us to refrain from starting to
1196 * forward data. Currently, the only reason for this is "balance url_param"
1197 * whichs need to parse/process the request after we've enabled forwarding.
1198 */
1199 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1200 if (!(s->res.flags & CF_READ_ATTACHED)) {
1201 channel_auto_connect(req);
1202 req->flags |= CF_WAKE_CONNECT;
1203 channel_dont_close(req); /* don't fail on early shutr */
1204 goto waiting;
1205 }
1206 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1207 }
1208
1209 /* in most states, we should abort in case of early close */
1210 channel_auto_close(req);
1211
1212 if (req->to_forward) {
1213 /* We can't process the buffer's contents yet */
1214 req->flags |= CF_WAKE_WRITE;
1215 goto missing_data_or_waiting;
1216 }
1217
Christopher Faulet9768c262018-10-22 09:34:31 +02001218 if (msg->msg_state >= HTTP_MSG_DONE)
1219 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001220 /* Forward input data. We get it by removing all outgoing data not
1221 * forwarded yet from HTX data size. If there are some data filters, we
1222 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001223 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 if (HAS_REQ_DATA_FILTERS(s)) {
1225 ret = flt_http_payload(s, msg, htx->data);
1226 if (ret < 0)
1227 goto return_bad_req;
1228 c_adv(req, ret);
1229 if (htx->data != co_data(req) || htx->extra)
1230 goto missing_data_or_waiting;
1231 }
1232 else {
1233 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001234
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001235 /* To let the function channel_forward work as expected we must update
1236 * the channel's buffer to pretend there is no more input data. The
1237 * right length is then restored. We must do that, because when an HTX
1238 * message is stored into a buffer, it appears as full.
1239 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001240 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1241 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001242 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001243
Christopher Faulet9768c262018-10-22 09:34:31 +02001244 /* Check if the end-of-message is reached and if so, switch the message
1245 * in HTTP_MSG_DONE state.
1246 */
1247 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1248 goto missing_data_or_waiting;
1249
1250 msg->msg_state = HTTP_MSG_DONE;
1251
1252 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001253 /* other states, DONE...TUNNEL */
1254 /* we don't want to forward closes on DONE except in tunnel mode. */
1255 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1256 channel_dont_close(req);
1257
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001258 if (HAS_REQ_DATA_FILTERS(s)) {
1259 ret = flt_http_end(s, msg);
1260 if (ret <= 0) {
1261 if (!ret)
1262 goto missing_data_or_waiting;
1263 goto return_bad_req;
1264 }
1265 }
1266
Christopher Fauletf2824e62018-10-01 12:12:37 +02001267 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001268 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001269 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001270 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1271 if (req->flags & CF_SHUTW) {
1272 /* request errors are most likely due to the
1273 * server aborting the transfer. */
1274 goto aborted_xfer;
1275 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001276 goto return_bad_req;
1277 }
1278 return 1;
1279 }
1280
1281 /* If "option abortonclose" is set on the backend, we want to monitor
1282 * the client's connection and forward any shutdown notification to the
1283 * server, which will decide whether to close or to go on processing the
1284 * request. We only do that in tunnel mode, and not in other modes since
1285 * it can be abused to exhaust source ports. */
1286 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1287 channel_auto_read(req);
1288 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1289 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1290 s->si[1].flags |= SI_FL_NOLINGER;
1291 channel_auto_close(req);
1292 }
1293 else if (s->txn->meth == HTTP_METH_POST) {
1294 /* POST requests may require to read extra CRLF sent by broken
1295 * browsers and which could cause an RST to be sent upon close
1296 * on some systems (eg: Linux). */
1297 channel_auto_read(req);
1298 }
1299 return 0;
1300
1301 missing_data_or_waiting:
1302 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001303 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001304 if (!(s->flags & SF_ERR_MASK))
1305 s->flags |= SF_ERR_CLICL;
1306 if (!(s->flags & SF_FINST_MASK)) {
1307 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1308 s->flags |= SF_FINST_H;
1309 else
1310 s->flags |= SF_FINST_D;
1311 }
1312
1313 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1314 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1315 if (objt_server(s->target))
1316 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1317
1318 goto return_bad_req_stats_ok;
1319 }
1320
1321 waiting:
1322 /* waiting for the last bits to leave the buffer */
1323 if (req->flags & CF_SHUTW)
1324 goto aborted_xfer;
1325
Christopher Faulet47365272018-10-31 17:40:50 +01001326 if (htx->flags & HTX_FL_PARSING_ERROR)
1327 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001328
Christopher Faulete0768eb2018-10-03 16:38:02 +02001329 /* When TE: chunked is used, we need to get there again to parse remaining
1330 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1331 * And when content-length is used, we never want to let the possible
1332 * shutdown be forwarded to the other side, as the state machine will
1333 * take care of it once the client responds. It's also important to
1334 * prevent TIME_WAITs from accumulating on the backend side, and for
1335 * HTTP/2 where the last frame comes with a shutdown.
1336 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001337 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001338 channel_dont_close(req);
1339
1340 /* We know that more data are expected, but we couldn't send more that
1341 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1342 * system knows it must not set a PUSH on this first part. Interactive
1343 * modes are already handled by the stream sock layer. We must not do
1344 * this in content-length mode because it could present the MSG_MORE
1345 * flag with the last block of forwarded data, which would cause an
1346 * additional delay to be observed by the receiver.
1347 */
1348 if (msg->flags & HTTP_MSGF_TE_CHNK)
1349 req->flags |= CF_EXPECT_MORE;
1350
1351 return 0;
1352
1353 return_bad_req: /* let's centralize all bad requests */
1354 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1355 if (sess->listener->counters)
1356 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1357
1358 return_bad_req_stats_ok:
1359 txn->req.err_state = txn->req.msg_state;
1360 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001361 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001362 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001363 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001364 } else {
1365 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001366 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001367 }
1368 req->analysers &= AN_REQ_FLT_END;
1369 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1370
1371 if (!(s->flags & SF_ERR_MASK))
1372 s->flags |= SF_ERR_PRXCOND;
1373 if (!(s->flags & SF_FINST_MASK)) {
1374 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1375 s->flags |= SF_FINST_H;
1376 else
1377 s->flags |= SF_FINST_D;
1378 }
1379 return 0;
1380
1381 aborted_xfer:
1382 txn->req.err_state = txn->req.msg_state;
1383 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001384 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001385 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001386 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001387 } else {
1388 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001389 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001390 }
1391 req->analysers &= AN_REQ_FLT_END;
1392 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1393
1394 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1395 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1396 if (objt_server(s->target))
1397 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1398
1399 if (!(s->flags & SF_ERR_MASK))
1400 s->flags |= SF_ERR_SRVCL;
1401 if (!(s->flags & SF_FINST_MASK)) {
1402 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1403 s->flags |= SF_FINST_H;
1404 else
1405 s->flags |= SF_FINST_D;
1406 }
1407 return 0;
1408}
1409
1410/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1411 * processing can continue on next analysers, or zero if it either needs more
1412 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1413 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1414 * when it has nothing left to do, and may remove any analyser when it wants to
1415 * abort.
1416 */
1417int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1418{
Christopher Faulet9768c262018-10-22 09:34:31 +02001419 /*
1420 * We will analyze a complete HTTP response to check the its syntax.
1421 *
1422 * Once the start line and all headers are received, we may perform a
1423 * capture of the error (if any), and we will set a few fields. We also
1424 * logging and finally headers capture.
1425 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001426 struct session *sess = s->sess;
1427 struct http_txn *txn = s->txn;
1428 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001429 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001430 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001431 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001432 int n;
1433
1434 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1435 now_ms, __FUNCTION__,
1436 s,
1437 rep,
1438 rep->rex, rep->wex,
1439 rep->flags,
1440 ci_data(rep),
1441 rep->analysers);
1442
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001443 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001444
1445 /*
1446 * Now we quickly check if we have found a full valid response.
1447 * If not so, we check the FD and buffer states before leaving.
1448 * A full response is indicated by the fact that we have seen
1449 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1450 * responses are checked first.
1451 *
1452 * Depending on whether the client is still there or not, we
1453 * may send an error response back or not. Note that normally
1454 * we should only check for HTTP status there, and check I/O
1455 * errors somewhere else.
1456 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001457 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001458 /*
1459 * First catch invalid response
1460 */
1461 if (htx->flags & HTX_FL_PARSING_ERROR)
1462 goto return_bad_res;
1463
Christopher Faulet9768c262018-10-22 09:34:31 +02001464 /* 1: have we encountered a read error ? */
1465 if (rep->flags & CF_READ_ERROR) {
1466 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001467 goto abort_keep_alive;
1468
1469 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1470 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001471 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1472 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001473 }
1474
Christopher Faulete0768eb2018-10-03 16:38:02 +02001475 rep->analysers &= AN_RES_FLT_END;
1476 txn->status = 502;
1477
1478 /* Check to see if the server refused the early data.
1479 * If so, just send a 425
1480 */
1481 if (objt_cs(s->si[1].end)) {
1482 struct connection *conn = objt_cs(s->si[1].end)->conn;
1483
1484 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1485 txn->status = 425;
1486 }
1487
1488 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001489 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001490
1491 if (!(s->flags & SF_ERR_MASK))
1492 s->flags |= SF_ERR_SRVCL;
1493 if (!(s->flags & SF_FINST_MASK))
1494 s->flags |= SF_FINST_H;
1495 return 0;
1496 }
1497
Christopher Faulet9768c262018-10-22 09:34:31 +02001498 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001499 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1501 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001502 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1503 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001504 }
1505
Christopher Faulete0768eb2018-10-03 16:38:02 +02001506 rep->analysers &= AN_RES_FLT_END;
1507 txn->status = 504;
1508 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001509 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001510
1511 if (!(s->flags & SF_ERR_MASK))
1512 s->flags |= SF_ERR_SRVTO;
1513 if (!(s->flags & SF_FINST_MASK))
1514 s->flags |= SF_FINST_H;
1515 return 0;
1516 }
1517
Christopher Faulet9768c262018-10-22 09:34:31 +02001518 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1520 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1521 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1522 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001523 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001524
1525 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001526 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001527 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528
1529 if (!(s->flags & SF_ERR_MASK))
1530 s->flags |= SF_ERR_CLICL;
1531 if (!(s->flags & SF_FINST_MASK))
1532 s->flags |= SF_FINST_H;
1533
1534 /* process_stream() will take care of the error */
1535 return 0;
1536 }
1537
Christopher Faulet9768c262018-10-22 09:34:31 +02001538 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001539 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001540 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001541 goto abort_keep_alive;
1542
1543 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1544 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001545 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1546 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001547 }
1548
Christopher Faulete0768eb2018-10-03 16:38:02 +02001549 rep->analysers &= AN_RES_FLT_END;
1550 txn->status = 502;
1551 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001552 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001553
1554 if (!(s->flags & SF_ERR_MASK))
1555 s->flags |= SF_ERR_SRVCL;
1556 if (!(s->flags & SF_FINST_MASK))
1557 s->flags |= SF_FINST_H;
1558 return 0;
1559 }
1560
Christopher Faulet9768c262018-10-22 09:34:31 +02001561 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001563 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001564 goto abort_keep_alive;
1565
1566 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1567 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001568
1569 if (!(s->flags & SF_ERR_MASK))
1570 s->flags |= SF_ERR_CLICL;
1571 if (!(s->flags & SF_FINST_MASK))
1572 s->flags |= SF_FINST_H;
1573
1574 /* process_stream() will take care of the error */
1575 return 0;
1576 }
1577
1578 channel_dont_close(rep);
1579 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1580 return 0;
1581 }
1582
1583 /* More interesting part now : we know that we have a complete
1584 * response which at least looks like HTTP. We have an indicator
1585 * of each header's length, so we can parse them quickly.
1586 */
1587
Christopher Faulet9768c262018-10-22 09:34:31 +02001588 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001589 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001590
Christopher Faulet9768c262018-10-22 09:34:31 +02001591 /* 0: we might have to print this header in debug mode */
1592 if (unlikely((global.mode & MODE_DEBUG) &&
1593 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1594 int32_t pos;
1595
Christopher Faulet03599112018-11-27 11:21:21 +01001596 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001597
1598 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1599 struct htx_blk *blk = htx_get_blk(htx, pos);
1600 enum htx_blk_type type = htx_get_blk_type(blk);
1601
1602 if (type == HTX_BLK_EOH)
1603 break;
1604 if (type != HTX_BLK_HDR)
1605 continue;
1606
1607 htx_debug_hdr("srvhdr", s,
1608 htx_get_blk_name(htx, blk),
1609 htx_get_blk_value(htx, blk));
1610 }
1611 }
1612
Christopher Faulet03599112018-11-27 11:21:21 +01001613 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001614 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001615 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001616 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001617 if (sl->flags & HTX_SL_F_XFER_LEN) {
1618 msg->flags |= HTTP_MSGF_XFER_LEN;
1619 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001620 if (sl->flags & HTX_SL_F_BODYLESS)
1621 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001622 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001623
1624 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001625 if (n < 1 || n > 5)
1626 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001627
Christopher Faulete0768eb2018-10-03 16:38:02 +02001628 /* when the client triggers a 4xx from the server, it's most often due
1629 * to a missing object or permission. These events should be tracked
1630 * because if they happen often, it may indicate a brute force or a
1631 * vulnerability scan.
1632 */
1633 if (n == 4)
1634 stream_inc_http_err_ctr(s);
1635
1636 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001637 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001638
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639 /* Adjust server's health based on status code. Note: status codes 501
1640 * and 505 are triggered on demand by client request, so we must not
1641 * count them as server failures.
1642 */
1643 if (objt_server(s->target)) {
1644 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001645 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001646 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001647 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 }
1649
1650 /*
1651 * We may be facing a 100-continue response, or any other informational
1652 * 1xx response which is non-final, in which case this is not the right
1653 * response, and we're waiting for the next one. Let's allow this response
1654 * to go to the client and wait for the next one. There's an exception for
1655 * 101 which is used later in the code to switch protocols.
1656 */
1657 if (txn->status < 200 &&
1658 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001659 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001660 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001661 msg->msg_state = HTTP_MSG_RPBEFORE;
1662 txn->status = 0;
1663 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001664 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001665 }
1666
1667 /*
1668 * 2: check for cacheability.
1669 */
1670
1671 switch (txn->status) {
1672 case 200:
1673 case 203:
1674 case 204:
1675 case 206:
1676 case 300:
1677 case 301:
1678 case 404:
1679 case 405:
1680 case 410:
1681 case 414:
1682 case 501:
1683 break;
1684 default:
1685 /* RFC7231#6.1:
1686 * Responses with status codes that are defined as
1687 * cacheable by default (e.g., 200, 203, 204, 206,
1688 * 300, 301, 404, 405, 410, 414, and 501 in this
1689 * specification) can be reused by a cache with
1690 * heuristic expiration unless otherwise indicated
1691 * by the method definition or explicit cache
1692 * controls [RFC7234]; all other status codes are
1693 * not cacheable by default.
1694 */
1695 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1696 break;
1697 }
1698
1699 /*
1700 * 3: we may need to capture headers
1701 */
1702 s->logs.logwait &= ~LW_RESP;
1703 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001704 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001705
Christopher Faulet9768c262018-10-22 09:34:31 +02001706 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001707 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1708 txn->status == 101)) {
1709 /* Either we've established an explicit tunnel, or we're
1710 * switching the protocol. In both cases, we're very unlikely
1711 * to understand the next protocols. We have to switch to tunnel
1712 * mode, so that we transfer the request and responses then let
1713 * this protocol pass unmodified. When we later implement specific
1714 * parsers for such protocols, we'll want to check the Upgrade
1715 * header which contains information about that protocol for
1716 * responses with status 101 (eg: see RFC2817 about TLS).
1717 */
1718 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001719 }
1720
Christopher Faulet61608322018-11-23 16:23:45 +01001721 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1722 * 407 (Proxy-Authenticate) responses and set the connection to private
1723 */
1724 srv_conn = cs_conn(objt_cs(s->si[1].end));
1725 if (srv_conn) {
1726 struct ist hdr;
1727 struct http_hdr_ctx ctx;
1728
1729 if (txn->status == 401)
1730 hdr = ist("WWW-Authenticate");
1731 else if (txn->status == 407)
1732 hdr = ist("Proxy-Authenticate");
1733 else
1734 goto end;
1735
1736 ctx.blk = NULL;
1737 while (http_find_header(htx, hdr, &ctx, 0)) {
1738 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1739 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1740 srv_conn->flags |= CO_FL_PRIVATE;
1741 }
1742 }
1743
1744 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001745 /* we want to have the response time before we start processing it */
1746 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1747
1748 /* end of job, return OK */
1749 rep->analysers &= ~an_bit;
1750 rep->analyse_exp = TICK_ETERNITY;
1751 channel_auto_close(rep);
1752 return 1;
1753
Christopher Faulet47365272018-10-31 17:40:50 +01001754 return_bad_res:
1755 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1756 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001757 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1758 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001759 }
1760 txn->status = 502;
1761 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001762 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001763 rep->analysers &= AN_RES_FLT_END;
1764
1765 if (!(s->flags & SF_ERR_MASK))
1766 s->flags |= SF_ERR_PRXCOND;
1767 if (!(s->flags & SF_FINST_MASK))
1768 s->flags |= SF_FINST_H;
1769 return 0;
1770
Christopher Faulete0768eb2018-10-03 16:38:02 +02001771 abort_keep_alive:
1772 /* A keep-alive request to the server failed on a network error.
1773 * The client is required to retry. We need to close without returning
1774 * any other information so that the client retries.
1775 */
1776 txn->status = 0;
1777 rep->analysers &= AN_RES_FLT_END;
1778 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001779 s->logs.logwait = 0;
1780 s->logs.level = 0;
1781 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001782 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001783 return 0;
1784}
1785
1786/* This function performs all the processing enabled for the current response.
1787 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1788 * and updates s->res.analysers. It might make sense to explode it into several
1789 * other functions. It works like process_request (see indications above).
1790 */
1791int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1792{
1793 struct session *sess = s->sess;
1794 struct http_txn *txn = s->txn;
1795 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001796 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001797 struct proxy *cur_proxy;
1798 struct cond_wordlist *wl;
1799 enum rule_result ret = HTTP_RULE_RES_CONT;
1800
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001801 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1802 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001803
Christopher Faulete0768eb2018-10-03 16:38:02 +02001804 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1805 now_ms, __FUNCTION__,
1806 s,
1807 rep,
1808 rep->rex, rep->wex,
1809 rep->flags,
1810 ci_data(rep),
1811 rep->analysers);
1812
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001813 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001814
1815 /* The stats applet needs to adjust the Connection header but we don't
1816 * apply any filter there.
1817 */
1818 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1819 rep->analysers &= ~an_bit;
1820 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001821 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001822 }
1823
1824 /*
1825 * We will have to evaluate the filters.
1826 * As opposed to version 1.2, now they will be evaluated in the
1827 * filters order and not in the header order. This means that
1828 * each filter has to be validated among all headers.
1829 *
1830 * Filters are tried with ->be first, then with ->fe if it is
1831 * different from ->be.
1832 *
1833 * Maybe we are in resume condiion. In this case I choose the
1834 * "struct proxy" which contains the rule list matching the resume
1835 * pointer. If none of theses "struct proxy" match, I initialise
1836 * the process with the first one.
1837 *
1838 * In fact, I check only correspondance betwwen the current list
1839 * pointer and the ->fe rule list. If it doesn't match, I initialize
1840 * the loop with the ->be.
1841 */
1842 if (s->current_rule_list == &sess->fe->http_res_rules)
1843 cur_proxy = sess->fe;
1844 else
1845 cur_proxy = s->be;
1846 while (1) {
1847 struct proxy *rule_set = cur_proxy;
1848
1849 /* evaluate http-response rules */
1850 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001851 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001852
1853 if (ret == HTTP_RULE_RES_BADREQ)
1854 goto return_srv_prx_502;
1855
1856 if (ret == HTTP_RULE_RES_DONE) {
1857 rep->analysers &= ~an_bit;
1858 rep->analyse_exp = TICK_ETERNITY;
1859 return 1;
1860 }
1861 }
1862
1863 /* we need to be called again. */
1864 if (ret == HTTP_RULE_RES_YIELD) {
1865 channel_dont_close(rep);
1866 return 0;
1867 }
1868
1869 /* try headers filters */
1870 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001871 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1872 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001873 }
1874
1875 /* has the response been denied ? */
1876 if (txn->flags & TX_SVDENY) {
1877 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001878 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001879
1880 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1881 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1882 if (sess->listener->counters)
1883 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001884 goto return_srv_prx_502;
1885 }
1886
1887 /* add response headers from the rule sets in the same order */
1888 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001889 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001890 if (txn->status < 200 && txn->status != 101)
1891 break;
1892 if (wl->cond) {
1893 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1894 ret = acl_pass(ret);
1895 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1896 ret = !ret;
1897 if (!ret)
1898 continue;
1899 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001900
1901 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1902 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001903 goto return_bad_resp;
1904 }
1905
1906 /* check whether we're already working on the frontend */
1907 if (cur_proxy == sess->fe)
1908 break;
1909 cur_proxy = sess->fe;
1910 }
1911
1912 /* After this point, this anayzer can't return yield, so we can
1913 * remove the bit corresponding to this analyzer from the list.
1914 *
1915 * Note that the intermediate returns and goto found previously
1916 * reset the analyzers.
1917 */
1918 rep->analysers &= ~an_bit;
1919 rep->analyse_exp = TICK_ETERNITY;
1920
1921 /* OK that's all we can do for 1xx responses */
1922 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001923 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001924
1925 /*
1926 * Now check for a server cookie.
1927 */
1928 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001929 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001930
1931 /*
1932 * Check for cache-control or pragma headers if required.
1933 */
1934 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1935 check_response_for_cacheability(s, rep);
1936
1937 /*
1938 * Add server cookie in the response if needed
1939 */
1940 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1941 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1942 (!(s->flags & SF_DIRECT) ||
1943 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1944 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1945 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1946 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1947 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1948 !(s->flags & SF_IGNORE_PRST)) {
1949 /* the server is known, it's not the one the client requested, or the
1950 * cookie's last seen date needs to be refreshed. We have to
1951 * insert a set-cookie here, except if we want to insert only on POST
1952 * requests and this one isn't. Note that servers which don't have cookies
1953 * (eg: some backup servers) will return a full cookie removal request.
1954 */
1955 if (!objt_server(s->target)->cookie) {
1956 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001957 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001958 s->be->cookie_name);
1959 }
1960 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001961 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001962
1963 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1964 /* emit last_date, which is mandatory */
1965 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1966 s30tob64((date.tv_sec+3) >> 2,
1967 trash.area + trash.data);
1968 trash.data += 5;
1969
1970 if (s->be->cookie_maxlife) {
1971 /* emit first_date, which is either the original one or
1972 * the current date.
1973 */
1974 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1975 s30tob64(txn->cookie_first_date ?
1976 txn->cookie_first_date >> 2 :
1977 (date.tv_sec+3) >> 2,
1978 trash.area + trash.data);
1979 trash.data += 5;
1980 }
1981 }
1982 chunk_appendf(&trash, "; path=/");
1983 }
1984
1985 if (s->be->cookie_domain)
1986 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1987
1988 if (s->be->ck_opts & PR_CK_HTTPONLY)
1989 chunk_appendf(&trash, "; HttpOnly");
1990
1991 if (s->be->ck_opts & PR_CK_SECURE)
1992 chunk_appendf(&trash, "; Secure");
1993
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001994 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001995 goto return_bad_resp;
1996
1997 txn->flags &= ~TX_SCK_MASK;
1998 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1999 /* the server did not change, only the date was updated */
2000 txn->flags |= TX_SCK_UPDATED;
2001 else
2002 txn->flags |= TX_SCK_INSERTED;
2003
2004 /* Here, we will tell an eventual cache on the client side that we don't
2005 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2006 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2007 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2008 */
2009 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2010
2011 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2012
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002013 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002014 goto return_bad_resp;
2015 }
2016 }
2017
2018 /*
2019 * Check if result will be cacheable with a cookie.
2020 * We'll block the response if security checks have caught
2021 * nasty things such as a cacheable cookie.
2022 */
2023 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2024 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2025 (s->be->options & PR_O_CHK_CACHE)) {
2026 /* we're in presence of a cacheable response containing
2027 * a set-cookie header. We'll block it as requested by
2028 * the 'checkcache' option, and send an alert.
2029 */
2030 if (objt_server(s->target))
2031 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2032
2033 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2034 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2035 if (sess->listener->counters)
2036 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2037
2038 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2039 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2040 send_log(s->be, LOG_ALERT,
2041 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2042 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2043 goto return_srv_prx_502;
2044 }
2045
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002046 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002047 /* Always enter in the body analyzer */
2048 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2049 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2050
2051 /* if the user wants to log as soon as possible, without counting
2052 * bytes from the server, then this is the right moment. We have
2053 * to temporarily assign bytes_out to log what we currently have.
2054 */
2055 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2056 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002057 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002058 s->do_log(s);
2059 s->logs.bytes_out = 0;
2060 }
2061 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062
2063 return_bad_resp:
2064 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002065 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2066 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002067 }
2068 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2069
2070 return_srv_prx_502:
2071 rep->analysers &= AN_RES_FLT_END;
2072 txn->status = 502;
2073 s->logs.t_data = -1; /* was not a valid response */
2074 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002075 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002076 if (!(s->flags & SF_ERR_MASK))
2077 s->flags |= SF_ERR_PRXCOND;
2078 if (!(s->flags & SF_FINST_MASK))
2079 s->flags |= SF_FINST_H;
2080 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002081}
2082
2083/* This function is an analyser which forwards response body (including chunk
2084 * sizes if any). It is called as soon as we must forward, even if we forward
2085 * zero byte. The only situation where it must not be called is when we're in
2086 * tunnel mode and we want to forward till the close. It's used both to forward
2087 * remaining data and to resync after end of body. It expects the msg_state to
2088 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2089 * read more data, or 1 once we can go on with next request or end the stream.
2090 *
2091 * It is capable of compressing response data both in content-length mode and
2092 * in chunked mode. The state machines follows different flows depending on
2093 * whether content-length and chunked modes are used, since there are no
2094 * trailers in content-length :
2095 *
2096 * chk-mode cl-mode
2097 * ,----- BODY -----.
2098 * / \
2099 * V size > 0 V chk-mode
2100 * .--> SIZE -------------> DATA -------------> CRLF
2101 * | | size == 0 | last byte |
2102 * | v final crlf v inspected |
2103 * | TRAILERS -----------> DONE |
2104 * | |
2105 * `----------------------------------------------'
2106 *
2107 * Compression only happens in the DATA state, and must be flushed in final
2108 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2109 * is performed at once on final states for all bytes parsed, or when leaving
2110 * on missing data.
2111 */
2112int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2113{
2114 struct session *sess = s->sess;
2115 struct http_txn *txn = s->txn;
2116 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002117 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002118 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002119
2120 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2121 now_ms, __FUNCTION__,
2122 s,
2123 res,
2124 res->rex, res->wex,
2125 res->flags,
2126 ci_data(res),
2127 res->analysers);
2128
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002129 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002130
2131 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002132 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002133 /* Output closed while we were sending data. We must abort and
2134 * wake the other side up.
2135 */
2136 msg->err_state = msg->msg_state;
2137 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002138 htx_end_response(s);
2139 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002140 return 1;
2141 }
2142
Christopher Faulet9768c262018-10-22 09:34:31 +02002143 if (msg->msg_state == HTTP_MSG_BODY)
2144 msg->msg_state = HTTP_MSG_DATA;
2145
Christopher Faulete0768eb2018-10-03 16:38:02 +02002146 /* in most states, we should abort in case of early close */
2147 channel_auto_close(res);
2148
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 if (res->to_forward) {
2150 /* We can't process the buffer's contents yet */
2151 res->flags |= CF_WAKE_WRITE;
2152 goto missing_data_or_waiting;
2153 }
2154
Christopher Faulet9768c262018-10-22 09:34:31 +02002155 if (msg->msg_state >= HTTP_MSG_DONE)
2156 goto done;
2157
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002158 /* Forward input data. We get it by removing all outgoing data not
2159 * forwarded yet from HTX data size. If there are some data filters, we
2160 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002161 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002162 if (HAS_RSP_DATA_FILTERS(s)) {
2163 ret = flt_http_payload(s, msg, htx->data);
2164 if (ret < 0)
2165 goto return_bad_res;
2166 c_adv(res, ret);
2167 if (htx->data != co_data(res) || htx->extra)
2168 goto missing_data_or_waiting;
2169 }
2170 else {
2171 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002172
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002173 /* To let the function channel_forward work as expected we must update
2174 * the channel's buffer to pretend there is no more input data. The
2175 * right length is then restored. We must do that, because when an HTX
2176 * message is stored into a buffer, it appears as full.
2177 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002178 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2179 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002180 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002181
2182 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2183 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002184 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002185 msg->msg_state = HTTP_MSG_TUNNEL;
2186 goto done;
2187 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002188 }
2189
Christopher Faulet9768c262018-10-22 09:34:31 +02002190 /* Check if the end-of-message is reached and if so, switch the message
2191 * in HTTP_MSG_DONE state.
2192 */
2193 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2194 goto missing_data_or_waiting;
2195
2196 msg->msg_state = HTTP_MSG_DONE;
2197
2198 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002199 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002200 channel_dont_close(res);
2201
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002202 if (HAS_RSP_DATA_FILTERS(s)) {
2203 ret = flt_http_end(s, msg);
2204 if (ret <= 0) {
2205 if (!ret)
2206 goto missing_data_or_waiting;
2207 goto return_bad_res;
2208 }
2209 }
2210
Christopher Fauletf2824e62018-10-01 12:12:37 +02002211 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002213 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002214 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2215 if (res->flags & CF_SHUTW) {
2216 /* response errors are most likely due to the
2217 * client aborting the transfer. */
2218 goto aborted_xfer;
2219 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002220 goto return_bad_res;
2221 }
2222 return 1;
2223 }
2224 return 0;
2225
2226 missing_data_or_waiting:
2227 if (res->flags & CF_SHUTW)
2228 goto aborted_xfer;
2229
Christopher Faulet47365272018-10-31 17:40:50 +01002230 if (htx->flags & HTX_FL_PARSING_ERROR)
2231 goto return_bad_res;
2232
Christopher Faulete0768eb2018-10-03 16:38:02 +02002233 /* stop waiting for data if the input is closed before the end. If the
2234 * client side was already closed, it means that the client has aborted,
2235 * so we don't want to count this as a server abort. Otherwise it's a
2236 * server abort.
2237 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002238 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002239 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2240 goto aborted_xfer;
2241 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002242 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002243 if (!(s->flags & SF_ERR_MASK))
2244 s->flags |= SF_ERR_SRVCL;
2245 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2246 if (objt_server(s->target))
2247 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2248 goto return_bad_res_stats_ok;
2249 }
2250 }
2251
Christopher Faulete0768eb2018-10-03 16:38:02 +02002252 /* When TE: chunked is used, we need to get there again to parse
2253 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002254 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2255 * are filters registered on the stream, we don't want to forward a
2256 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002257 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002258 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002259 channel_dont_close(res);
2260
2261 /* We know that more data are expected, but we couldn't send more that
2262 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2263 * system knows it must not set a PUSH on this first part. Interactive
2264 * modes are already handled by the stream sock layer. We must not do
2265 * this in content-length mode because it could present the MSG_MORE
2266 * flag with the last block of forwarded data, which would cause an
2267 * additional delay to be observed by the receiver.
2268 */
2269 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2270 res->flags |= CF_EXPECT_MORE;
2271
2272 /* the stream handler will take care of timeouts and errors */
2273 return 0;
2274
2275 return_bad_res: /* let's centralize all bad responses */
2276 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2277 if (objt_server(s->target))
2278 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2279
2280 return_bad_res_stats_ok:
2281 txn->rsp.err_state = txn->rsp.msg_state;
2282 txn->rsp.msg_state = HTTP_MSG_ERROR;
2283 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002284 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002285 res->analysers &= AN_RES_FLT_END;
2286 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2287 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002288 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002289
2290 if (!(s->flags & SF_ERR_MASK))
2291 s->flags |= SF_ERR_PRXCOND;
2292 if (!(s->flags & SF_FINST_MASK))
2293 s->flags |= SF_FINST_D;
2294 return 0;
2295
2296 aborted_xfer:
2297 txn->rsp.err_state = txn->rsp.msg_state;
2298 txn->rsp.msg_state = HTTP_MSG_ERROR;
2299 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002300 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002301 res->analysers &= AN_RES_FLT_END;
2302 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2303
2304 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2305 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2306 if (objt_server(s->target))
2307 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2308
2309 if (!(s->flags & SF_ERR_MASK))
2310 s->flags |= SF_ERR_CLICL;
2311 if (!(s->flags & SF_FINST_MASK))
2312 s->flags |= SF_FINST_D;
2313 return 0;
2314}
2315
Christopher Faulet0f226952018-10-22 09:29:56 +02002316void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002317{
2318 struct proxy *fe = strm_fe(s);
2319 int tmp = TX_CON_WANT_CLO;
2320
2321 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2322 tmp = TX_CON_WANT_TUN;
2323
2324 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002325 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002326}
2327
2328/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002329 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002330 * as too large a request to build a valid response.
2331 */
2332int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2333{
Christopher Faulet99daf282018-11-28 22:58:13 +01002334 struct channel *req = &s->req;
2335 struct channel *res = &s->res;
2336 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002337 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002338 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002339 struct ist status, reason, location;
2340 unsigned int flags;
2341 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002342
2343 chunk = alloc_trash_chunk();
2344 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002345 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002346
Christopher Faulet99daf282018-11-28 22:58:13 +01002347 /*
2348 * Create the location
2349 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002350 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002351 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002352 case REDIRECT_TYPE_SCHEME: {
2353 struct http_hdr_ctx ctx;
2354 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 host = ist("");
2357 ctx.blk = NULL;
2358 if (http_find_header(htx, ist("Host"), &ctx, 0))
2359 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002360
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 sl = http_find_stline(htx);
2362 path = http_get_path(htx_sl_req_uri(sl));
2363 /* build message using path */
2364 if (path.ptr) {
2365 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2366 int qs = 0;
2367 while (qs < path.len) {
2368 if (*(path.ptr + qs) == '?') {
2369 path.len = qs;
2370 break;
2371 }
2372 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002373 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374 }
2375 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002376 else
2377 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002378
Christopher Faulet99daf282018-11-28 22:58:13 +01002379 if (rule->rdr_str) { /* this is an old "redirect" rule */
2380 /* add scheme */
2381 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2382 goto fail;
2383 }
2384 else {
2385 /* add scheme with executing log format */
2386 chunk->data += build_logline(s, chunk->area + chunk->data,
2387 chunk->size - chunk->data,
2388 &rule->rdr_fmt);
2389 }
2390 /* add "://" + host + path */
2391 if (!chunk_memcat(chunk, "://", 3) ||
2392 !chunk_memcat(chunk, host.ptr, host.len) ||
2393 !chunk_memcat(chunk, path.ptr, path.len))
2394 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002395
Christopher Faulet99daf282018-11-28 22:58:13 +01002396 /* append a slash at the end of the location if needed and missing */
2397 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2398 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2399 if (chunk->data + 1 >= chunk->size)
2400 goto fail;
2401 chunk->area[chunk->data++] = '/';
2402 }
2403 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405
Christopher Faulet99daf282018-11-28 22:58:13 +01002406 case REDIRECT_TYPE_PREFIX: {
2407 struct ist path;
2408
2409 sl = http_find_stline(htx);
2410 path = http_get_path(htx_sl_req_uri(sl));
2411 /* build message using path */
2412 if (path.ptr) {
2413 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2414 int qs = 0;
2415 while (qs < path.len) {
2416 if (*(path.ptr + qs) == '?') {
2417 path.len = qs;
2418 break;
2419 }
2420 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002421 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422 }
2423 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002424 else
2425 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002426
Christopher Faulet99daf282018-11-28 22:58:13 +01002427 if (rule->rdr_str) { /* this is an old "redirect" rule */
2428 /* add prefix. Note that if prefix == "/", we don't want to
2429 * add anything, otherwise it makes it hard for the user to
2430 * configure a self-redirection.
2431 */
2432 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2433 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2434 goto fail;
2435 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002436 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002437 else {
2438 /* add prefix with executing log format */
2439 chunk->data += build_logline(s, chunk->area + chunk->data,
2440 chunk->size - chunk->data,
2441 &rule->rdr_fmt);
2442 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002443
Christopher Faulet99daf282018-11-28 22:58:13 +01002444 /* add path */
2445 if (!chunk_memcat(chunk, path.ptr, path.len))
2446 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002447
Christopher Faulet99daf282018-11-28 22:58:13 +01002448 /* append a slash at the end of the location if needed and missing */
2449 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2450 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2451 if (chunk->data + 1 >= chunk->size)
2452 goto fail;
2453 chunk->area[chunk->data++] = '/';
2454 }
2455 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002457 case REDIRECT_TYPE_LOCATION:
2458 default:
2459 if (rule->rdr_str) { /* this is an old "redirect" rule */
2460 /* add location */
2461 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2462 goto fail;
2463 }
2464 else {
2465 /* add location with executing log format */
2466 chunk->data += build_logline(s, chunk->area + chunk->data,
2467 chunk->size - chunk->data,
2468 &rule->rdr_fmt);
2469 }
2470 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002471 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002472 location = ist2(chunk->area, chunk->data);
2473
2474 /*
2475 * Create the 30x response
2476 */
2477 switch (rule->code) {
2478 case 308:
2479 status = ist("308");
2480 reason = ist("Permanent Redirect");
2481 break;
2482 case 307:
2483 status = ist("307");
2484 reason = ist("Temporary Redirect");
2485 break;
2486 case 303:
2487 status = ist("303");
2488 reason = ist("See Other");
2489 break;
2490 case 301:
2491 status = ist("301");
2492 reason = ist("Moved Permanently");
2493 break;
2494 case 302:
2495 default:
2496 status = ist("302");
2497 reason = ist("Found");
2498 break;
2499 }
2500
2501 htx = htx_from_buf(&res->buf);
2502 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2503 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2504 if (!sl)
2505 goto fail;
2506 sl->info.res.status = rule->code;
2507 s->txn->status = rule->code;
2508
2509 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2510 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2511 !htx_add_header(htx, ist("Location"), location))
2512 goto fail;
2513
2514 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2515 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2516 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002517 }
2518
2519 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002520 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2521 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002522 }
2523
Christopher Faulet99daf282018-11-28 22:58:13 +01002524 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2525 goto fail;
2526
Christopher Fauletf2824e62018-10-01 12:12:37 +02002527 /* let's log the request time */
2528 s->logs.tv_request = now;
2529
Christopher Faulet99daf282018-11-28 22:58:13 +01002530 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 c_adv(res, data);
2532 res->total += data;
2533
2534 channel_auto_read(req);
2535 channel_abort(req);
2536 channel_auto_close(req);
2537 channel_erase(req);
2538
2539 res->wex = tick_add_ifset(now_ms, res->wto);
2540 channel_auto_read(res);
2541 channel_auto_close(res);
2542 channel_shutr_now(res);
2543
2544 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002545
2546 if (!(s->flags & SF_ERR_MASK))
2547 s->flags |= SF_ERR_LOCAL;
2548 if (!(s->flags & SF_FINST_MASK))
2549 s->flags |= SF_FINST_R;
2550
Christopher Faulet99daf282018-11-28 22:58:13 +01002551 free_trash_chunk(chunk);
2552 return 1;
2553
2554 fail:
2555 /* If an error occurred, remove the incomplete HTTP response from the
2556 * buffer */
2557 channel_truncate(res);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002558 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002559 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002560}
2561
Christopher Faulet72333522018-10-24 11:25:02 +02002562int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2563 struct ist name, const char *str, struct my_regex *re, int action)
2564{
2565 struct http_hdr_ctx ctx;
2566 struct buffer *output = get_trash_chunk();
2567
2568 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2569 ctx.blk = NULL;
2570 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2571 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2572 continue;
2573
2574 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2575 if (output->data == -1)
2576 return -1;
2577 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2578 return -1;
2579 }
2580 return 0;
2581}
2582
2583static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2584 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2585{
2586 struct buffer *replace;
2587 int ret = -1;
2588
2589 replace = alloc_trash_chunk();
2590 if (!replace)
2591 goto leave;
2592
2593 replace->data = build_logline(s, replace->area, replace->size, fmt);
2594 if (replace->data >= replace->size - 1)
2595 goto leave;
2596
2597 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2598
2599 leave:
2600 free_trash_chunk(replace);
2601 return ret;
2602}
2603
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002604
2605/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2606 * on success and -1 on error. The response channel is updated accordingly.
2607 */
2608static int htx_reply_103_early_hints(struct channel *res)
2609{
2610 struct htx *htx = htx_from_buf(&res->buf);
2611 size_t data;
2612
2613 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2614 /* If an error occurred during an Early-hint rule,
2615 * remove the incomplete HTTP 103 response from the
2616 * buffer */
2617 channel_truncate(res);
2618 return -1;
2619 }
2620
2621 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 c_adv(res, data);
2623 res->total += data;
2624 return 0;
2625}
2626
Christopher Faulet6eb92892018-11-15 16:39:29 +01002627/*
2628 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2629 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002630 * If <early_hints> is 0, it is starts a new response by adding the start
2631 * line. If an error occurred -1 is returned. On success 0 is returned. The
2632 * channel is not updated here. It must be done calling the function
2633 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002635static 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 +01002636{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002637 struct channel *res = &s->res;
2638 struct htx *htx = htx_from_buf(&res->buf);
2639 struct buffer *value = alloc_trash_chunk();
2640
Christopher Faulet6eb92892018-11-15 16:39:29 +01002641 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 struct htx_sl *sl;
2643 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2644 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2645
2646 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2647 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2648 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002649 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002650 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002651 }
2652
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002653 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2654 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002655 goto fail;
2656
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002657 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002659
2660 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002661 /* If an error occurred during an Early-hint rule, remove the incomplete
2662 * HTTP 103 response from the buffer */
2663 channel_truncate(res);
2664 free_trash_chunk(value);
2665 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002666}
2667
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002668/* This function executes one of the set-{method,path,query,uri} actions. It
2669 * takes the string from the variable 'replace' with length 'len', then modifies
2670 * the relevant part of the request line accordingly. Then it updates various
2671 * pointers to the next elements which were moved, and the total buffer length.
2672 * It finds the action to be performed in p[2], previously filled by function
2673 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2674 * error, though this can be revisited when this code is finally exploited.
2675 *
2676 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2677 * query string and 3 to replace uri.
2678 *
2679 * In query string case, the mark question '?' must be set at the start of the
2680 * string by the caller, event if the replacement query string is empty.
2681 */
2682int htx_req_replace_stline(int action, const char *replace, int len,
2683 struct proxy *px, struct stream *s)
2684{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002685 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002686
2687 switch (action) {
2688 case 0: // method
2689 if (!http_replace_req_meth(htx, ist2(replace, len)))
2690 return -1;
2691 break;
2692
2693 case 1: // path
2694 if (!http_replace_req_path(htx, ist2(replace, len)))
2695 return -1;
2696 break;
2697
2698 case 2: // query
2699 if (!http_replace_req_query(htx, ist2(replace, len)))
2700 return -1;
2701 break;
2702
2703 case 3: // uri
2704 if (!http_replace_req_uri(htx, ist2(replace, len)))
2705 return -1;
2706 break;
2707
2708 default:
2709 return -1;
2710 }
2711 return 0;
2712}
2713
2714/* This function replace the HTTP status code and the associated message. The
2715 * variable <status> contains the new status code. This function never fails.
2716 */
2717void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2718{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002719 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002720 char *res;
2721
2722 chunk_reset(&trash);
2723 res = ultoa_o(status, trash.area, trash.size);
2724 trash.data = res - trash.area;
2725
2726 /* Do we have a custom reason format string? */
2727 if (reason == NULL)
2728 reason = http_get_reason(status);
2729
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002730 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002731 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2732}
2733
Christopher Faulet3e964192018-10-24 11:39:23 +02002734/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2735 * transaction <txn>. Returns the verdict of the first rule that prevents
2736 * further processing of the request (auth, deny, ...), and defaults to
2737 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2738 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2739 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2740 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2741 * status.
2742 */
2743static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2744 struct stream *s, int *deny_status)
2745{
2746 struct session *sess = strm_sess(s);
2747 struct http_txn *txn = s->txn;
2748 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002749 struct act_rule *rule;
2750 struct http_hdr_ctx ctx;
2751 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002752 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2753 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002754 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002755
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002756 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002757
2758 /* If "the current_rule_list" match the executed rule list, we are in
2759 * resume condition. If a resume is needed it is always in the action
2760 * and never in the ACL or converters. In this case, we initialise the
2761 * current rule, and go to the action execution point.
2762 */
2763 if (s->current_rule) {
2764 rule = s->current_rule;
2765 s->current_rule = NULL;
2766 if (s->current_rule_list == rules)
2767 goto resume_execution;
2768 }
2769 s->current_rule_list = rules;
2770
2771 list_for_each_entry(rule, rules, list) {
2772 /* check optional condition */
2773 if (rule->cond) {
2774 int ret;
2775
2776 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2777 ret = acl_pass(ret);
2778
2779 if (rule->cond->pol == ACL_COND_UNLESS)
2780 ret = !ret;
2781
2782 if (!ret) /* condition not matched */
2783 continue;
2784 }
2785
2786 act_flags |= ACT_FLAG_FIRST;
2787 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002788 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2789 early_hints = 0;
2790 if (htx_reply_103_early_hints(&s->res) == -1) {
2791 rule_ret = HTTP_RULE_RES_BADREQ;
2792 goto end;
2793 }
2794 }
2795
Christopher Faulet3e964192018-10-24 11:39:23 +02002796 switch (rule->action) {
2797 case ACT_ACTION_ALLOW:
2798 rule_ret = HTTP_RULE_RES_STOP;
2799 goto end;
2800
2801 case ACT_ACTION_DENY:
2802 if (deny_status)
2803 *deny_status = rule->deny_status;
2804 rule_ret = HTTP_RULE_RES_DENY;
2805 goto end;
2806
2807 case ACT_HTTP_REQ_TARPIT:
2808 txn->flags |= TX_CLTARPIT;
2809 if (deny_status)
2810 *deny_status = rule->deny_status;
2811 rule_ret = HTTP_RULE_RES_DENY;
2812 goto end;
2813
2814 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002815 /* Auth might be performed on regular http-req rules as well as on stats */
2816 auth_realm = rule->arg.auth.realm;
2817 if (!auth_realm) {
2818 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2819 auth_realm = STATS_DEFAULT_REALM;
2820 else
2821 auth_realm = px->id;
2822 }
2823 /* send 401/407 depending on whether we use a proxy or not. We still
2824 * count one error, because normal browsing won't significantly
2825 * increase the counter but brute force attempts will.
2826 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002827 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002828 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2829 rule_ret = HTTP_RULE_RES_BADREQ;
2830 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002831 goto end;
2832
2833 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002834 rule_ret = HTTP_RULE_RES_DONE;
2835 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2836 rule_ret = HTTP_RULE_RES_BADREQ;
2837 goto end;
2838
2839 case ACT_HTTP_SET_NICE:
2840 s->task->nice = rule->arg.nice;
2841 break;
2842
2843 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002844 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002845 break;
2846
2847 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002848 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002849 break;
2850
2851 case ACT_HTTP_SET_LOGL:
2852 s->logs.level = rule->arg.loglevel;
2853 break;
2854
2855 case ACT_HTTP_REPLACE_HDR:
2856 case ACT_HTTP_REPLACE_VAL:
2857 if (htx_transform_header(s, &s->req, htx,
2858 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2859 &rule->arg.hdr_add.fmt,
2860 &rule->arg.hdr_add.re, rule->action)) {
2861 rule_ret = HTTP_RULE_RES_BADREQ;
2862 goto end;
2863 }
2864 break;
2865
2866 case ACT_HTTP_DEL_HDR:
2867 /* remove all occurrences of the header */
2868 ctx.blk = NULL;
2869 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2870 http_remove_header(htx, &ctx);
2871 break;
2872
2873 case ACT_HTTP_SET_HDR:
2874 case ACT_HTTP_ADD_HDR: {
2875 /* The scope of the trash buffer must be limited to this function. The
2876 * build_logline() function can execute a lot of other function which
2877 * can use the trash buffer. So for limiting the scope of this global
2878 * buffer, we build first the header value using build_logline, and
2879 * after we store the header name.
2880 */
2881 struct buffer *replace;
2882 struct ist n, v;
2883
2884 replace = alloc_trash_chunk();
2885 if (!replace) {
2886 rule_ret = HTTP_RULE_RES_BADREQ;
2887 goto end;
2888 }
2889
2890 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2891 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2892 v = ist2(replace->area, replace->data);
2893
2894 if (rule->action == ACT_HTTP_SET_HDR) {
2895 /* remove all occurrences of the header */
2896 ctx.blk = NULL;
2897 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2898 http_remove_header(htx, &ctx);
2899 }
2900
2901 if (!http_add_header(htx, n, v)) {
2902 static unsigned char rate_limit = 0;
2903
2904 if ((rate_limit++ & 255) == 0) {
2905 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);
2906 }
2907
2908 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2909 if (sess->fe != s->be)
2910 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2911 if (sess->listener->counters)
2912 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2913 }
2914 free_trash_chunk(replace);
2915 break;
2916 }
2917
2918 case ACT_HTTP_DEL_ACL:
2919 case ACT_HTTP_DEL_MAP: {
2920 struct pat_ref *ref;
2921 struct buffer *key;
2922
2923 /* collect reference */
2924 ref = pat_ref_lookup(rule->arg.map.ref);
2925 if (!ref)
2926 continue;
2927
2928 /* allocate key */
2929 key = alloc_trash_chunk();
2930 if (!key) {
2931 rule_ret = HTTP_RULE_RES_BADREQ;
2932 goto end;
2933 }
2934
2935 /* collect key */
2936 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2937 key->area[key->data] = '\0';
2938
2939 /* perform update */
2940 /* returned code: 1=ok, 0=ko */
2941 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2942 pat_ref_delete(ref, key->area);
2943 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2944
2945 free_trash_chunk(key);
2946 break;
2947 }
2948
2949 case ACT_HTTP_ADD_ACL: {
2950 struct pat_ref *ref;
2951 struct buffer *key;
2952
2953 /* collect reference */
2954 ref = pat_ref_lookup(rule->arg.map.ref);
2955 if (!ref)
2956 continue;
2957
2958 /* allocate key */
2959 key = alloc_trash_chunk();
2960 if (!key) {
2961 rule_ret = HTTP_RULE_RES_BADREQ;
2962 goto end;
2963 }
2964
2965 /* collect key */
2966 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2967 key->area[key->data] = '\0';
2968
2969 /* perform update */
2970 /* add entry only if it does not already exist */
2971 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2972 if (pat_ref_find_elt(ref, key->area) == NULL)
2973 pat_ref_add(ref, key->area, NULL, NULL);
2974 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2975
2976 free_trash_chunk(key);
2977 break;
2978 }
2979
2980 case ACT_HTTP_SET_MAP: {
2981 struct pat_ref *ref;
2982 struct buffer *key, *value;
2983
2984 /* collect reference */
2985 ref = pat_ref_lookup(rule->arg.map.ref);
2986 if (!ref)
2987 continue;
2988
2989 /* allocate key */
2990 key = alloc_trash_chunk();
2991 if (!key) {
2992 rule_ret = HTTP_RULE_RES_BADREQ;
2993 goto end;
2994 }
2995
2996 /* allocate value */
2997 value = alloc_trash_chunk();
2998 if (!value) {
2999 free_trash_chunk(key);
3000 rule_ret = HTTP_RULE_RES_BADREQ;
3001 goto end;
3002 }
3003
3004 /* collect key */
3005 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3006 key->area[key->data] = '\0';
3007
3008 /* collect value */
3009 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3010 value->area[value->data] = '\0';
3011
3012 /* perform update */
3013 if (pat_ref_find_elt(ref, key->area) != NULL)
3014 /* update entry if it exists */
3015 pat_ref_set(ref, key->area, value->area, NULL);
3016 else
3017 /* insert a new entry */
3018 pat_ref_add(ref, key->area, value->area, NULL);
3019
3020 free_trash_chunk(key);
3021 free_trash_chunk(value);
3022 break;
3023 }
3024
3025 case ACT_HTTP_EARLY_HINT:
3026 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3027 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003028 early_hints = htx_add_early_hint_header(s, early_hints,
3029 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003030 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003031 if (early_hints == -1) {
3032 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003033 goto end;
3034 }
3035 break;
3036
3037 case ACT_CUSTOM:
3038 if ((s->req.flags & CF_READ_ERROR) ||
3039 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3040 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3041 (px->options & PR_O_ABRT_CLOSE)))
3042 act_flags |= ACT_FLAG_FINAL;
3043
3044 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3045 case ACT_RET_ERR:
3046 case ACT_RET_CONT:
3047 break;
3048 case ACT_RET_STOP:
3049 rule_ret = HTTP_RULE_RES_DONE;
3050 goto end;
3051 case ACT_RET_YIELD:
3052 s->current_rule = rule;
3053 rule_ret = HTTP_RULE_RES_YIELD;
3054 goto end;
3055 }
3056 break;
3057
3058 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3059 /* Note: only the first valid tracking parameter of each
3060 * applies.
3061 */
3062
3063 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3064 struct stktable *t;
3065 struct stksess *ts;
3066 struct stktable_key *key;
3067 void *ptr1, *ptr2;
3068
3069 t = rule->arg.trk_ctr.table.t;
3070 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3071 rule->arg.trk_ctr.expr, NULL);
3072
3073 if (key && (ts = stktable_get_entry(t, key))) {
3074 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3075
3076 /* let's count a new HTTP request as it's the first time we do it */
3077 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3078 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3079 if (ptr1 || ptr2) {
3080 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3081
3082 if (ptr1)
3083 stktable_data_cast(ptr1, http_req_cnt)++;
3084
3085 if (ptr2)
3086 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3087 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3088
3089 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3090
3091 /* If data was modified, we need to touch to re-schedule sync */
3092 stktable_touch_local(t, ts, 0);
3093 }
3094
3095 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3096 if (sess->fe != s->be)
3097 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3098 }
3099 }
3100 break;
3101
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003102 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003103 default:
3104 break;
3105 }
3106 }
3107
3108 end:
3109 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003110 if (htx_reply_103_early_hints(&s->res) == -1)
3111 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003112 }
3113
3114 /* we reached the end of the rules, nothing to report */
3115 return rule_ret;
3116}
3117
3118/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3119 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3120 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3121 * is returned, the process can continue the evaluation of next rule list. If
3122 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3123 * is returned, it means the operation could not be processed and a server error
3124 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3125 * deny rule. If *YIELD is returned, the caller must call again the function
3126 * with the same context.
3127 */
3128static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3129 struct stream *s)
3130{
3131 struct session *sess = strm_sess(s);
3132 struct http_txn *txn = s->txn;
3133 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003134 struct act_rule *rule;
3135 struct http_hdr_ctx ctx;
3136 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3137 int act_flags = 0;
3138
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003139 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003140
3141 /* If "the current_rule_list" match the executed rule list, we are in
3142 * resume condition. If a resume is needed it is always in the action
3143 * and never in the ACL or converters. In this case, we initialise the
3144 * current rule, and go to the action execution point.
3145 */
3146 if (s->current_rule) {
3147 rule = s->current_rule;
3148 s->current_rule = NULL;
3149 if (s->current_rule_list == rules)
3150 goto resume_execution;
3151 }
3152 s->current_rule_list = rules;
3153
3154 list_for_each_entry(rule, rules, list) {
3155 /* check optional condition */
3156 if (rule->cond) {
3157 int ret;
3158
3159 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3160 ret = acl_pass(ret);
3161
3162 if (rule->cond->pol == ACL_COND_UNLESS)
3163 ret = !ret;
3164
3165 if (!ret) /* condition not matched */
3166 continue;
3167 }
3168
3169 act_flags |= ACT_FLAG_FIRST;
3170resume_execution:
3171 switch (rule->action) {
3172 case ACT_ACTION_ALLOW:
3173 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3174 goto end;
3175
3176 case ACT_ACTION_DENY:
3177 txn->flags |= TX_SVDENY;
3178 rule_ret = HTTP_RULE_RES_STOP;
3179 goto end;
3180
3181 case ACT_HTTP_SET_NICE:
3182 s->task->nice = rule->arg.nice;
3183 break;
3184
3185 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003186 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003187 break;
3188
3189 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003190 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003191 break;
3192
3193 case ACT_HTTP_SET_LOGL:
3194 s->logs.level = rule->arg.loglevel;
3195 break;
3196
3197 case ACT_HTTP_REPLACE_HDR:
3198 case ACT_HTTP_REPLACE_VAL:
3199 if (htx_transform_header(s, &s->res, htx,
3200 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3201 &rule->arg.hdr_add.fmt,
3202 &rule->arg.hdr_add.re, rule->action)) {
3203 rule_ret = HTTP_RULE_RES_BADREQ;
3204 goto end;
3205 }
3206 break;
3207
3208 case ACT_HTTP_DEL_HDR:
3209 /* remove all occurrences of the header */
3210 ctx.blk = NULL;
3211 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3212 http_remove_header(htx, &ctx);
3213 break;
3214
3215 case ACT_HTTP_SET_HDR:
3216 case ACT_HTTP_ADD_HDR: {
3217 struct buffer *replace;
3218 struct ist n, v;
3219
3220 replace = alloc_trash_chunk();
3221 if (!replace) {
3222 rule_ret = HTTP_RULE_RES_BADREQ;
3223 goto end;
3224 }
3225
3226 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3227 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3228 v = ist2(replace->area, replace->data);
3229
3230 if (rule->action == ACT_HTTP_SET_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 }
3236
3237 if (!http_add_header(htx, n, v)) {
3238 static unsigned char rate_limit = 0;
3239
3240 if ((rate_limit++ & 255) == 0) {
3241 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);
3242 }
3243
3244 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3245 if (sess->fe != s->be)
3246 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3247 if (sess->listener->counters)
3248 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3249 if (objt_server(s->target))
3250 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3251 }
3252 free_trash_chunk(replace);
3253 break;
3254 }
3255
3256 case ACT_HTTP_DEL_ACL:
3257 case ACT_HTTP_DEL_MAP: {
3258 struct pat_ref *ref;
3259 struct buffer *key;
3260
3261 /* collect reference */
3262 ref = pat_ref_lookup(rule->arg.map.ref);
3263 if (!ref)
3264 continue;
3265
3266 /* allocate key */
3267 key = alloc_trash_chunk();
3268 if (!key) {
3269 rule_ret = HTTP_RULE_RES_BADREQ;
3270 goto end;
3271 }
3272
3273 /* collect key */
3274 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3275 key->area[key->data] = '\0';
3276
3277 /* perform update */
3278 /* returned code: 1=ok, 0=ko */
3279 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3280 pat_ref_delete(ref, key->area);
3281 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3282
3283 free_trash_chunk(key);
3284 break;
3285 }
3286
3287 case ACT_HTTP_ADD_ACL: {
3288 struct pat_ref *ref;
3289 struct buffer *key;
3290
3291 /* collect reference */
3292 ref = pat_ref_lookup(rule->arg.map.ref);
3293 if (!ref)
3294 continue;
3295
3296 /* allocate key */
3297 key = alloc_trash_chunk();
3298 if (!key) {
3299 rule_ret = HTTP_RULE_RES_BADREQ;
3300 goto end;
3301 }
3302
3303 /* collect key */
3304 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3305 key->area[key->data] = '\0';
3306
3307 /* perform update */
3308 /* check if the entry already exists */
3309 if (pat_ref_find_elt(ref, key->area) == NULL)
3310 pat_ref_add(ref, key->area, NULL, NULL);
3311
3312 free_trash_chunk(key);
3313 break;
3314 }
3315
3316 case ACT_HTTP_SET_MAP: {
3317 struct pat_ref *ref;
3318 struct buffer *key, *value;
3319
3320 /* collect reference */
3321 ref = pat_ref_lookup(rule->arg.map.ref);
3322 if (!ref)
3323 continue;
3324
3325 /* allocate key */
3326 key = alloc_trash_chunk();
3327 if (!key) {
3328 rule_ret = HTTP_RULE_RES_BADREQ;
3329 goto end;
3330 }
3331
3332 /* allocate value */
3333 value = alloc_trash_chunk();
3334 if (!value) {
3335 free_trash_chunk(key);
3336 rule_ret = HTTP_RULE_RES_BADREQ;
3337 goto end;
3338 }
3339
3340 /* collect key */
3341 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3342 key->area[key->data] = '\0';
3343
3344 /* collect value */
3345 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3346 value->area[value->data] = '\0';
3347
3348 /* perform update */
3349 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3350 if (pat_ref_find_elt(ref, key->area) != NULL)
3351 /* update entry if it exists */
3352 pat_ref_set(ref, key->area, value->area, NULL);
3353 else
3354 /* insert a new entry */
3355 pat_ref_add(ref, key->area, value->area, NULL);
3356 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3357 free_trash_chunk(key);
3358 free_trash_chunk(value);
3359 break;
3360 }
3361
3362 case ACT_HTTP_REDIR:
3363 rule_ret = HTTP_RULE_RES_DONE;
3364 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3365 rule_ret = HTTP_RULE_RES_BADREQ;
3366 goto end;
3367
3368 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3369 /* Note: only the first valid tracking parameter of each
3370 * applies.
3371 */
3372 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3373 struct stktable *t;
3374 struct stksess *ts;
3375 struct stktable_key *key;
3376 void *ptr;
3377
3378 t = rule->arg.trk_ctr.table.t;
3379 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3380 rule->arg.trk_ctr.expr, NULL);
3381
3382 if (key && (ts = stktable_get_entry(t, key))) {
3383 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3384
3385 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3386
3387 /* let's count a new HTTP request as it's the first time we do it */
3388 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3389 if (ptr)
3390 stktable_data_cast(ptr, http_req_cnt)++;
3391
3392 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3393 if (ptr)
3394 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3395 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3396
3397 /* When the client triggers a 4xx from the server, it's most often due
3398 * to a missing object or permission. These events should be tracked
3399 * because if they happen often, it may indicate a brute force or a
3400 * vulnerability scan. Normally this is done when receiving the response
3401 * but here we're tracking after this ought to have been done so we have
3402 * to do it on purpose.
3403 */
3404 if ((unsigned)(txn->status - 400) < 100) {
3405 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3406 if (ptr)
3407 stktable_data_cast(ptr, http_err_cnt)++;
3408
3409 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3410 if (ptr)
3411 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3412 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3413 }
3414
3415 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3416
3417 /* If data was modified, we need to touch to re-schedule sync */
3418 stktable_touch_local(t, ts, 0);
3419
3420 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3421 if (sess->fe != s->be)
3422 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3423 }
3424 }
3425 break;
3426
3427 case ACT_CUSTOM:
3428 if ((s->req.flags & CF_READ_ERROR) ||
3429 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3430 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3431 (px->options & PR_O_ABRT_CLOSE)))
3432 act_flags |= ACT_FLAG_FINAL;
3433
3434 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3435 case ACT_RET_ERR:
3436 case ACT_RET_CONT:
3437 break;
3438 case ACT_RET_STOP:
3439 rule_ret = HTTP_RULE_RES_STOP;
3440 goto end;
3441 case ACT_RET_YIELD:
3442 s->current_rule = rule;
3443 rule_ret = HTTP_RULE_RES_YIELD;
3444 goto end;
3445 }
3446 break;
3447
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003448 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003449 default:
3450 break;
3451 }
3452 }
3453
3454 end:
3455 /* we reached the end of the rules, nothing to report */
3456 return rule_ret;
3457}
3458
Christopher Faulet33640082018-10-24 11:53:01 +02003459/* Iterate the same filter through all request headers.
3460 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3461 * Since it can manage the switch to another backend, it updates the per-proxy
3462 * DENY stats.
3463 */
3464static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3465{
3466 struct http_txn *txn = s->txn;
3467 struct htx *htx;
3468 struct buffer *hdr = get_trash_chunk();
3469 int32_t pos;
3470
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003471 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003472
3473 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3474 struct htx_blk *blk = htx_get_blk(htx, pos);
3475 enum htx_blk_type type;
3476 struct ist n, v;
3477
3478 next_hdr:
3479 type = htx_get_blk_type(blk);
3480 if (type == HTX_BLK_EOH)
3481 break;
3482 if (type != HTX_BLK_HDR)
3483 continue;
3484
3485 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3486 return 1;
3487 else if (unlikely(txn->flags & TX_CLALLOW) &&
3488 (exp->action == ACT_ALLOW ||
3489 exp->action == ACT_DENY ||
3490 exp->action == ACT_TARPIT))
3491 return 0;
3492
3493 n = htx_get_blk_name(htx, blk);
3494 v = htx_get_blk_value(htx, blk);
3495
3496 chunk_memcat(hdr, n.ptr, n.len);
3497 hdr->area[hdr->data++] = ':';
3498 hdr->area[hdr->data++] = ' ';
3499 chunk_memcat(hdr, v.ptr, v.len);
3500
3501 /* Now we have one header in <hdr> */
3502
3503 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3504 struct http_hdr_ctx ctx;
3505 int len;
3506
3507 switch (exp->action) {
3508 case ACT_ALLOW:
3509 txn->flags |= TX_CLALLOW;
3510 goto end;
3511
3512 case ACT_DENY:
3513 txn->flags |= TX_CLDENY;
3514 goto end;
3515
3516 case ACT_TARPIT:
3517 txn->flags |= TX_CLTARPIT;
3518 goto end;
3519
3520 case ACT_REPLACE:
3521 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3522 if (len < 0)
3523 return -1;
3524
3525 http_parse_header(ist2(trash.area, len), &n, &v);
3526 ctx.blk = blk;
3527 ctx.value = v;
3528 if (!http_replace_header(htx, &ctx, n, v))
3529 return -1;
3530 if (!ctx.blk)
3531 goto end;
3532 pos = htx_get_blk_pos(htx, blk);
3533 break;
3534
3535 case ACT_REMOVE:
3536 ctx.blk = blk;
3537 ctx.value = v;
3538 if (!http_remove_header(htx, &ctx))
3539 return -1;
3540 if (!ctx.blk)
3541 goto end;
3542 pos = htx_get_blk_pos(htx, blk);
3543 goto next_hdr;
3544
3545 }
3546 }
3547 }
3548 end:
3549 return 0;
3550}
3551
3552/* Apply the filter to the request line.
3553 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3554 * or -1 if a replacement resulted in an invalid request line.
3555 * Since it can manage the switch to another backend, it updates the per-proxy
3556 * DENY stats.
3557 */
3558static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3559{
3560 struct http_txn *txn = s->txn;
3561 struct htx *htx;
3562 struct buffer *reqline = get_trash_chunk();
3563 int done;
3564
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003565 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003566
3567 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3568 return 1;
3569 else if (unlikely(txn->flags & TX_CLALLOW) &&
3570 (exp->action == ACT_ALLOW ||
3571 exp->action == ACT_DENY ||
3572 exp->action == ACT_TARPIT))
3573 return 0;
3574 else if (exp->action == ACT_REMOVE)
3575 return 0;
3576
3577 done = 0;
3578
3579 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3580
3581 /* Now we have the request line between cur_ptr and cur_end */
3582 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003583 struct htx_sl *sl = http_find_stline(htx);
3584 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003585 int len;
3586
3587 switch (exp->action) {
3588 case ACT_ALLOW:
3589 txn->flags |= TX_CLALLOW;
3590 done = 1;
3591 break;
3592
3593 case ACT_DENY:
3594 txn->flags |= TX_CLDENY;
3595 done = 1;
3596 break;
3597
3598 case ACT_TARPIT:
3599 txn->flags |= TX_CLTARPIT;
3600 done = 1;
3601 break;
3602
3603 case ACT_REPLACE:
3604 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3605 if (len < 0)
3606 return -1;
3607
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003608 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3609 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3610 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003611 return -1;
3612 done = 1;
3613 break;
3614 }
3615 }
3616 return done;
3617}
3618
3619/*
3620 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3621 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3622 * unparsable request. Since it can manage the switch to another backend, it
3623 * updates the per-proxy DENY stats.
3624 */
3625static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3626{
3627 struct session *sess = s->sess;
3628 struct http_txn *txn = s->txn;
3629 struct hdr_exp *exp;
3630
3631 for (exp = px->req_exp; exp; exp = exp->next) {
3632 int ret;
3633
3634 /*
3635 * The interleaving of transformations and verdicts
3636 * makes it difficult to decide to continue or stop
3637 * the evaluation.
3638 */
3639
3640 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3641 break;
3642
3643 if ((txn->flags & TX_CLALLOW) &&
3644 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3645 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3646 continue;
3647
3648 /* if this filter had a condition, evaluate it now and skip to
3649 * next filter if the condition does not match.
3650 */
3651 if (exp->cond) {
3652 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3653 ret = acl_pass(ret);
3654 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3655 ret = !ret;
3656
3657 if (!ret)
3658 continue;
3659 }
3660
3661 /* Apply the filter to the request line. */
3662 ret = htx_apply_filter_to_req_line(s, req, exp);
3663 if (unlikely(ret < 0))
3664 return -1;
3665
3666 if (likely(ret == 0)) {
3667 /* The filter did not match the request, it can be
3668 * iterated through all headers.
3669 */
3670 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3671 return -1;
3672 }
3673 }
3674 return 0;
3675}
3676
3677/* Iterate the same filter through all response headers contained in <res>.
3678 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3679 */
3680static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3681{
3682 struct http_txn *txn = s->txn;
3683 struct htx *htx;
3684 struct buffer *hdr = get_trash_chunk();
3685 int32_t pos;
3686
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003687 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003688
3689 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3690 struct htx_blk *blk = htx_get_blk(htx, pos);
3691 enum htx_blk_type type;
3692 struct ist n, v;
3693
3694 next_hdr:
3695 type = htx_get_blk_type(blk);
3696 if (type == HTX_BLK_EOH)
3697 break;
3698 if (type != HTX_BLK_HDR)
3699 continue;
3700
3701 if (unlikely(txn->flags & TX_SVDENY))
3702 return 1;
3703 else if (unlikely(txn->flags & TX_SVALLOW) &&
3704 (exp->action == ACT_ALLOW ||
3705 exp->action == ACT_DENY))
3706 return 0;
3707
3708 n = htx_get_blk_name(htx, blk);
3709 v = htx_get_blk_value(htx, blk);
3710
3711 chunk_memcat(hdr, n.ptr, n.len);
3712 hdr->area[hdr->data++] = ':';
3713 hdr->area[hdr->data++] = ' ';
3714 chunk_memcat(hdr, v.ptr, v.len);
3715
3716 /* Now we have one header in <hdr> */
3717
3718 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3719 struct http_hdr_ctx ctx;
3720 int len;
3721
3722 switch (exp->action) {
3723 case ACT_ALLOW:
3724 txn->flags |= TX_SVALLOW;
3725 goto end;
3726 break;
3727
3728 case ACT_DENY:
3729 txn->flags |= TX_SVDENY;
3730 goto end;
3731 break;
3732
3733 case ACT_REPLACE:
3734 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3735 if (len < 0)
3736 return -1;
3737
3738 http_parse_header(ist2(trash.area, len), &n, &v);
3739 ctx.blk = blk;
3740 ctx.value = v;
3741 if (!http_replace_header(htx, &ctx, n, v))
3742 return -1;
3743 if (!ctx.blk)
3744 goto end;
3745 pos = htx_get_blk_pos(htx, blk);
3746 break;
3747
3748 case ACT_REMOVE:
3749 ctx.blk = blk;
3750 ctx.value = v;
3751 if (!http_remove_header(htx, &ctx))
3752 return -1;
3753 if (!ctx.blk)
3754 goto end;
3755 pos = htx_get_blk_pos(htx, blk);
3756 goto next_hdr;
3757 }
3758 }
3759
3760 }
3761 end:
3762 return 0;
3763}
3764
3765/* Apply the filter to the status line in the response buffer <res>.
3766 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3767 * or -1 if a replacement resulted in an invalid status line.
3768 */
3769static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3770{
3771 struct http_txn *txn = s->txn;
3772 struct htx *htx;
3773 struct buffer *resline = get_trash_chunk();
3774 int done;
3775
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003776 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003777
3778 if (unlikely(txn->flags & TX_SVDENY))
3779 return 1;
3780 else if (unlikely(txn->flags & TX_SVALLOW) &&
3781 (exp->action == ACT_ALLOW ||
3782 exp->action == ACT_DENY))
3783 return 0;
3784 else if (exp->action == ACT_REMOVE)
3785 return 0;
3786
3787 done = 0;
3788 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3789
3790 /* Now we have the status line between cur_ptr and cur_end */
3791 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003792 struct htx_sl *sl = http_find_stline(htx);
3793 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003794 int len;
3795
3796 switch (exp->action) {
3797 case ACT_ALLOW:
3798 txn->flags |= TX_SVALLOW;
3799 done = 1;
3800 break;
3801
3802 case ACT_DENY:
3803 txn->flags |= TX_SVDENY;
3804 done = 1;
3805 break;
3806
3807 case ACT_REPLACE:
3808 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3809 if (len < 0)
3810 return -1;
3811
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003812 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3813 sl->info.res.status = strl2ui(code.ptr, code.len);
3814 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003815 return -1;
3816
3817 done = 1;
3818 return 1;
3819 }
3820 }
3821 return done;
3822}
3823
3824/*
3825 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3826 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3827 * unparsable response.
3828 */
3829static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3830{
3831 struct session *sess = s->sess;
3832 struct http_txn *txn = s->txn;
3833 struct hdr_exp *exp;
3834
3835 for (exp = px->rsp_exp; exp; exp = exp->next) {
3836 int ret;
3837
3838 /*
3839 * The interleaving of transformations and verdicts
3840 * makes it difficult to decide to continue or stop
3841 * the evaluation.
3842 */
3843
3844 if (txn->flags & TX_SVDENY)
3845 break;
3846
3847 if ((txn->flags & TX_SVALLOW) &&
3848 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3849 exp->action == ACT_PASS)) {
3850 exp = exp->next;
3851 continue;
3852 }
3853
3854 /* if this filter had a condition, evaluate it now and skip to
3855 * next filter if the condition does not match.
3856 */
3857 if (exp->cond) {
3858 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3859 ret = acl_pass(ret);
3860 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3861 ret = !ret;
3862 if (!ret)
3863 continue;
3864 }
3865
3866 /* Apply the filter to the status line. */
3867 ret = htx_apply_filter_to_sts_line(s, res, exp);
3868 if (unlikely(ret < 0))
3869 return -1;
3870
3871 if (likely(ret == 0)) {
3872 /* The filter did not match the response, it can be
3873 * iterated through all headers.
3874 */
3875 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3876 return -1;
3877 }
3878 }
3879 return 0;
3880}
3881
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003882/*
3883 * Manage client-side cookie. It can impact performance by about 2% so it is
3884 * desirable to call it only when needed. This code is quite complex because
3885 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3886 * highly recommended not to touch this part without a good reason !
3887 */
3888static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3889{
3890 struct session *sess = s->sess;
3891 struct http_txn *txn = s->txn;
3892 struct htx *htx;
3893 struct http_hdr_ctx ctx;
3894 char *hdr_beg, *hdr_end, *del_from;
3895 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3896 int preserve_hdr;
3897
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003898 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003899 ctx.blk = NULL;
3900 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3901 del_from = NULL; /* nothing to be deleted */
3902 preserve_hdr = 0; /* assume we may kill the whole header */
3903
3904 /* Now look for cookies. Conforming to RFC2109, we have to support
3905 * attributes whose name begin with a '$', and associate them with
3906 * the right cookie, if we want to delete this cookie.
3907 * So there are 3 cases for each cookie read :
3908 * 1) it's a special attribute, beginning with a '$' : ignore it.
3909 * 2) it's a server id cookie that we *MAY* want to delete : save
3910 * some pointers on it (last semi-colon, beginning of cookie...)
3911 * 3) it's an application cookie : we *MAY* have to delete a previous
3912 * "special" cookie.
3913 * At the end of loop, if a "special" cookie remains, we may have to
3914 * remove it. If no application cookie persists in the header, we
3915 * *MUST* delete it.
3916 *
3917 * Note: RFC2965 is unclear about the processing of spaces around
3918 * the equal sign in the ATTR=VALUE form. A careful inspection of
3919 * the RFC explicitly allows spaces before it, and not within the
3920 * tokens (attrs or values). An inspection of RFC2109 allows that
3921 * too but section 10.1.3 lets one think that spaces may be allowed
3922 * after the equal sign too, resulting in some (rare) buggy
3923 * implementations trying to do that. So let's do what servers do.
3924 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3925 * allowed quoted strings in values, with any possible character
3926 * after a backslash, including control chars and delimitors, which
3927 * causes parsing to become ambiguous. Browsers also allow spaces
3928 * within values even without quotes.
3929 *
3930 * We have to keep multiple pointers in order to support cookie
3931 * removal at the beginning, middle or end of header without
3932 * corrupting the header. All of these headers are valid :
3933 *
3934 * hdr_beg hdr_end
3935 * | |
3936 * v |
3937 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3938 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3939 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3940 * | | | | | | |
3941 * | | | | | | |
3942 * | | | | | | +--> next
3943 * | | | | | +----> val_end
3944 * | | | | +-----------> val_beg
3945 * | | | +--------------> equal
3946 * | | +----------------> att_end
3947 * | +---------------------> att_beg
3948 * +--------------------------> prev
3949 *
3950 */
3951 hdr_beg = ctx.value.ptr;
3952 hdr_end = hdr_beg + ctx.value.len;
3953 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3954 /* Iterate through all cookies on this line */
3955
3956 /* find att_beg */
3957 att_beg = prev;
3958 if (prev > hdr_beg)
3959 att_beg++;
3960
3961 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3962 att_beg++;
3963
3964 /* find att_end : this is the first character after the last non
3965 * space before the equal. It may be equal to hdr_end.
3966 */
3967 equal = att_end = att_beg;
3968 while (equal < hdr_end) {
3969 if (*equal == '=' || *equal == ',' || *equal == ';')
3970 break;
3971 if (HTTP_IS_SPHT(*equal++))
3972 continue;
3973 att_end = equal;
3974 }
3975
3976 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3977 * is between <att_beg> and <equal>, both may be identical.
3978 */
3979 /* look for end of cookie if there is an equal sign */
3980 if (equal < hdr_end && *equal == '=') {
3981 /* look for the beginning of the value */
3982 val_beg = equal + 1;
3983 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3984 val_beg++;
3985
3986 /* find the end of the value, respecting quotes */
3987 next = http_find_cookie_value_end(val_beg, hdr_end);
3988
3989 /* make val_end point to the first white space or delimitor after the value */
3990 val_end = next;
3991 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3992 val_end--;
3993 }
3994 else
3995 val_beg = val_end = next = equal;
3996
3997 /* We have nothing to do with attributes beginning with
3998 * '$'. However, they will automatically be removed if a
3999 * header before them is removed, since they're supposed
4000 * to be linked together.
4001 */
4002 if (*att_beg == '$')
4003 continue;
4004
4005 /* Ignore cookies with no equal sign */
4006 if (equal == next) {
4007 /* This is not our cookie, so we must preserve it. But if we already
4008 * scheduled another cookie for removal, we cannot remove the
4009 * complete header, but we can remove the previous block itself.
4010 */
4011 preserve_hdr = 1;
4012 if (del_from != NULL) {
4013 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4014 val_end += delta;
4015 next += delta;
4016 hdr_end += delta;
4017 prev = del_from;
4018 del_from = NULL;
4019 }
4020 continue;
4021 }
4022
4023 /* if there are spaces around the equal sign, we need to
4024 * strip them otherwise we'll get trouble for cookie captures,
4025 * or even for rewrites. Since this happens extremely rarely,
4026 * it does not hurt performance.
4027 */
4028 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4029 int stripped_before = 0;
4030 int stripped_after = 0;
4031
4032 if (att_end != equal) {
4033 memmove(att_end, equal, hdr_end - equal);
4034 stripped_before = (att_end - equal);
4035 equal += stripped_before;
4036 val_beg += stripped_before;
4037 }
4038
4039 if (val_beg > equal + 1) {
4040 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4041 stripped_after = (equal + 1) - val_beg;
4042 val_beg += stripped_after;
4043 stripped_before += stripped_after;
4044 }
4045
4046 val_end += stripped_before;
4047 next += stripped_before;
4048 hdr_end += stripped_before;
4049 }
4050 /* now everything is as on the diagram above */
4051
4052 /* First, let's see if we want to capture this cookie. We check
4053 * that we don't already have a client side cookie, because we
4054 * can only capture one. Also as an optimisation, we ignore
4055 * cookies shorter than the declared name.
4056 */
4057 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4058 (val_end - att_beg >= sess->fe->capture_namelen) &&
4059 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4060 int log_len = val_end - att_beg;
4061
4062 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4063 ha_alert("HTTP logging : out of memory.\n");
4064 } else {
4065 if (log_len > sess->fe->capture_len)
4066 log_len = sess->fe->capture_len;
4067 memcpy(txn->cli_cookie, att_beg, log_len);
4068 txn->cli_cookie[log_len] = 0;
4069 }
4070 }
4071
4072 /* Persistence cookies in passive, rewrite or insert mode have the
4073 * following form :
4074 *
4075 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4076 *
4077 * For cookies in prefix mode, the form is :
4078 *
4079 * Cookie: NAME=SRV~VALUE
4080 */
4081 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4082 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4083 struct server *srv = s->be->srv;
4084 char *delim;
4085
4086 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4087 * have the server ID between val_beg and delim, and the original cookie between
4088 * delim+1 and val_end. Otherwise, delim==val_end :
4089 *
4090 * hdr_beg
4091 * |
4092 * v
4093 * NAME=SRV; # in all but prefix modes
4094 * NAME=SRV~OPAQUE ; # in prefix mode
4095 * || || | |+-> next
4096 * || || | +--> val_end
4097 * || || +---------> delim
4098 * || |+------------> val_beg
4099 * || +-------------> att_end = equal
4100 * |+-----------------> att_beg
4101 * +------------------> prev
4102 *
4103 */
4104 if (s->be->ck_opts & PR_CK_PFX) {
4105 for (delim = val_beg; delim < val_end; delim++)
4106 if (*delim == COOKIE_DELIM)
4107 break;
4108 }
4109 else {
4110 char *vbar1;
4111 delim = val_end;
4112 /* Now check if the cookie contains a date field, which would
4113 * appear after a vertical bar ('|') just after the server name
4114 * and before the delimiter.
4115 */
4116 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4117 if (vbar1) {
4118 /* OK, so left of the bar is the server's cookie and
4119 * right is the last seen date. It is a base64 encoded
4120 * 30-bit value representing the UNIX date since the
4121 * epoch in 4-second quantities.
4122 */
4123 int val;
4124 delim = vbar1++;
4125 if (val_end - vbar1 >= 5) {
4126 val = b64tos30(vbar1);
4127 if (val > 0)
4128 txn->cookie_last_date = val << 2;
4129 }
4130 /* look for a second vertical bar */
4131 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4132 if (vbar1 && (val_end - vbar1 > 5)) {
4133 val = b64tos30(vbar1 + 1);
4134 if (val > 0)
4135 txn->cookie_first_date = val << 2;
4136 }
4137 }
4138 }
4139
4140 /* if the cookie has an expiration date and the proxy wants to check
4141 * it, then we do that now. We first check if the cookie is too old,
4142 * then only if it has expired. We detect strict overflow because the
4143 * time resolution here is not great (4 seconds). Cookies with dates
4144 * in the future are ignored if their offset is beyond one day. This
4145 * allows an admin to fix timezone issues without expiring everyone
4146 * and at the same time avoids keeping unwanted side effects for too
4147 * long.
4148 */
4149 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4150 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4151 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4152 txn->flags &= ~TX_CK_MASK;
4153 txn->flags |= TX_CK_OLD;
4154 delim = val_beg; // let's pretend we have not found the cookie
4155 txn->cookie_first_date = 0;
4156 txn->cookie_last_date = 0;
4157 }
4158 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4159 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4160 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4161 txn->flags &= ~TX_CK_MASK;
4162 txn->flags |= TX_CK_EXPIRED;
4163 delim = val_beg; // let's pretend we have not found the cookie
4164 txn->cookie_first_date = 0;
4165 txn->cookie_last_date = 0;
4166 }
4167
4168 /* Here, we'll look for the first running server which supports the cookie.
4169 * This allows to share a same cookie between several servers, for example
4170 * to dedicate backup servers to specific servers only.
4171 * However, to prevent clients from sticking to cookie-less backup server
4172 * when they have incidentely learned an empty cookie, we simply ignore
4173 * empty cookies and mark them as invalid.
4174 * The same behaviour is applied when persistence must be ignored.
4175 */
4176 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4177 srv = NULL;
4178
4179 while (srv) {
4180 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4181 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4182 if ((srv->cur_state != SRV_ST_STOPPED) ||
4183 (s->be->options & PR_O_PERSIST) ||
4184 (s->flags & SF_FORCE_PRST)) {
4185 /* we found the server and we can use it */
4186 txn->flags &= ~TX_CK_MASK;
4187 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4188 s->flags |= SF_DIRECT | SF_ASSIGNED;
4189 s->target = &srv->obj_type;
4190 break;
4191 } else {
4192 /* we found a server, but it's down,
4193 * mark it as such and go on in case
4194 * another one is available.
4195 */
4196 txn->flags &= ~TX_CK_MASK;
4197 txn->flags |= TX_CK_DOWN;
4198 }
4199 }
4200 srv = srv->next;
4201 }
4202
4203 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4204 /* no server matched this cookie or we deliberately skipped it */
4205 txn->flags &= ~TX_CK_MASK;
4206 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4207 txn->flags |= TX_CK_UNUSED;
4208 else
4209 txn->flags |= TX_CK_INVALID;
4210 }
4211
4212 /* depending on the cookie mode, we may have to either :
4213 * - delete the complete cookie if we're in insert+indirect mode, so that
4214 * the server never sees it ;
4215 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004216 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004217 * if we're in cookie prefix mode
4218 */
4219 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4220 int delta; /* negative */
4221
4222 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4223 delta = val_beg - (delim + 1);
4224 val_end += delta;
4225 next += delta;
4226 hdr_end += delta;
4227 del_from = NULL;
4228 preserve_hdr = 1; /* we want to keep this cookie */
4229 }
4230 else if (del_from == NULL &&
4231 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4232 del_from = prev;
4233 }
4234 }
4235 else {
4236 /* This is not our cookie, so we must preserve it. But if we already
4237 * scheduled another cookie for removal, we cannot remove the
4238 * complete header, but we can remove the previous block itself.
4239 */
4240 preserve_hdr = 1;
4241
4242 if (del_from != NULL) {
4243 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4244 if (att_beg >= del_from)
4245 att_beg += delta;
4246 if (att_end >= del_from)
4247 att_end += delta;
4248 val_beg += delta;
4249 val_end += delta;
4250 next += delta;
4251 hdr_end += delta;
4252 prev = del_from;
4253 del_from = NULL;
4254 }
4255 }
4256
4257 /* continue with next cookie on this header line */
4258 att_beg = next;
4259 } /* for each cookie */
4260
4261
4262 /* There are no more cookies on this line.
4263 * We may still have one (or several) marked for deletion at the
4264 * end of the line. We must do this now in two ways :
4265 * - if some cookies must be preserved, we only delete from the
4266 * mark to the end of line ;
4267 * - if nothing needs to be preserved, simply delete the whole header
4268 */
4269 if (del_from) {
4270 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4271 }
4272 if ((hdr_end - hdr_beg) != ctx.value.len) {
4273 if (hdr_beg != hdr_end) {
4274 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4275 htx->data -= (hdr_end - ctx.value.ptr);
4276 }
4277 else
4278 http_remove_header(htx, &ctx);
4279 }
4280 } /* for each "Cookie header */
4281}
4282
4283/*
4284 * Manage server-side cookies. It can impact performance by about 2% so it is
4285 * desirable to call it only when needed. This function is also used when we
4286 * just need to know if there is a cookie (eg: for check-cache).
4287 */
4288static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4289{
4290 struct session *sess = s->sess;
4291 struct http_txn *txn = s->txn;
4292 struct htx *htx;
4293 struct http_hdr_ctx ctx;
4294 struct server *srv;
4295 char *hdr_beg, *hdr_end;
4296 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4297 int is_cookie2;
4298
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004299 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004300
4301 ctx.blk = NULL;
4302 while (1) {
4303 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4304 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4305 break;
4306 is_cookie2 = 1;
4307 }
4308
4309 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4310 * <prev> points to the colon.
4311 */
4312 txn->flags |= TX_SCK_PRESENT;
4313
4314 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4315 * check-cache is enabled) and we are not interested in checking
4316 * them. Warning, the cookie capture is declared in the frontend.
4317 */
4318 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4319 break;
4320
4321 /* OK so now we know we have to process this response cookie.
4322 * The format of the Set-Cookie header is slightly different
4323 * from the format of the Cookie header in that it does not
4324 * support the comma as a cookie delimiter (thus the header
4325 * cannot be folded) because the Expires attribute described in
4326 * the original Netscape's spec may contain an unquoted date
4327 * with a comma inside. We have to live with this because
4328 * many browsers don't support Max-Age and some browsers don't
4329 * support quoted strings. However the Set-Cookie2 header is
4330 * clean.
4331 *
4332 * We have to keep multiple pointers in order to support cookie
4333 * removal at the beginning, middle or end of header without
4334 * corrupting the header (in case of set-cookie2). A special
4335 * pointer, <scav> points to the beginning of the set-cookie-av
4336 * fields after the first semi-colon. The <next> pointer points
4337 * either to the end of line (set-cookie) or next unquoted comma
4338 * (set-cookie2). All of these headers are valid :
4339 *
4340 * hdr_beg hdr_end
4341 * | |
4342 * v |
4343 * NAME1 = VALUE 1 ; Secure; Path="/" |
4344 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4345 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4346 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4347 * | | | | | | | |
4348 * | | | | | | | +-> next
4349 * | | | | | | +------------> scav
4350 * | | | | | +--------------> val_end
4351 * | | | | +--------------------> val_beg
4352 * | | | +----------------------> equal
4353 * | | +------------------------> att_end
4354 * | +----------------------------> att_beg
4355 * +------------------------------> prev
4356 * -------------------------------> hdr_beg
4357 */
4358 hdr_beg = ctx.value.ptr;
4359 hdr_end = hdr_beg + ctx.value.len;
4360 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4361
4362 /* Iterate through all cookies on this line */
4363
4364 /* find att_beg */
4365 att_beg = prev;
4366 if (prev > hdr_beg)
4367 att_beg++;
4368
4369 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4370 att_beg++;
4371
4372 /* find att_end : this is the first character after the last non
4373 * space before the equal. It may be equal to hdr_end.
4374 */
4375 equal = att_end = att_beg;
4376
4377 while (equal < hdr_end) {
4378 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4379 break;
4380 if (HTTP_IS_SPHT(*equal++))
4381 continue;
4382 att_end = equal;
4383 }
4384
4385 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4386 * is between <att_beg> and <equal>, both may be identical.
4387 */
4388
4389 /* look for end of cookie if there is an equal sign */
4390 if (equal < hdr_end && *equal == '=') {
4391 /* look for the beginning of the value */
4392 val_beg = equal + 1;
4393 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4394 val_beg++;
4395
4396 /* find the end of the value, respecting quotes */
4397 next = http_find_cookie_value_end(val_beg, hdr_end);
4398
4399 /* make val_end point to the first white space or delimitor after the value */
4400 val_end = next;
4401 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4402 val_end--;
4403 }
4404 else {
4405 /* <equal> points to next comma, semi-colon or EOL */
4406 val_beg = val_end = next = equal;
4407 }
4408
4409 if (next < hdr_end) {
4410 /* Set-Cookie2 supports multiple cookies, and <next> points to
4411 * a colon or semi-colon before the end. So skip all attr-value
4412 * pairs and look for the next comma. For Set-Cookie, since
4413 * commas are permitted in values, skip to the end.
4414 */
4415 if (is_cookie2)
4416 next = http_find_hdr_value_end(next, hdr_end);
4417 else
4418 next = hdr_end;
4419 }
4420
4421 /* Now everything is as on the diagram above */
4422
4423 /* Ignore cookies with no equal sign */
4424 if (equal == val_end)
4425 continue;
4426
4427 /* If there are spaces around the equal sign, we need to
4428 * strip them otherwise we'll get trouble for cookie captures,
4429 * or even for rewrites. Since this happens extremely rarely,
4430 * it does not hurt performance.
4431 */
4432 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4433 int stripped_before = 0;
4434 int stripped_after = 0;
4435
4436 if (att_end != equal) {
4437 memmove(att_end, equal, hdr_end - equal);
4438 stripped_before = (att_end - equal);
4439 equal += stripped_before;
4440 val_beg += stripped_before;
4441 }
4442
4443 if (val_beg > equal + 1) {
4444 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4445 stripped_after = (equal + 1) - val_beg;
4446 val_beg += stripped_after;
4447 stripped_before += stripped_after;
4448 }
4449
4450 val_end += stripped_before;
4451 next += stripped_before;
4452 hdr_end += stripped_before;
4453
4454 ctx.value.len = hdr_end - hdr_beg;
4455 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4456 htx->data -= (hdr_end - ctx.value.ptr);
4457 }
4458
4459 /* First, let's see if we want to capture this cookie. We check
4460 * that we don't already have a server side cookie, because we
4461 * can only capture one. Also as an optimisation, we ignore
4462 * cookies shorter than the declared name.
4463 */
4464 if (sess->fe->capture_name != NULL &&
4465 txn->srv_cookie == NULL &&
4466 (val_end - att_beg >= sess->fe->capture_namelen) &&
4467 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4468 int log_len = val_end - att_beg;
4469 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4470 ha_alert("HTTP logging : out of memory.\n");
4471 }
4472 else {
4473 if (log_len > sess->fe->capture_len)
4474 log_len = sess->fe->capture_len;
4475 memcpy(txn->srv_cookie, att_beg, log_len);
4476 txn->srv_cookie[log_len] = 0;
4477 }
4478 }
4479
4480 srv = objt_server(s->target);
4481 /* now check if we need to process it for persistence */
4482 if (!(s->flags & SF_IGNORE_PRST) &&
4483 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4484 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4485 /* assume passive cookie by default */
4486 txn->flags &= ~TX_SCK_MASK;
4487 txn->flags |= TX_SCK_FOUND;
4488
4489 /* If the cookie is in insert mode on a known server, we'll delete
4490 * this occurrence because we'll insert another one later.
4491 * We'll delete it too if the "indirect" option is set and we're in
4492 * a direct access.
4493 */
4494 if (s->be->ck_opts & PR_CK_PSV) {
4495 /* The "preserve" flag was set, we don't want to touch the
4496 * server's cookie.
4497 */
4498 }
4499 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4500 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4501 /* this cookie must be deleted */
4502 if (prev == hdr_beg && next == hdr_end) {
4503 /* whole header */
4504 http_remove_header(htx, &ctx);
4505 /* note: while both invalid now, <next> and <hdr_end>
4506 * are still equal, so the for() will stop as expected.
4507 */
4508 } else {
4509 /* just remove the value */
4510 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4511 next = prev;
4512 hdr_end += delta;
4513 }
4514 txn->flags &= ~TX_SCK_MASK;
4515 txn->flags |= TX_SCK_DELETED;
4516 /* and go on with next cookie */
4517 }
4518 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4519 /* replace bytes val_beg->val_end with the cookie name associated
4520 * with this server since we know it.
4521 */
4522 int sliding, delta;
4523
4524 ctx.value = ist2(val_beg, val_end - val_beg);
4525 ctx.lws_before = ctx.lws_after = 0;
4526 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4527 delta = srv->cklen - (val_end - val_beg);
4528 sliding = (ctx.value.ptr - val_beg);
4529 hdr_beg += sliding;
4530 val_beg += sliding;
4531 next += sliding + delta;
4532 hdr_end += sliding + delta;
4533
4534 txn->flags &= ~TX_SCK_MASK;
4535 txn->flags |= TX_SCK_REPLACED;
4536 }
4537 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4538 /* insert the cookie name associated with this server
4539 * before existing cookie, and insert a delimiter between them..
4540 */
4541 int sliding, delta;
4542 ctx.value = ist2(val_beg, 0);
4543 ctx.lws_before = ctx.lws_after = 0;
4544 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4545 delta = srv->cklen + 1;
4546 sliding = (ctx.value.ptr - val_beg);
4547 hdr_beg += sliding;
4548 val_beg += sliding;
4549 next += sliding + delta;
4550 hdr_end += sliding + delta;
4551
4552 val_beg[srv->cklen] = COOKIE_DELIM;
4553 txn->flags &= ~TX_SCK_MASK;
4554 txn->flags |= TX_SCK_REPLACED;
4555 }
4556 }
4557 /* that's done for this cookie, check the next one on the same
4558 * line when next != hdr_end (only if is_cookie2).
4559 */
4560 }
4561 }
4562}
4563
Christopher Faulet25a02f62018-10-24 12:00:25 +02004564/*
4565 * Parses the Cache-Control and Pragma request header fields to determine if
4566 * the request may be served from the cache and/or if it is cacheable. Updates
4567 * s->txn->flags.
4568 */
4569void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4570{
4571 struct http_txn *txn = s->txn;
4572 struct htx *htx;
4573 int32_t pos;
4574 int pragma_found, cc_found, i;
4575
4576 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4577 return; /* nothing more to do here */
4578
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004579 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004580 pragma_found = cc_found = 0;
4581 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4582 struct htx_blk *blk = htx_get_blk(htx, pos);
4583 enum htx_blk_type type = htx_get_blk_type(blk);
4584 struct ist n, v;
4585
4586 if (type == HTX_BLK_EOH)
4587 break;
4588 if (type != HTX_BLK_HDR)
4589 continue;
4590
4591 n = htx_get_blk_name(htx, blk);
4592 v = htx_get_blk_value(htx, blk);
4593
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004594 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004595 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4596 pragma_found = 1;
4597 continue;
4598 }
4599 }
4600
4601 /* Don't use the cache and don't try to store if we found the
4602 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004603 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004604 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4605 txn->flags |= TX_CACHE_IGNORE;
4606 continue;
4607 }
4608
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004609 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004610 continue;
4611
4612 /* OK, right now we know we have a cache-control header */
4613 cc_found = 1;
4614 if (!v.len) /* no info */
4615 continue;
4616
4617 i = 0;
4618 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4619 !isspace((unsigned char)*(v.ptr+i)))
4620 i++;
4621
4622 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4623 * values after max-age, max-stale nor min-fresh, we simply don't
4624 * use the cache when they're specified.
4625 */
4626 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4627 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4628 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4629 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4630 txn->flags |= TX_CACHE_IGNORE;
4631 continue;
4632 }
4633
4634 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4635 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4636 continue;
4637 }
4638 }
4639
4640 /* RFC7234#5.4:
4641 * When the Cache-Control header field is also present and
4642 * understood in a request, Pragma is ignored.
4643 * When the Cache-Control header field is not present in a
4644 * request, caches MUST consider the no-cache request
4645 * pragma-directive as having the same effect as if
4646 * "Cache-Control: no-cache" were present.
4647 */
4648 if (!cc_found && pragma_found)
4649 txn->flags |= TX_CACHE_IGNORE;
4650}
4651
4652/*
4653 * Check if response is cacheable or not. Updates s->txn->flags.
4654 */
4655void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4656{
4657 struct http_txn *txn = s->txn;
4658 struct htx *htx;
4659 int32_t pos;
4660 int i;
4661
4662 if (txn->status < 200) {
4663 /* do not try to cache interim responses! */
4664 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4665 return;
4666 }
4667
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004668 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004669 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4670 struct htx_blk *blk = htx_get_blk(htx, pos);
4671 enum htx_blk_type type = htx_get_blk_type(blk);
4672 struct ist n, v;
4673
4674 if (type == HTX_BLK_EOH)
4675 break;
4676 if (type != HTX_BLK_HDR)
4677 continue;
4678
4679 n = htx_get_blk_name(htx, blk);
4680 v = htx_get_blk_value(htx, blk);
4681
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004682 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004683 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4684 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4685 return;
4686 }
4687 }
4688
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004689 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004690 continue;
4691
4692 /* OK, right now we know we have a cache-control header */
4693 if (!v.len) /* no info */
4694 continue;
4695
4696 i = 0;
4697 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4698 !isspace((unsigned char)*(v.ptr+i)))
4699 i++;
4700
4701 /* we have a complete value between v.ptr and (v.ptr+i) */
4702 if (i < v.len && *(v.ptr + i) == '=') {
4703 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4704 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4705 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4706 continue;
4707 }
4708
4709 /* we have something of the form no-cache="set-cookie" */
4710 if ((v.len >= 21) &&
4711 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4712 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4713 txn->flags &= ~TX_CACHE_COOK;
4714 continue;
4715 }
4716
4717 /* OK, so we know that either p2 points to the end of string or to a comma */
4718 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4719 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4720 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4721 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4722 return;
4723 }
4724
4725 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4726 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4727 continue;
4728 }
4729 }
4730}
4731
Christopher Faulet64159df2018-10-24 21:15:35 +02004732/* send a server's name with an outgoing request over an established connection.
4733 * Note: this function is designed to be called once the request has been
4734 * scheduled for being forwarded. This is the reason why the number of forwarded
4735 * bytes have to be adjusted.
4736 */
4737int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4738{
4739 struct htx *htx;
4740 struct http_hdr_ctx ctx;
4741 struct ist hdr;
4742 uint32_t data;
4743
4744 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004745 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004746 data = htx->data;
4747
4748 ctx.blk = NULL;
4749 while (http_find_header(htx, hdr, &ctx, 1))
4750 http_remove_header(htx, &ctx);
4751 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4752
4753 if (co_data(&s->req)) {
4754 if (data >= htx->data)
4755 c_rew(&s->req, data - htx->data);
4756 else
4757 c_adv(&s->req, htx->data - data);
4758 }
4759 return 0;
4760}
4761
Christopher Faulet377c5a52018-10-24 21:21:30 +02004762/*
4763 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4764 * for the current backend.
4765 *
4766 * It is assumed that the request is either a HEAD, GET, or POST and that the
4767 * uri_auth field is valid.
4768 *
4769 * Returns 1 if stats should be provided, otherwise 0.
4770 */
4771static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4772{
4773 struct uri_auth *uri_auth = backend->uri_auth;
4774 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004775 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004776 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004777
4778 if (!uri_auth)
4779 return 0;
4780
4781 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4782 return 0;
4783
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004784 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004785 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004786 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004787
4788 /* check URI size */
4789 if (uri_auth->uri_len > uri.len)
4790 return 0;
4791
4792 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4793 return 0;
4794
4795 return 1;
4796}
4797
4798/* This function prepares an applet to handle the stats. It can deal with the
4799 * "100-continue" expectation, check that admin rules are met for POST requests,
4800 * and program a response message if something was unexpected. It cannot fail
4801 * and always relies on the stats applet to complete the job. It does not touch
4802 * analysers nor counters, which are left to the caller. It does not touch
4803 * s->target which is supposed to already point to the stats applet. The caller
4804 * is expected to have already assigned an appctx to the stream.
4805 */
4806static int htx_handle_stats(struct stream *s, struct channel *req)
4807{
4808 struct stats_admin_rule *stats_admin_rule;
4809 struct stream_interface *si = &s->si[1];
4810 struct session *sess = s->sess;
4811 struct http_txn *txn = s->txn;
4812 struct http_msg *msg = &txn->req;
4813 struct uri_auth *uri_auth = s->be->uri_auth;
4814 const char *h, *lookup, *end;
4815 struct appctx *appctx;
4816 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004817 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004818
4819 appctx = si_appctx(si);
4820 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4821 appctx->st1 = appctx->st2 = 0;
4822 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4823 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4824 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4825 appctx->ctx.stats.flags |= STAT_CHUNKED;
4826
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004827 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004828 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004829 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4830 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004831
4832 for (h = lookup; h <= end - 3; h++) {
4833 if (memcmp(h, ";up", 3) == 0) {
4834 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4835 break;
4836 }
4837 }
4838
4839 if (uri_auth->refresh) {
4840 for (h = lookup; h <= end - 10; h++) {
4841 if (memcmp(h, ";norefresh", 10) == 0) {
4842 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4843 break;
4844 }
4845 }
4846 }
4847
4848 for (h = lookup; h <= end - 4; h++) {
4849 if (memcmp(h, ";csv", 4) == 0) {
4850 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4851 break;
4852 }
4853 }
4854
4855 for (h = lookup; h <= end - 6; h++) {
4856 if (memcmp(h, ";typed", 6) == 0) {
4857 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4858 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4859 break;
4860 }
4861 }
4862
4863 for (h = lookup; h <= end - 8; h++) {
4864 if (memcmp(h, ";st=", 4) == 0) {
4865 int i;
4866 h += 4;
4867 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4868 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4869 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4870 appctx->ctx.stats.st_code = i;
4871 break;
4872 }
4873 }
4874 break;
4875 }
4876 }
4877
4878 appctx->ctx.stats.scope_str = 0;
4879 appctx->ctx.stats.scope_len = 0;
4880 for (h = lookup; h <= end - 8; h++) {
4881 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4882 int itx = 0;
4883 const char *h2;
4884 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4885 const char *err;
4886
4887 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4888 h2 = h;
4889 appctx->ctx.stats.scope_str = h2 - s->txn->uri;
4890 while (h <= end) {
4891 if (*h == ';' || *h == '&' || *h == ' ')
4892 break;
4893 itx++;
4894 h++;
4895 }
4896
4897 if (itx > STAT_SCOPE_TXT_MAXLEN)
4898 itx = STAT_SCOPE_TXT_MAXLEN;
4899 appctx->ctx.stats.scope_len = itx;
4900
4901 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4902 memcpy(scope_txt, h2, itx);
4903 scope_txt[itx] = '\0';
4904 err = invalid_char(scope_txt);
4905 if (err) {
4906 /* bad char in search text => clear scope */
4907 appctx->ctx.stats.scope_str = 0;
4908 appctx->ctx.stats.scope_len = 0;
4909 }
4910 break;
4911 }
4912 }
4913
4914 /* now check whether we have some admin rules for this request */
4915 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4916 int ret = 1;
4917
4918 if (stats_admin_rule->cond) {
4919 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4920 ret = acl_pass(ret);
4921 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4922 ret = !ret;
4923 }
4924
4925 if (ret) {
4926 /* no rule, or the rule matches */
4927 appctx->ctx.stats.flags |= STAT_ADMIN;
4928 break;
4929 }
4930 }
4931
4932 /* Was the status page requested with a POST ? */
4933 if (unlikely(txn->meth == HTTP_METH_POST)) {
4934 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4935 /* we'll need the request body, possibly after sending 100-continue */
4936 if (msg->msg_state < HTTP_MSG_DATA)
4937 req->analysers |= AN_REQ_HTTP_BODY;
4938 appctx->st0 = STAT_HTTP_POST;
4939 }
4940 else {
4941 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4942 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4943 appctx->st0 = STAT_HTTP_LAST;
4944 }
4945 }
4946 else {
4947 /* So it was another method (GET/HEAD) */
4948 appctx->st0 = STAT_HTTP_HEAD;
4949 }
4950
4951 s->task->nice = -32; /* small boost for HTTP statistics */
4952 return 1;
4953}
4954
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004955void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4956{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004957 struct channel *req = &s->req;
4958 struct channel *res = &s->res;
4959 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004960 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004961 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004962 struct ist path, location;
4963 unsigned int flags;
4964 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004965
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004966 /*
4967 * Create the location
4968 */
4969 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004970
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004971 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004972 /* special prefix "/" means don't change URL */
4973 srv = __objt_server(s->target);
4974 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4975 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4976 return;
4977 }
4978
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004979 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004980 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004981 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004982 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004983 if (!path.ptr)
4984 return;
4985
4986 if (!chunk_memcat(&trash, path.ptr, path.len))
4987 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004988 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004989
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004990 /*
4991 * Create the 302 respone
4992 */
4993 htx = htx_from_buf(&res->buf);
4994 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4995 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4996 ist("HTTP/1.1"), ist("302"), ist("Found"));
4997 if (!sl)
4998 goto fail;
4999 sl->info.res.status = 302;
5000 s->txn->status = 302;
5001
5002 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5003 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5004 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5005 !htx_add_header(htx, ist("Location"), location))
5006 goto fail;
5007
5008 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5009 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005010
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005011 /*
5012 * Send the message
5013 */
5014 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005015 c_adv(res, data);
5016 res->total += data;
5017
5018 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005019 si_shutr(si);
5020 si_shutw(si);
5021 si->err_type = SI_ET_NONE;
5022 si->state = SI_ST_CLO;
5023
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005024 channel_auto_read(req);
5025 channel_abort(req);
5026 channel_auto_close(req);
5027 channel_erase(req);
5028 channel_auto_read(res);
5029 channel_auto_close(res);
5030
5031 if (!(s->flags & SF_ERR_MASK))
5032 s->flags |= SF_ERR_LOCAL;
5033 if (!(s->flags & SF_FINST_MASK))
5034 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005035
5036 /* FIXME: we should increase a counter of redirects per server and per backend. */
5037 srv_inc_sess_ctr(srv);
5038 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005039 return;
5040
5041 fail:
5042 /* If an error occurred, remove the incomplete HTTP response from the
5043 * buffer */
5044 channel_truncate(res);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005045}
5046
Christopher Fauletf2824e62018-10-01 12:12:37 +02005047/* This function terminates the request because it was completly analyzed or
5048 * because an error was triggered during the body forwarding.
5049 */
5050static void htx_end_request(struct stream *s)
5051{
5052 struct channel *chn = &s->req;
5053 struct http_txn *txn = s->txn;
5054
5055 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5056 now_ms, __FUNCTION__, s,
5057 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5058 s->req.analysers, s->res.analysers);
5059
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005060 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5061 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005062 channel_abort(chn);
5063 channel_truncate(chn);
5064 goto end;
5065 }
5066
5067 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5068 return;
5069
5070 if (txn->req.msg_state == HTTP_MSG_DONE) {
5071 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5072 /* The server has not finished to respond, so we
5073 * don't want to move in order not to upset it.
5074 */
5075 return;
5076 }
5077
5078 /* No need to read anymore, the request was completely parsed.
5079 * We can shut the read side unless we want to abort_on_close,
5080 * or we have a POST request. The issue with POST requests is
5081 * that some browsers still send a CRLF after the request, and
5082 * this CRLF must be read so that it does not remain in the kernel
5083 * buffers, otherwise a close could cause an RST on some systems
5084 * (eg: Linux).
5085 */
5086 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5087 txn->meth != HTTP_METH_POST)
5088 channel_dont_read(chn);
5089
5090 /* if the server closes the connection, we want to immediately react
5091 * and close the socket to save packets and syscalls.
5092 */
5093 s->si[1].flags |= SI_FL_NOHALF;
5094
5095 /* In any case we've finished parsing the request so we must
5096 * disable Nagle when sending data because 1) we're not going
5097 * to shut this side, and 2) the server is waiting for us to
5098 * send pending data.
5099 */
5100 chn->flags |= CF_NEVER_WAIT;
5101
5102 /* When we get here, it means that both the request and the
5103 * response have finished receiving. Depending on the connection
5104 * mode, we'll have to wait for the last bytes to leave in either
5105 * direction, and sometimes for a close to be effective.
5106 */
5107 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5108 /* Tunnel mode will not have any analyser so it needs to
5109 * poll for reads.
5110 */
5111 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005112 if (b_data(&chn->buf))
5113 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005114 txn->req.msg_state = HTTP_MSG_TUNNEL;
5115 }
5116 else {
5117 /* we're not expecting any new data to come for this
5118 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005119 *
5120 * However, there is an exception if the response
5121 * length is undefined. In this case, we need to wait
5122 * the close from the server. The response will be
5123 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005124 */
5125 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5126 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005127 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005128
5129 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5130 channel_shutr_now(chn);
5131 channel_shutw_now(chn);
5132 }
5133 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005134 goto check_channel_flags;
5135 }
5136
5137 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5138 http_msg_closing:
5139 /* nothing else to forward, just waiting for the output buffer
5140 * to be empty and for the shutw_now to take effect.
5141 */
5142 if (channel_is_empty(chn)) {
5143 txn->req.msg_state = HTTP_MSG_CLOSED;
5144 goto http_msg_closed;
5145 }
5146 else if (chn->flags & CF_SHUTW) {
5147 txn->req.err_state = txn->req.msg_state;
5148 txn->req.msg_state = HTTP_MSG_ERROR;
5149 goto end;
5150 }
5151 return;
5152 }
5153
5154 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5155 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005156 /* if we don't know whether the server will close, we need to hard close */
5157 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5158 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005159 /* see above in MSG_DONE why we only do this in these states */
5160 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5161 channel_dont_read(chn);
5162 goto end;
5163 }
5164
5165 check_channel_flags:
5166 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5167 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5168 /* if we've just closed an output, let's switch */
5169 txn->req.msg_state = HTTP_MSG_CLOSING;
5170 goto http_msg_closing;
5171 }
5172
5173 end:
5174 chn->analysers &= AN_REQ_FLT_END;
5175 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5176 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5177 channel_auto_close(chn);
5178 channel_auto_read(chn);
5179}
5180
5181
5182/* This function terminates the response because it was completly analyzed or
5183 * because an error was triggered during the body forwarding.
5184 */
5185static void htx_end_response(struct stream *s)
5186{
5187 struct channel *chn = &s->res;
5188 struct http_txn *txn = s->txn;
5189
5190 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5191 now_ms, __FUNCTION__, s,
5192 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5193 s->req.analysers, s->res.analysers);
5194
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005195 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5196 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf3d48052018-12-04 16:23:54 +01005197 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005198 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005199 goto end;
5200 }
5201
5202 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5203 return;
5204
5205 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5206 /* In theory, we don't need to read anymore, but we must
5207 * still monitor the server connection for a possible close
5208 * while the request is being uploaded, so we don't disable
5209 * reading.
5210 */
5211 /* channel_dont_read(chn); */
5212
5213 if (txn->req.msg_state < HTTP_MSG_DONE) {
5214 /* The client seems to still be sending data, probably
5215 * because we got an error response during an upload.
5216 * We have the choice of either breaking the connection
5217 * or letting it pass through. Let's do the later.
5218 */
5219 return;
5220 }
5221
5222 /* When we get here, it means that both the request and the
5223 * response have finished receiving. Depending on the connection
5224 * mode, we'll have to wait for the last bytes to leave in either
5225 * direction, and sometimes for a close to be effective.
5226 */
5227 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5228 channel_auto_read(chn);
5229 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005230 if (b_data(&chn->buf))
5231 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005232 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5233 }
5234 else {
5235 /* we're not expecting any new data to come for this
5236 * transaction, so we can close it.
5237 */
5238 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5239 channel_shutr_now(chn);
5240 channel_shutw_now(chn);
5241 }
5242 }
5243 goto check_channel_flags;
5244 }
5245
5246 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5247 http_msg_closing:
5248 /* nothing else to forward, just waiting for the output buffer
5249 * to be empty and for the shutw_now to take effect.
5250 */
5251 if (channel_is_empty(chn)) {
5252 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5253 goto http_msg_closed;
5254 }
5255 else if (chn->flags & CF_SHUTW) {
5256 txn->rsp.err_state = txn->rsp.msg_state;
5257 txn->rsp.msg_state = HTTP_MSG_ERROR;
5258 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5259 if (objt_server(s->target))
5260 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5261 goto end;
5262 }
5263 return;
5264 }
5265
5266 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5267 http_msg_closed:
5268 /* drop any pending data */
Christopher Fauletf3d48052018-12-04 16:23:54 +01005269 channel_truncate(&s->req);
Christopher Faulet9768c262018-10-22 09:34:31 +02005270 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005271 goto end;
5272 }
5273
5274 check_channel_flags:
5275 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5276 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5277 /* if we've just closed an output, let's switch */
5278 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5279 goto http_msg_closing;
5280 }
5281
5282 end:
5283 chn->analysers &= AN_RES_FLT_END;
5284 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5285 chn->analysers |= AN_RES_FLT_XFER_DATA;
5286 channel_auto_close(chn);
5287 channel_auto_read(chn);
5288}
5289
Christopher Faulet0f226952018-10-22 09:29:56 +02005290void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5291 int finst, const struct buffer *msg)
5292{
5293 channel_auto_read(si_oc(si));
5294 channel_abort(si_oc(si));
5295 channel_auto_close(si_oc(si));
5296 channel_erase(si_oc(si));
5297 channel_auto_close(si_ic(si));
5298 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005299
5300 /* <msg> is an HTX structure. So we copy it in the response's
5301 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005302 if (msg) {
5303 struct channel *chn = si_ic(si);
5304 struct htx *htx;
5305
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005306 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005307 chn->buf.data = msg->data;
5308 memcpy(chn->buf.area, msg->area, msg->data);
5309 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005310 c_adv(chn, htx->data);
5311 chn->total += htx->data;
5312 }
5313 if (!(s->flags & SF_ERR_MASK))
5314 s->flags |= err;
5315 if (!(s->flags & SF_FINST_MASK))
5316 s->flags |= finst;
5317}
5318
5319void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5320{
5321 channel_auto_read(&s->req);
5322 channel_abort(&s->req);
5323 channel_auto_close(&s->req);
5324 channel_erase(&s->req);
5325 channel_truncate(&s->res);
5326
5327 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005328
5329 /* <msg> is an HTX structure. So we copy it in the response's
5330 * channel */
5331 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005332 if (msg) {
5333 struct channel *chn = &s->res;
5334 struct htx *htx;
5335
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005336 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005337 chn->buf.data = msg->data;
5338 memcpy(chn->buf.area, msg->area, msg->data);
5339 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005340 c_adv(chn, htx->data);
5341 chn->total += htx->data;
5342 }
5343
5344 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5345 channel_auto_read(&s->res);
5346 channel_auto_close(&s->res);
5347 channel_shutr_now(&s->res);
5348}
5349
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005350struct buffer *htx_error_message(struct stream *s)
5351{
5352 const int msgnum = http_get_status_idx(s->txn->status);
5353
5354 if (s->be->errmsg[msgnum].area)
5355 return &s->be->errmsg[msgnum];
5356 else if (strm_fe(s)->errmsg[msgnum].area)
5357 return &strm_fe(s)->errmsg[msgnum];
5358 else
5359 return &htx_err_chunks[msgnum];
5360}
5361
5362
Christopher Faulet23a3c792018-11-28 10:01:23 +01005363/* Send a 100-Continue response to the client. It returns 0 on success and -1
5364 * on error. The response channel is updated accordingly.
5365 */
5366static int htx_reply_100_continue(struct stream *s)
5367{
5368 struct channel *res = &s->res;
5369 struct htx *htx = htx_from_buf(&res->buf);
5370 struct htx_sl *sl;
5371 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5372 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5373 size_t data;
5374
5375 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5376 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5377 if (!sl)
5378 goto fail;
5379 sl->info.res.status = 100;
5380
5381 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5382 goto fail;
5383
5384 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005385 c_adv(res, data);
5386 res->total += data;
5387 return 0;
5388
5389 fail:
5390 /* If an error occurred, remove the incomplete HTTP response from the
5391 * buffer */
5392 channel_truncate(res);
5393 return -1;
5394}
5395
Christopher Faulet12c51e22018-11-28 15:59:42 +01005396
5397/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5398 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5399 * error. The response channel is updated accordingly.
5400 */
5401static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5402{
5403 struct channel *res = &s->res;
5404 struct htx *htx = htx_from_buf(&res->buf);
5405 struct htx_sl *sl;
5406 struct ist code, body;
5407 int status;
5408 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5409 size_t data;
5410
5411 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5412 status = 401;
5413 code = ist("401");
5414 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5415 "You need a valid user and password to access this content.\n"
5416 "</body></html>\n");
5417 }
5418 else {
5419 status = 407;
5420 code = ist("407");
5421 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5422 "You need a valid user and password to access this content.\n"
5423 "</body></html>\n");
5424 }
5425
5426 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5427 ist("HTTP/1.1"), code, ist("Unauthorized"));
5428 if (!sl)
5429 goto fail;
5430 sl->info.res.status = status;
5431 s->txn->status = status;
5432
5433 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5434 goto fail;
5435
5436 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5437 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5438 !htx_add_header(htx, ist("Content-Type"), ist("text/html")) ||
5439 !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
5440 goto fail;
5441
5442 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5443 goto fail;
5444
5445 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005446 c_adv(res, data);
5447 res->total += data;
5448
5449 channel_auto_read(&s->req);
5450 channel_abort(&s->req);
5451 channel_auto_close(&s->req);
5452 channel_erase(&s->req);
5453
5454 res->wex = tick_add_ifset(now_ms, res->wto);
5455 channel_auto_read(res);
5456 channel_auto_close(res);
5457 channel_shutr_now(res);
5458 return 0;
5459
5460 fail:
5461 /* If an error occurred, remove the incomplete HTTP response from the
5462 * buffer */
5463 channel_truncate(res);
5464 return -1;
5465}
5466
Christopher Faulet0f226952018-10-22 09:29:56 +02005467/*
5468 * Capture headers from message <htx> according to header list <cap_hdr>, and
5469 * fill the <cap> pointers appropriately.
5470 */
5471static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5472{
5473 struct cap_hdr *h;
5474 int32_t pos;
5475
5476 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5477 struct htx_blk *blk = htx_get_blk(htx, pos);
5478 enum htx_blk_type type = htx_get_blk_type(blk);
5479 struct ist n, v;
5480
5481 if (type == HTX_BLK_EOH)
5482 break;
5483 if (type != HTX_BLK_HDR)
5484 continue;
5485
5486 n = htx_get_blk_name(htx, blk);
5487
5488 for (h = cap_hdr; h; h = h->next) {
5489 if (h->namelen && (h->namelen == n.len) &&
5490 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5491 if (cap[h->index] == NULL)
5492 cap[h->index] =
5493 pool_alloc(h->pool);
5494
5495 if (cap[h->index] == NULL) {
5496 ha_alert("HTTP capture : out of memory.\n");
5497 break;
5498 }
5499
5500 v = htx_get_blk_value(htx, blk);
5501 if (v.len > h->len)
5502 v.len = h->len;
5503
5504 memcpy(cap[h->index], v.ptr, v.len);
5505 cap[h->index][v.len]=0;
5506 }
5507 }
5508 }
5509}
5510
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005511/* Delete a value in a header between delimiters <from> and <next>. The header
5512 * itself is delimited by <start> and <end> pointers. The number of characters
5513 * displaced is returned, and the pointer to the first delimiter is updated if
5514 * required. The function tries as much as possible to respect the following
5515 * principles :
5516 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5517 * in which case <next> is simply removed
5518 * - set exactly one space character after the new first delimiter, unless there
5519 * are not enough characters in the block being moved to do so.
5520 * - remove unneeded spaces before the previous delimiter and after the new
5521 * one.
5522 *
5523 * It is the caller's responsibility to ensure that :
5524 * - <from> points to a valid delimiter or <start> ;
5525 * - <next> points to a valid delimiter or <end> ;
5526 * - there are non-space chars before <from>.
5527 */
5528static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5529{
5530 char *prev = *from;
5531
5532 if (prev == start) {
5533 /* We're removing the first value. eat the semicolon, if <next>
5534 * is lower than <end> */
5535 if (next < end)
5536 next++;
5537
5538 while (next < end && HTTP_IS_SPHT(*next))
5539 next++;
5540 }
5541 else {
5542 /* Remove useless spaces before the old delimiter. */
5543 while (HTTP_IS_SPHT(*(prev-1)))
5544 prev--;
5545 *from = prev;
5546
5547 /* copy the delimiter and if possible a space if we're
5548 * not at the end of the line.
5549 */
5550 if (next < end) {
5551 *prev++ = *next++;
5552 if (prev + 1 < next)
5553 *prev++ = ' ';
5554 while (next < end && HTTP_IS_SPHT(*next))
5555 next++;
5556 }
5557 }
5558 memmove(prev, next, end - next);
5559 return (prev - next);
5560}
5561
Christopher Faulet0f226952018-10-22 09:29:56 +02005562
5563/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005564 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005565 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005566static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005567{
5568 struct ist dst = ist2(str, 0);
5569
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005570 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005571 goto end;
5572 if (dst.len + 1 > len)
5573 goto end;
5574 dst.ptr[dst.len++] = ' ';
5575
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005576 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005577 goto end;
5578 if (dst.len + 1 > len)
5579 goto end;
5580 dst.ptr[dst.len++] = ' ';
5581
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005582 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005583 end:
5584 return dst.len;
5585}
5586
Christopher Fauletf0523542018-10-24 11:06:58 +02005587/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005588 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005589 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005590static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005591{
5592 struct ist dst = ist2(str, 0);
5593
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005594 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005595 goto end;
5596 if (dst.len + 1 > len)
5597 goto end;
5598 dst.ptr[dst.len++] = ' ';
5599
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005600 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005601 goto end;
5602 if (dst.len + 1 > len)
5603 goto end;
5604 dst.ptr[dst.len++] = ' ';
5605
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005606 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005607 end:
5608 return dst.len;
5609}
5610
5611
Christopher Faulet0f226952018-10-22 09:29:56 +02005612/*
5613 * Print a debug line with a start line.
5614 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005615static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005616{
5617 struct session *sess = strm_sess(s);
5618 int max;
5619
5620 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5621 dir,
5622 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5623 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5624
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005625 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005626 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005628 trash.area[trash.data++] = ' ';
5629
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005631 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005632 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005633 trash.area[trash.data++] = ' ';
5634
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005635 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005636 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005637 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005638 trash.area[trash.data++] = '\n';
5639
5640 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5641}
5642
5643/*
5644 * Print a debug line with a header.
5645 */
5646static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5647{
5648 struct session *sess = strm_sess(s);
5649 int max;
5650
5651 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5652 dir,
5653 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5654 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5655
5656 max = n.len;
5657 UBOUND(max, trash.size - trash.data - 3);
5658 chunk_memcat(&trash, n.ptr, max);
5659 trash.area[trash.data++] = ':';
5660 trash.area[trash.data++] = ' ';
5661
5662 max = v.len;
5663 UBOUND(max, trash.size - trash.data - 1);
5664 chunk_memcat(&trash, v.ptr, max);
5665 trash.area[trash.data++] = '\n';
5666
5667 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5668}
5669
5670
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005671__attribute__((constructor))
5672static void __htx_protocol_init(void)
5673{
5674}
5675
5676
5677/*
5678 * Local variables:
5679 * c-indent-level: 8
5680 * c-basic-offset: 8
5681 * End:
5682 */