blob: 9fa82065396296606a2b8285b0a481e826c3ba37 [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;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100551 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200552 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 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100668 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200669
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)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100941 s->txn->meth == HTTP_METH_POST &&
942 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200943 channel_dont_connect(req);
944 req->analysers |= AN_REQ_HTTP_BODY;
945 }
946
947 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
948 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100949
Christopher Faulete0768eb2018-10-03 16:38:02 +0200950 /* We expect some data from the client. Unless we know for sure
951 * we already have a full request, we have to re-enable quick-ack
952 * in case we previously disabled it, otherwise we might cause
953 * the client to delay further data.
954 */
955 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200956 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100957 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200958
959 /*************************************************************
960 * OK, that's finished for the headers. We have done what we *
961 * could. Let's switch to the DATA state. *
962 ************************************************************/
963 req->analyse_exp = TICK_ETERNITY;
964 req->analysers &= ~an_bit;
965
966 s->logs.tv_request = now;
967 /* OK let's go on with the BODY now */
968 return 1;
969
970 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200971 txn->req.err_state = txn->req.msg_state;
972 txn->req.msg_state = HTTP_MSG_ERROR;
973 txn->status = 400;
974 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100975 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200976
977 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
978 if (sess->listener->counters)
979 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
980
981 if (!(s->flags & SF_ERR_MASK))
982 s->flags |= SF_ERR_PRXCOND;
983 if (!(s->flags & SF_FINST_MASK))
984 s->flags |= SF_FINST_R;
985 return 0;
986}
987
988/* This function is an analyser which processes the HTTP tarpit. It always
989 * returns zero, at the beginning because it prevents any other processing
990 * from occurring, and at the end because it terminates the request.
991 */
992int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
993{
994 struct http_txn *txn = s->txn;
995
996 /* This connection is being tarpitted. The CLIENT side has
997 * already set the connect expiration date to the right
998 * timeout. We just have to check that the client is still
999 * there and that the timeout has not expired.
1000 */
1001 channel_dont_connect(req);
1002 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1003 !tick_is_expired(req->analyse_exp, now_ms))
1004 return 0;
1005
1006 /* We will set the queue timer to the time spent, just for
1007 * logging purposes. We fake a 500 server error, so that the
1008 * attacker will not suspect his connection has been tarpitted.
1009 * It will not cause trouble to the logs because we can exclude
1010 * the tarpitted connections by filtering on the 'PT' status flags.
1011 */
1012 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1013
1014 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001015 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001016
1017 req->analysers &= AN_REQ_FLT_END;
1018 req->analyse_exp = TICK_ETERNITY;
1019
1020 if (!(s->flags & SF_ERR_MASK))
1021 s->flags |= SF_ERR_PRXCOND;
1022 if (!(s->flags & SF_FINST_MASK))
1023 s->flags |= SF_FINST_T;
1024 return 0;
1025}
1026
1027/* This function is an analyser which waits for the HTTP request body. It waits
1028 * for either the buffer to be full, or the full advertised contents to have
1029 * reached the buffer. It must only be called after the standard HTTP request
1030 * processing has occurred, because it expects the request to be parsed and will
1031 * look for the Expect header. It may send a 100-Continue interim response. It
1032 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1033 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1034 * needs to read more data, or 1 once it has completed its analysis.
1035 */
1036int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1037{
1038 struct session *sess = s->sess;
1039 struct http_txn *txn = s->txn;
1040 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001041 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001042
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001043
1044 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1045 now_ms, __FUNCTION__,
1046 s,
1047 req,
1048 req->rex, req->wex,
1049 req->flags,
1050 ci_data(req),
1051 req->analysers);
1052
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001053 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001054
1055 if (msg->msg_state < HTTP_MSG_BODY)
1056 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001057
Christopher Faulete0768eb2018-10-03 16:38:02 +02001058 /* We have to parse the HTTP request body to find any required data.
1059 * "balance url_param check_post" should have been the only way to get
1060 * into this. We were brought here after HTTP header analysis, so all
1061 * related structures are ready.
1062 */
1063
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001064 if (msg->msg_state < HTTP_MSG_DATA) {
1065 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1066 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001067 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068 if (msg->flags & HTTP_MSGF_VER_11) {
1069 struct ist hdr = { .ptr = "Expect", .len = 6 };
1070 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001072 ctx.blk = NULL;
1073 /* Expect is allowed in 1.1, look for it */
1074 if (http_find_header(htx, hdr, &ctx, 0) &&
1075 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001076 if (htx_reply_100_continue(s) == -1)
1077 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001078 http_remove_header(htx, &ctx);
1079 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001081 }
1082
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001083 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1086 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
1089 htx_used_space(htx) + global.tune.maxrewrite >= htx->size)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 goto http_end;
1091
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001092 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001093 if (htx->flags & HTX_FL_PARSING_ERROR)
1094 goto return_bad_req;
1095
Christopher Faulete0768eb2018-10-03 16:38:02 +02001096 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1097 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001098 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001099
1100 if (!(s->flags & SF_ERR_MASK))
1101 s->flags |= SF_ERR_CLITO;
1102 if (!(s->flags & SF_FINST_MASK))
1103 s->flags |= SF_FINST_D;
1104 goto return_err_msg;
1105 }
1106
1107 /* we get here if we need to wait for more data */
1108 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1109 /* Not enough data. We'll re-use the http-request
1110 * timeout here. Ideally, we should set the timeout
1111 * relative to the accept() date. We just set the
1112 * request timeout once at the beginning of the
1113 * request.
1114 */
1115 channel_dont_connect(req);
1116 if (!tick_isset(req->analyse_exp))
1117 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1118 return 0;
1119 }
1120
1121 http_end:
1122 /* The situation will not evolve, so let's give up on the analysis. */
1123 s->logs.tv_request = now; /* update the request timer to reflect full request */
1124 req->analysers &= ~an_bit;
1125 req->analyse_exp = TICK_ETERNITY;
1126 return 1;
1127
1128 return_bad_req: /* let's centralize all bad requests */
1129 txn->req.err_state = txn->req.msg_state;
1130 txn->req.msg_state = HTTP_MSG_ERROR;
1131 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001132 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001133
1134 if (!(s->flags & SF_ERR_MASK))
1135 s->flags |= SF_ERR_PRXCOND;
1136 if (!(s->flags & SF_FINST_MASK))
1137 s->flags |= SF_FINST_R;
1138
1139 return_err_msg:
1140 req->analysers &= AN_REQ_FLT_END;
1141 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1142 if (sess->listener->counters)
1143 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1144 return 0;
1145}
1146
1147/* This function is an analyser which forwards request body (including chunk
1148 * sizes if any). It is called as soon as we must forward, even if we forward
1149 * zero byte. The only situation where it must not be called is when we're in
1150 * tunnel mode and we want to forward till the close. It's used both to forward
1151 * remaining data and to resync after end of body. It expects the msg_state to
1152 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1153 * read more data, or 1 once we can go on with next request or end the stream.
1154 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1155 * bytes of pending data + the headers if not already done.
1156 */
1157int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1158{
1159 struct session *sess = s->sess;
1160 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001161 struct http_msg *msg = &txn->req;
1162 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001163 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001164
1165 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1166 now_ms, __FUNCTION__,
1167 s,
1168 req,
1169 req->rex, req->wex,
1170 req->flags,
1171 ci_data(req),
1172 req->analysers);
1173
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001174 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001175
1176 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1177 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1178 /* Output closed while we were sending data. We must abort and
1179 * wake the other side up.
1180 */
1181 msg->err_state = msg->msg_state;
1182 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001183 htx_end_request(s);
1184 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001185 return 1;
1186 }
1187
1188 /* Note that we don't have to send 100-continue back because we don't
1189 * need the data to complete our job, and it's up to the server to
1190 * decide whether to return 100, 417 or anything else in return of
1191 * an "Expect: 100-continue" header.
1192 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001193 if (msg->msg_state == HTTP_MSG_BODY)
1194 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001195
1196 /* Some post-connect processing might want us to refrain from starting to
1197 * forward data. Currently, the only reason for this is "balance url_param"
1198 * whichs need to parse/process the request after we've enabled forwarding.
1199 */
1200 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1201 if (!(s->res.flags & CF_READ_ATTACHED)) {
1202 channel_auto_connect(req);
1203 req->flags |= CF_WAKE_CONNECT;
1204 channel_dont_close(req); /* don't fail on early shutr */
1205 goto waiting;
1206 }
1207 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1208 }
1209
1210 /* in most states, we should abort in case of early close */
1211 channel_auto_close(req);
1212
1213 if (req->to_forward) {
1214 /* We can't process the buffer's contents yet */
1215 req->flags |= CF_WAKE_WRITE;
1216 goto missing_data_or_waiting;
1217 }
1218
Christopher Faulet9768c262018-10-22 09:34:31 +02001219 if (msg->msg_state >= HTTP_MSG_DONE)
1220 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001221 /* Forward input data. We get it by removing all outgoing data not
1222 * forwarded yet from HTX data size. If there are some data filters, we
1223 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001224 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001225 if (HAS_REQ_DATA_FILTERS(s)) {
1226 ret = flt_http_payload(s, msg, htx->data);
1227 if (ret < 0)
1228 goto return_bad_req;
1229 c_adv(req, ret);
1230 if (htx->data != co_data(req) || htx->extra)
1231 goto missing_data_or_waiting;
1232 }
1233 else {
1234 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001235
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001236 /* To let the function channel_forward work as expected we must update
1237 * the channel's buffer to pretend there is no more input data. The
1238 * right length is then restored. We must do that, because when an HTX
1239 * message is stored into a buffer, it appears as full.
1240 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001241 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1242 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001243 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001244
Christopher Faulet9768c262018-10-22 09:34:31 +02001245 /* Check if the end-of-message is reached and if so, switch the message
1246 * in HTTP_MSG_DONE state.
1247 */
1248 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1249 goto missing_data_or_waiting;
1250
1251 msg->msg_state = HTTP_MSG_DONE;
1252
1253 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001254 /* other states, DONE...TUNNEL */
1255 /* we don't want to forward closes on DONE except in tunnel mode. */
1256 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1257 channel_dont_close(req);
1258
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001259 if (HAS_REQ_DATA_FILTERS(s)) {
1260 ret = flt_http_end(s, msg);
1261 if (ret <= 0) {
1262 if (!ret)
1263 goto missing_data_or_waiting;
1264 goto return_bad_req;
1265 }
1266 }
1267
Christopher Fauletf2824e62018-10-01 12:12:37 +02001268 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001269 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001270 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001271 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1272 if (req->flags & CF_SHUTW) {
1273 /* request errors are most likely due to the
1274 * server aborting the transfer. */
1275 goto aborted_xfer;
1276 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001277 goto return_bad_req;
1278 }
1279 return 1;
1280 }
1281
1282 /* If "option abortonclose" is set on the backend, we want to monitor
1283 * the client's connection and forward any shutdown notification to the
1284 * server, which will decide whether to close or to go on processing the
1285 * request. We only do that in tunnel mode, and not in other modes since
1286 * it can be abused to exhaust source ports. */
1287 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1288 channel_auto_read(req);
1289 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1290 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1291 s->si[1].flags |= SI_FL_NOLINGER;
1292 channel_auto_close(req);
1293 }
1294 else if (s->txn->meth == HTTP_METH_POST) {
1295 /* POST requests may require to read extra CRLF sent by broken
1296 * browsers and which could cause an RST to be sent upon close
1297 * on some systems (eg: Linux). */
1298 channel_auto_read(req);
1299 }
1300 return 0;
1301
1302 missing_data_or_waiting:
1303 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001304 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001305 if (!(s->flags & SF_ERR_MASK))
1306 s->flags |= SF_ERR_CLICL;
1307 if (!(s->flags & SF_FINST_MASK)) {
1308 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1309 s->flags |= SF_FINST_H;
1310 else
1311 s->flags |= SF_FINST_D;
1312 }
1313
1314 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1315 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1316 if (objt_server(s->target))
1317 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1318
1319 goto return_bad_req_stats_ok;
1320 }
1321
1322 waiting:
1323 /* waiting for the last bits to leave the buffer */
1324 if (req->flags & CF_SHUTW)
1325 goto aborted_xfer;
1326
Christopher Faulet47365272018-10-31 17:40:50 +01001327 if (htx->flags & HTX_FL_PARSING_ERROR)
1328 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001329
Christopher Faulete0768eb2018-10-03 16:38:02 +02001330 /* When TE: chunked is used, we need to get there again to parse remaining
1331 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1332 * And when content-length is used, we never want to let the possible
1333 * shutdown be forwarded to the other side, as the state machine will
1334 * take care of it once the client responds. It's also important to
1335 * prevent TIME_WAITs from accumulating on the backend side, and for
1336 * HTTP/2 where the last frame comes with a shutdown.
1337 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001338 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001339 channel_dont_close(req);
1340
1341 /* We know that more data are expected, but we couldn't send more that
1342 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1343 * system knows it must not set a PUSH on this first part. Interactive
1344 * modes are already handled by the stream sock layer. We must not do
1345 * this in content-length mode because it could present the MSG_MORE
1346 * flag with the last block of forwarded data, which would cause an
1347 * additional delay to be observed by the receiver.
1348 */
1349 if (msg->flags & HTTP_MSGF_TE_CHNK)
1350 req->flags |= CF_EXPECT_MORE;
1351
1352 return 0;
1353
1354 return_bad_req: /* let's centralize all bad requests */
1355 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1356 if (sess->listener->counters)
1357 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1358
1359 return_bad_req_stats_ok:
1360 txn->req.err_state = txn->req.msg_state;
1361 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001362 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001363 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001364 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001365 } else {
1366 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001367 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 }
1369 req->analysers &= AN_REQ_FLT_END;
1370 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1371
1372 if (!(s->flags & SF_ERR_MASK))
1373 s->flags |= SF_ERR_PRXCOND;
1374 if (!(s->flags & SF_FINST_MASK)) {
1375 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1376 s->flags |= SF_FINST_H;
1377 else
1378 s->flags |= SF_FINST_D;
1379 }
1380 return 0;
1381
1382 aborted_xfer:
1383 txn->req.err_state = txn->req.msg_state;
1384 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001385 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001386 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001387 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001388 } else {
1389 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001390 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 }
1392 req->analysers &= AN_REQ_FLT_END;
1393 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1394
1395 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1396 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1397 if (objt_server(s->target))
1398 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1399
1400 if (!(s->flags & SF_ERR_MASK))
1401 s->flags |= SF_ERR_SRVCL;
1402 if (!(s->flags & SF_FINST_MASK)) {
1403 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1404 s->flags |= SF_FINST_H;
1405 else
1406 s->flags |= SF_FINST_D;
1407 }
1408 return 0;
1409}
1410
1411/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1412 * processing can continue on next analysers, or zero if it either needs more
1413 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1414 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1415 * when it has nothing left to do, and may remove any analyser when it wants to
1416 * abort.
1417 */
1418int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1419{
Christopher Faulet9768c262018-10-22 09:34:31 +02001420 /*
1421 * We will analyze a complete HTTP response to check the its syntax.
1422 *
1423 * Once the start line and all headers are received, we may perform a
1424 * capture of the error (if any), and we will set a few fields. We also
1425 * logging and finally headers capture.
1426 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001427 struct session *sess = s->sess;
1428 struct http_txn *txn = s->txn;
1429 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001430 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001431 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001432 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001433 int n;
1434
1435 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1436 now_ms, __FUNCTION__,
1437 s,
1438 rep,
1439 rep->rex, rep->wex,
1440 rep->flags,
1441 ci_data(rep),
1442 rep->analysers);
1443
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001444 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001445
1446 /*
1447 * Now we quickly check if we have found a full valid response.
1448 * If not so, we check the FD and buffer states before leaving.
1449 * A full response is indicated by the fact that we have seen
1450 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1451 * responses are checked first.
1452 *
1453 * Depending on whether the client is still there or not, we
1454 * may send an error response back or not. Note that normally
1455 * we should only check for HTTP status there, and check I/O
1456 * errors somewhere else.
1457 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001458 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001459 /*
1460 * First catch invalid response
1461 */
1462 if (htx->flags & HTX_FL_PARSING_ERROR)
1463 goto return_bad_res;
1464
Christopher Faulet9768c262018-10-22 09:34:31 +02001465 /* 1: have we encountered a read error ? */
1466 if (rep->flags & CF_READ_ERROR) {
1467 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001468 goto abort_keep_alive;
1469
1470 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1471 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001472 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1473 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001474 }
1475
Christopher Faulete0768eb2018-10-03 16:38:02 +02001476 rep->analysers &= AN_RES_FLT_END;
1477 txn->status = 502;
1478
1479 /* Check to see if the server refused the early data.
1480 * If so, just send a 425
1481 */
1482 if (objt_cs(s->si[1].end)) {
1483 struct connection *conn = objt_cs(s->si[1].end)->conn;
1484
1485 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1486 txn->status = 425;
1487 }
1488
1489 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001490 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001491
1492 if (!(s->flags & SF_ERR_MASK))
1493 s->flags |= SF_ERR_SRVCL;
1494 if (!(s->flags & SF_FINST_MASK))
1495 s->flags |= SF_FINST_H;
1496 return 0;
1497 }
1498
Christopher Faulet9768c262018-10-22 09:34:31 +02001499 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001500 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001501 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1502 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001503 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1504 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001505 }
1506
Christopher Faulete0768eb2018-10-03 16:38:02 +02001507 rep->analysers &= AN_RES_FLT_END;
1508 txn->status = 504;
1509 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001510 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001511
1512 if (!(s->flags & SF_ERR_MASK))
1513 s->flags |= SF_ERR_SRVTO;
1514 if (!(s->flags & SF_FINST_MASK))
1515 s->flags |= SF_FINST_H;
1516 return 0;
1517 }
1518
Christopher Faulet9768c262018-10-22 09:34:31 +02001519 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001520 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1521 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1522 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1523 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001524 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001525
1526 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001527 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001528 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001529
1530 if (!(s->flags & SF_ERR_MASK))
1531 s->flags |= SF_ERR_CLICL;
1532 if (!(s->flags & SF_FINST_MASK))
1533 s->flags |= SF_FINST_H;
1534
1535 /* process_stream() will take care of the error */
1536 return 0;
1537 }
1538
Christopher Faulet9768c262018-10-22 09:34:31 +02001539 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001541 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001542 goto abort_keep_alive;
1543
1544 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1545 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001546 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1547 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 }
1549
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 rep->analysers &= AN_RES_FLT_END;
1551 txn->status = 502;
1552 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001553 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001554
1555 if (!(s->flags & SF_ERR_MASK))
1556 s->flags |= SF_ERR_SRVCL;
1557 if (!(s->flags & SF_FINST_MASK))
1558 s->flags |= SF_FINST_H;
1559 return 0;
1560 }
1561
Christopher Faulet9768c262018-10-22 09:34:31 +02001562 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001563 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001564 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001565 goto abort_keep_alive;
1566
1567 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1568 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001569
1570 if (!(s->flags & SF_ERR_MASK))
1571 s->flags |= SF_ERR_CLICL;
1572 if (!(s->flags & SF_FINST_MASK))
1573 s->flags |= SF_FINST_H;
1574
1575 /* process_stream() will take care of the error */
1576 return 0;
1577 }
1578
1579 channel_dont_close(rep);
1580 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1581 return 0;
1582 }
1583
1584 /* More interesting part now : we know that we have a complete
1585 * response which at least looks like HTTP. We have an indicator
1586 * of each header's length, so we can parse them quickly.
1587 */
1588
Christopher Faulet9768c262018-10-22 09:34:31 +02001589 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001590 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001591
Christopher Faulet9768c262018-10-22 09:34:31 +02001592 /* 0: we might have to print this header in debug mode */
1593 if (unlikely((global.mode & MODE_DEBUG) &&
1594 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1595 int32_t pos;
1596
Christopher Faulet03599112018-11-27 11:21:21 +01001597 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001598
1599 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1600 struct htx_blk *blk = htx_get_blk(htx, pos);
1601 enum htx_blk_type type = htx_get_blk_type(blk);
1602
1603 if (type == HTX_BLK_EOH)
1604 break;
1605 if (type != HTX_BLK_HDR)
1606 continue;
1607
1608 htx_debug_hdr("srvhdr", s,
1609 htx_get_blk_name(htx, blk),
1610 htx_get_blk_value(htx, blk));
1611 }
1612 }
1613
Christopher Faulet03599112018-11-27 11:21:21 +01001614 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001615 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001616 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001617 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001618 if (sl->flags & HTX_SL_F_XFER_LEN) {
1619 msg->flags |= HTTP_MSGF_XFER_LEN;
1620 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001621 if (sl->flags & HTX_SL_F_BODYLESS)
1622 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001623 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001624
1625 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001626 if (n < 1 || n > 5)
1627 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001628
Christopher Faulete0768eb2018-10-03 16:38:02 +02001629 /* when the client triggers a 4xx from the server, it's most often due
1630 * to a missing object or permission. These events should be tracked
1631 * because if they happen often, it may indicate a brute force or a
1632 * vulnerability scan.
1633 */
1634 if (n == 4)
1635 stream_inc_http_err_ctr(s);
1636
1637 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001638 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639
Christopher Faulete0768eb2018-10-03 16:38:02 +02001640 /* Adjust server's health based on status code. Note: status codes 501
1641 * and 505 are triggered on demand by client request, so we must not
1642 * count them as server failures.
1643 */
1644 if (objt_server(s->target)) {
1645 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001646 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001648 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001649 }
1650
1651 /*
1652 * We may be facing a 100-continue response, or any other informational
1653 * 1xx response which is non-final, in which case this is not the right
1654 * response, and we're waiting for the next one. Let's allow this response
1655 * to go to the client and wait for the next one. There's an exception for
1656 * 101 which is used later in the code to switch protocols.
1657 */
1658 if (txn->status < 200 &&
1659 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001660 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001661 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001662 msg->msg_state = HTTP_MSG_RPBEFORE;
1663 txn->status = 0;
1664 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001665 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001666 }
1667
1668 /*
1669 * 2: check for cacheability.
1670 */
1671
1672 switch (txn->status) {
1673 case 200:
1674 case 203:
1675 case 204:
1676 case 206:
1677 case 300:
1678 case 301:
1679 case 404:
1680 case 405:
1681 case 410:
1682 case 414:
1683 case 501:
1684 break;
1685 default:
1686 /* RFC7231#6.1:
1687 * Responses with status codes that are defined as
1688 * cacheable by default (e.g., 200, 203, 204, 206,
1689 * 300, 301, 404, 405, 410, 414, and 501 in this
1690 * specification) can be reused by a cache with
1691 * heuristic expiration unless otherwise indicated
1692 * by the method definition or explicit cache
1693 * controls [RFC7234]; all other status codes are
1694 * not cacheable by default.
1695 */
1696 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1697 break;
1698 }
1699
1700 /*
1701 * 3: we may need to capture headers
1702 */
1703 s->logs.logwait &= ~LW_RESP;
1704 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001705 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001706
Christopher Faulet9768c262018-10-22 09:34:31 +02001707 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001708 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1709 txn->status == 101)) {
1710 /* Either we've established an explicit tunnel, or we're
1711 * switching the protocol. In both cases, we're very unlikely
1712 * to understand the next protocols. We have to switch to tunnel
1713 * mode, so that we transfer the request and responses then let
1714 * this protocol pass unmodified. When we later implement specific
1715 * parsers for such protocols, we'll want to check the Upgrade
1716 * header which contains information about that protocol for
1717 * responses with status 101 (eg: see RFC2817 about TLS).
1718 */
1719 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001720 }
1721
Christopher Faulet61608322018-11-23 16:23:45 +01001722 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1723 * 407 (Proxy-Authenticate) responses and set the connection to private
1724 */
1725 srv_conn = cs_conn(objt_cs(s->si[1].end));
1726 if (srv_conn) {
1727 struct ist hdr;
1728 struct http_hdr_ctx ctx;
1729
1730 if (txn->status == 401)
1731 hdr = ist("WWW-Authenticate");
1732 else if (txn->status == 407)
1733 hdr = ist("Proxy-Authenticate");
1734 else
1735 goto end;
1736
1737 ctx.blk = NULL;
1738 while (http_find_header(htx, hdr, &ctx, 0)) {
1739 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1740 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1741 srv_conn->flags |= CO_FL_PRIVATE;
1742 }
1743 }
1744
1745 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001746 /* we want to have the response time before we start processing it */
1747 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1748
1749 /* end of job, return OK */
1750 rep->analysers &= ~an_bit;
1751 rep->analyse_exp = TICK_ETERNITY;
1752 channel_auto_close(rep);
1753 return 1;
1754
Christopher Faulet47365272018-10-31 17:40:50 +01001755 return_bad_res:
1756 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1757 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001758 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1759 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001760 }
1761 txn->status = 502;
1762 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001763 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001764 rep->analysers &= AN_RES_FLT_END;
1765
1766 if (!(s->flags & SF_ERR_MASK))
1767 s->flags |= SF_ERR_PRXCOND;
1768 if (!(s->flags & SF_FINST_MASK))
1769 s->flags |= SF_FINST_H;
1770 return 0;
1771
Christopher Faulete0768eb2018-10-03 16:38:02 +02001772 abort_keep_alive:
1773 /* A keep-alive request to the server failed on a network error.
1774 * The client is required to retry. We need to close without returning
1775 * any other information so that the client retries.
1776 */
1777 txn->status = 0;
1778 rep->analysers &= AN_RES_FLT_END;
1779 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001780 s->logs.logwait = 0;
1781 s->logs.level = 0;
1782 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001783 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001784 return 0;
1785}
1786
1787/* This function performs all the processing enabled for the current response.
1788 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1789 * and updates s->res.analysers. It might make sense to explode it into several
1790 * other functions. It works like process_request (see indications above).
1791 */
1792int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1793{
1794 struct session *sess = s->sess;
1795 struct http_txn *txn = s->txn;
1796 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001797 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001798 struct proxy *cur_proxy;
1799 struct cond_wordlist *wl;
1800 enum rule_result ret = HTTP_RULE_RES_CONT;
1801
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001802 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1803 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001804
Christopher Faulete0768eb2018-10-03 16:38:02 +02001805 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1806 now_ms, __FUNCTION__,
1807 s,
1808 rep,
1809 rep->rex, rep->wex,
1810 rep->flags,
1811 ci_data(rep),
1812 rep->analysers);
1813
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001814 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001815
1816 /* The stats applet needs to adjust the Connection header but we don't
1817 * apply any filter there.
1818 */
1819 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1820 rep->analysers &= ~an_bit;
1821 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001822 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001823 }
1824
1825 /*
1826 * We will have to evaluate the filters.
1827 * As opposed to version 1.2, now they will be evaluated in the
1828 * filters order and not in the header order. This means that
1829 * each filter has to be validated among all headers.
1830 *
1831 * Filters are tried with ->be first, then with ->fe if it is
1832 * different from ->be.
1833 *
1834 * Maybe we are in resume condiion. In this case I choose the
1835 * "struct proxy" which contains the rule list matching the resume
1836 * pointer. If none of theses "struct proxy" match, I initialise
1837 * the process with the first one.
1838 *
1839 * In fact, I check only correspondance betwwen the current list
1840 * pointer and the ->fe rule list. If it doesn't match, I initialize
1841 * the loop with the ->be.
1842 */
1843 if (s->current_rule_list == &sess->fe->http_res_rules)
1844 cur_proxy = sess->fe;
1845 else
1846 cur_proxy = s->be;
1847 while (1) {
1848 struct proxy *rule_set = cur_proxy;
1849
1850 /* evaluate http-response rules */
1851 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001852 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001853
1854 if (ret == HTTP_RULE_RES_BADREQ)
1855 goto return_srv_prx_502;
1856
1857 if (ret == HTTP_RULE_RES_DONE) {
1858 rep->analysers &= ~an_bit;
1859 rep->analyse_exp = TICK_ETERNITY;
1860 return 1;
1861 }
1862 }
1863
1864 /* we need to be called again. */
1865 if (ret == HTTP_RULE_RES_YIELD) {
1866 channel_dont_close(rep);
1867 return 0;
1868 }
1869
1870 /* try headers filters */
1871 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001872 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1873 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001874 }
1875
1876 /* has the response been denied ? */
1877 if (txn->flags & TX_SVDENY) {
1878 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001879 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001880
1881 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1882 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1883 if (sess->listener->counters)
1884 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001885 goto return_srv_prx_502;
1886 }
1887
1888 /* add response headers from the rule sets in the same order */
1889 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001890 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001891 if (txn->status < 200 && txn->status != 101)
1892 break;
1893 if (wl->cond) {
1894 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1895 ret = acl_pass(ret);
1896 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1897 ret = !ret;
1898 if (!ret)
1899 continue;
1900 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001901
1902 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1903 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001904 goto return_bad_resp;
1905 }
1906
1907 /* check whether we're already working on the frontend */
1908 if (cur_proxy == sess->fe)
1909 break;
1910 cur_proxy = sess->fe;
1911 }
1912
1913 /* After this point, this anayzer can't return yield, so we can
1914 * remove the bit corresponding to this analyzer from the list.
1915 *
1916 * Note that the intermediate returns and goto found previously
1917 * reset the analyzers.
1918 */
1919 rep->analysers &= ~an_bit;
1920 rep->analyse_exp = TICK_ETERNITY;
1921
1922 /* OK that's all we can do for 1xx responses */
1923 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001924 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001925
1926 /*
1927 * Now check for a server cookie.
1928 */
1929 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001930 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001931
1932 /*
1933 * Check for cache-control or pragma headers if required.
1934 */
1935 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1936 check_response_for_cacheability(s, rep);
1937
1938 /*
1939 * Add server cookie in the response if needed
1940 */
1941 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1942 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1943 (!(s->flags & SF_DIRECT) ||
1944 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1945 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1946 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1947 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1948 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1949 !(s->flags & SF_IGNORE_PRST)) {
1950 /* the server is known, it's not the one the client requested, or the
1951 * cookie's last seen date needs to be refreshed. We have to
1952 * insert a set-cookie here, except if we want to insert only on POST
1953 * requests and this one isn't. Note that servers which don't have cookies
1954 * (eg: some backup servers) will return a full cookie removal request.
1955 */
1956 if (!objt_server(s->target)->cookie) {
1957 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001958 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001959 s->be->cookie_name);
1960 }
1961 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001962 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001963
1964 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1965 /* emit last_date, which is mandatory */
1966 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1967 s30tob64((date.tv_sec+3) >> 2,
1968 trash.area + trash.data);
1969 trash.data += 5;
1970
1971 if (s->be->cookie_maxlife) {
1972 /* emit first_date, which is either the original one or
1973 * the current date.
1974 */
1975 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1976 s30tob64(txn->cookie_first_date ?
1977 txn->cookie_first_date >> 2 :
1978 (date.tv_sec+3) >> 2,
1979 trash.area + trash.data);
1980 trash.data += 5;
1981 }
1982 }
1983 chunk_appendf(&trash, "; path=/");
1984 }
1985
1986 if (s->be->cookie_domain)
1987 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1988
1989 if (s->be->ck_opts & PR_CK_HTTPONLY)
1990 chunk_appendf(&trash, "; HttpOnly");
1991
1992 if (s->be->ck_opts & PR_CK_SECURE)
1993 chunk_appendf(&trash, "; Secure");
1994
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001995 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001996 goto return_bad_resp;
1997
1998 txn->flags &= ~TX_SCK_MASK;
1999 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2000 /* the server did not change, only the date was updated */
2001 txn->flags |= TX_SCK_UPDATED;
2002 else
2003 txn->flags |= TX_SCK_INSERTED;
2004
2005 /* Here, we will tell an eventual cache on the client side that we don't
2006 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2007 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2008 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2009 */
2010 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2011
2012 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2013
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002014 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002015 goto return_bad_resp;
2016 }
2017 }
2018
2019 /*
2020 * Check if result will be cacheable with a cookie.
2021 * We'll block the response if security checks have caught
2022 * nasty things such as a cacheable cookie.
2023 */
2024 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2025 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2026 (s->be->options & PR_O_CHK_CACHE)) {
2027 /* we're in presence of a cacheable response containing
2028 * a set-cookie header. We'll block it as requested by
2029 * the 'checkcache' option, and send an alert.
2030 */
2031 if (objt_server(s->target))
2032 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2033
2034 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2035 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2036 if (sess->listener->counters)
2037 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2038
2039 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2040 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2041 send_log(s->be, LOG_ALERT,
2042 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2043 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2044 goto return_srv_prx_502;
2045 }
2046
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002047 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002048 /* Always enter in the body analyzer */
2049 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2050 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2051
2052 /* if the user wants to log as soon as possible, without counting
2053 * bytes from the server, then this is the right moment. We have
2054 * to temporarily assign bytes_out to log what we currently have.
2055 */
2056 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2057 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002058 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002059 s->do_log(s);
2060 s->logs.bytes_out = 0;
2061 }
2062 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002063
2064 return_bad_resp:
2065 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002066 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2067 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002068 }
2069 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2070
2071 return_srv_prx_502:
2072 rep->analysers &= AN_RES_FLT_END;
2073 txn->status = 502;
2074 s->logs.t_data = -1; /* was not a valid response */
2075 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002076 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002077 if (!(s->flags & SF_ERR_MASK))
2078 s->flags |= SF_ERR_PRXCOND;
2079 if (!(s->flags & SF_FINST_MASK))
2080 s->flags |= SF_FINST_H;
2081 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002082}
2083
2084/* This function is an analyser which forwards response body (including chunk
2085 * sizes if any). It is called as soon as we must forward, even if we forward
2086 * zero byte. The only situation where it must not be called is when we're in
2087 * tunnel mode and we want to forward till the close. It's used both to forward
2088 * remaining data and to resync after end of body. It expects the msg_state to
2089 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2090 * read more data, or 1 once we can go on with next request or end the stream.
2091 *
2092 * It is capable of compressing response data both in content-length mode and
2093 * in chunked mode. The state machines follows different flows depending on
2094 * whether content-length and chunked modes are used, since there are no
2095 * trailers in content-length :
2096 *
2097 * chk-mode cl-mode
2098 * ,----- BODY -----.
2099 * / \
2100 * V size > 0 V chk-mode
2101 * .--> SIZE -------------> DATA -------------> CRLF
2102 * | | size == 0 | last byte |
2103 * | v final crlf v inspected |
2104 * | TRAILERS -----------> DONE |
2105 * | |
2106 * `----------------------------------------------'
2107 *
2108 * Compression only happens in the DATA state, and must be flushed in final
2109 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2110 * is performed at once on final states for all bytes parsed, or when leaving
2111 * on missing data.
2112 */
2113int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2114{
2115 struct session *sess = s->sess;
2116 struct http_txn *txn = s->txn;
2117 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002118 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002119 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002120
2121 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2122 now_ms, __FUNCTION__,
2123 s,
2124 res,
2125 res->rex, res->wex,
2126 res->flags,
2127 ci_data(res),
2128 res->analysers);
2129
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002130 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002131
2132 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002133 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002134 /* Output closed while we were sending data. We must abort and
2135 * wake the other side up.
2136 */
2137 msg->err_state = msg->msg_state;
2138 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002139 htx_end_response(s);
2140 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002141 return 1;
2142 }
2143
Christopher Faulet9768c262018-10-22 09:34:31 +02002144 if (msg->msg_state == HTTP_MSG_BODY)
2145 msg->msg_state = HTTP_MSG_DATA;
2146
Christopher Faulete0768eb2018-10-03 16:38:02 +02002147 /* in most states, we should abort in case of early close */
2148 channel_auto_close(res);
2149
Christopher Faulete0768eb2018-10-03 16:38:02 +02002150 if (res->to_forward) {
2151 /* We can't process the buffer's contents yet */
2152 res->flags |= CF_WAKE_WRITE;
2153 goto missing_data_or_waiting;
2154 }
2155
Christopher Faulet9768c262018-10-22 09:34:31 +02002156 if (msg->msg_state >= HTTP_MSG_DONE)
2157 goto done;
2158
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002159 /* Forward input data. We get it by removing all outgoing data not
2160 * forwarded yet from HTX data size. If there are some data filters, we
2161 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002162 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002163 if (HAS_RSP_DATA_FILTERS(s)) {
2164 ret = flt_http_payload(s, msg, htx->data);
2165 if (ret < 0)
2166 goto return_bad_res;
2167 c_adv(res, ret);
2168 if (htx->data != co_data(res) || htx->extra)
2169 goto missing_data_or_waiting;
2170 }
2171 else {
2172 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002173
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002174 /* To let the function channel_forward work as expected we must update
2175 * the channel's buffer to pretend there is no more input data. The
2176 * right length is then restored. We must do that, because when an HTX
2177 * message is stored into a buffer, it appears as full.
2178 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002179 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2180 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002181 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002182
2183 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2184 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002185 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002186 msg->msg_state = HTTP_MSG_TUNNEL;
2187 goto done;
2188 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002189 }
2190
Christopher Faulet9768c262018-10-22 09:34:31 +02002191 /* Check if the end-of-message is reached and if so, switch the message
2192 * in HTTP_MSG_DONE state.
2193 */
2194 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2195 goto missing_data_or_waiting;
2196
2197 msg->msg_state = HTTP_MSG_DONE;
2198
2199 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002200 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002201 channel_dont_close(res);
2202
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002203 if (HAS_RSP_DATA_FILTERS(s)) {
2204 ret = flt_http_end(s, msg);
2205 if (ret <= 0) {
2206 if (!ret)
2207 goto missing_data_or_waiting;
2208 goto return_bad_res;
2209 }
2210 }
2211
Christopher Fauletf2824e62018-10-01 12:12:37 +02002212 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002214 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002215 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2216 if (res->flags & CF_SHUTW) {
2217 /* response errors are most likely due to the
2218 * client aborting the transfer. */
2219 goto aborted_xfer;
2220 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002221 goto return_bad_res;
2222 }
2223 return 1;
2224 }
2225 return 0;
2226
2227 missing_data_or_waiting:
2228 if (res->flags & CF_SHUTW)
2229 goto aborted_xfer;
2230
Christopher Faulet47365272018-10-31 17:40:50 +01002231 if (htx->flags & HTX_FL_PARSING_ERROR)
2232 goto return_bad_res;
2233
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 /* stop waiting for data if the input is closed before the end. If the
2235 * client side was already closed, it means that the client has aborted,
2236 * so we don't want to count this as a server abort. Otherwise it's a
2237 * server abort.
2238 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002239 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002240 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2241 goto aborted_xfer;
2242 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002243 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 if (!(s->flags & SF_ERR_MASK))
2245 s->flags |= SF_ERR_SRVCL;
2246 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2247 if (objt_server(s->target))
2248 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2249 goto return_bad_res_stats_ok;
2250 }
2251 }
2252
Christopher Faulete0768eb2018-10-03 16:38:02 +02002253 /* When TE: chunked is used, we need to get there again to parse
2254 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002255 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2256 * are filters registered on the stream, we don't want to forward a
2257 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002258 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002259 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002260 channel_dont_close(res);
2261
2262 /* We know that more data are expected, but we couldn't send more that
2263 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2264 * system knows it must not set a PUSH on this first part. Interactive
2265 * modes are already handled by the stream sock layer. We must not do
2266 * this in content-length mode because it could present the MSG_MORE
2267 * flag with the last block of forwarded data, which would cause an
2268 * additional delay to be observed by the receiver.
2269 */
2270 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2271 res->flags |= CF_EXPECT_MORE;
2272
2273 /* the stream handler will take care of timeouts and errors */
2274 return 0;
2275
2276 return_bad_res: /* let's centralize all bad responses */
2277 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2278 if (objt_server(s->target))
2279 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2280
2281 return_bad_res_stats_ok:
2282 txn->rsp.err_state = txn->rsp.msg_state;
2283 txn->rsp.msg_state = HTTP_MSG_ERROR;
2284 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002285 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 res->analysers &= AN_RES_FLT_END;
2287 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2288 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002289 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290
2291 if (!(s->flags & SF_ERR_MASK))
2292 s->flags |= SF_ERR_PRXCOND;
2293 if (!(s->flags & SF_FINST_MASK))
2294 s->flags |= SF_FINST_D;
2295 return 0;
2296
2297 aborted_xfer:
2298 txn->rsp.err_state = txn->rsp.msg_state;
2299 txn->rsp.msg_state = HTTP_MSG_ERROR;
2300 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002301 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002302 res->analysers &= AN_RES_FLT_END;
2303 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2304
2305 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2306 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2307 if (objt_server(s->target))
2308 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2309
2310 if (!(s->flags & SF_ERR_MASK))
2311 s->flags |= SF_ERR_CLICL;
2312 if (!(s->flags & SF_FINST_MASK))
2313 s->flags |= SF_FINST_D;
2314 return 0;
2315}
2316
Christopher Faulet0f226952018-10-22 09:29:56 +02002317void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002318{
2319 struct proxy *fe = strm_fe(s);
2320 int tmp = TX_CON_WANT_CLO;
2321
2322 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2323 tmp = TX_CON_WANT_TUN;
2324
2325 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002326 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327}
2328
2329/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002330 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002331 * as too large a request to build a valid response.
2332 */
2333int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2334{
Christopher Faulet99daf282018-11-28 22:58:13 +01002335 struct channel *req = &s->req;
2336 struct channel *res = &s->res;
2337 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002338 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002339 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002340 struct ist status, reason, location;
2341 unsigned int flags;
2342 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002343
2344 chunk = alloc_trash_chunk();
2345 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002346 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002347
Christopher Faulet99daf282018-11-28 22:58:13 +01002348 /*
2349 * Create the location
2350 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002351 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002352 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002353 case REDIRECT_TYPE_SCHEME: {
2354 struct http_hdr_ctx ctx;
2355 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002356
Christopher Faulet99daf282018-11-28 22:58:13 +01002357 host = ist("");
2358 ctx.blk = NULL;
2359 if (http_find_header(htx, ist("Host"), &ctx, 0))
2360 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002361
Christopher Faulet99daf282018-11-28 22:58:13 +01002362 sl = http_find_stline(htx);
2363 path = http_get_path(htx_sl_req_uri(sl));
2364 /* build message using path */
2365 if (path.ptr) {
2366 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2367 int qs = 0;
2368 while (qs < path.len) {
2369 if (*(path.ptr + qs) == '?') {
2370 path.len = qs;
2371 break;
2372 }
2373 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002374 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002375 }
2376 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002377 else
2378 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002379
Christopher Faulet99daf282018-11-28 22:58:13 +01002380 if (rule->rdr_str) { /* this is an old "redirect" rule */
2381 /* add scheme */
2382 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2383 goto fail;
2384 }
2385 else {
2386 /* add scheme with executing log format */
2387 chunk->data += build_logline(s, chunk->area + chunk->data,
2388 chunk->size - chunk->data,
2389 &rule->rdr_fmt);
2390 }
2391 /* add "://" + host + path */
2392 if (!chunk_memcat(chunk, "://", 3) ||
2393 !chunk_memcat(chunk, host.ptr, host.len) ||
2394 !chunk_memcat(chunk, path.ptr, path.len))
2395 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002396
Christopher Faulet99daf282018-11-28 22:58:13 +01002397 /* append a slash at the end of the location if needed and missing */
2398 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2399 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2400 if (chunk->data + 1 >= chunk->size)
2401 goto fail;
2402 chunk->area[chunk->data++] = '/';
2403 }
2404 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002405 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406
Christopher Faulet99daf282018-11-28 22:58:13 +01002407 case REDIRECT_TYPE_PREFIX: {
2408 struct ist path;
2409
2410 sl = http_find_stline(htx);
2411 path = http_get_path(htx_sl_req_uri(sl));
2412 /* build message using path */
2413 if (path.ptr) {
2414 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2415 int qs = 0;
2416 while (qs < path.len) {
2417 if (*(path.ptr + qs) == '?') {
2418 path.len = qs;
2419 break;
2420 }
2421 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002422 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002423 }
2424 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002425 else
2426 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002427
Christopher Faulet99daf282018-11-28 22:58:13 +01002428 if (rule->rdr_str) { /* this is an old "redirect" rule */
2429 /* add prefix. Note that if prefix == "/", we don't want to
2430 * add anything, otherwise it makes it hard for the user to
2431 * configure a self-redirection.
2432 */
2433 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2434 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2435 goto fail;
2436 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002437 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002438 else {
2439 /* add prefix with executing log format */
2440 chunk->data += build_logline(s, chunk->area + chunk->data,
2441 chunk->size - chunk->data,
2442 &rule->rdr_fmt);
2443 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002444
Christopher Faulet99daf282018-11-28 22:58:13 +01002445 /* add path */
2446 if (!chunk_memcat(chunk, path.ptr, path.len))
2447 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002448
Christopher Faulet99daf282018-11-28 22:58:13 +01002449 /* append a slash at the end of the location if needed and missing */
2450 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2451 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2452 if (chunk->data + 1 >= chunk->size)
2453 goto fail;
2454 chunk->area[chunk->data++] = '/';
2455 }
2456 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002457 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002458 case REDIRECT_TYPE_LOCATION:
2459 default:
2460 if (rule->rdr_str) { /* this is an old "redirect" rule */
2461 /* add location */
2462 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2463 goto fail;
2464 }
2465 else {
2466 /* add location with executing log format */
2467 chunk->data += build_logline(s, chunk->area + chunk->data,
2468 chunk->size - chunk->data,
2469 &rule->rdr_fmt);
2470 }
2471 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002472 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002473 location = ist2(chunk->area, chunk->data);
2474
2475 /*
2476 * Create the 30x response
2477 */
2478 switch (rule->code) {
2479 case 308:
2480 status = ist("308");
2481 reason = ist("Permanent Redirect");
2482 break;
2483 case 307:
2484 status = ist("307");
2485 reason = ist("Temporary Redirect");
2486 break;
2487 case 303:
2488 status = ist("303");
2489 reason = ist("See Other");
2490 break;
2491 case 301:
2492 status = ist("301");
2493 reason = ist("Moved Permanently");
2494 break;
2495 case 302:
2496 default:
2497 status = ist("302");
2498 reason = ist("Found");
2499 break;
2500 }
2501
2502 htx = htx_from_buf(&res->buf);
2503 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2504 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2505 if (!sl)
2506 goto fail;
2507 sl->info.res.status = rule->code;
2508 s->txn->status = rule->code;
2509
2510 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2511 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2512 !htx_add_header(htx, ist("Location"), location))
2513 goto fail;
2514
2515 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2516 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2517 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002518 }
2519
2520 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002521 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2522 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002523 }
2524
Christopher Faulet99daf282018-11-28 22:58:13 +01002525 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2526 goto fail;
2527
Christopher Fauletf2824e62018-10-01 12:12:37 +02002528 /* let's log the request time */
2529 s->logs.tv_request = now;
2530
Christopher Faulet99daf282018-11-28 22:58:13 +01002531 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002532 c_adv(res, data);
2533 res->total += data;
2534
2535 channel_auto_read(req);
2536 channel_abort(req);
2537 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002538 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002539
2540 res->wex = tick_add_ifset(now_ms, res->wto);
2541 channel_auto_read(res);
2542 channel_auto_close(res);
2543 channel_shutr_now(res);
2544
2545 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002546
2547 if (!(s->flags & SF_ERR_MASK))
2548 s->flags |= SF_ERR_LOCAL;
2549 if (!(s->flags & SF_FINST_MASK))
2550 s->flags |= SF_FINST_R;
2551
Christopher Faulet99daf282018-11-28 22:58:13 +01002552 free_trash_chunk(chunk);
2553 return 1;
2554
2555 fail:
2556 /* If an error occurred, remove the incomplete HTTP response from the
2557 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002558 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002559 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002560 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002561}
2562
Christopher Faulet72333522018-10-24 11:25:02 +02002563int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2564 struct ist name, const char *str, struct my_regex *re, int action)
2565{
2566 struct http_hdr_ctx ctx;
2567 struct buffer *output = get_trash_chunk();
2568
2569 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2570 ctx.blk = NULL;
2571 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2572 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2573 continue;
2574
2575 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2576 if (output->data == -1)
2577 return -1;
2578 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2579 return -1;
2580 }
2581 return 0;
2582}
2583
2584static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2585 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2586{
2587 struct buffer *replace;
2588 int ret = -1;
2589
2590 replace = alloc_trash_chunk();
2591 if (!replace)
2592 goto leave;
2593
2594 replace->data = build_logline(s, replace->area, replace->size, fmt);
2595 if (replace->data >= replace->size - 1)
2596 goto leave;
2597
2598 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2599
2600 leave:
2601 free_trash_chunk(replace);
2602 return ret;
2603}
2604
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002605
2606/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2607 * on success and -1 on error. The response channel is updated accordingly.
2608 */
2609static int htx_reply_103_early_hints(struct channel *res)
2610{
2611 struct htx *htx = htx_from_buf(&res->buf);
2612 size_t data;
2613
2614 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2615 /* If an error occurred during an Early-hint rule,
2616 * remove the incomplete HTTP 103 response from the
2617 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002618 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002619 return -1;
2620 }
2621
2622 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002623 c_adv(res, data);
2624 res->total += data;
2625 return 0;
2626}
2627
Christopher Faulet6eb92892018-11-15 16:39:29 +01002628/*
2629 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2630 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002631 * If <early_hints> is 0, it is starts a new response by adding the start
2632 * line. If an error occurred -1 is returned. On success 0 is returned. The
2633 * channel is not updated here. It must be done calling the function
2634 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002635 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002636static 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 +01002637{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 struct channel *res = &s->res;
2639 struct htx *htx = htx_from_buf(&res->buf);
2640 struct buffer *value = alloc_trash_chunk();
2641
Christopher Faulet6eb92892018-11-15 16:39:29 +01002642 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 struct htx_sl *sl;
2644 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2645 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2646
2647 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2648 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2649 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002650 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002652 }
2653
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002654 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2655 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002656 goto fail;
2657
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002658 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002659 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002660
2661 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 /* If an error occurred during an Early-hint rule, remove the incomplete
2663 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002664 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002665 free_trash_chunk(value);
2666 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002667}
2668
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002669/* This function executes one of the set-{method,path,query,uri} actions. It
2670 * takes the string from the variable 'replace' with length 'len', then modifies
2671 * the relevant part of the request line accordingly. Then it updates various
2672 * pointers to the next elements which were moved, and the total buffer length.
2673 * It finds the action to be performed in p[2], previously filled by function
2674 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2675 * error, though this can be revisited when this code is finally exploited.
2676 *
2677 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2678 * query string and 3 to replace uri.
2679 *
2680 * In query string case, the mark question '?' must be set at the start of the
2681 * string by the caller, event if the replacement query string is empty.
2682 */
2683int htx_req_replace_stline(int action, const char *replace, int len,
2684 struct proxy *px, struct stream *s)
2685{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002686 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002687
2688 switch (action) {
2689 case 0: // method
2690 if (!http_replace_req_meth(htx, ist2(replace, len)))
2691 return -1;
2692 break;
2693
2694 case 1: // path
2695 if (!http_replace_req_path(htx, ist2(replace, len)))
2696 return -1;
2697 break;
2698
2699 case 2: // query
2700 if (!http_replace_req_query(htx, ist2(replace, len)))
2701 return -1;
2702 break;
2703
2704 case 3: // uri
2705 if (!http_replace_req_uri(htx, ist2(replace, len)))
2706 return -1;
2707 break;
2708
2709 default:
2710 return -1;
2711 }
2712 return 0;
2713}
2714
2715/* This function replace the HTTP status code and the associated message. The
2716 * variable <status> contains the new status code. This function never fails.
2717 */
2718void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2719{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002720 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002721 char *res;
2722
2723 chunk_reset(&trash);
2724 res = ultoa_o(status, trash.area, trash.size);
2725 trash.data = res - trash.area;
2726
2727 /* Do we have a custom reason format string? */
2728 if (reason == NULL)
2729 reason = http_get_reason(status);
2730
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002731 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002732 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2733}
2734
Christopher Faulet3e964192018-10-24 11:39:23 +02002735/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2736 * transaction <txn>. Returns the verdict of the first rule that prevents
2737 * further processing of the request (auth, deny, ...), and defaults to
2738 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2739 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2740 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2741 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2742 * status.
2743 */
2744static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2745 struct stream *s, int *deny_status)
2746{
2747 struct session *sess = strm_sess(s);
2748 struct http_txn *txn = s->txn;
2749 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002750 struct act_rule *rule;
2751 struct http_hdr_ctx ctx;
2752 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002753 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2754 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002755 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002756
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002757 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002758
2759 /* If "the current_rule_list" match the executed rule list, we are in
2760 * resume condition. If a resume is needed it is always in the action
2761 * and never in the ACL or converters. In this case, we initialise the
2762 * current rule, and go to the action execution point.
2763 */
2764 if (s->current_rule) {
2765 rule = s->current_rule;
2766 s->current_rule = NULL;
2767 if (s->current_rule_list == rules)
2768 goto resume_execution;
2769 }
2770 s->current_rule_list = rules;
2771
2772 list_for_each_entry(rule, rules, list) {
2773 /* check optional condition */
2774 if (rule->cond) {
2775 int ret;
2776
2777 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2778 ret = acl_pass(ret);
2779
2780 if (rule->cond->pol == ACL_COND_UNLESS)
2781 ret = !ret;
2782
2783 if (!ret) /* condition not matched */
2784 continue;
2785 }
2786
2787 act_flags |= ACT_FLAG_FIRST;
2788 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002789 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2790 early_hints = 0;
2791 if (htx_reply_103_early_hints(&s->res) == -1) {
2792 rule_ret = HTTP_RULE_RES_BADREQ;
2793 goto end;
2794 }
2795 }
2796
Christopher Faulet3e964192018-10-24 11:39:23 +02002797 switch (rule->action) {
2798 case ACT_ACTION_ALLOW:
2799 rule_ret = HTTP_RULE_RES_STOP;
2800 goto end;
2801
2802 case ACT_ACTION_DENY:
2803 if (deny_status)
2804 *deny_status = rule->deny_status;
2805 rule_ret = HTTP_RULE_RES_DENY;
2806 goto end;
2807
2808 case ACT_HTTP_REQ_TARPIT:
2809 txn->flags |= TX_CLTARPIT;
2810 if (deny_status)
2811 *deny_status = rule->deny_status;
2812 rule_ret = HTTP_RULE_RES_DENY;
2813 goto end;
2814
2815 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002816 /* Auth might be performed on regular http-req rules as well as on stats */
2817 auth_realm = rule->arg.auth.realm;
2818 if (!auth_realm) {
2819 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2820 auth_realm = STATS_DEFAULT_REALM;
2821 else
2822 auth_realm = px->id;
2823 }
2824 /* send 401/407 depending on whether we use a proxy or not. We still
2825 * count one error, because normal browsing won't significantly
2826 * increase the counter but brute force attempts will.
2827 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002828 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002829 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2830 rule_ret = HTTP_RULE_RES_BADREQ;
2831 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002832 goto end;
2833
2834 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002835 rule_ret = HTTP_RULE_RES_DONE;
2836 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2837 rule_ret = HTTP_RULE_RES_BADREQ;
2838 goto end;
2839
2840 case ACT_HTTP_SET_NICE:
2841 s->task->nice = rule->arg.nice;
2842 break;
2843
2844 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002845 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002846 break;
2847
2848 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002849 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002850 break;
2851
2852 case ACT_HTTP_SET_LOGL:
2853 s->logs.level = rule->arg.loglevel;
2854 break;
2855
2856 case ACT_HTTP_REPLACE_HDR:
2857 case ACT_HTTP_REPLACE_VAL:
2858 if (htx_transform_header(s, &s->req, htx,
2859 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2860 &rule->arg.hdr_add.fmt,
2861 &rule->arg.hdr_add.re, rule->action)) {
2862 rule_ret = HTTP_RULE_RES_BADREQ;
2863 goto end;
2864 }
2865 break;
2866
2867 case ACT_HTTP_DEL_HDR:
2868 /* remove all occurrences of the header */
2869 ctx.blk = NULL;
2870 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2871 http_remove_header(htx, &ctx);
2872 break;
2873
2874 case ACT_HTTP_SET_HDR:
2875 case ACT_HTTP_ADD_HDR: {
2876 /* The scope of the trash buffer must be limited to this function. The
2877 * build_logline() function can execute a lot of other function which
2878 * can use the trash buffer. So for limiting the scope of this global
2879 * buffer, we build first the header value using build_logline, and
2880 * after we store the header name.
2881 */
2882 struct buffer *replace;
2883 struct ist n, v;
2884
2885 replace = alloc_trash_chunk();
2886 if (!replace) {
2887 rule_ret = HTTP_RULE_RES_BADREQ;
2888 goto end;
2889 }
2890
2891 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2892 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2893 v = ist2(replace->area, replace->data);
2894
2895 if (rule->action == ACT_HTTP_SET_HDR) {
2896 /* remove all occurrences of the header */
2897 ctx.blk = NULL;
2898 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2899 http_remove_header(htx, &ctx);
2900 }
2901
2902 if (!http_add_header(htx, n, v)) {
2903 static unsigned char rate_limit = 0;
2904
2905 if ((rate_limit++ & 255) == 0) {
2906 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);
2907 }
2908
2909 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2910 if (sess->fe != s->be)
2911 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2912 if (sess->listener->counters)
2913 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2914 }
2915 free_trash_chunk(replace);
2916 break;
2917 }
2918
2919 case ACT_HTTP_DEL_ACL:
2920 case ACT_HTTP_DEL_MAP: {
2921 struct pat_ref *ref;
2922 struct buffer *key;
2923
2924 /* collect reference */
2925 ref = pat_ref_lookup(rule->arg.map.ref);
2926 if (!ref)
2927 continue;
2928
2929 /* allocate key */
2930 key = alloc_trash_chunk();
2931 if (!key) {
2932 rule_ret = HTTP_RULE_RES_BADREQ;
2933 goto end;
2934 }
2935
2936 /* collect key */
2937 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2938 key->area[key->data] = '\0';
2939
2940 /* perform update */
2941 /* returned code: 1=ok, 0=ko */
2942 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2943 pat_ref_delete(ref, key->area);
2944 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2945
2946 free_trash_chunk(key);
2947 break;
2948 }
2949
2950 case ACT_HTTP_ADD_ACL: {
2951 struct pat_ref *ref;
2952 struct buffer *key;
2953
2954 /* collect reference */
2955 ref = pat_ref_lookup(rule->arg.map.ref);
2956 if (!ref)
2957 continue;
2958
2959 /* allocate key */
2960 key = alloc_trash_chunk();
2961 if (!key) {
2962 rule_ret = HTTP_RULE_RES_BADREQ;
2963 goto end;
2964 }
2965
2966 /* collect key */
2967 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2968 key->area[key->data] = '\0';
2969
2970 /* perform update */
2971 /* add entry only if it does not already exist */
2972 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2973 if (pat_ref_find_elt(ref, key->area) == NULL)
2974 pat_ref_add(ref, key->area, NULL, NULL);
2975 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2976
2977 free_trash_chunk(key);
2978 break;
2979 }
2980
2981 case ACT_HTTP_SET_MAP: {
2982 struct pat_ref *ref;
2983 struct buffer *key, *value;
2984
2985 /* collect reference */
2986 ref = pat_ref_lookup(rule->arg.map.ref);
2987 if (!ref)
2988 continue;
2989
2990 /* allocate key */
2991 key = alloc_trash_chunk();
2992 if (!key) {
2993 rule_ret = HTTP_RULE_RES_BADREQ;
2994 goto end;
2995 }
2996
2997 /* allocate value */
2998 value = alloc_trash_chunk();
2999 if (!value) {
3000 free_trash_chunk(key);
3001 rule_ret = HTTP_RULE_RES_BADREQ;
3002 goto end;
3003 }
3004
3005 /* collect key */
3006 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3007 key->area[key->data] = '\0';
3008
3009 /* collect value */
3010 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3011 value->area[value->data] = '\0';
3012
3013 /* perform update */
3014 if (pat_ref_find_elt(ref, key->area) != NULL)
3015 /* update entry if it exists */
3016 pat_ref_set(ref, key->area, value->area, NULL);
3017 else
3018 /* insert a new entry */
3019 pat_ref_add(ref, key->area, value->area, NULL);
3020
3021 free_trash_chunk(key);
3022 free_trash_chunk(value);
3023 break;
3024 }
3025
3026 case ACT_HTTP_EARLY_HINT:
3027 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3028 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003029 early_hints = htx_add_early_hint_header(s, early_hints,
3030 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003031 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003032 if (early_hints == -1) {
3033 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003034 goto end;
3035 }
3036 break;
3037
3038 case ACT_CUSTOM:
3039 if ((s->req.flags & CF_READ_ERROR) ||
3040 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3041 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3042 (px->options & PR_O_ABRT_CLOSE)))
3043 act_flags |= ACT_FLAG_FINAL;
3044
3045 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3046 case ACT_RET_ERR:
3047 case ACT_RET_CONT:
3048 break;
3049 case ACT_RET_STOP:
3050 rule_ret = HTTP_RULE_RES_DONE;
3051 goto end;
3052 case ACT_RET_YIELD:
3053 s->current_rule = rule;
3054 rule_ret = HTTP_RULE_RES_YIELD;
3055 goto end;
3056 }
3057 break;
3058
3059 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3060 /* Note: only the first valid tracking parameter of each
3061 * applies.
3062 */
3063
3064 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3065 struct stktable *t;
3066 struct stksess *ts;
3067 struct stktable_key *key;
3068 void *ptr1, *ptr2;
3069
3070 t = rule->arg.trk_ctr.table.t;
3071 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3072 rule->arg.trk_ctr.expr, NULL);
3073
3074 if (key && (ts = stktable_get_entry(t, key))) {
3075 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3076
3077 /* let's count a new HTTP request as it's the first time we do it */
3078 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3079 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3080 if (ptr1 || ptr2) {
3081 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3082
3083 if (ptr1)
3084 stktable_data_cast(ptr1, http_req_cnt)++;
3085
3086 if (ptr2)
3087 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3088 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3089
3090 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3091
3092 /* If data was modified, we need to touch to re-schedule sync */
3093 stktable_touch_local(t, ts, 0);
3094 }
3095
3096 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3097 if (sess->fe != s->be)
3098 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3099 }
3100 }
3101 break;
3102
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003103 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003104 default:
3105 break;
3106 }
3107 }
3108
3109 end:
3110 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003111 if (htx_reply_103_early_hints(&s->res) == -1)
3112 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003113 }
3114
3115 /* we reached the end of the rules, nothing to report */
3116 return rule_ret;
3117}
3118
3119/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3120 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3121 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3122 * is returned, the process can continue the evaluation of next rule list. If
3123 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3124 * is returned, it means the operation could not be processed and a server error
3125 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3126 * deny rule. If *YIELD is returned, the caller must call again the function
3127 * with the same context.
3128 */
3129static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3130 struct stream *s)
3131{
3132 struct session *sess = strm_sess(s);
3133 struct http_txn *txn = s->txn;
3134 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003135 struct act_rule *rule;
3136 struct http_hdr_ctx ctx;
3137 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3138 int act_flags = 0;
3139
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003140 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003141
3142 /* If "the current_rule_list" match the executed rule list, we are in
3143 * resume condition. If a resume is needed it is always in the action
3144 * and never in the ACL or converters. In this case, we initialise the
3145 * current rule, and go to the action execution point.
3146 */
3147 if (s->current_rule) {
3148 rule = s->current_rule;
3149 s->current_rule = NULL;
3150 if (s->current_rule_list == rules)
3151 goto resume_execution;
3152 }
3153 s->current_rule_list = rules;
3154
3155 list_for_each_entry(rule, rules, list) {
3156 /* check optional condition */
3157 if (rule->cond) {
3158 int ret;
3159
3160 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3161 ret = acl_pass(ret);
3162
3163 if (rule->cond->pol == ACL_COND_UNLESS)
3164 ret = !ret;
3165
3166 if (!ret) /* condition not matched */
3167 continue;
3168 }
3169
3170 act_flags |= ACT_FLAG_FIRST;
3171resume_execution:
3172 switch (rule->action) {
3173 case ACT_ACTION_ALLOW:
3174 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3175 goto end;
3176
3177 case ACT_ACTION_DENY:
3178 txn->flags |= TX_SVDENY;
3179 rule_ret = HTTP_RULE_RES_STOP;
3180 goto end;
3181
3182 case ACT_HTTP_SET_NICE:
3183 s->task->nice = rule->arg.nice;
3184 break;
3185
3186 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003187 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003188 break;
3189
3190 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003191 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003192 break;
3193
3194 case ACT_HTTP_SET_LOGL:
3195 s->logs.level = rule->arg.loglevel;
3196 break;
3197
3198 case ACT_HTTP_REPLACE_HDR:
3199 case ACT_HTTP_REPLACE_VAL:
3200 if (htx_transform_header(s, &s->res, htx,
3201 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3202 &rule->arg.hdr_add.fmt,
3203 &rule->arg.hdr_add.re, rule->action)) {
3204 rule_ret = HTTP_RULE_RES_BADREQ;
3205 goto end;
3206 }
3207 break;
3208
3209 case ACT_HTTP_DEL_HDR:
3210 /* remove all occurrences of the header */
3211 ctx.blk = NULL;
3212 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3213 http_remove_header(htx, &ctx);
3214 break;
3215
3216 case ACT_HTTP_SET_HDR:
3217 case ACT_HTTP_ADD_HDR: {
3218 struct buffer *replace;
3219 struct ist n, v;
3220
3221 replace = alloc_trash_chunk();
3222 if (!replace) {
3223 rule_ret = HTTP_RULE_RES_BADREQ;
3224 goto end;
3225 }
3226
3227 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3228 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3229 v = ist2(replace->area, replace->data);
3230
3231 if (rule->action == ACT_HTTP_SET_HDR) {
3232 /* remove all occurrences of the header */
3233 ctx.blk = NULL;
3234 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3235 http_remove_header(htx, &ctx);
3236 }
3237
3238 if (!http_add_header(htx, n, v)) {
3239 static unsigned char rate_limit = 0;
3240
3241 if ((rate_limit++ & 255) == 0) {
3242 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);
3243 }
3244
3245 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3246 if (sess->fe != s->be)
3247 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3248 if (sess->listener->counters)
3249 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3250 if (objt_server(s->target))
3251 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3252 }
3253 free_trash_chunk(replace);
3254 break;
3255 }
3256
3257 case ACT_HTTP_DEL_ACL:
3258 case ACT_HTTP_DEL_MAP: {
3259 struct pat_ref *ref;
3260 struct buffer *key;
3261
3262 /* collect reference */
3263 ref = pat_ref_lookup(rule->arg.map.ref);
3264 if (!ref)
3265 continue;
3266
3267 /* allocate key */
3268 key = alloc_trash_chunk();
3269 if (!key) {
3270 rule_ret = HTTP_RULE_RES_BADREQ;
3271 goto end;
3272 }
3273
3274 /* collect key */
3275 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3276 key->area[key->data] = '\0';
3277
3278 /* perform update */
3279 /* returned code: 1=ok, 0=ko */
3280 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3281 pat_ref_delete(ref, key->area);
3282 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3283
3284 free_trash_chunk(key);
3285 break;
3286 }
3287
3288 case ACT_HTTP_ADD_ACL: {
3289 struct pat_ref *ref;
3290 struct buffer *key;
3291
3292 /* collect reference */
3293 ref = pat_ref_lookup(rule->arg.map.ref);
3294 if (!ref)
3295 continue;
3296
3297 /* allocate key */
3298 key = alloc_trash_chunk();
3299 if (!key) {
3300 rule_ret = HTTP_RULE_RES_BADREQ;
3301 goto end;
3302 }
3303
3304 /* collect key */
3305 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3306 key->area[key->data] = '\0';
3307
3308 /* perform update */
3309 /* check if the entry already exists */
3310 if (pat_ref_find_elt(ref, key->area) == NULL)
3311 pat_ref_add(ref, key->area, NULL, NULL);
3312
3313 free_trash_chunk(key);
3314 break;
3315 }
3316
3317 case ACT_HTTP_SET_MAP: {
3318 struct pat_ref *ref;
3319 struct buffer *key, *value;
3320
3321 /* collect reference */
3322 ref = pat_ref_lookup(rule->arg.map.ref);
3323 if (!ref)
3324 continue;
3325
3326 /* allocate key */
3327 key = alloc_trash_chunk();
3328 if (!key) {
3329 rule_ret = HTTP_RULE_RES_BADREQ;
3330 goto end;
3331 }
3332
3333 /* allocate value */
3334 value = alloc_trash_chunk();
3335 if (!value) {
3336 free_trash_chunk(key);
3337 rule_ret = HTTP_RULE_RES_BADREQ;
3338 goto end;
3339 }
3340
3341 /* collect key */
3342 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3343 key->area[key->data] = '\0';
3344
3345 /* collect value */
3346 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3347 value->area[value->data] = '\0';
3348
3349 /* perform update */
3350 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3351 if (pat_ref_find_elt(ref, key->area) != NULL)
3352 /* update entry if it exists */
3353 pat_ref_set(ref, key->area, value->area, NULL);
3354 else
3355 /* insert a new entry */
3356 pat_ref_add(ref, key->area, value->area, NULL);
3357 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3358 free_trash_chunk(key);
3359 free_trash_chunk(value);
3360 break;
3361 }
3362
3363 case ACT_HTTP_REDIR:
3364 rule_ret = HTTP_RULE_RES_DONE;
3365 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3366 rule_ret = HTTP_RULE_RES_BADREQ;
3367 goto end;
3368
3369 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3370 /* Note: only the first valid tracking parameter of each
3371 * applies.
3372 */
3373 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3374 struct stktable *t;
3375 struct stksess *ts;
3376 struct stktable_key *key;
3377 void *ptr;
3378
3379 t = rule->arg.trk_ctr.table.t;
3380 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3381 rule->arg.trk_ctr.expr, NULL);
3382
3383 if (key && (ts = stktable_get_entry(t, key))) {
3384 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3385
3386 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3387
3388 /* let's count a new HTTP request as it's the first time we do it */
3389 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3390 if (ptr)
3391 stktable_data_cast(ptr, http_req_cnt)++;
3392
3393 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3394 if (ptr)
3395 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3396 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3397
3398 /* When the client triggers a 4xx from the server, it's most often due
3399 * to a missing object or permission. These events should be tracked
3400 * because if they happen often, it may indicate a brute force or a
3401 * vulnerability scan. Normally this is done when receiving the response
3402 * but here we're tracking after this ought to have been done so we have
3403 * to do it on purpose.
3404 */
3405 if ((unsigned)(txn->status - 400) < 100) {
3406 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3407 if (ptr)
3408 stktable_data_cast(ptr, http_err_cnt)++;
3409
3410 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3411 if (ptr)
3412 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3413 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3414 }
3415
3416 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3417
3418 /* If data was modified, we need to touch to re-schedule sync */
3419 stktable_touch_local(t, ts, 0);
3420
3421 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3422 if (sess->fe != s->be)
3423 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3424 }
3425 }
3426 break;
3427
3428 case ACT_CUSTOM:
3429 if ((s->req.flags & CF_READ_ERROR) ||
3430 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3431 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3432 (px->options & PR_O_ABRT_CLOSE)))
3433 act_flags |= ACT_FLAG_FINAL;
3434
3435 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3436 case ACT_RET_ERR:
3437 case ACT_RET_CONT:
3438 break;
3439 case ACT_RET_STOP:
3440 rule_ret = HTTP_RULE_RES_STOP;
3441 goto end;
3442 case ACT_RET_YIELD:
3443 s->current_rule = rule;
3444 rule_ret = HTTP_RULE_RES_YIELD;
3445 goto end;
3446 }
3447 break;
3448
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003449 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003450 default:
3451 break;
3452 }
3453 }
3454
3455 end:
3456 /* we reached the end of the rules, nothing to report */
3457 return rule_ret;
3458}
3459
Christopher Faulet33640082018-10-24 11:53:01 +02003460/* Iterate the same filter through all request headers.
3461 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3462 * Since it can manage the switch to another backend, it updates the per-proxy
3463 * DENY stats.
3464 */
3465static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3466{
3467 struct http_txn *txn = s->txn;
3468 struct htx *htx;
3469 struct buffer *hdr = get_trash_chunk();
3470 int32_t pos;
3471
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003472 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003473
3474 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3475 struct htx_blk *blk = htx_get_blk(htx, pos);
3476 enum htx_blk_type type;
3477 struct ist n, v;
3478
3479 next_hdr:
3480 type = htx_get_blk_type(blk);
3481 if (type == HTX_BLK_EOH)
3482 break;
3483 if (type != HTX_BLK_HDR)
3484 continue;
3485
3486 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3487 return 1;
3488 else if (unlikely(txn->flags & TX_CLALLOW) &&
3489 (exp->action == ACT_ALLOW ||
3490 exp->action == ACT_DENY ||
3491 exp->action == ACT_TARPIT))
3492 return 0;
3493
3494 n = htx_get_blk_name(htx, blk);
3495 v = htx_get_blk_value(htx, blk);
3496
3497 chunk_memcat(hdr, n.ptr, n.len);
3498 hdr->area[hdr->data++] = ':';
3499 hdr->area[hdr->data++] = ' ';
3500 chunk_memcat(hdr, v.ptr, v.len);
3501
3502 /* Now we have one header in <hdr> */
3503
3504 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3505 struct http_hdr_ctx ctx;
3506 int len;
3507
3508 switch (exp->action) {
3509 case ACT_ALLOW:
3510 txn->flags |= TX_CLALLOW;
3511 goto end;
3512
3513 case ACT_DENY:
3514 txn->flags |= TX_CLDENY;
3515 goto end;
3516
3517 case ACT_TARPIT:
3518 txn->flags |= TX_CLTARPIT;
3519 goto end;
3520
3521 case ACT_REPLACE:
3522 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3523 if (len < 0)
3524 return -1;
3525
3526 http_parse_header(ist2(trash.area, len), &n, &v);
3527 ctx.blk = blk;
3528 ctx.value = v;
3529 if (!http_replace_header(htx, &ctx, n, v))
3530 return -1;
3531 if (!ctx.blk)
3532 goto end;
3533 pos = htx_get_blk_pos(htx, blk);
3534 break;
3535
3536 case ACT_REMOVE:
3537 ctx.blk = blk;
3538 ctx.value = v;
3539 if (!http_remove_header(htx, &ctx))
3540 return -1;
3541 if (!ctx.blk)
3542 goto end;
3543 pos = htx_get_blk_pos(htx, blk);
3544 goto next_hdr;
3545
3546 }
3547 }
3548 }
3549 end:
3550 return 0;
3551}
3552
3553/* Apply the filter to the request line.
3554 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3555 * or -1 if a replacement resulted in an invalid request line.
3556 * Since it can manage the switch to another backend, it updates the per-proxy
3557 * DENY stats.
3558 */
3559static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3560{
3561 struct http_txn *txn = s->txn;
3562 struct htx *htx;
3563 struct buffer *reqline = get_trash_chunk();
3564 int done;
3565
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003566 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003567
3568 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3569 return 1;
3570 else if (unlikely(txn->flags & TX_CLALLOW) &&
3571 (exp->action == ACT_ALLOW ||
3572 exp->action == ACT_DENY ||
3573 exp->action == ACT_TARPIT))
3574 return 0;
3575 else if (exp->action == ACT_REMOVE)
3576 return 0;
3577
3578 done = 0;
3579
3580 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3581
3582 /* Now we have the request line between cur_ptr and cur_end */
3583 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003584 struct htx_sl *sl = http_find_stline(htx);
3585 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003586 int len;
3587
3588 switch (exp->action) {
3589 case ACT_ALLOW:
3590 txn->flags |= TX_CLALLOW;
3591 done = 1;
3592 break;
3593
3594 case ACT_DENY:
3595 txn->flags |= TX_CLDENY;
3596 done = 1;
3597 break;
3598
3599 case ACT_TARPIT:
3600 txn->flags |= TX_CLTARPIT;
3601 done = 1;
3602 break;
3603
3604 case ACT_REPLACE:
3605 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3606 if (len < 0)
3607 return -1;
3608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003609 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3610 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3611 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003612 return -1;
3613 done = 1;
3614 break;
3615 }
3616 }
3617 return done;
3618}
3619
3620/*
3621 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3622 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3623 * unparsable request. Since it can manage the switch to another backend, it
3624 * updates the per-proxy DENY stats.
3625 */
3626static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3627{
3628 struct session *sess = s->sess;
3629 struct http_txn *txn = s->txn;
3630 struct hdr_exp *exp;
3631
3632 for (exp = px->req_exp; exp; exp = exp->next) {
3633 int ret;
3634
3635 /*
3636 * The interleaving of transformations and verdicts
3637 * makes it difficult to decide to continue or stop
3638 * the evaluation.
3639 */
3640
3641 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3642 break;
3643
3644 if ((txn->flags & TX_CLALLOW) &&
3645 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3646 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3647 continue;
3648
3649 /* if this filter had a condition, evaluate it now and skip to
3650 * next filter if the condition does not match.
3651 */
3652 if (exp->cond) {
3653 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3654 ret = acl_pass(ret);
3655 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3656 ret = !ret;
3657
3658 if (!ret)
3659 continue;
3660 }
3661
3662 /* Apply the filter to the request line. */
3663 ret = htx_apply_filter_to_req_line(s, req, exp);
3664 if (unlikely(ret < 0))
3665 return -1;
3666
3667 if (likely(ret == 0)) {
3668 /* The filter did not match the request, it can be
3669 * iterated through all headers.
3670 */
3671 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3672 return -1;
3673 }
3674 }
3675 return 0;
3676}
3677
3678/* Iterate the same filter through all response headers contained in <res>.
3679 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3680 */
3681static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3682{
3683 struct http_txn *txn = s->txn;
3684 struct htx *htx;
3685 struct buffer *hdr = get_trash_chunk();
3686 int32_t pos;
3687
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003688 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003689
3690 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3691 struct htx_blk *blk = htx_get_blk(htx, pos);
3692 enum htx_blk_type type;
3693 struct ist n, v;
3694
3695 next_hdr:
3696 type = htx_get_blk_type(blk);
3697 if (type == HTX_BLK_EOH)
3698 break;
3699 if (type != HTX_BLK_HDR)
3700 continue;
3701
3702 if (unlikely(txn->flags & TX_SVDENY))
3703 return 1;
3704 else if (unlikely(txn->flags & TX_SVALLOW) &&
3705 (exp->action == ACT_ALLOW ||
3706 exp->action == ACT_DENY))
3707 return 0;
3708
3709 n = htx_get_blk_name(htx, blk);
3710 v = htx_get_blk_value(htx, blk);
3711
3712 chunk_memcat(hdr, n.ptr, n.len);
3713 hdr->area[hdr->data++] = ':';
3714 hdr->area[hdr->data++] = ' ';
3715 chunk_memcat(hdr, v.ptr, v.len);
3716
3717 /* Now we have one header in <hdr> */
3718
3719 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3720 struct http_hdr_ctx ctx;
3721 int len;
3722
3723 switch (exp->action) {
3724 case ACT_ALLOW:
3725 txn->flags |= TX_SVALLOW;
3726 goto end;
3727 break;
3728
3729 case ACT_DENY:
3730 txn->flags |= TX_SVDENY;
3731 goto end;
3732 break;
3733
3734 case ACT_REPLACE:
3735 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3736 if (len < 0)
3737 return -1;
3738
3739 http_parse_header(ist2(trash.area, len), &n, &v);
3740 ctx.blk = blk;
3741 ctx.value = v;
3742 if (!http_replace_header(htx, &ctx, n, v))
3743 return -1;
3744 if (!ctx.blk)
3745 goto end;
3746 pos = htx_get_blk_pos(htx, blk);
3747 break;
3748
3749 case ACT_REMOVE:
3750 ctx.blk = blk;
3751 ctx.value = v;
3752 if (!http_remove_header(htx, &ctx))
3753 return -1;
3754 if (!ctx.blk)
3755 goto end;
3756 pos = htx_get_blk_pos(htx, blk);
3757 goto next_hdr;
3758 }
3759 }
3760
3761 }
3762 end:
3763 return 0;
3764}
3765
3766/* Apply the filter to the status line in the response buffer <res>.
3767 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3768 * or -1 if a replacement resulted in an invalid status line.
3769 */
3770static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3771{
3772 struct http_txn *txn = s->txn;
3773 struct htx *htx;
3774 struct buffer *resline = get_trash_chunk();
3775 int done;
3776
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003777 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003778
3779 if (unlikely(txn->flags & TX_SVDENY))
3780 return 1;
3781 else if (unlikely(txn->flags & TX_SVALLOW) &&
3782 (exp->action == ACT_ALLOW ||
3783 exp->action == ACT_DENY))
3784 return 0;
3785 else if (exp->action == ACT_REMOVE)
3786 return 0;
3787
3788 done = 0;
3789 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3790
3791 /* Now we have the status line between cur_ptr and cur_end */
3792 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003793 struct htx_sl *sl = http_find_stline(htx);
3794 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003795 int len;
3796
3797 switch (exp->action) {
3798 case ACT_ALLOW:
3799 txn->flags |= TX_SVALLOW;
3800 done = 1;
3801 break;
3802
3803 case ACT_DENY:
3804 txn->flags |= TX_SVDENY;
3805 done = 1;
3806 break;
3807
3808 case ACT_REPLACE:
3809 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3810 if (len < 0)
3811 return -1;
3812
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003813 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3814 sl->info.res.status = strl2ui(code.ptr, code.len);
3815 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003816 return -1;
3817
3818 done = 1;
3819 return 1;
3820 }
3821 }
3822 return done;
3823}
3824
3825/*
3826 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3827 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3828 * unparsable response.
3829 */
3830static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3831{
3832 struct session *sess = s->sess;
3833 struct http_txn *txn = s->txn;
3834 struct hdr_exp *exp;
3835
3836 for (exp = px->rsp_exp; exp; exp = exp->next) {
3837 int ret;
3838
3839 /*
3840 * The interleaving of transformations and verdicts
3841 * makes it difficult to decide to continue or stop
3842 * the evaluation.
3843 */
3844
3845 if (txn->flags & TX_SVDENY)
3846 break;
3847
3848 if ((txn->flags & TX_SVALLOW) &&
3849 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3850 exp->action == ACT_PASS)) {
3851 exp = exp->next;
3852 continue;
3853 }
3854
3855 /* if this filter had a condition, evaluate it now and skip to
3856 * next filter if the condition does not match.
3857 */
3858 if (exp->cond) {
3859 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3860 ret = acl_pass(ret);
3861 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3862 ret = !ret;
3863 if (!ret)
3864 continue;
3865 }
3866
3867 /* Apply the filter to the status line. */
3868 ret = htx_apply_filter_to_sts_line(s, res, exp);
3869 if (unlikely(ret < 0))
3870 return -1;
3871
3872 if (likely(ret == 0)) {
3873 /* The filter did not match the response, it can be
3874 * iterated through all headers.
3875 */
3876 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3877 return -1;
3878 }
3879 }
3880 return 0;
3881}
3882
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003883/*
3884 * Manage client-side cookie. It can impact performance by about 2% so it is
3885 * desirable to call it only when needed. This code is quite complex because
3886 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3887 * highly recommended not to touch this part without a good reason !
3888 */
3889static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3890{
3891 struct session *sess = s->sess;
3892 struct http_txn *txn = s->txn;
3893 struct htx *htx;
3894 struct http_hdr_ctx ctx;
3895 char *hdr_beg, *hdr_end, *del_from;
3896 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3897 int preserve_hdr;
3898
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003899 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003900 ctx.blk = NULL;
3901 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3902 del_from = NULL; /* nothing to be deleted */
3903 preserve_hdr = 0; /* assume we may kill the whole header */
3904
3905 /* Now look for cookies. Conforming to RFC2109, we have to support
3906 * attributes whose name begin with a '$', and associate them with
3907 * the right cookie, if we want to delete this cookie.
3908 * So there are 3 cases for each cookie read :
3909 * 1) it's a special attribute, beginning with a '$' : ignore it.
3910 * 2) it's a server id cookie that we *MAY* want to delete : save
3911 * some pointers on it (last semi-colon, beginning of cookie...)
3912 * 3) it's an application cookie : we *MAY* have to delete a previous
3913 * "special" cookie.
3914 * At the end of loop, if a "special" cookie remains, we may have to
3915 * remove it. If no application cookie persists in the header, we
3916 * *MUST* delete it.
3917 *
3918 * Note: RFC2965 is unclear about the processing of spaces around
3919 * the equal sign in the ATTR=VALUE form. A careful inspection of
3920 * the RFC explicitly allows spaces before it, and not within the
3921 * tokens (attrs or values). An inspection of RFC2109 allows that
3922 * too but section 10.1.3 lets one think that spaces may be allowed
3923 * after the equal sign too, resulting in some (rare) buggy
3924 * implementations trying to do that. So let's do what servers do.
3925 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3926 * allowed quoted strings in values, with any possible character
3927 * after a backslash, including control chars and delimitors, which
3928 * causes parsing to become ambiguous. Browsers also allow spaces
3929 * within values even without quotes.
3930 *
3931 * We have to keep multiple pointers in order to support cookie
3932 * removal at the beginning, middle or end of header without
3933 * corrupting the header. All of these headers are valid :
3934 *
3935 * hdr_beg hdr_end
3936 * | |
3937 * v |
3938 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3939 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3940 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3941 * | | | | | | |
3942 * | | | | | | |
3943 * | | | | | | +--> next
3944 * | | | | | +----> val_end
3945 * | | | | +-----------> val_beg
3946 * | | | +--------------> equal
3947 * | | +----------------> att_end
3948 * | +---------------------> att_beg
3949 * +--------------------------> prev
3950 *
3951 */
3952 hdr_beg = ctx.value.ptr;
3953 hdr_end = hdr_beg + ctx.value.len;
3954 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3955 /* Iterate through all cookies on this line */
3956
3957 /* find att_beg */
3958 att_beg = prev;
3959 if (prev > hdr_beg)
3960 att_beg++;
3961
3962 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3963 att_beg++;
3964
3965 /* find att_end : this is the first character after the last non
3966 * space before the equal. It may be equal to hdr_end.
3967 */
3968 equal = att_end = att_beg;
3969 while (equal < hdr_end) {
3970 if (*equal == '=' || *equal == ',' || *equal == ';')
3971 break;
3972 if (HTTP_IS_SPHT(*equal++))
3973 continue;
3974 att_end = equal;
3975 }
3976
3977 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3978 * is between <att_beg> and <equal>, both may be identical.
3979 */
3980 /* look for end of cookie if there is an equal sign */
3981 if (equal < hdr_end && *equal == '=') {
3982 /* look for the beginning of the value */
3983 val_beg = equal + 1;
3984 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3985 val_beg++;
3986
3987 /* find the end of the value, respecting quotes */
3988 next = http_find_cookie_value_end(val_beg, hdr_end);
3989
3990 /* make val_end point to the first white space or delimitor after the value */
3991 val_end = next;
3992 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3993 val_end--;
3994 }
3995 else
3996 val_beg = val_end = next = equal;
3997
3998 /* We have nothing to do with attributes beginning with
3999 * '$'. However, they will automatically be removed if a
4000 * header before them is removed, since they're supposed
4001 * to be linked together.
4002 */
4003 if (*att_beg == '$')
4004 continue;
4005
4006 /* Ignore cookies with no equal sign */
4007 if (equal == next) {
4008 /* This is not our cookie, so we must preserve it. But if we already
4009 * scheduled another cookie for removal, we cannot remove the
4010 * complete header, but we can remove the previous block itself.
4011 */
4012 preserve_hdr = 1;
4013 if (del_from != NULL) {
4014 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4015 val_end += delta;
4016 next += delta;
4017 hdr_end += delta;
4018 prev = del_from;
4019 del_from = NULL;
4020 }
4021 continue;
4022 }
4023
4024 /* if there are spaces around the equal sign, we need to
4025 * strip them otherwise we'll get trouble for cookie captures,
4026 * or even for rewrites. Since this happens extremely rarely,
4027 * it does not hurt performance.
4028 */
4029 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4030 int stripped_before = 0;
4031 int stripped_after = 0;
4032
4033 if (att_end != equal) {
4034 memmove(att_end, equal, hdr_end - equal);
4035 stripped_before = (att_end - equal);
4036 equal += stripped_before;
4037 val_beg += stripped_before;
4038 }
4039
4040 if (val_beg > equal + 1) {
4041 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4042 stripped_after = (equal + 1) - val_beg;
4043 val_beg += stripped_after;
4044 stripped_before += stripped_after;
4045 }
4046
4047 val_end += stripped_before;
4048 next += stripped_before;
4049 hdr_end += stripped_before;
4050 }
4051 /* now everything is as on the diagram above */
4052
4053 /* First, let's see if we want to capture this cookie. We check
4054 * that we don't already have a client side cookie, because we
4055 * can only capture one. Also as an optimisation, we ignore
4056 * cookies shorter than the declared name.
4057 */
4058 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4059 (val_end - att_beg >= sess->fe->capture_namelen) &&
4060 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4061 int log_len = val_end - att_beg;
4062
4063 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4064 ha_alert("HTTP logging : out of memory.\n");
4065 } else {
4066 if (log_len > sess->fe->capture_len)
4067 log_len = sess->fe->capture_len;
4068 memcpy(txn->cli_cookie, att_beg, log_len);
4069 txn->cli_cookie[log_len] = 0;
4070 }
4071 }
4072
4073 /* Persistence cookies in passive, rewrite or insert mode have the
4074 * following form :
4075 *
4076 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4077 *
4078 * For cookies in prefix mode, the form is :
4079 *
4080 * Cookie: NAME=SRV~VALUE
4081 */
4082 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4083 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4084 struct server *srv = s->be->srv;
4085 char *delim;
4086
4087 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4088 * have the server ID between val_beg and delim, and the original cookie between
4089 * delim+1 and val_end. Otherwise, delim==val_end :
4090 *
4091 * hdr_beg
4092 * |
4093 * v
4094 * NAME=SRV; # in all but prefix modes
4095 * NAME=SRV~OPAQUE ; # in prefix mode
4096 * || || | |+-> next
4097 * || || | +--> val_end
4098 * || || +---------> delim
4099 * || |+------------> val_beg
4100 * || +-------------> att_end = equal
4101 * |+-----------------> att_beg
4102 * +------------------> prev
4103 *
4104 */
4105 if (s->be->ck_opts & PR_CK_PFX) {
4106 for (delim = val_beg; delim < val_end; delim++)
4107 if (*delim == COOKIE_DELIM)
4108 break;
4109 }
4110 else {
4111 char *vbar1;
4112 delim = val_end;
4113 /* Now check if the cookie contains a date field, which would
4114 * appear after a vertical bar ('|') just after the server name
4115 * and before the delimiter.
4116 */
4117 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4118 if (vbar1) {
4119 /* OK, so left of the bar is the server's cookie and
4120 * right is the last seen date. It is a base64 encoded
4121 * 30-bit value representing the UNIX date since the
4122 * epoch in 4-second quantities.
4123 */
4124 int val;
4125 delim = vbar1++;
4126 if (val_end - vbar1 >= 5) {
4127 val = b64tos30(vbar1);
4128 if (val > 0)
4129 txn->cookie_last_date = val << 2;
4130 }
4131 /* look for a second vertical bar */
4132 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4133 if (vbar1 && (val_end - vbar1 > 5)) {
4134 val = b64tos30(vbar1 + 1);
4135 if (val > 0)
4136 txn->cookie_first_date = val << 2;
4137 }
4138 }
4139 }
4140
4141 /* if the cookie has an expiration date and the proxy wants to check
4142 * it, then we do that now. We first check if the cookie is too old,
4143 * then only if it has expired. We detect strict overflow because the
4144 * time resolution here is not great (4 seconds). Cookies with dates
4145 * in the future are ignored if their offset is beyond one day. This
4146 * allows an admin to fix timezone issues without expiring everyone
4147 * and at the same time avoids keeping unwanted side effects for too
4148 * long.
4149 */
4150 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4151 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4152 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4153 txn->flags &= ~TX_CK_MASK;
4154 txn->flags |= TX_CK_OLD;
4155 delim = val_beg; // let's pretend we have not found the cookie
4156 txn->cookie_first_date = 0;
4157 txn->cookie_last_date = 0;
4158 }
4159 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4160 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4161 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4162 txn->flags &= ~TX_CK_MASK;
4163 txn->flags |= TX_CK_EXPIRED;
4164 delim = val_beg; // let's pretend we have not found the cookie
4165 txn->cookie_first_date = 0;
4166 txn->cookie_last_date = 0;
4167 }
4168
4169 /* Here, we'll look for the first running server which supports the cookie.
4170 * This allows to share a same cookie between several servers, for example
4171 * to dedicate backup servers to specific servers only.
4172 * However, to prevent clients from sticking to cookie-less backup server
4173 * when they have incidentely learned an empty cookie, we simply ignore
4174 * empty cookies and mark them as invalid.
4175 * The same behaviour is applied when persistence must be ignored.
4176 */
4177 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4178 srv = NULL;
4179
4180 while (srv) {
4181 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4182 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4183 if ((srv->cur_state != SRV_ST_STOPPED) ||
4184 (s->be->options & PR_O_PERSIST) ||
4185 (s->flags & SF_FORCE_PRST)) {
4186 /* we found the server and we can use it */
4187 txn->flags &= ~TX_CK_MASK;
4188 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4189 s->flags |= SF_DIRECT | SF_ASSIGNED;
4190 s->target = &srv->obj_type;
4191 break;
4192 } else {
4193 /* we found a server, but it's down,
4194 * mark it as such and go on in case
4195 * another one is available.
4196 */
4197 txn->flags &= ~TX_CK_MASK;
4198 txn->flags |= TX_CK_DOWN;
4199 }
4200 }
4201 srv = srv->next;
4202 }
4203
4204 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4205 /* no server matched this cookie or we deliberately skipped it */
4206 txn->flags &= ~TX_CK_MASK;
4207 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4208 txn->flags |= TX_CK_UNUSED;
4209 else
4210 txn->flags |= TX_CK_INVALID;
4211 }
4212
4213 /* depending on the cookie mode, we may have to either :
4214 * - delete the complete cookie if we're in insert+indirect mode, so that
4215 * the server never sees it ;
4216 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004217 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004218 * if we're in cookie prefix mode
4219 */
4220 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4221 int delta; /* negative */
4222
4223 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4224 delta = val_beg - (delim + 1);
4225 val_end += delta;
4226 next += delta;
4227 hdr_end += delta;
4228 del_from = NULL;
4229 preserve_hdr = 1; /* we want to keep this cookie */
4230 }
4231 else if (del_from == NULL &&
4232 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4233 del_from = prev;
4234 }
4235 }
4236 else {
4237 /* This is not our cookie, so we must preserve it. But if we already
4238 * scheduled another cookie for removal, we cannot remove the
4239 * complete header, but we can remove the previous block itself.
4240 */
4241 preserve_hdr = 1;
4242
4243 if (del_from != NULL) {
4244 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4245 if (att_beg >= del_from)
4246 att_beg += delta;
4247 if (att_end >= del_from)
4248 att_end += delta;
4249 val_beg += delta;
4250 val_end += delta;
4251 next += delta;
4252 hdr_end += delta;
4253 prev = del_from;
4254 del_from = NULL;
4255 }
4256 }
4257
4258 /* continue with next cookie on this header line */
4259 att_beg = next;
4260 } /* for each cookie */
4261
4262
4263 /* There are no more cookies on this line.
4264 * We may still have one (or several) marked for deletion at the
4265 * end of the line. We must do this now in two ways :
4266 * - if some cookies must be preserved, we only delete from the
4267 * mark to the end of line ;
4268 * - if nothing needs to be preserved, simply delete the whole header
4269 */
4270 if (del_from) {
4271 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4272 }
4273 if ((hdr_end - hdr_beg) != ctx.value.len) {
4274 if (hdr_beg != hdr_end) {
4275 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4276 htx->data -= (hdr_end - ctx.value.ptr);
4277 }
4278 else
4279 http_remove_header(htx, &ctx);
4280 }
4281 } /* for each "Cookie header */
4282}
4283
4284/*
4285 * Manage server-side cookies. It can impact performance by about 2% so it is
4286 * desirable to call it only when needed. This function is also used when we
4287 * just need to know if there is a cookie (eg: for check-cache).
4288 */
4289static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4290{
4291 struct session *sess = s->sess;
4292 struct http_txn *txn = s->txn;
4293 struct htx *htx;
4294 struct http_hdr_ctx ctx;
4295 struct server *srv;
4296 char *hdr_beg, *hdr_end;
4297 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4298 int is_cookie2;
4299
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004300 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004301
4302 ctx.blk = NULL;
4303 while (1) {
4304 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4305 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4306 break;
4307 is_cookie2 = 1;
4308 }
4309
4310 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4311 * <prev> points to the colon.
4312 */
4313 txn->flags |= TX_SCK_PRESENT;
4314
4315 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4316 * check-cache is enabled) and we are not interested in checking
4317 * them. Warning, the cookie capture is declared in the frontend.
4318 */
4319 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4320 break;
4321
4322 /* OK so now we know we have to process this response cookie.
4323 * The format of the Set-Cookie header is slightly different
4324 * from the format of the Cookie header in that it does not
4325 * support the comma as a cookie delimiter (thus the header
4326 * cannot be folded) because the Expires attribute described in
4327 * the original Netscape's spec may contain an unquoted date
4328 * with a comma inside. We have to live with this because
4329 * many browsers don't support Max-Age and some browsers don't
4330 * support quoted strings. However the Set-Cookie2 header is
4331 * clean.
4332 *
4333 * We have to keep multiple pointers in order to support cookie
4334 * removal at the beginning, middle or end of header without
4335 * corrupting the header (in case of set-cookie2). A special
4336 * pointer, <scav> points to the beginning of the set-cookie-av
4337 * fields after the first semi-colon. The <next> pointer points
4338 * either to the end of line (set-cookie) or next unquoted comma
4339 * (set-cookie2). All of these headers are valid :
4340 *
4341 * hdr_beg hdr_end
4342 * | |
4343 * v |
4344 * NAME1 = VALUE 1 ; Secure; Path="/" |
4345 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4346 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4347 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4348 * | | | | | | | |
4349 * | | | | | | | +-> next
4350 * | | | | | | +------------> scav
4351 * | | | | | +--------------> val_end
4352 * | | | | +--------------------> val_beg
4353 * | | | +----------------------> equal
4354 * | | +------------------------> att_end
4355 * | +----------------------------> att_beg
4356 * +------------------------------> prev
4357 * -------------------------------> hdr_beg
4358 */
4359 hdr_beg = ctx.value.ptr;
4360 hdr_end = hdr_beg + ctx.value.len;
4361 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4362
4363 /* Iterate through all cookies on this line */
4364
4365 /* find att_beg */
4366 att_beg = prev;
4367 if (prev > hdr_beg)
4368 att_beg++;
4369
4370 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4371 att_beg++;
4372
4373 /* find att_end : this is the first character after the last non
4374 * space before the equal. It may be equal to hdr_end.
4375 */
4376 equal = att_end = att_beg;
4377
4378 while (equal < hdr_end) {
4379 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4380 break;
4381 if (HTTP_IS_SPHT(*equal++))
4382 continue;
4383 att_end = equal;
4384 }
4385
4386 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4387 * is between <att_beg> and <equal>, both may be identical.
4388 */
4389
4390 /* look for end of cookie if there is an equal sign */
4391 if (equal < hdr_end && *equal == '=') {
4392 /* look for the beginning of the value */
4393 val_beg = equal + 1;
4394 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4395 val_beg++;
4396
4397 /* find the end of the value, respecting quotes */
4398 next = http_find_cookie_value_end(val_beg, hdr_end);
4399
4400 /* make val_end point to the first white space or delimitor after the value */
4401 val_end = next;
4402 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4403 val_end--;
4404 }
4405 else {
4406 /* <equal> points to next comma, semi-colon or EOL */
4407 val_beg = val_end = next = equal;
4408 }
4409
4410 if (next < hdr_end) {
4411 /* Set-Cookie2 supports multiple cookies, and <next> points to
4412 * a colon or semi-colon before the end. So skip all attr-value
4413 * pairs and look for the next comma. For Set-Cookie, since
4414 * commas are permitted in values, skip to the end.
4415 */
4416 if (is_cookie2)
4417 next = http_find_hdr_value_end(next, hdr_end);
4418 else
4419 next = hdr_end;
4420 }
4421
4422 /* Now everything is as on the diagram above */
4423
4424 /* Ignore cookies with no equal sign */
4425 if (equal == val_end)
4426 continue;
4427
4428 /* If there are spaces around the equal sign, we need to
4429 * strip them otherwise we'll get trouble for cookie captures,
4430 * or even for rewrites. Since this happens extremely rarely,
4431 * it does not hurt performance.
4432 */
4433 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4434 int stripped_before = 0;
4435 int stripped_after = 0;
4436
4437 if (att_end != equal) {
4438 memmove(att_end, equal, hdr_end - equal);
4439 stripped_before = (att_end - equal);
4440 equal += stripped_before;
4441 val_beg += stripped_before;
4442 }
4443
4444 if (val_beg > equal + 1) {
4445 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4446 stripped_after = (equal + 1) - val_beg;
4447 val_beg += stripped_after;
4448 stripped_before += stripped_after;
4449 }
4450
4451 val_end += stripped_before;
4452 next += stripped_before;
4453 hdr_end += stripped_before;
4454
4455 ctx.value.len = hdr_end - hdr_beg;
4456 htx_set_blk_value_len(ctx.blk, ctx.value.len);
4457 htx->data -= (hdr_end - ctx.value.ptr);
4458 }
4459
4460 /* First, let's see if we want to capture this cookie. We check
4461 * that we don't already have a server side cookie, because we
4462 * can only capture one. Also as an optimisation, we ignore
4463 * cookies shorter than the declared name.
4464 */
4465 if (sess->fe->capture_name != NULL &&
4466 txn->srv_cookie == NULL &&
4467 (val_end - att_beg >= sess->fe->capture_namelen) &&
4468 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4469 int log_len = val_end - att_beg;
4470 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4471 ha_alert("HTTP logging : out of memory.\n");
4472 }
4473 else {
4474 if (log_len > sess->fe->capture_len)
4475 log_len = sess->fe->capture_len;
4476 memcpy(txn->srv_cookie, att_beg, log_len);
4477 txn->srv_cookie[log_len] = 0;
4478 }
4479 }
4480
4481 srv = objt_server(s->target);
4482 /* now check if we need to process it for persistence */
4483 if (!(s->flags & SF_IGNORE_PRST) &&
4484 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4485 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4486 /* assume passive cookie by default */
4487 txn->flags &= ~TX_SCK_MASK;
4488 txn->flags |= TX_SCK_FOUND;
4489
4490 /* If the cookie is in insert mode on a known server, we'll delete
4491 * this occurrence because we'll insert another one later.
4492 * We'll delete it too if the "indirect" option is set and we're in
4493 * a direct access.
4494 */
4495 if (s->be->ck_opts & PR_CK_PSV) {
4496 /* The "preserve" flag was set, we don't want to touch the
4497 * server's cookie.
4498 */
4499 }
4500 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4501 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4502 /* this cookie must be deleted */
4503 if (prev == hdr_beg && next == hdr_end) {
4504 /* whole header */
4505 http_remove_header(htx, &ctx);
4506 /* note: while both invalid now, <next> and <hdr_end>
4507 * are still equal, so the for() will stop as expected.
4508 */
4509 } else {
4510 /* just remove the value */
4511 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4512 next = prev;
4513 hdr_end += delta;
4514 }
4515 txn->flags &= ~TX_SCK_MASK;
4516 txn->flags |= TX_SCK_DELETED;
4517 /* and go on with next cookie */
4518 }
4519 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4520 /* replace bytes val_beg->val_end with the cookie name associated
4521 * with this server since we know it.
4522 */
4523 int sliding, delta;
4524
4525 ctx.value = ist2(val_beg, val_end - val_beg);
4526 ctx.lws_before = ctx.lws_after = 0;
4527 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4528 delta = srv->cklen - (val_end - val_beg);
4529 sliding = (ctx.value.ptr - val_beg);
4530 hdr_beg += sliding;
4531 val_beg += sliding;
4532 next += sliding + delta;
4533 hdr_end += sliding + delta;
4534
4535 txn->flags &= ~TX_SCK_MASK;
4536 txn->flags |= TX_SCK_REPLACED;
4537 }
4538 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4539 /* insert the cookie name associated with this server
4540 * before existing cookie, and insert a delimiter between them..
4541 */
4542 int sliding, delta;
4543 ctx.value = ist2(val_beg, 0);
4544 ctx.lws_before = ctx.lws_after = 0;
4545 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4546 delta = srv->cklen + 1;
4547 sliding = (ctx.value.ptr - val_beg);
4548 hdr_beg += sliding;
4549 val_beg += sliding;
4550 next += sliding + delta;
4551 hdr_end += sliding + delta;
4552
4553 val_beg[srv->cklen] = COOKIE_DELIM;
4554 txn->flags &= ~TX_SCK_MASK;
4555 txn->flags |= TX_SCK_REPLACED;
4556 }
4557 }
4558 /* that's done for this cookie, check the next one on the same
4559 * line when next != hdr_end (only if is_cookie2).
4560 */
4561 }
4562 }
4563}
4564
Christopher Faulet25a02f62018-10-24 12:00:25 +02004565/*
4566 * Parses the Cache-Control and Pragma request header fields to determine if
4567 * the request may be served from the cache and/or if it is cacheable. Updates
4568 * s->txn->flags.
4569 */
4570void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4571{
4572 struct http_txn *txn = s->txn;
4573 struct htx *htx;
4574 int32_t pos;
4575 int pragma_found, cc_found, i;
4576
4577 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4578 return; /* nothing more to do here */
4579
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004580 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004581 pragma_found = cc_found = 0;
4582 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4583 struct htx_blk *blk = htx_get_blk(htx, pos);
4584 enum htx_blk_type type = htx_get_blk_type(blk);
4585 struct ist n, v;
4586
4587 if (type == HTX_BLK_EOH)
4588 break;
4589 if (type != HTX_BLK_HDR)
4590 continue;
4591
4592 n = htx_get_blk_name(htx, blk);
4593 v = htx_get_blk_value(htx, blk);
4594
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004595 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004596 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4597 pragma_found = 1;
4598 continue;
4599 }
4600 }
4601
4602 /* Don't use the cache and don't try to store if we found the
4603 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004604 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004605 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4606 txn->flags |= TX_CACHE_IGNORE;
4607 continue;
4608 }
4609
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004610 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004611 continue;
4612
4613 /* OK, right now we know we have a cache-control header */
4614 cc_found = 1;
4615 if (!v.len) /* no info */
4616 continue;
4617
4618 i = 0;
4619 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4620 !isspace((unsigned char)*(v.ptr+i)))
4621 i++;
4622
4623 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4624 * values after max-age, max-stale nor min-fresh, we simply don't
4625 * use the cache when they're specified.
4626 */
4627 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4628 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4629 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4630 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4631 txn->flags |= TX_CACHE_IGNORE;
4632 continue;
4633 }
4634
4635 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4636 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4637 continue;
4638 }
4639 }
4640
4641 /* RFC7234#5.4:
4642 * When the Cache-Control header field is also present and
4643 * understood in a request, Pragma is ignored.
4644 * When the Cache-Control header field is not present in a
4645 * request, caches MUST consider the no-cache request
4646 * pragma-directive as having the same effect as if
4647 * "Cache-Control: no-cache" were present.
4648 */
4649 if (!cc_found && pragma_found)
4650 txn->flags |= TX_CACHE_IGNORE;
4651}
4652
4653/*
4654 * Check if response is cacheable or not. Updates s->txn->flags.
4655 */
4656void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4657{
4658 struct http_txn *txn = s->txn;
4659 struct htx *htx;
4660 int32_t pos;
4661 int i;
4662
4663 if (txn->status < 200) {
4664 /* do not try to cache interim responses! */
4665 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4666 return;
4667 }
4668
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004669 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004670 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4671 struct htx_blk *blk = htx_get_blk(htx, pos);
4672 enum htx_blk_type type = htx_get_blk_type(blk);
4673 struct ist n, v;
4674
4675 if (type == HTX_BLK_EOH)
4676 break;
4677 if (type != HTX_BLK_HDR)
4678 continue;
4679
4680 n = htx_get_blk_name(htx, blk);
4681 v = htx_get_blk_value(htx, blk);
4682
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004683 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004684 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4685 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4686 return;
4687 }
4688 }
4689
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004690 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004691 continue;
4692
4693 /* OK, right now we know we have a cache-control header */
4694 if (!v.len) /* no info */
4695 continue;
4696
4697 i = 0;
4698 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4699 !isspace((unsigned char)*(v.ptr+i)))
4700 i++;
4701
4702 /* we have a complete value between v.ptr and (v.ptr+i) */
4703 if (i < v.len && *(v.ptr + i) == '=') {
4704 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4705 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4706 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4707 continue;
4708 }
4709
4710 /* we have something of the form no-cache="set-cookie" */
4711 if ((v.len >= 21) &&
4712 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4713 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4714 txn->flags &= ~TX_CACHE_COOK;
4715 continue;
4716 }
4717
4718 /* OK, so we know that either p2 points to the end of string or to a comma */
4719 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4720 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4721 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4722 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4723 return;
4724 }
4725
4726 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4727 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4728 continue;
4729 }
4730 }
4731}
4732
Christopher Faulet64159df2018-10-24 21:15:35 +02004733/* send a server's name with an outgoing request over an established connection.
4734 * Note: this function is designed to be called once the request has been
4735 * scheduled for being forwarded. This is the reason why the number of forwarded
4736 * bytes have to be adjusted.
4737 */
4738int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4739{
4740 struct htx *htx;
4741 struct http_hdr_ctx ctx;
4742 struct ist hdr;
4743 uint32_t data;
4744
4745 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004746 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004747 data = htx->data;
4748
4749 ctx.blk = NULL;
4750 while (http_find_header(htx, hdr, &ctx, 1))
4751 http_remove_header(htx, &ctx);
4752 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4753
4754 if (co_data(&s->req)) {
4755 if (data >= htx->data)
4756 c_rew(&s->req, data - htx->data);
4757 else
4758 c_adv(&s->req, htx->data - data);
4759 }
4760 return 0;
4761}
4762
Christopher Faulet377c5a52018-10-24 21:21:30 +02004763/*
4764 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4765 * for the current backend.
4766 *
4767 * It is assumed that the request is either a HEAD, GET, or POST and that the
4768 * uri_auth field is valid.
4769 *
4770 * Returns 1 if stats should be provided, otherwise 0.
4771 */
4772static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4773{
4774 struct uri_auth *uri_auth = backend->uri_auth;
4775 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004776 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004777 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004778
4779 if (!uri_auth)
4780 return 0;
4781
4782 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4783 return 0;
4784
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004785 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004786 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004787 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004788
4789 /* check URI size */
4790 if (uri_auth->uri_len > uri.len)
4791 return 0;
4792
4793 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4794 return 0;
4795
4796 return 1;
4797}
4798
4799/* This function prepares an applet to handle the stats. It can deal with the
4800 * "100-continue" expectation, check that admin rules are met for POST requests,
4801 * and program a response message if something was unexpected. It cannot fail
4802 * and always relies on the stats applet to complete the job. It does not touch
4803 * analysers nor counters, which are left to the caller. It does not touch
4804 * s->target which is supposed to already point to the stats applet. The caller
4805 * is expected to have already assigned an appctx to the stream.
4806 */
4807static int htx_handle_stats(struct stream *s, struct channel *req)
4808{
4809 struct stats_admin_rule *stats_admin_rule;
4810 struct stream_interface *si = &s->si[1];
4811 struct session *sess = s->sess;
4812 struct http_txn *txn = s->txn;
4813 struct http_msg *msg = &txn->req;
4814 struct uri_auth *uri_auth = s->be->uri_auth;
4815 const char *h, *lookup, *end;
4816 struct appctx *appctx;
4817 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004818 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004819
4820 appctx = si_appctx(si);
4821 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4822 appctx->st1 = appctx->st2 = 0;
4823 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4824 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4825 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4826 appctx->ctx.stats.flags |= STAT_CHUNKED;
4827
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004828 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004829 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004830 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4831 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004832
4833 for (h = lookup; h <= end - 3; h++) {
4834 if (memcmp(h, ";up", 3) == 0) {
4835 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4836 break;
4837 }
4838 }
4839
4840 if (uri_auth->refresh) {
4841 for (h = lookup; h <= end - 10; h++) {
4842 if (memcmp(h, ";norefresh", 10) == 0) {
4843 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4844 break;
4845 }
4846 }
4847 }
4848
4849 for (h = lookup; h <= end - 4; h++) {
4850 if (memcmp(h, ";csv", 4) == 0) {
4851 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4852 break;
4853 }
4854 }
4855
4856 for (h = lookup; h <= end - 6; h++) {
4857 if (memcmp(h, ";typed", 6) == 0) {
4858 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4859 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4860 break;
4861 }
4862 }
4863
4864 for (h = lookup; h <= end - 8; h++) {
4865 if (memcmp(h, ";st=", 4) == 0) {
4866 int i;
4867 h += 4;
4868 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4869 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4870 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4871 appctx->ctx.stats.st_code = i;
4872 break;
4873 }
4874 }
4875 break;
4876 }
4877 }
4878
4879 appctx->ctx.stats.scope_str = 0;
4880 appctx->ctx.stats.scope_len = 0;
4881 for (h = lookup; h <= end - 8; h++) {
4882 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4883 int itx = 0;
4884 const char *h2;
4885 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4886 const char *err;
4887
4888 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4889 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004890 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4891 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004892 if (*h == ';' || *h == '&' || *h == ' ')
4893 break;
4894 itx++;
4895 h++;
4896 }
4897
4898 if (itx > STAT_SCOPE_TXT_MAXLEN)
4899 itx = STAT_SCOPE_TXT_MAXLEN;
4900 appctx->ctx.stats.scope_len = itx;
4901
4902 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4903 memcpy(scope_txt, h2, itx);
4904 scope_txt[itx] = '\0';
4905 err = invalid_char(scope_txt);
4906 if (err) {
4907 /* bad char in search text => clear scope */
4908 appctx->ctx.stats.scope_str = 0;
4909 appctx->ctx.stats.scope_len = 0;
4910 }
4911 break;
4912 }
4913 }
4914
4915 /* now check whether we have some admin rules for this request */
4916 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4917 int ret = 1;
4918
4919 if (stats_admin_rule->cond) {
4920 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4921 ret = acl_pass(ret);
4922 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4923 ret = !ret;
4924 }
4925
4926 if (ret) {
4927 /* no rule, or the rule matches */
4928 appctx->ctx.stats.flags |= STAT_ADMIN;
4929 break;
4930 }
4931 }
4932
4933 /* Was the status page requested with a POST ? */
4934 if (unlikely(txn->meth == HTTP_METH_POST)) {
4935 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4936 /* we'll need the request body, possibly after sending 100-continue */
4937 if (msg->msg_state < HTTP_MSG_DATA)
4938 req->analysers |= AN_REQ_HTTP_BODY;
4939 appctx->st0 = STAT_HTTP_POST;
4940 }
4941 else {
4942 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4943 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4944 appctx->st0 = STAT_HTTP_LAST;
4945 }
4946 }
4947 else {
4948 /* So it was another method (GET/HEAD) */
4949 appctx->st0 = STAT_HTTP_HEAD;
4950 }
4951
4952 s->task->nice = -32; /* small boost for HTTP statistics */
4953 return 1;
4954}
4955
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004956void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4957{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004958 struct channel *req = &s->req;
4959 struct channel *res = &s->res;
4960 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004961 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004962 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004963 struct ist path, location;
4964 unsigned int flags;
4965 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004966
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004967 /*
4968 * Create the location
4969 */
4970 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004971
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004972 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004973 /* special prefix "/" means don't change URL */
4974 srv = __objt_server(s->target);
4975 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4976 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4977 return;
4978 }
4979
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004980 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004981 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004982 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004983 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004984 if (!path.ptr)
4985 return;
4986
4987 if (!chunk_memcat(&trash, path.ptr, path.len))
4988 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004989 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004991 /*
4992 * Create the 302 respone
4993 */
4994 htx = htx_from_buf(&res->buf);
4995 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4996 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4997 ist("HTTP/1.1"), ist("302"), ist("Found"));
4998 if (!sl)
4999 goto fail;
5000 sl->info.res.status = 302;
5001 s->txn->status = 302;
5002
5003 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5004 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5005 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5006 !htx_add_header(htx, ist("Location"), location))
5007 goto fail;
5008
5009 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5010 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005011
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005012 /*
5013 * Send the message
5014 */
5015 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005016 c_adv(res, data);
5017 res->total += data;
5018
5019 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005020 si_shutr(si);
5021 si_shutw(si);
5022 si->err_type = SI_ET_NONE;
5023 si->state = SI_ST_CLO;
5024
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005025 channel_auto_read(req);
5026 channel_abort(req);
5027 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005028 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005029 channel_auto_read(res);
5030 channel_auto_close(res);
5031
5032 if (!(s->flags & SF_ERR_MASK))
5033 s->flags |= SF_ERR_LOCAL;
5034 if (!(s->flags & SF_FINST_MASK))
5035 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005036
5037 /* FIXME: we should increase a counter of redirects per server and per backend. */
5038 srv_inc_sess_ctr(srv);
5039 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005040 return;
5041
5042 fail:
5043 /* If an error occurred, remove the incomplete HTTP response from the
5044 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005045 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005046}
5047
Christopher Fauletf2824e62018-10-01 12:12:37 +02005048/* This function terminates the request because it was completly analyzed or
5049 * because an error was triggered during the body forwarding.
5050 */
5051static void htx_end_request(struct stream *s)
5052{
5053 struct channel *chn = &s->req;
5054 struct http_txn *txn = s->txn;
5055
5056 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5057 now_ms, __FUNCTION__, s,
5058 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5059 s->req.analysers, s->res.analysers);
5060
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005061 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5062 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005063 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005064 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005065 goto end;
5066 }
5067
5068 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5069 return;
5070
5071 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005072 /* No need to read anymore, the request was completely parsed.
5073 * We can shut the read side unless we want to abort_on_close,
5074 * or we have a POST request. The issue with POST requests is
5075 * that some browsers still send a CRLF after the request, and
5076 * this CRLF must be read so that it does not remain in the kernel
5077 * buffers, otherwise a close could cause an RST on some systems
5078 * (eg: Linux).
5079 */
5080 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5081 txn->meth != HTTP_METH_POST)
5082 channel_dont_read(chn);
5083
5084 /* if the server closes the connection, we want to immediately react
5085 * and close the socket to save packets and syscalls.
5086 */
5087 s->si[1].flags |= SI_FL_NOHALF;
5088
5089 /* In any case we've finished parsing the request so we must
5090 * disable Nagle when sending data because 1) we're not going
5091 * to shut this side, and 2) the server is waiting for us to
5092 * send pending data.
5093 */
5094 chn->flags |= CF_NEVER_WAIT;
5095
Christopher Fauletd01ce402019-01-02 17:44:13 +01005096 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5097 /* The server has not finished to respond, so we
5098 * don't want to move in order not to upset it.
5099 */
5100 return;
5101 }
5102
Christopher Fauletf2824e62018-10-01 12:12:37 +02005103 /* When we get here, it means that both the request and the
5104 * response have finished receiving. Depending on the connection
5105 * mode, we'll have to wait for the last bytes to leave in either
5106 * direction, and sometimes for a close to be effective.
5107 */
5108 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5109 /* Tunnel mode will not have any analyser so it needs to
5110 * poll for reads.
5111 */
5112 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005113 if (b_data(&chn->buf))
5114 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 txn->req.msg_state = HTTP_MSG_TUNNEL;
5116 }
5117 else {
5118 /* we're not expecting any new data to come for this
5119 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005120 *
5121 * However, there is an exception if the response
5122 * length is undefined. In this case, we need to wait
5123 * the close from the server. The response will be
5124 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005125 */
5126 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5127 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005128 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005129
5130 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5131 channel_shutr_now(chn);
5132 channel_shutw_now(chn);
5133 }
5134 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005135 goto check_channel_flags;
5136 }
5137
5138 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5139 http_msg_closing:
5140 /* nothing else to forward, just waiting for the output buffer
5141 * to be empty and for the shutw_now to take effect.
5142 */
5143 if (channel_is_empty(chn)) {
5144 txn->req.msg_state = HTTP_MSG_CLOSED;
5145 goto http_msg_closed;
5146 }
5147 else if (chn->flags & CF_SHUTW) {
5148 txn->req.err_state = txn->req.msg_state;
5149 txn->req.msg_state = HTTP_MSG_ERROR;
5150 goto end;
5151 }
5152 return;
5153 }
5154
5155 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5156 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005157 /* if we don't know whether the server will close, we need to hard close */
5158 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5159 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005160 /* see above in MSG_DONE why we only do this in these states */
5161 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5162 channel_dont_read(chn);
5163 goto end;
5164 }
5165
5166 check_channel_flags:
5167 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5168 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5169 /* if we've just closed an output, let's switch */
5170 txn->req.msg_state = HTTP_MSG_CLOSING;
5171 goto http_msg_closing;
5172 }
5173
5174 end:
5175 chn->analysers &= AN_REQ_FLT_END;
5176 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5177 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5178 channel_auto_close(chn);
5179 channel_auto_read(chn);
5180}
5181
5182
5183/* This function terminates the response because it was completly analyzed or
5184 * because an error was triggered during the body forwarding.
5185 */
5186static void htx_end_response(struct stream *s)
5187{
5188 struct channel *chn = &s->res;
5189 struct http_txn *txn = s->txn;
5190
5191 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5192 now_ms, __FUNCTION__, s,
5193 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5194 s->req.analysers, s->res.analysers);
5195
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005196 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5197 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005198 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005199 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005200 goto end;
5201 }
5202
5203 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5204 return;
5205
5206 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5207 /* In theory, we don't need to read anymore, but we must
5208 * still monitor the server connection for a possible close
5209 * while the request is being uploaded, so we don't disable
5210 * reading.
5211 */
5212 /* channel_dont_read(chn); */
5213
5214 if (txn->req.msg_state < HTTP_MSG_DONE) {
5215 /* The client seems to still be sending data, probably
5216 * because we got an error response during an upload.
5217 * We have the choice of either breaking the connection
5218 * or letting it pass through. Let's do the later.
5219 */
5220 return;
5221 }
5222
5223 /* When we get here, it means that both the request and the
5224 * response have finished receiving. Depending on the connection
5225 * mode, we'll have to wait for the last bytes to leave in either
5226 * direction, and sometimes for a close to be effective.
5227 */
5228 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5229 channel_auto_read(chn);
5230 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005231 if (b_data(&chn->buf))
5232 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005233 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5234 }
5235 else {
5236 /* we're not expecting any new data to come for this
5237 * transaction, so we can close it.
5238 */
5239 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5240 channel_shutr_now(chn);
5241 channel_shutw_now(chn);
5242 }
5243 }
5244 goto check_channel_flags;
5245 }
5246
5247 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5248 http_msg_closing:
5249 /* nothing else to forward, just waiting for the output buffer
5250 * to be empty and for the shutw_now to take effect.
5251 */
5252 if (channel_is_empty(chn)) {
5253 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5254 goto http_msg_closed;
5255 }
5256 else if (chn->flags & CF_SHUTW) {
5257 txn->rsp.err_state = txn->rsp.msg_state;
5258 txn->rsp.msg_state = HTTP_MSG_ERROR;
5259 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5260 if (objt_server(s->target))
5261 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5262 goto end;
5263 }
5264 return;
5265 }
5266
5267 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5268 http_msg_closed:
5269 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005270 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005271 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005272 goto end;
5273 }
5274
5275 check_channel_flags:
5276 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5277 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5278 /* if we've just closed an output, let's switch */
5279 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5280 goto http_msg_closing;
5281 }
5282
5283 end:
5284 chn->analysers &= AN_RES_FLT_END;
5285 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5286 chn->analysers |= AN_RES_FLT_XFER_DATA;
5287 channel_auto_close(chn);
5288 channel_auto_read(chn);
5289}
5290
Christopher Faulet0f226952018-10-22 09:29:56 +02005291void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5292 int finst, const struct buffer *msg)
5293{
5294 channel_auto_read(si_oc(si));
5295 channel_abort(si_oc(si));
5296 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005297 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005298 channel_auto_close(si_ic(si));
5299 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005300
5301 /* <msg> is an HTX structure. So we copy it in the response's
5302 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005303 if (msg) {
5304 struct channel *chn = si_ic(si);
5305 struct htx *htx;
5306
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005307 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005308 chn->buf.data = msg->data;
5309 memcpy(chn->buf.area, msg->area, msg->data);
5310 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005311 c_adv(chn, htx->data);
5312 chn->total += htx->data;
5313 }
5314 if (!(s->flags & SF_ERR_MASK))
5315 s->flags |= err;
5316 if (!(s->flags & SF_FINST_MASK))
5317 s->flags |= finst;
5318}
5319
5320void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5321{
5322 channel_auto_read(&s->req);
5323 channel_abort(&s->req);
5324 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005325 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5326 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005327
5328 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005329
5330 /* <msg> is an HTX structure. So we copy it in the response's
5331 * channel */
5332 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005333 if (msg) {
5334 struct channel *chn = &s->res;
5335 struct htx *htx;
5336
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005337 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005338 chn->buf.data = msg->data;
5339 memcpy(chn->buf.area, msg->area, msg->data);
5340 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005341 c_adv(chn, htx->data);
5342 chn->total += htx->data;
5343 }
5344
5345 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5346 channel_auto_read(&s->res);
5347 channel_auto_close(&s->res);
5348 channel_shutr_now(&s->res);
5349}
5350
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005351struct buffer *htx_error_message(struct stream *s)
5352{
5353 const int msgnum = http_get_status_idx(s->txn->status);
5354
5355 if (s->be->errmsg[msgnum].area)
5356 return &s->be->errmsg[msgnum];
5357 else if (strm_fe(s)->errmsg[msgnum].area)
5358 return &strm_fe(s)->errmsg[msgnum];
5359 else
5360 return &htx_err_chunks[msgnum];
5361}
5362
5363
Christopher Faulet23a3c792018-11-28 10:01:23 +01005364/* Send a 100-Continue response to the client. It returns 0 on success and -1
5365 * on error. The response channel is updated accordingly.
5366 */
5367static int htx_reply_100_continue(struct stream *s)
5368{
5369 struct channel *res = &s->res;
5370 struct htx *htx = htx_from_buf(&res->buf);
5371 struct htx_sl *sl;
5372 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5373 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5374 size_t data;
5375
5376 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5377 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5378 if (!sl)
5379 goto fail;
5380 sl->info.res.status = 100;
5381
5382 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5383 goto fail;
5384
5385 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005386 c_adv(res, data);
5387 res->total += data;
5388 return 0;
5389
5390 fail:
5391 /* If an error occurred, remove the incomplete HTTP response from the
5392 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005393 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005394 return -1;
5395}
5396
Christopher Faulet12c51e22018-11-28 15:59:42 +01005397
5398/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5399 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5400 * error. The response channel is updated accordingly.
5401 */
5402static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5403{
5404 struct channel *res = &s->res;
5405 struct htx *htx = htx_from_buf(&res->buf);
5406 struct htx_sl *sl;
5407 struct ist code, body;
5408 int status;
5409 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5410 size_t data;
5411
5412 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5413 status = 401;
5414 code = ist("401");
5415 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5416 "You need a valid user and password to access this content.\n"
5417 "</body></html>\n");
5418 }
5419 else {
5420 status = 407;
5421 code = ist("407");
5422 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5423 "You need a valid user and password to access this content.\n"
5424 "</body></html>\n");
5425 }
5426
5427 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5428 ist("HTTP/1.1"), code, ist("Unauthorized"));
5429 if (!sl)
5430 goto fail;
5431 sl->info.res.status = status;
5432 s->txn->status = status;
5433
5434 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5435 goto fail;
5436
5437 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5438 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005439 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5440 goto fail;
5441 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5442 goto fail;
5443 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005444 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005445 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5446 goto fail;
5447
5448 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005449 c_adv(res, data);
5450 res->total += data;
5451
5452 channel_auto_read(&s->req);
5453 channel_abort(&s->req);
5454 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005455 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456
5457 res->wex = tick_add_ifset(now_ms, res->wto);
5458 channel_auto_read(res);
5459 channel_auto_close(res);
5460 channel_shutr_now(res);
5461 return 0;
5462
5463 fail:
5464 /* If an error occurred, remove the incomplete HTTP response from the
5465 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005466 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005467 return -1;
5468}
5469
Christopher Faulet0f226952018-10-22 09:29:56 +02005470/*
5471 * Capture headers from message <htx> according to header list <cap_hdr>, and
5472 * fill the <cap> pointers appropriately.
5473 */
5474static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5475{
5476 struct cap_hdr *h;
5477 int32_t pos;
5478
5479 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5480 struct htx_blk *blk = htx_get_blk(htx, pos);
5481 enum htx_blk_type type = htx_get_blk_type(blk);
5482 struct ist n, v;
5483
5484 if (type == HTX_BLK_EOH)
5485 break;
5486 if (type != HTX_BLK_HDR)
5487 continue;
5488
5489 n = htx_get_blk_name(htx, blk);
5490
5491 for (h = cap_hdr; h; h = h->next) {
5492 if (h->namelen && (h->namelen == n.len) &&
5493 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5494 if (cap[h->index] == NULL)
5495 cap[h->index] =
5496 pool_alloc(h->pool);
5497
5498 if (cap[h->index] == NULL) {
5499 ha_alert("HTTP capture : out of memory.\n");
5500 break;
5501 }
5502
5503 v = htx_get_blk_value(htx, blk);
5504 if (v.len > h->len)
5505 v.len = h->len;
5506
5507 memcpy(cap[h->index], v.ptr, v.len);
5508 cap[h->index][v.len]=0;
5509 }
5510 }
5511 }
5512}
5513
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005514/* Delete a value in a header between delimiters <from> and <next>. The header
5515 * itself is delimited by <start> and <end> pointers. The number of characters
5516 * displaced is returned, and the pointer to the first delimiter is updated if
5517 * required. The function tries as much as possible to respect the following
5518 * principles :
5519 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5520 * in which case <next> is simply removed
5521 * - set exactly one space character after the new first delimiter, unless there
5522 * are not enough characters in the block being moved to do so.
5523 * - remove unneeded spaces before the previous delimiter and after the new
5524 * one.
5525 *
5526 * It is the caller's responsibility to ensure that :
5527 * - <from> points to a valid delimiter or <start> ;
5528 * - <next> points to a valid delimiter or <end> ;
5529 * - there are non-space chars before <from>.
5530 */
5531static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5532{
5533 char *prev = *from;
5534
5535 if (prev == start) {
5536 /* We're removing the first value. eat the semicolon, if <next>
5537 * is lower than <end> */
5538 if (next < end)
5539 next++;
5540
5541 while (next < end && HTTP_IS_SPHT(*next))
5542 next++;
5543 }
5544 else {
5545 /* Remove useless spaces before the old delimiter. */
5546 while (HTTP_IS_SPHT(*(prev-1)))
5547 prev--;
5548 *from = prev;
5549
5550 /* copy the delimiter and if possible a space if we're
5551 * not at the end of the line.
5552 */
5553 if (next < end) {
5554 *prev++ = *next++;
5555 if (prev + 1 < next)
5556 *prev++ = ' ';
5557 while (next < end && HTTP_IS_SPHT(*next))
5558 next++;
5559 }
5560 }
5561 memmove(prev, next, end - next);
5562 return (prev - next);
5563}
5564
Christopher Faulet0f226952018-10-22 09:29:56 +02005565
5566/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005567 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005568 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005569static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005570{
5571 struct ist dst = ist2(str, 0);
5572
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005573 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005574 goto end;
5575 if (dst.len + 1 > len)
5576 goto end;
5577 dst.ptr[dst.len++] = ' ';
5578
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005579 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005580 goto end;
5581 if (dst.len + 1 > len)
5582 goto end;
5583 dst.ptr[dst.len++] = ' ';
5584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005586 end:
5587 return dst.len;
5588}
5589
Christopher Fauletf0523542018-10-24 11:06:58 +02005590/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005591 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005592 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005593static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005594{
5595 struct ist dst = ist2(str, 0);
5596
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005597 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005598 goto end;
5599 if (dst.len + 1 > len)
5600 goto end;
5601 dst.ptr[dst.len++] = ' ';
5602
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005603 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005604 goto end;
5605 if (dst.len + 1 > len)
5606 goto end;
5607 dst.ptr[dst.len++] = ' ';
5608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005609 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005610 end:
5611 return dst.len;
5612}
5613
5614
Christopher Faulet0f226952018-10-22 09:29:56 +02005615/*
5616 * Print a debug line with a start line.
5617 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005618static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005619{
5620 struct session *sess = strm_sess(s);
5621 int max;
5622
5623 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5624 dir,
5625 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5626 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5627
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005628 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005629 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005631 trash.area[trash.data++] = ' ';
5632
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005633 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005634 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005635 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005636 trash.area[trash.data++] = ' ';
5637
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 trash.area[trash.data++] = '\n';
5642
5643 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5644}
5645
5646/*
5647 * Print a debug line with a header.
5648 */
5649static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5650{
5651 struct session *sess = strm_sess(s);
5652 int max;
5653
5654 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5655 dir,
5656 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5657 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5658
5659 max = n.len;
5660 UBOUND(max, trash.size - trash.data - 3);
5661 chunk_memcat(&trash, n.ptr, max);
5662 trash.area[trash.data++] = ':';
5663 trash.area[trash.data++] = ' ';
5664
5665 max = v.len;
5666 UBOUND(max, trash.size - trash.data - 1);
5667 chunk_memcat(&trash, v.ptr, max);
5668 trash.area[trash.data++] = '\n';
5669
5670 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5671}
5672
5673
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005674__attribute__((constructor))
5675static void __htx_protocol_init(void)
5676{
5677}
5678
5679
5680/*
5681 * Local variables:
5682 * c-indent-level: 8
5683 * c-basic-offset: 8
5684 * End:
5685 */