blob: 2f100886f05ee9e2470252ca63bf7a5edd7573c6 [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 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +0100129 * First catch invalid request because of a parsing error or
130 * because only part of headers have been transfered.
131 * Multiplexers have the responsibility to emit all headers at
132 * once.
Christopher Faulet47365272018-10-31 17:40:50 +0100133 */
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +0100134 if ((htx->flags & HTX_FL_PARSING_ERROR) || htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100135 stream_inc_http_req_ctr(s);
136 stream_inc_http_err_ctr(s);
137 proxy_inc_fe_req_ctr(sess->fe);
138 goto return_bad_req;
139 }
140
Christopher Faulet9768c262018-10-22 09:34:31 +0200141 /* 1: have we encountered a read error ? */
142 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200143 if (!(s->flags & SF_ERR_MASK))
144 s->flags |= SF_ERR_CLICL;
145
146 if (txn->flags & TX_WAIT_NEXT_RQ)
147 goto failed_keep_alive;
148
149 if (sess->fe->options & PR_O_IGNORE_PRB)
150 goto failed_keep_alive;
151
Christopher Faulet9768c262018-10-22 09:34:31 +0200152 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200153 stream_inc_http_req_ctr(s);
154 proxy_inc_fe_req_ctr(sess->fe);
155 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
156 if (sess->listener->counters)
157 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 txn->status = 400;
160 msg->err_state = msg->msg_state;
161 msg->msg_state = HTTP_MSG_ERROR;
162 htx_reply_and_close(s, txn->status, NULL);
163 req->analysers &= AN_REQ_FLT_END;
164
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165 if (!(s->flags & SF_FINST_MASK))
166 s->flags |= SF_FINST_R;
167 return 0;
168 }
169
Christopher Faulet9768c262018-10-22 09:34:31 +0200170 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200171 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
172 if (!(s->flags & SF_ERR_MASK))
173 s->flags |= SF_ERR_CLITO;
174
175 if (txn->flags & TX_WAIT_NEXT_RQ)
176 goto failed_keep_alive;
177
178 if (sess->fe->options & PR_O_IGNORE_PRB)
179 goto failed_keep_alive;
180
Christopher Faulet9768c262018-10-22 09:34:31 +0200181 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200182 stream_inc_http_req_ctr(s);
183 proxy_inc_fe_req_ctr(sess->fe);
184 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
185 if (sess->listener->counters)
186 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 txn->status = 408;
189 msg->err_state = msg->msg_state;
190 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100191 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200192 req->analysers &= AN_REQ_FLT_END;
193
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194 if (!(s->flags & SF_FINST_MASK))
195 s->flags |= SF_FINST_R;
196 return 0;
197 }
198
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200200 else if (req->flags & CF_SHUTR) {
201 if (!(s->flags & SF_ERR_MASK))
202 s->flags |= SF_ERR_CLICL;
203
204 if (txn->flags & TX_WAIT_NEXT_RQ)
205 goto failed_keep_alive;
206
207 if (sess->fe->options & PR_O_IGNORE_PRB)
208 goto failed_keep_alive;
209
Christopher Faulete0768eb2018-10-03 16:38:02 +0200210 stream_inc_http_err_ctr(s);
211 stream_inc_http_req_ctr(s);
212 proxy_inc_fe_req_ctr(sess->fe);
213 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
214 if (sess->listener->counters)
215 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
216
Christopher Faulet9768c262018-10-22 09:34:31 +0200217 txn->status = 400;
218 msg->err_state = msg->msg_state;
219 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100220 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200221 req->analysers &= AN_REQ_FLT_END;
222
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223 if (!(s->flags & SF_FINST_MASK))
224 s->flags |= SF_FINST_R;
225 return 0;
226 }
227
228 channel_dont_connect(req);
229 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
230 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100231
Christopher Faulet9768c262018-10-22 09:34:31 +0200232 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200233 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
234 /* We need more data, we have to re-enable quick-ack in case we
235 * previously disabled it, otherwise we might cause the client
236 * to delay next data.
237 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200239 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100240
Christopher Faulet47365272018-10-31 17:40:50 +0100241 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200242 /* If the client starts to talk, let's fall back to
243 * request timeout processing.
244 */
245 txn->flags &= ~TX_WAIT_NEXT_RQ;
246 req->analyse_exp = TICK_ETERNITY;
247 }
248
249 /* just set the request timeout once at the beginning of the request */
250 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100251 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200252 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
253 else
254 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
255 }
256
257 /* we're not ready yet */
258 return 0;
259
260 failed_keep_alive:
261 /* Here we process low-level errors for keep-alive requests. In
262 * short, if the request is not the first one and it experiences
263 * a timeout, read error or shutdown, we just silently close so
264 * that the client can try again.
265 */
266 txn->status = 0;
267 msg->msg_state = HTTP_MSG_RQBEFORE;
268 req->analysers &= AN_REQ_FLT_END;
269 s->logs.logwait = 0;
270 s->logs.level = 0;
271 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200272 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200273 return 0;
274 }
275
Christopher Faulet9768c262018-10-22 09:34:31 +0200276 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200277 stream_inc_http_req_ctr(s);
278 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
279
Christopher Faulet9768c262018-10-22 09:34:31 +0200280 /* kill the pending keep-alive timeout */
281 txn->flags &= ~TX_WAIT_NEXT_RQ;
282 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200283
Christopher Faulet03599112018-11-27 11:21:21 +0100284 sl = http_find_stline(htx);
285
Christopher Faulet9768c262018-10-22 09:34:31 +0200286 /* 0: we might have to print this header in debug mode */
287 if (unlikely((global.mode & MODE_DEBUG) &&
288 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
289 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200292
293 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
294 struct htx_blk *blk = htx_get_blk(htx, pos);
295 enum htx_blk_type type = htx_get_blk_type(blk);
296
297 if (type == HTX_BLK_EOH)
298 break;
299 if (type != HTX_BLK_HDR)
300 continue;
301
302 htx_debug_hdr("clihdr", s,
303 htx_get_blk_name(htx, blk),
304 htx_get_blk_value(htx, blk));
305 }
306 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200307
308 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100309 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200310 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100311 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100312 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200313 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100314 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100315 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100316 if (sl->flags & HTX_SL_F_BODYLESS)
317 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200318
319 /* we can make use of server redirect on GET and HEAD */
320 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
321 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100322 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200323 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200324 goto return_bad_req;
325 }
326
327 /*
328 * 2: check if the URI matches the monitor_uri.
329 * We have to do this for every request which gets in, because
330 * the monitor-uri is defined by the frontend.
331 */
332 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100333 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200334 /*
335 * We have found the monitor URI
336 */
337 struct acl_cond *cond;
338
339 s->flags |= SF_MONITOR;
340 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
341
342 /* Check if we want to fail this monitor request or not */
343 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
344 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
345
346 ret = acl_pass(ret);
347 if (cond->pol == ACL_COND_UNLESS)
348 ret = !ret;
349
350 if (ret) {
351 /* we fail this request, let's return 503 service unavail */
352 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100353 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200354 if (!(s->flags & SF_ERR_MASK))
355 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
356 goto return_prx_cond;
357 }
358 }
359
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800360 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100362 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200363 if (!(s->flags & SF_ERR_MASK))
364 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
365 goto return_prx_cond;
366 }
367
368 /*
369 * 3: Maybe we have to copy the original REQURI for the logs ?
370 * Note: we cannot log anymore if the request has been
371 * classified as invalid.
372 */
373 if (unlikely(s->logs.logwait & LW_REQ)) {
374 /* we have a complete HTTP request that we must log */
375 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200376 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200377
Christopher Faulet9768c262018-10-22 09:34:31 +0200378 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
379 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200380
381 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
382 s->do_log(s);
383 } else {
384 ha_alert("HTTP logging : out of memory.\n");
385 }
386 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
Christopher Faulete0768eb2018-10-03 16:38:02 +0200388 /* if the frontend has "option http-use-proxy-header", we'll check if
389 * we have what looks like a proxied connection instead of a connection,
390 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
391 * Note that this is *not* RFC-compliant, however browsers and proxies
392 * happen to do that despite being non-standard :-(
393 * We consider that a request not beginning with either '/' or '*' is
394 * a proxied connection, which covers both "scheme://location" and
395 * CONNECT ip:port.
396 */
397 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100398 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200399 txn->flags |= TX_USE_PX_CONN;
400
Christopher Faulete0768eb2018-10-03 16:38:02 +0200401 /* 5: we may need to capture headers */
402 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200403 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200404
405 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
406 * only change if both the request and the config reference something else.
407 * Option httpclose by itself sets tunnel mode where headers are mangled.
408 * However, if another mode is set, it will affect it (eg: server-close/
409 * keep-alive + httpclose = close). Note that we avoid to redo the same work
410 * if FE and BE have the same settings (common). The method consists in
411 * checking if options changed between the two calls (implying that either
412 * one is non-null, or one of them is non-null and we are there for the first
413 * time.
414 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200415 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200416 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200417
418 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200419 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200420 req->analysers |= AN_REQ_HTTP_BODY;
421
422 /*
423 * RFC7234#4:
424 * A cache MUST write through requests with methods
425 * that are unsafe (Section 4.2.1 of [RFC7231]) to
426 * the origin server; i.e., a cache is not allowed
427 * to generate a reply to such a request before
428 * having forwarded the request and having received
429 * a corresponding response.
430 *
431 * RFC7231#4.2.1:
432 * Of the request methods defined by this
433 * specification, the GET, HEAD, OPTIONS, and TRACE
434 * methods are defined to be safe.
435 */
436 if (likely(txn->meth == HTTP_METH_GET ||
437 txn->meth == HTTP_METH_HEAD ||
438 txn->meth == HTTP_METH_OPTIONS ||
439 txn->meth == HTTP_METH_TRACE))
440 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
441
442 /* end of job, return OK */
443 req->analysers &= ~an_bit;
444 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200445
Christopher Faulete0768eb2018-10-03 16:38:02 +0200446 return 1;
447
448 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200449 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200450 txn->req.err_state = txn->req.msg_state;
451 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100452 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
454 if (sess->listener->counters)
455 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
456
457 return_prx_cond:
458 if (!(s->flags & SF_ERR_MASK))
459 s->flags |= SF_ERR_PRXCOND;
460 if (!(s->flags & SF_FINST_MASK))
461 s->flags |= SF_FINST_R;
462
463 req->analysers &= AN_REQ_FLT_END;
464 req->analyse_exp = TICK_ETERNITY;
465 return 0;
466}
467
468
469/* This stream analyser runs all HTTP request processing which is common to
470 * frontends and backends, which means blocking ACLs, filters, connection-close,
471 * reqadd, stats and redirects. This is performed for the designated proxy.
472 * It returns 1 if the processing can continue on next analysers, or zero if it
473 * either needs more data or wants to immediately abort the request (eg: deny,
474 * error, ...).
475 */
476int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
477{
478 struct session *sess = s->sess;
479 struct http_txn *txn = s->txn;
480 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200481 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200482 struct redirect_rule *rule;
483 struct cond_wordlist *wl;
484 enum rule_result verdict;
485 int deny_status = HTTP_ERR_403;
486 struct connection *conn = objt_conn(sess->origin);
487
488 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
489 /* we need more data */
490 goto return_prx_yield;
491 }
492
493 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
494 now_ms, __FUNCTION__,
495 s,
496 req,
497 req->rex, req->wex,
498 req->flags,
499 ci_data(req),
500 req->analysers);
501
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100502 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200503
Christopher Faulete0768eb2018-10-03 16:38:02 +0200504 /* just in case we have some per-backend tracking */
505 stream_inc_be_http_req_ctr(s);
506
507 /* evaluate http-request rules */
508 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200509 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200510
511 switch (verdict) {
512 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
513 goto return_prx_yield;
514
515 case HTTP_RULE_RES_CONT:
516 case HTTP_RULE_RES_STOP: /* nothing to do */
517 break;
518
519 case HTTP_RULE_RES_DENY: /* deny or tarpit */
520 if (txn->flags & TX_CLTARPIT)
521 goto tarpit;
522 goto deny;
523
524 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
525 goto return_prx_cond;
526
527 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
528 goto done;
529
530 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
531 goto return_bad_req;
532 }
533 }
534
535 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
536 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200537 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200538
Christopher Fauletff2759f2018-10-24 11:13:16 +0200539 ctx.blk = NULL;
540 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
541 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200542 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200543 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200544 }
545
546 /* OK at this stage, we know that the request was accepted according to
547 * the http-request rules, we can check for the stats. Note that the
548 * URI is detected *before* the req* rules in order not to be affected
549 * by a possible reqrep, while they are processed *after* so that a
550 * reqdeny can still block them. This clearly needs to change in 1.6!
551 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200552 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200553 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100554 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200555 txn->status = 500;
556 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100557 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200558
559 if (!(s->flags & SF_ERR_MASK))
560 s->flags |= SF_ERR_RESOURCE;
561 goto return_prx_cond;
562 }
563
564 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200565 htx_handle_stats(s, req);
566 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200567 /* not all actions implemented: deny, allow, auth */
568
569 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
570 goto deny;
571
572 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
573 goto return_prx_cond;
574 }
575
576 /* evaluate the req* rules except reqadd */
577 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200578 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200579 goto return_bad_req;
580
581 if (txn->flags & TX_CLDENY)
582 goto deny;
583
584 if (txn->flags & TX_CLTARPIT) {
585 deny_status = HTTP_ERR_500;
586 goto tarpit;
587 }
588 }
589
590 /* add request headers from the rule sets in the same order */
591 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200592 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200593 if (wl->cond) {
594 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
595 ret = acl_pass(ret);
596 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
597 ret = !ret;
598 if (!ret)
599 continue;
600 }
601
Christopher Fauletff2759f2018-10-24 11:13:16 +0200602 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
603 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200604 goto return_bad_req;
605 }
606
Christopher Faulete0768eb2018-10-03 16:38:02 +0200607 /* Proceed with the stats now. */
608 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
609 unlikely(objt_applet(s->target) == &http_cache_applet)) {
610 /* process the stats request now */
611 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
612 HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
613
614 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
615 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
616 if (!(s->flags & SF_FINST_MASK))
617 s->flags |= SF_FINST_R;
618
619 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
620 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
621 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
622 req->analysers |= AN_REQ_HTTP_XFER_BODY;
623 goto done;
624 }
625
626 /* check whether we have some ACLs set to redirect this request */
627 list_for_each_entry(rule, &px->redirect_rules, list) {
628 if (rule->cond) {
629 int ret;
630
631 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
632 ret = acl_pass(ret);
633 if (rule->cond->pol == ACL_COND_UNLESS)
634 ret = !ret;
635 if (!ret)
636 continue;
637 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200638 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200639 goto return_bad_req;
640 goto done;
641 }
642
643 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
644 * If this happens, then the data will not come immediately, so we must
645 * send all what we have without waiting. Note that due to the small gain
646 * in waiting for the body of the request, it's easier to simply put the
647 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
648 * itself once used.
649 */
650 req->flags |= CF_SEND_DONTWAIT;
651
652 done: /* done with this analyser, continue with next ones that the calling
653 * points will have set, if any.
654 */
655 req->analyse_exp = TICK_ETERNITY;
656 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
657 req->analysers &= ~an_bit;
658 return 1;
659
660 tarpit:
661 /* Allow cookie logging
662 */
663 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200664 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200665
666 /* When a connection is tarpitted, we use the tarpit timeout,
667 * which may be the same as the connect timeout if unspecified.
668 * If unset, then set it to zero because we really want it to
669 * eventually expire. We build the tarpit as an analyser.
670 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100671 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200672
673 /* wipe the request out so that we can drop the connection early
674 * if the client closes first.
675 */
676 channel_dont_connect(req);
677
678 txn->status = http_err_codes[deny_status];
679
680 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
681 req->analysers |= AN_REQ_HTTP_TARPIT;
682 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
683 if (!req->analyse_exp)
684 req->analyse_exp = tick_add(now_ms, 0);
685 stream_inc_http_err_ctr(s);
686 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
687 if (sess->fe != s->be)
688 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
689 if (sess->listener->counters)
690 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
691 goto done_without_exp;
692
693 deny: /* this request was blocked (denied) */
694
695 /* Allow cookie logging
696 */
697 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200698 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200699
700 txn->flags |= TX_CLDENY;
701 txn->status = http_err_codes[deny_status];
702 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100703 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200704 stream_inc_http_err_ctr(s);
705 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
706 if (sess->fe != s->be)
707 HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
708 if (sess->listener->counters)
709 HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
710 goto return_prx_cond;
711
712 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200713 txn->req.err_state = txn->req.msg_state;
714 txn->req.msg_state = HTTP_MSG_ERROR;
715 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100716 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717
718 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
719 if (sess->listener->counters)
720 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
721
722 return_prx_cond:
723 if (!(s->flags & SF_ERR_MASK))
724 s->flags |= SF_ERR_PRXCOND;
725 if (!(s->flags & SF_FINST_MASK))
726 s->flags |= SF_FINST_R;
727
728 req->analysers &= AN_REQ_FLT_END;
729 req->analyse_exp = TICK_ETERNITY;
730 return 0;
731
732 return_prx_yield:
733 channel_dont_connect(req);
734 return 0;
735}
736
737/* This function performs all the processing enabled for the current request.
738 * It returns 1 if the processing can continue on next analysers, or zero if it
739 * needs more data, encounters an error, or wants to immediately abort the
740 * request. It relies on buffers flags, and updates s->req.analysers.
741 */
742int htx_process_request(struct stream *s, struct channel *req, int an_bit)
743{
744 struct session *sess = s->sess;
745 struct http_txn *txn = s->txn;
746 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200747 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200748 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
749
750 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
751 /* we need more data */
752 channel_dont_connect(req);
753 return 0;
754 }
755
756 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
757 now_ms, __FUNCTION__,
758 s,
759 req,
760 req->rex, req->wex,
761 req->flags,
762 ci_data(req),
763 req->analysers);
764
765 /*
766 * Right now, we know that we have processed the entire headers
767 * and that unwanted requests have been filtered out. We can do
768 * whatever we want with the remaining request. Also, now we
769 * may have separate values for ->fe, ->be.
770 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100771 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200772
773 /*
774 * If HTTP PROXY is set we simply get remote server address parsing
775 * incoming request. Note that this requires that a connection is
776 * allocated on the server side.
777 */
778 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
779 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100780 struct htx_sl *sl;
781 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200782
783 /* Note that for now we don't reuse existing proxy connections */
784 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
785 txn->req.err_state = txn->req.msg_state;
786 txn->req.msg_state = HTTP_MSG_ERROR;
787 txn->status = 500;
788 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100789 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200790
791 if (!(s->flags & SF_ERR_MASK))
792 s->flags |= SF_ERR_RESOURCE;
793 if (!(s->flags & SF_FINST_MASK))
794 s->flags |= SF_FINST_R;
795
796 return 0;
797 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200798 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100799 uri = htx_sl_req_uri(sl);
800 path = http_get_path(uri);
801 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200802 goto return_bad_req;
803
804 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 * uri.ptr and path.ptr (excluded). If it was not found, we need
806 * to replace from all the uri by a single "/".
807 *
808 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100809 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200810 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200811 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100812 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200813 }
814
815 /*
816 * 7: Now we can work with the cookies.
817 * Note that doing so might move headers in the request, but
818 * the fields will stay coherent and the URI will not move.
819 * This should only be performed in the backend.
820 */
821 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100822 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200823
824 /* add unique-id if "header-unique-id" is specified */
825
826 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
827 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
828 goto return_bad_req;
829 s->unique_id[0] = '\0';
830 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
831 }
832
833 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200834 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
835 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
836
837 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200838 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200839 }
840
841 /*
842 * 9: add X-Forwarded-For if either the frontend or the backend
843 * asks for it.
844 */
845 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200846 struct http_hdr_ctx ctx = { .blk = NULL };
847 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
848 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
849
Christopher Faulete0768eb2018-10-03 16:38:02 +0200850 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200851 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200852 /* The header is set to be added only if none is present
853 * and we found it, so don't do anything.
854 */
855 }
856 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
857 /* Add an X-Forwarded-For header unless the source IP is
858 * in the 'except' network range.
859 */
860 if ((!sess->fe->except_mask.s_addr ||
861 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
862 != sess->fe->except_net.s_addr) &&
863 (!s->be->except_mask.s_addr ||
864 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
865 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200866 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200867
868 /* Note: we rely on the backend to get the header name to be used for
869 * x-forwarded-for, because the header is really meant for the backends.
870 * However, if the backend did not specify any option, we have to rely
871 * on the frontend's header name.
872 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200873 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
874 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200875 goto return_bad_req;
876 }
877 }
878 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
879 /* FIXME: for the sake of completeness, we should also support
880 * 'except' here, although it is mostly useless in this case.
881 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200882 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200883
Christopher Faulete0768eb2018-10-03 16:38:02 +0200884 inet_ntop(AF_INET6,
885 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
886 pn, sizeof(pn));
887
888 /* Note: we rely on the backend to get the header name to be used for
889 * x-forwarded-for, because the header is really meant for the backends.
890 * However, if the backend did not specify any option, we have to rely
891 * on the frontend's header name.
892 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200893 chunk_printf(&trash, "%s", pn);
894 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200895 goto return_bad_req;
896 }
897 }
898
899 /*
900 * 10: add X-Original-To if either the frontend or the backend
901 * asks for it.
902 */
903 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
904
905 /* FIXME: don't know if IPv6 can handle that case too. */
906 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
907 /* Add an X-Original-To header unless the destination IP is
908 * in the 'except' network range.
909 */
910 conn_get_to_addr(cli_conn);
911
912 if (cli_conn->addr.to.ss_family == AF_INET &&
913 ((!sess->fe->except_mask_to.s_addr ||
914 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
915 != sess->fe->except_to.s_addr) &&
916 (!s->be->except_mask_to.s_addr ||
917 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
918 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200919 struct ist hdr;
920 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200921
922 /* Note: we rely on the backend to get the header name to be used for
923 * x-original-to, because the header is really meant for the backends.
924 * However, if the backend did not specify any option, we have to rely
925 * on the frontend's header name.
926 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200927 if (s->be->orgto_hdr_len)
928 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
929 else
930 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200931
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200932 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
933 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200934 goto return_bad_req;
935 }
936 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200937 }
938
Christopher Faulete0768eb2018-10-03 16:38:02 +0200939 /* If we have no server assigned yet and we're balancing on url_param
940 * with a POST request, we may be interested in checking the body for
941 * that parameter. This will be done in another analyser.
942 */
943 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100944 s->txn->meth == HTTP_METH_POST &&
945 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200946 channel_dont_connect(req);
947 req->analysers |= AN_REQ_HTTP_BODY;
948 }
949
950 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
951 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100952
Christopher Faulete0768eb2018-10-03 16:38:02 +0200953 /* We expect some data from the client. Unless we know for sure
954 * we already have a full request, we have to re-enable quick-ack
955 * in case we previously disabled it, otherwise we might cause
956 * the client to delay further data.
957 */
958 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200959 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100960 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200961
962 /*************************************************************
963 * OK, that's finished for the headers. We have done what we *
964 * could. Let's switch to the DATA state. *
965 ************************************************************/
966 req->analyse_exp = TICK_ETERNITY;
967 req->analysers &= ~an_bit;
968
969 s->logs.tv_request = now;
970 /* OK let's go on with the BODY now */
971 return 1;
972
973 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200974 txn->req.err_state = txn->req.msg_state;
975 txn->req.msg_state = HTTP_MSG_ERROR;
976 txn->status = 400;
977 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100978 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200979
980 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
981 if (sess->listener->counters)
982 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
983
984 if (!(s->flags & SF_ERR_MASK))
985 s->flags |= SF_ERR_PRXCOND;
986 if (!(s->flags & SF_FINST_MASK))
987 s->flags |= SF_FINST_R;
988 return 0;
989}
990
991/* This function is an analyser which processes the HTTP tarpit. It always
992 * returns zero, at the beginning because it prevents any other processing
993 * from occurring, and at the end because it terminates the request.
994 */
995int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
996{
997 struct http_txn *txn = s->txn;
998
999 /* This connection is being tarpitted. The CLIENT side has
1000 * already set the connect expiration date to the right
1001 * timeout. We just have to check that the client is still
1002 * there and that the timeout has not expired.
1003 */
1004 channel_dont_connect(req);
1005 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1006 !tick_is_expired(req->analyse_exp, now_ms))
1007 return 0;
1008
1009 /* We will set the queue timer to the time spent, just for
1010 * logging purposes. We fake a 500 server error, so that the
1011 * attacker will not suspect his connection has been tarpitted.
1012 * It will not cause trouble to the logs because we can exclude
1013 * the tarpitted connections by filtering on the 'PT' status flags.
1014 */
1015 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1016
1017 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001018 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001019
1020 req->analysers &= AN_REQ_FLT_END;
1021 req->analyse_exp = TICK_ETERNITY;
1022
1023 if (!(s->flags & SF_ERR_MASK))
1024 s->flags |= SF_ERR_PRXCOND;
1025 if (!(s->flags & SF_FINST_MASK))
1026 s->flags |= SF_FINST_T;
1027 return 0;
1028}
1029
1030/* This function is an analyser which waits for the HTTP request body. It waits
1031 * for either the buffer to be full, or the full advertised contents to have
1032 * reached the buffer. It must only be called after the standard HTTP request
1033 * processing has occurred, because it expects the request to be parsed and will
1034 * look for the Expect header. It may send a 100-Continue interim response. It
1035 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1036 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1037 * needs to read more data, or 1 once it has completed its analysis.
1038 */
1039int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1040{
1041 struct session *sess = s->sess;
1042 struct http_txn *txn = s->txn;
1043 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001044 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001045
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001046
1047 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1048 now_ms, __FUNCTION__,
1049 s,
1050 req,
1051 req->rex, req->wex,
1052 req->flags,
1053 ci_data(req),
1054 req->analysers);
1055
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001056 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001057
1058 if (msg->msg_state < HTTP_MSG_BODY)
1059 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001060
Christopher Faulete0768eb2018-10-03 16:38:02 +02001061 /* We have to parse the HTTP request body to find any required data.
1062 * "balance url_param check_post" should have been the only way to get
1063 * into this. We were brought here after HTTP header analysis, so all
1064 * related structures are ready.
1065 */
1066
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001067 if (msg->msg_state < HTTP_MSG_DATA) {
1068 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1069 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001070 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001071 if (msg->flags & HTTP_MSGF_VER_11) {
1072 struct ist hdr = { .ptr = "Expect", .len = 6 };
1073 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001074
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001075 ctx.blk = NULL;
1076 /* Expect is allowed in 1.1, look for it */
1077 if (http_find_header(htx, hdr, &ctx, 0) &&
1078 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001079 if (htx_reply_100_continue(s) == -1)
1080 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 http_remove_header(htx, &ctx);
1082 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001083 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084 }
1085
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001086 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001087
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001088 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1089 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001090 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001092 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 goto http_end;
1094
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001095 missing_data:
Christopher Faulet47365272018-10-31 17:40:50 +01001096 if (htx->flags & HTX_FL_PARSING_ERROR)
1097 goto return_bad_req;
1098
Christopher Faulete0768eb2018-10-03 16:38:02 +02001099 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1100 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001101 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001102
1103 if (!(s->flags & SF_ERR_MASK))
1104 s->flags |= SF_ERR_CLITO;
1105 if (!(s->flags & SF_FINST_MASK))
1106 s->flags |= SF_FINST_D;
1107 goto return_err_msg;
1108 }
1109
1110 /* we get here if we need to wait for more data */
1111 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1112 /* Not enough data. We'll re-use the http-request
1113 * timeout here. Ideally, we should set the timeout
1114 * relative to the accept() date. We just set the
1115 * request timeout once at the beginning of the
1116 * request.
1117 */
1118 channel_dont_connect(req);
1119 if (!tick_isset(req->analyse_exp))
1120 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1121 return 0;
1122 }
1123
1124 http_end:
1125 /* The situation will not evolve, so let's give up on the analysis. */
1126 s->logs.tv_request = now; /* update the request timer to reflect full request */
1127 req->analysers &= ~an_bit;
1128 req->analyse_exp = TICK_ETERNITY;
1129 return 1;
1130
1131 return_bad_req: /* let's centralize all bad requests */
1132 txn->req.err_state = txn->req.msg_state;
1133 txn->req.msg_state = HTTP_MSG_ERROR;
1134 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001135 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001136
1137 if (!(s->flags & SF_ERR_MASK))
1138 s->flags |= SF_ERR_PRXCOND;
1139 if (!(s->flags & SF_FINST_MASK))
1140 s->flags |= SF_FINST_R;
1141
1142 return_err_msg:
1143 req->analysers &= AN_REQ_FLT_END;
1144 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1145 if (sess->listener->counters)
1146 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1147 return 0;
1148}
1149
1150/* This function is an analyser which forwards request body (including chunk
1151 * sizes if any). It is called as soon as we must forward, even if we forward
1152 * zero byte. The only situation where it must not be called is when we're in
1153 * tunnel mode and we want to forward till the close. It's used both to forward
1154 * remaining data and to resync after end of body. It expects the msg_state to
1155 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1156 * read more data, or 1 once we can go on with next request or end the stream.
1157 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1158 * bytes of pending data + the headers if not already done.
1159 */
1160int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1161{
1162 struct session *sess = s->sess;
1163 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001164 struct http_msg *msg = &txn->req;
1165 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001166 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001167
1168 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1169 now_ms, __FUNCTION__,
1170 s,
1171 req,
1172 req->rex, req->wex,
1173 req->flags,
1174 ci_data(req),
1175 req->analysers);
1176
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001177 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001178
1179 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1180 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1181 /* Output closed while we were sending data. We must abort and
1182 * wake the other side up.
1183 */
1184 msg->err_state = msg->msg_state;
1185 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001186 htx_end_request(s);
1187 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001188 return 1;
1189 }
1190
1191 /* Note that we don't have to send 100-continue back because we don't
1192 * need the data to complete our job, and it's up to the server to
1193 * decide whether to return 100, 417 or anything else in return of
1194 * an "Expect: 100-continue" header.
1195 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001196 if (msg->msg_state == HTTP_MSG_BODY)
1197 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001198
1199 /* Some post-connect processing might want us to refrain from starting to
1200 * forward data. Currently, the only reason for this is "balance url_param"
1201 * whichs need to parse/process the request after we've enabled forwarding.
1202 */
1203 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1204 if (!(s->res.flags & CF_READ_ATTACHED)) {
1205 channel_auto_connect(req);
1206 req->flags |= CF_WAKE_CONNECT;
1207 channel_dont_close(req); /* don't fail on early shutr */
1208 goto waiting;
1209 }
1210 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1211 }
1212
1213 /* in most states, we should abort in case of early close */
1214 channel_auto_close(req);
1215
1216 if (req->to_forward) {
1217 /* We can't process the buffer's contents yet */
1218 req->flags |= CF_WAKE_WRITE;
1219 goto missing_data_or_waiting;
1220 }
1221
Christopher Faulet9768c262018-10-22 09:34:31 +02001222 if (msg->msg_state >= HTTP_MSG_DONE)
1223 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001224 /* Forward input data. We get it by removing all outgoing data not
1225 * forwarded yet from HTX data size. If there are some data filters, we
1226 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001227 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001228 if (HAS_REQ_DATA_FILTERS(s)) {
1229 ret = flt_http_payload(s, msg, htx->data);
1230 if (ret < 0)
1231 goto return_bad_req;
1232 c_adv(req, ret);
1233 if (htx->data != co_data(req) || htx->extra)
1234 goto missing_data_or_waiting;
1235 }
1236 else {
1237 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001238
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001239 /* To let the function channel_forward work as expected we must update
1240 * the channel's buffer to pretend there is no more input data. The
1241 * right length is then restored. We must do that, because when an HTX
1242 * message is stored into a buffer, it appears as full.
1243 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001244 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1245 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001246 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001247
Christopher Faulet9768c262018-10-22 09:34:31 +02001248 /* Check if the end-of-message is reached and if so, switch the message
1249 * in HTTP_MSG_DONE state.
1250 */
1251 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1252 goto missing_data_or_waiting;
1253
1254 msg->msg_state = HTTP_MSG_DONE;
1255
1256 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001257 /* other states, DONE...TUNNEL */
1258 /* we don't want to forward closes on DONE except in tunnel mode. */
1259 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1260 channel_dont_close(req);
1261
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001262 if (HAS_REQ_DATA_FILTERS(s)) {
1263 ret = flt_http_end(s, msg);
1264 if (ret <= 0) {
1265 if (!ret)
1266 goto missing_data_or_waiting;
1267 goto return_bad_req;
1268 }
1269 }
1270
Christopher Fauletf2824e62018-10-01 12:12:37 +02001271 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001272 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001273 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001274 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1275 if (req->flags & CF_SHUTW) {
1276 /* request errors are most likely due to the
1277 * server aborting the transfer. */
1278 goto aborted_xfer;
1279 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 goto return_bad_req;
1281 }
1282 return 1;
1283 }
1284
1285 /* If "option abortonclose" is set on the backend, we want to monitor
1286 * the client's connection and forward any shutdown notification to the
1287 * server, which will decide whether to close or to go on processing the
1288 * request. We only do that in tunnel mode, and not in other modes since
1289 * it can be abused to exhaust source ports. */
1290 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1291 channel_auto_read(req);
1292 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1293 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1294 s->si[1].flags |= SI_FL_NOLINGER;
1295 channel_auto_close(req);
1296 }
1297 else if (s->txn->meth == HTTP_METH_POST) {
1298 /* POST requests may require to read extra CRLF sent by broken
1299 * browsers and which could cause an RST to be sent upon close
1300 * on some systems (eg: Linux). */
1301 channel_auto_read(req);
1302 }
1303 return 0;
1304
1305 missing_data_or_waiting:
1306 /* stop waiting for data if the input is closed before the end */
Christopher Faulet9768c262018-10-22 09:34:31 +02001307 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001308 if (!(s->flags & SF_ERR_MASK))
1309 s->flags |= SF_ERR_CLICL;
1310 if (!(s->flags & SF_FINST_MASK)) {
1311 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1312 s->flags |= SF_FINST_H;
1313 else
1314 s->flags |= SF_FINST_D;
1315 }
1316
1317 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1318 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1319 if (objt_server(s->target))
1320 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1321
1322 goto return_bad_req_stats_ok;
1323 }
1324
1325 waiting:
1326 /* waiting for the last bits to leave the buffer */
1327 if (req->flags & CF_SHUTW)
1328 goto aborted_xfer;
1329
Christopher Faulet47365272018-10-31 17:40:50 +01001330 if (htx->flags & HTX_FL_PARSING_ERROR)
1331 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001332
Christopher Faulete0768eb2018-10-03 16:38:02 +02001333 /* When TE: chunked is used, we need to get there again to parse remaining
1334 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1335 * And when content-length is used, we never want to let the possible
1336 * shutdown be forwarded to the other side, as the state machine will
1337 * take care of it once the client responds. It's also important to
1338 * prevent TIME_WAITs from accumulating on the backend side, and for
1339 * HTTP/2 where the last frame comes with a shutdown.
1340 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001341 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001342 channel_dont_close(req);
1343
1344 /* We know that more data are expected, but we couldn't send more that
1345 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1346 * system knows it must not set a PUSH on this first part. Interactive
1347 * modes are already handled by the stream sock layer. We must not do
1348 * this in content-length mode because it could present the MSG_MORE
1349 * flag with the last block of forwarded data, which would cause an
1350 * additional delay to be observed by the receiver.
1351 */
1352 if (msg->flags & HTTP_MSGF_TE_CHNK)
1353 req->flags |= CF_EXPECT_MORE;
1354
1355 return 0;
1356
1357 return_bad_req: /* let's centralize all bad requests */
1358 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
1359 if (sess->listener->counters)
1360 HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
1361
1362 return_bad_req_stats_ok:
1363 txn->req.err_state = txn->req.msg_state;
1364 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001365 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001366 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001367 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001368 } else {
1369 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001370 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001371 }
1372 req->analysers &= AN_REQ_FLT_END;
1373 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1374
1375 if (!(s->flags & SF_ERR_MASK))
1376 s->flags |= SF_ERR_PRXCOND;
1377 if (!(s->flags & SF_FINST_MASK)) {
1378 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1379 s->flags |= SF_FINST_H;
1380 else
1381 s->flags |= SF_FINST_D;
1382 }
1383 return 0;
1384
1385 aborted_xfer:
1386 txn->req.err_state = txn->req.msg_state;
1387 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001388 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001389 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001390 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001391 } else {
1392 txn->status = 502;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001393 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001394 }
1395 req->analysers &= AN_REQ_FLT_END;
1396 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
1397
1398 HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1399 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1400 if (objt_server(s->target))
1401 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1402
1403 if (!(s->flags & SF_ERR_MASK))
1404 s->flags |= SF_ERR_SRVCL;
1405 if (!(s->flags & SF_FINST_MASK)) {
1406 if (txn->rsp.msg_state < HTTP_MSG_ERROR)
1407 s->flags |= SF_FINST_H;
1408 else
1409 s->flags |= SF_FINST_D;
1410 }
1411 return 0;
1412}
1413
1414/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1415 * processing can continue on next analysers, or zero if it either needs more
1416 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1417 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1418 * when it has nothing left to do, and may remove any analyser when it wants to
1419 * abort.
1420 */
1421int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1422{
Christopher Faulet9768c262018-10-22 09:34:31 +02001423 /*
1424 * We will analyze a complete HTTP response to check the its syntax.
1425 *
1426 * Once the start line and all headers are received, we may perform a
1427 * capture of the error (if any), and we will set a few fields. We also
1428 * logging and finally headers capture.
1429 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001430 struct session *sess = s->sess;
1431 struct http_txn *txn = s->txn;
1432 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001433 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001434 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001435 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001436 int n;
1437
1438 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1439 now_ms, __FUNCTION__,
1440 s,
1441 rep,
1442 rep->rex, rep->wex,
1443 rep->flags,
1444 ci_data(rep),
1445 rep->analysers);
1446
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001447 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001448
1449 /*
1450 * Now we quickly check if we have found a full valid response.
1451 * If not so, we check the FD and buffer states before leaving.
1452 * A full response is indicated by the fact that we have seen
1453 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1454 * responses are checked first.
1455 *
1456 * Depending on whether the client is still there or not, we
1457 * may send an error response back or not. Note that normally
1458 * we should only check for HTTP status there, and check I/O
1459 * errors somewhere else.
1460 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001461 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001462 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001463 * First catch invalid response because of a parsing error or
1464 * because only part of headers have been transfered.
1465 * Multiplexers have the responsibility to emit all headers at
1466 * once. We must be sure to have forwarded all outgoing data
1467 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001468 */
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001469 if (!co_data(rep) &&
1470 ((htx->flags & HTX_FL_PARSING_ERROR) || htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001471 goto return_bad_res;
1472
Christopher Faulet9768c262018-10-22 09:34:31 +02001473 /* 1: have we encountered a read error ? */
1474 if (rep->flags & CF_READ_ERROR) {
1475 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001476 goto abort_keep_alive;
1477
1478 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1479 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001480 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1481 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001482 }
1483
Christopher Faulete0768eb2018-10-03 16:38:02 +02001484 rep->analysers &= AN_RES_FLT_END;
1485 txn->status = 502;
1486
1487 /* Check to see if the server refused the early data.
1488 * If so, just send a 425
1489 */
1490 if (objt_cs(s->si[1].end)) {
1491 struct connection *conn = objt_cs(s->si[1].end)->conn;
1492
1493 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1494 txn->status = 425;
1495 }
1496
1497 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001498 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001499
1500 if (!(s->flags & SF_ERR_MASK))
1501 s->flags |= SF_ERR_SRVCL;
1502 if (!(s->flags & SF_FINST_MASK))
1503 s->flags |= SF_FINST_H;
1504 return 0;
1505 }
1506
Christopher Faulet9768c262018-10-22 09:34:31 +02001507 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001508 else if (rep->flags & CF_READ_TIMEOUT) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001509 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1510 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001511 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1512 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001513 }
1514
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 rep->analysers &= AN_RES_FLT_END;
1516 txn->status = 504;
1517 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001518 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519
1520 if (!(s->flags & SF_ERR_MASK))
1521 s->flags |= SF_ERR_SRVTO;
1522 if (!(s->flags & SF_FINST_MASK))
1523 s->flags |= SF_FINST_H;
1524 return 0;
1525 }
1526
Christopher Faulet9768c262018-10-22 09:34:31 +02001527 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001528 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
1529 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1530 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1531 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001532 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001533
1534 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001535 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001536 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537
1538 if (!(s->flags & SF_ERR_MASK))
1539 s->flags |= SF_ERR_CLICL;
1540 if (!(s->flags & SF_FINST_MASK))
1541 s->flags |= SF_FINST_H;
1542
1543 /* process_stream() will take care of the error */
1544 return 0;
1545 }
1546
Christopher Faulet9768c262018-10-22 09:34:31 +02001547 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001548 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001549 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001550 goto abort_keep_alive;
1551
1552 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1553 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001554 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1555 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001556 }
1557
Christopher Faulete0768eb2018-10-03 16:38:02 +02001558 rep->analysers &= AN_RES_FLT_END;
1559 txn->status = 502;
1560 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001561 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001562
1563 if (!(s->flags & SF_ERR_MASK))
1564 s->flags |= SF_ERR_SRVCL;
1565 if (!(s->flags & SF_FINST_MASK))
1566 s->flags |= SF_FINST_H;
1567 return 0;
1568 }
1569
Christopher Faulet9768c262018-10-22 09:34:31 +02001570 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001571 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001572 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001573 goto abort_keep_alive;
1574
1575 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1576 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001577
1578 if (!(s->flags & SF_ERR_MASK))
1579 s->flags |= SF_ERR_CLICL;
1580 if (!(s->flags & SF_FINST_MASK))
1581 s->flags |= SF_FINST_H;
1582
1583 /* process_stream() will take care of the error */
1584 return 0;
1585 }
1586
1587 channel_dont_close(rep);
1588 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1589 return 0;
1590 }
1591
1592 /* More interesting part now : we know that we have a complete
1593 * response which at least looks like HTTP. We have an indicator
1594 * of each header's length, so we can parse them quickly.
1595 */
1596
Christopher Faulet9768c262018-10-22 09:34:31 +02001597 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001598 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001599
Christopher Faulet9768c262018-10-22 09:34:31 +02001600 /* 0: we might have to print this header in debug mode */
1601 if (unlikely((global.mode & MODE_DEBUG) &&
1602 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1603 int32_t pos;
1604
Christopher Faulet03599112018-11-27 11:21:21 +01001605 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001606
1607 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1608 struct htx_blk *blk = htx_get_blk(htx, pos);
1609 enum htx_blk_type type = htx_get_blk_type(blk);
1610
1611 if (type == HTX_BLK_EOH)
1612 break;
1613 if (type != HTX_BLK_HDR)
1614 continue;
1615
1616 htx_debug_hdr("srvhdr", s,
1617 htx_get_blk_name(htx, blk),
1618 htx_get_blk_value(htx, blk));
1619 }
1620 }
1621
Christopher Faulet03599112018-11-27 11:21:21 +01001622 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001623 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001624 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001625 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001626 if (sl->flags & HTX_SL_F_XFER_LEN) {
1627 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001628 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001629 if (sl->flags & HTX_SL_F_BODYLESS)
1630 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001631 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001632
1633 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001634 if (n < 1 || n > 5)
1635 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001636
Christopher Faulete0768eb2018-10-03 16:38:02 +02001637 /* when the client triggers a 4xx from the server, it's most often due
1638 * to a missing object or permission. These events should be tracked
1639 * because if they happen often, it may indicate a brute force or a
1640 * vulnerability scan.
1641 */
1642 if (n == 4)
1643 stream_inc_http_err_ctr(s);
1644
1645 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001646 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001647
Christopher Faulete0768eb2018-10-03 16:38:02 +02001648 /* Adjust server's health based on status code. Note: status codes 501
1649 * and 505 are triggered on demand by client request, so we must not
1650 * count them as server failures.
1651 */
1652 if (objt_server(s->target)) {
1653 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001654 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001655 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001656 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001657 }
1658
1659 /*
1660 * We may be facing a 100-continue response, or any other informational
1661 * 1xx response which is non-final, in which case this is not the right
1662 * response, and we're waiting for the next one. Let's allow this response
1663 * to go to the client and wait for the next one. There's an exception for
1664 * 101 which is used later in the code to switch protocols.
1665 */
1666 if (txn->status < 200 &&
1667 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001668 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001669 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001670 msg->msg_state = HTTP_MSG_RPBEFORE;
1671 txn->status = 0;
1672 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001673 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001674 }
1675
1676 /*
1677 * 2: check for cacheability.
1678 */
1679
1680 switch (txn->status) {
1681 case 200:
1682 case 203:
1683 case 204:
1684 case 206:
1685 case 300:
1686 case 301:
1687 case 404:
1688 case 405:
1689 case 410:
1690 case 414:
1691 case 501:
1692 break;
1693 default:
1694 /* RFC7231#6.1:
1695 * Responses with status codes that are defined as
1696 * cacheable by default (e.g., 200, 203, 204, 206,
1697 * 300, 301, 404, 405, 410, 414, and 501 in this
1698 * specification) can be reused by a cache with
1699 * heuristic expiration unless otherwise indicated
1700 * by the method definition or explicit cache
1701 * controls [RFC7234]; all other status codes are
1702 * not cacheable by default.
1703 */
1704 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1705 break;
1706 }
1707
1708 /*
1709 * 3: we may need to capture headers
1710 */
1711 s->logs.logwait &= ~LW_RESP;
1712 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001713 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001714
Christopher Faulet9768c262018-10-22 09:34:31 +02001715 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001716 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1717 txn->status == 101)) {
1718 /* Either we've established an explicit tunnel, or we're
1719 * switching the protocol. In both cases, we're very unlikely
1720 * to understand the next protocols. We have to switch to tunnel
1721 * mode, so that we transfer the request and responses then let
1722 * this protocol pass unmodified. When we later implement specific
1723 * parsers for such protocols, we'll want to check the Upgrade
1724 * header which contains information about that protocol for
1725 * responses with status 101 (eg: see RFC2817 about TLS).
1726 */
1727 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001728 }
1729
Christopher Faulet61608322018-11-23 16:23:45 +01001730 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1731 * 407 (Proxy-Authenticate) responses and set the connection to private
1732 */
1733 srv_conn = cs_conn(objt_cs(s->si[1].end));
1734 if (srv_conn) {
1735 struct ist hdr;
1736 struct http_hdr_ctx ctx;
1737
1738 if (txn->status == 401)
1739 hdr = ist("WWW-Authenticate");
1740 else if (txn->status == 407)
1741 hdr = ist("Proxy-Authenticate");
1742 else
1743 goto end;
1744
1745 ctx.blk = NULL;
1746 while (http_find_header(htx, hdr, &ctx, 0)) {
1747 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1748 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1749 srv_conn->flags |= CO_FL_PRIVATE;
1750 }
1751 }
1752
1753 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001754 /* we want to have the response time before we start processing it */
1755 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1756
1757 /* end of job, return OK */
1758 rep->analysers &= ~an_bit;
1759 rep->analyse_exp = TICK_ETERNITY;
1760 channel_auto_close(rep);
1761 return 1;
1762
Christopher Faulet47365272018-10-31 17:40:50 +01001763 return_bad_res:
1764 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
1765 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001766 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
1767 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001768 }
1769 txn->status = 502;
1770 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001771 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001772 rep->analysers &= AN_RES_FLT_END;
1773
1774 if (!(s->flags & SF_ERR_MASK))
1775 s->flags |= SF_ERR_PRXCOND;
1776 if (!(s->flags & SF_FINST_MASK))
1777 s->flags |= SF_FINST_H;
1778 return 0;
1779
Christopher Faulete0768eb2018-10-03 16:38:02 +02001780 abort_keep_alive:
1781 /* A keep-alive request to the server failed on a network error.
1782 * The client is required to retry. We need to close without returning
1783 * any other information so that the client retries.
1784 */
1785 txn->status = 0;
1786 rep->analysers &= AN_RES_FLT_END;
1787 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001788 s->logs.logwait = 0;
1789 s->logs.level = 0;
1790 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001791 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001792 return 0;
1793}
1794
1795/* This function performs all the processing enabled for the current response.
1796 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1797 * and updates s->res.analysers. It might make sense to explode it into several
1798 * other functions. It works like process_request (see indications above).
1799 */
1800int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1801{
1802 struct session *sess = s->sess;
1803 struct http_txn *txn = s->txn;
1804 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001805 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001806 struct proxy *cur_proxy;
1807 struct cond_wordlist *wl;
1808 enum rule_result ret = HTTP_RULE_RES_CONT;
1809
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001810 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1811 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001812
Christopher Faulete0768eb2018-10-03 16:38:02 +02001813 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1814 now_ms, __FUNCTION__,
1815 s,
1816 rep,
1817 rep->rex, rep->wex,
1818 rep->flags,
1819 ci_data(rep),
1820 rep->analysers);
1821
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001822 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001823
1824 /* The stats applet needs to adjust the Connection header but we don't
1825 * apply any filter there.
1826 */
1827 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1828 rep->analysers &= ~an_bit;
1829 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001830 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001831 }
1832
1833 /*
1834 * We will have to evaluate the filters.
1835 * As opposed to version 1.2, now they will be evaluated in the
1836 * filters order and not in the header order. This means that
1837 * each filter has to be validated among all headers.
1838 *
1839 * Filters are tried with ->be first, then with ->fe if it is
1840 * different from ->be.
1841 *
1842 * Maybe we are in resume condiion. In this case I choose the
1843 * "struct proxy" which contains the rule list matching the resume
1844 * pointer. If none of theses "struct proxy" match, I initialise
1845 * the process with the first one.
1846 *
1847 * In fact, I check only correspondance betwwen the current list
1848 * pointer and the ->fe rule list. If it doesn't match, I initialize
1849 * the loop with the ->be.
1850 */
1851 if (s->current_rule_list == &sess->fe->http_res_rules)
1852 cur_proxy = sess->fe;
1853 else
1854 cur_proxy = s->be;
1855 while (1) {
1856 struct proxy *rule_set = cur_proxy;
1857
1858 /* evaluate http-response rules */
1859 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001860 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001861
1862 if (ret == HTTP_RULE_RES_BADREQ)
1863 goto return_srv_prx_502;
1864
1865 if (ret == HTTP_RULE_RES_DONE) {
1866 rep->analysers &= ~an_bit;
1867 rep->analyse_exp = TICK_ETERNITY;
1868 return 1;
1869 }
1870 }
1871
1872 /* we need to be called again. */
1873 if (ret == HTTP_RULE_RES_YIELD) {
1874 channel_dont_close(rep);
1875 return 0;
1876 }
1877
1878 /* try headers filters */
1879 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001880 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1881 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001882 }
1883
1884 /* has the response been denied ? */
1885 if (txn->flags & TX_SVDENY) {
1886 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001887 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001888
1889 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1890 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
1891 if (sess->listener->counters)
1892 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001893 goto return_srv_prx_502;
1894 }
1895
1896 /* add response headers from the rule sets in the same order */
1897 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001898 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001899 if (txn->status < 200 && txn->status != 101)
1900 break;
1901 if (wl->cond) {
1902 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1903 ret = acl_pass(ret);
1904 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1905 ret = !ret;
1906 if (!ret)
1907 continue;
1908 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001909
1910 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1911 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001912 goto return_bad_resp;
1913 }
1914
1915 /* check whether we're already working on the frontend */
1916 if (cur_proxy == sess->fe)
1917 break;
1918 cur_proxy = sess->fe;
1919 }
1920
1921 /* After this point, this anayzer can't return yield, so we can
1922 * remove the bit corresponding to this analyzer from the list.
1923 *
1924 * Note that the intermediate returns and goto found previously
1925 * reset the analyzers.
1926 */
1927 rep->analysers &= ~an_bit;
1928 rep->analyse_exp = TICK_ETERNITY;
1929
1930 /* OK that's all we can do for 1xx responses */
1931 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001932 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001933
1934 /*
1935 * Now check for a server cookie.
1936 */
1937 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001938 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001939
1940 /*
1941 * Check for cache-control or pragma headers if required.
1942 */
1943 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1944 check_response_for_cacheability(s, rep);
1945
1946 /*
1947 * Add server cookie in the response if needed
1948 */
1949 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1950 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1951 (!(s->flags & SF_DIRECT) ||
1952 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1953 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1954 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1955 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1956 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1957 !(s->flags & SF_IGNORE_PRST)) {
1958 /* the server is known, it's not the one the client requested, or the
1959 * cookie's last seen date needs to be refreshed. We have to
1960 * insert a set-cookie here, except if we want to insert only on POST
1961 * requests and this one isn't. Note that servers which don't have cookies
1962 * (eg: some backup servers) will return a full cookie removal request.
1963 */
1964 if (!objt_server(s->target)->cookie) {
1965 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001966 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001967 s->be->cookie_name);
1968 }
1969 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001970 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001971
1972 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1973 /* emit last_date, which is mandatory */
1974 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1975 s30tob64((date.tv_sec+3) >> 2,
1976 trash.area + trash.data);
1977 trash.data += 5;
1978
1979 if (s->be->cookie_maxlife) {
1980 /* emit first_date, which is either the original one or
1981 * the current date.
1982 */
1983 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1984 s30tob64(txn->cookie_first_date ?
1985 txn->cookie_first_date >> 2 :
1986 (date.tv_sec+3) >> 2,
1987 trash.area + trash.data);
1988 trash.data += 5;
1989 }
1990 }
1991 chunk_appendf(&trash, "; path=/");
1992 }
1993
1994 if (s->be->cookie_domain)
1995 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1996
1997 if (s->be->ck_opts & PR_CK_HTTPONLY)
1998 chunk_appendf(&trash, "; HttpOnly");
1999
2000 if (s->be->ck_opts & PR_CK_SECURE)
2001 chunk_appendf(&trash, "; Secure");
2002
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002003 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002004 goto return_bad_resp;
2005
2006 txn->flags &= ~TX_SCK_MASK;
2007 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
2008 /* the server did not change, only the date was updated */
2009 txn->flags |= TX_SCK_UPDATED;
2010 else
2011 txn->flags |= TX_SCK_INSERTED;
2012
2013 /* Here, we will tell an eventual cache on the client side that we don't
2014 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
2015 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2016 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2017 */
2018 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2019
2020 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2021
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002022 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002023 goto return_bad_resp;
2024 }
2025 }
2026
2027 /*
2028 * Check if result will be cacheable with a cookie.
2029 * We'll block the response if security checks have caught
2030 * nasty things such as a cacheable cookie.
2031 */
2032 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2033 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2034 (s->be->options & PR_O_CHK_CACHE)) {
2035 /* we're in presence of a cacheable response containing
2036 * a set-cookie header. We'll block it as requested by
2037 * the 'checkcache' option, and send an alert.
2038 */
2039 if (objt_server(s->target))
2040 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
2041
2042 HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2043 HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
2044 if (sess->listener->counters)
2045 HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
2046
2047 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2048 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2049 send_log(s->be, LOG_ALERT,
2050 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2051 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2052 goto return_srv_prx_502;
2053 }
2054
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002055 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002056 /* Always enter in the body analyzer */
2057 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2058 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2059
2060 /* if the user wants to log as soon as possible, without counting
2061 * bytes from the server, then this is the right moment. We have
2062 * to temporarily assign bytes_out to log what we currently have.
2063 */
2064 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2065 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002066 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002067 s->do_log(s);
2068 s->logs.bytes_out = 0;
2069 }
2070 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002071
2072 return_bad_resp:
2073 if (objt_server(s->target)) {
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002074 HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
2075 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002076 }
2077 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2078
2079 return_srv_prx_502:
2080 rep->analysers &= AN_RES_FLT_END;
2081 txn->status = 502;
2082 s->logs.t_data = -1; /* was not a valid response */
2083 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002084 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002085 if (!(s->flags & SF_ERR_MASK))
2086 s->flags |= SF_ERR_PRXCOND;
2087 if (!(s->flags & SF_FINST_MASK))
2088 s->flags |= SF_FINST_H;
2089 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002090}
2091
2092/* This function is an analyser which forwards response body (including chunk
2093 * sizes if any). It is called as soon as we must forward, even if we forward
2094 * zero byte. The only situation where it must not be called is when we're in
2095 * tunnel mode and we want to forward till the close. It's used both to forward
2096 * remaining data and to resync after end of body. It expects the msg_state to
2097 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2098 * read more data, or 1 once we can go on with next request or end the stream.
2099 *
2100 * It is capable of compressing response data both in content-length mode and
2101 * in chunked mode. The state machines follows different flows depending on
2102 * whether content-length and chunked modes are used, since there are no
2103 * trailers in content-length :
2104 *
2105 * chk-mode cl-mode
2106 * ,----- BODY -----.
2107 * / \
2108 * V size > 0 V chk-mode
2109 * .--> SIZE -------------> DATA -------------> CRLF
2110 * | | size == 0 | last byte |
2111 * | v final crlf v inspected |
2112 * | TRAILERS -----------> DONE |
2113 * | |
2114 * `----------------------------------------------'
2115 *
2116 * Compression only happens in the DATA state, and must be flushed in final
2117 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2118 * is performed at once on final states for all bytes parsed, or when leaving
2119 * on missing data.
2120 */
2121int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2122{
2123 struct session *sess = s->sess;
2124 struct http_txn *txn = s->txn;
2125 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002126 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002127 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002128
2129 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2130 now_ms, __FUNCTION__,
2131 s,
2132 res,
2133 res->rex, res->wex,
2134 res->flags,
2135 ci_data(res),
2136 res->analysers);
2137
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002138 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002139
2140 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002141 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002142 /* Output closed while we were sending data. We must abort and
2143 * wake the other side up.
2144 */
2145 msg->err_state = msg->msg_state;
2146 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002147 htx_end_response(s);
2148 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002149 return 1;
2150 }
2151
Christopher Faulet9768c262018-10-22 09:34:31 +02002152 if (msg->msg_state == HTTP_MSG_BODY)
2153 msg->msg_state = HTTP_MSG_DATA;
2154
Christopher Faulete0768eb2018-10-03 16:38:02 +02002155 /* in most states, we should abort in case of early close */
2156 channel_auto_close(res);
2157
Christopher Faulete0768eb2018-10-03 16:38:02 +02002158 if (res->to_forward) {
2159 /* We can't process the buffer's contents yet */
2160 res->flags |= CF_WAKE_WRITE;
2161 goto missing_data_or_waiting;
2162 }
2163
Christopher Faulet9768c262018-10-22 09:34:31 +02002164 if (msg->msg_state >= HTTP_MSG_DONE)
2165 goto done;
2166
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002167 /* Forward input data. We get it by removing all outgoing data not
2168 * forwarded yet from HTX data size. If there are some data filters, we
2169 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002170 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002171 if (HAS_RSP_DATA_FILTERS(s)) {
2172 ret = flt_http_payload(s, msg, htx->data);
2173 if (ret < 0)
2174 goto return_bad_res;
2175 c_adv(res, ret);
2176 if (htx->data != co_data(res) || htx->extra)
2177 goto missing_data_or_waiting;
2178 }
2179 else {
2180 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002181
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002182 /* To let the function channel_forward work as expected we must update
2183 * the channel's buffer to pretend there is no more input data. The
2184 * right length is then restored. We must do that, because when an HTX
2185 * message is stored into a buffer, it appears as full.
2186 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002187 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2188 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002189 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002190
2191 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2192 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002193 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002194 msg->msg_state = HTTP_MSG_TUNNEL;
2195 goto done;
2196 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002197 }
2198
Christopher Faulet9768c262018-10-22 09:34:31 +02002199 /* Check if the end-of-message is reached and if so, switch the message
2200 * in HTTP_MSG_DONE state.
2201 */
2202 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2203 goto missing_data_or_waiting;
2204
2205 msg->msg_state = HTTP_MSG_DONE;
2206
2207 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002208 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002209 channel_dont_close(res);
2210
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002211 if (HAS_RSP_DATA_FILTERS(s)) {
2212 ret = flt_http_end(s, msg);
2213 if (ret <= 0) {
2214 if (!ret)
2215 goto missing_data_or_waiting;
2216 goto return_bad_res;
2217 }
2218 }
2219
Christopher Fauletf2824e62018-10-01 12:12:37 +02002220 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002221 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002222 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002223 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2224 if (res->flags & CF_SHUTW) {
2225 /* response errors are most likely due to the
2226 * client aborting the transfer. */
2227 goto aborted_xfer;
2228 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002229 goto return_bad_res;
2230 }
2231 return 1;
2232 }
2233 return 0;
2234
2235 missing_data_or_waiting:
2236 if (res->flags & CF_SHUTW)
2237 goto aborted_xfer;
2238
Christopher Faulet47365272018-10-31 17:40:50 +01002239 if (htx->flags & HTX_FL_PARSING_ERROR)
2240 goto return_bad_res;
2241
Christopher Faulete0768eb2018-10-03 16:38:02 +02002242 /* stop waiting for data if the input is closed before the end. If the
2243 * client side was already closed, it means that the client has aborted,
2244 * so we don't want to count this as a server abort. Otherwise it's a
2245 * server abort.
2246 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002247 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002248 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
2249 goto aborted_xfer;
2250 /* If we have some pending data, we continue the processing */
Christopher Faulet9768c262018-10-22 09:34:31 +02002251 if (htx_is_empty(htx)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002252 if (!(s->flags & SF_ERR_MASK))
2253 s->flags |= SF_ERR_SRVCL;
2254 HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
2255 if (objt_server(s->target))
2256 HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2257 goto return_bad_res_stats_ok;
2258 }
2259 }
2260
Christopher Faulete0768eb2018-10-03 16:38:02 +02002261 /* When TE: chunked is used, we need to get there again to parse
2262 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002263 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2264 * are filters registered on the stream, we don't want to forward a
2265 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002266 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002267 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002268 channel_dont_close(res);
2269
2270 /* We know that more data are expected, but we couldn't send more that
2271 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2272 * system knows it must not set a PUSH on this first part. Interactive
2273 * modes are already handled by the stream sock layer. We must not do
2274 * this in content-length mode because it could present the MSG_MORE
2275 * flag with the last block of forwarded data, which would cause an
2276 * additional delay to be observed by the receiver.
2277 */
2278 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2279 res->flags |= CF_EXPECT_MORE;
2280
2281 /* the stream handler will take care of timeouts and errors */
2282 return 0;
2283
2284 return_bad_res: /* let's centralize all bad responses */
2285 HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2286 if (objt_server(s->target))
2287 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2288
2289 return_bad_res_stats_ok:
2290 txn->rsp.err_state = txn->rsp.msg_state;
2291 txn->rsp.msg_state = HTTP_MSG_ERROR;
2292 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002293 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002294 res->analysers &= AN_RES_FLT_END;
2295 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2296 if (objt_server(s->target))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002297 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002298
2299 if (!(s->flags & SF_ERR_MASK))
2300 s->flags |= SF_ERR_PRXCOND;
2301 if (!(s->flags & SF_FINST_MASK))
2302 s->flags |= SF_FINST_D;
2303 return 0;
2304
2305 aborted_xfer:
2306 txn->rsp.err_state = txn->rsp.msg_state;
2307 txn->rsp.msg_state = HTTP_MSG_ERROR;
2308 /* don't send any error message as we're in the body */
Christopher Faulet9768c262018-10-22 09:34:31 +02002309 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002310 res->analysers &= AN_RES_FLT_END;
2311 s->req.analysers &= AN_REQ_FLT_END; /* we're in data phase, we want to abort both directions */
2312
2313 HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2314 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
2315 if (objt_server(s->target))
2316 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2317
2318 if (!(s->flags & SF_ERR_MASK))
2319 s->flags |= SF_ERR_CLICL;
2320 if (!(s->flags & SF_FINST_MASK))
2321 s->flags |= SF_FINST_D;
2322 return 0;
2323}
2324
Christopher Faulet0f226952018-10-22 09:29:56 +02002325void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002326{
2327 struct proxy *fe = strm_fe(s);
2328 int tmp = TX_CON_WANT_CLO;
2329
2330 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2331 tmp = TX_CON_WANT_TUN;
2332
2333 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002334 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002335}
2336
2337/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002338 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002339 * as too large a request to build a valid response.
2340 */
2341int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2342{
Christopher Faulet99daf282018-11-28 22:58:13 +01002343 struct channel *req = &s->req;
2344 struct channel *res = &s->res;
2345 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002346 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002347 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002348 struct ist status, reason, location;
2349 unsigned int flags;
2350 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002351
2352 chunk = alloc_trash_chunk();
2353 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002354 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002355
Christopher Faulet99daf282018-11-28 22:58:13 +01002356 /*
2357 * Create the location
2358 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002359 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002360 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 case REDIRECT_TYPE_SCHEME: {
2362 struct http_hdr_ctx ctx;
2363 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002364
Christopher Faulet99daf282018-11-28 22:58:13 +01002365 host = ist("");
2366 ctx.blk = NULL;
2367 if (http_find_header(htx, ist("Host"), &ctx, 0))
2368 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002369
Christopher Faulet99daf282018-11-28 22:58:13 +01002370 sl = http_find_stline(htx);
2371 path = http_get_path(htx_sl_req_uri(sl));
2372 /* build message using path */
2373 if (path.ptr) {
2374 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2375 int qs = 0;
2376 while (qs < path.len) {
2377 if (*(path.ptr + qs) == '?') {
2378 path.len = qs;
2379 break;
2380 }
2381 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002382 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002383 }
2384 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002385 else
2386 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002387
Christopher Faulet99daf282018-11-28 22:58:13 +01002388 if (rule->rdr_str) { /* this is an old "redirect" rule */
2389 /* add scheme */
2390 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2391 goto fail;
2392 }
2393 else {
2394 /* add scheme with executing log format */
2395 chunk->data += build_logline(s, chunk->area + chunk->data,
2396 chunk->size - chunk->data,
2397 &rule->rdr_fmt);
2398 }
2399 /* add "://" + host + path */
2400 if (!chunk_memcat(chunk, "://", 3) ||
2401 !chunk_memcat(chunk, host.ptr, host.len) ||
2402 !chunk_memcat(chunk, path.ptr, path.len))
2403 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002404
Christopher Faulet99daf282018-11-28 22:58:13 +01002405 /* append a slash at the end of the location if needed and missing */
2406 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2407 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2408 if (chunk->data + 1 >= chunk->size)
2409 goto fail;
2410 chunk->area[chunk->data++] = '/';
2411 }
2412 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002413 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002414
Christopher Faulet99daf282018-11-28 22:58:13 +01002415 case REDIRECT_TYPE_PREFIX: {
2416 struct ist path;
2417
2418 sl = http_find_stline(htx);
2419 path = http_get_path(htx_sl_req_uri(sl));
2420 /* build message using path */
2421 if (path.ptr) {
2422 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2423 int qs = 0;
2424 while (qs < path.len) {
2425 if (*(path.ptr + qs) == '?') {
2426 path.len = qs;
2427 break;
2428 }
2429 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002430 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002431 }
2432 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 else
2434 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002435
Christopher Faulet99daf282018-11-28 22:58:13 +01002436 if (rule->rdr_str) { /* this is an old "redirect" rule */
2437 /* add prefix. Note that if prefix == "/", we don't want to
2438 * add anything, otherwise it makes it hard for the user to
2439 * configure a self-redirection.
2440 */
2441 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2442 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2443 goto fail;
2444 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002445 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002446 else {
2447 /* add prefix with executing log format */
2448 chunk->data += build_logline(s, chunk->area + chunk->data,
2449 chunk->size - chunk->data,
2450 &rule->rdr_fmt);
2451 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002452
Christopher Faulet99daf282018-11-28 22:58:13 +01002453 /* add path */
2454 if (!chunk_memcat(chunk, path.ptr, path.len))
2455 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456
Christopher Faulet99daf282018-11-28 22:58:13 +01002457 /* append a slash at the end of the location if needed and missing */
2458 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2459 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2460 if (chunk->data + 1 >= chunk->size)
2461 goto fail;
2462 chunk->area[chunk->data++] = '/';
2463 }
2464 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002465 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002466 case REDIRECT_TYPE_LOCATION:
2467 default:
2468 if (rule->rdr_str) { /* this is an old "redirect" rule */
2469 /* add location */
2470 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2471 goto fail;
2472 }
2473 else {
2474 /* add location with executing log format */
2475 chunk->data += build_logline(s, chunk->area + chunk->data,
2476 chunk->size - chunk->data,
2477 &rule->rdr_fmt);
2478 }
2479 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002480 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002481 location = ist2(chunk->area, chunk->data);
2482
2483 /*
2484 * Create the 30x response
2485 */
2486 switch (rule->code) {
2487 case 308:
2488 status = ist("308");
2489 reason = ist("Permanent Redirect");
2490 break;
2491 case 307:
2492 status = ist("307");
2493 reason = ist("Temporary Redirect");
2494 break;
2495 case 303:
2496 status = ist("303");
2497 reason = ist("See Other");
2498 break;
2499 case 301:
2500 status = ist("301");
2501 reason = ist("Moved Permanently");
2502 break;
2503 case 302:
2504 default:
2505 status = ist("302");
2506 reason = ist("Found");
2507 break;
2508 }
2509
2510 htx = htx_from_buf(&res->buf);
2511 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2512 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2513 if (!sl)
2514 goto fail;
2515 sl->info.res.status = rule->code;
2516 s->txn->status = rule->code;
2517
2518 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2519 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2520 !htx_add_header(htx, ist("Location"), location))
2521 goto fail;
2522
2523 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2524 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2525 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002526 }
2527
2528 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002529 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2530 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002531 }
2532
Christopher Faulet99daf282018-11-28 22:58:13 +01002533 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2534 goto fail;
2535
Christopher Fauletf2824e62018-10-01 12:12:37 +02002536 /* let's log the request time */
2537 s->logs.tv_request = now;
2538
Christopher Faulet99daf282018-11-28 22:58:13 +01002539 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002540 c_adv(res, data);
2541 res->total += data;
2542
2543 channel_auto_read(req);
2544 channel_abort(req);
2545 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002546 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002547
2548 res->wex = tick_add_ifset(now_ms, res->wto);
2549 channel_auto_read(res);
2550 channel_auto_close(res);
2551 channel_shutr_now(res);
2552
2553 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002554
2555 if (!(s->flags & SF_ERR_MASK))
2556 s->flags |= SF_ERR_LOCAL;
2557 if (!(s->flags & SF_FINST_MASK))
2558 s->flags |= SF_FINST_R;
2559
Christopher Faulet99daf282018-11-28 22:58:13 +01002560 free_trash_chunk(chunk);
2561 return 1;
2562
2563 fail:
2564 /* If an error occurred, remove the incomplete HTTP response from the
2565 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002566 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002567 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002568 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002569}
2570
Christopher Faulet72333522018-10-24 11:25:02 +02002571int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2572 struct ist name, const char *str, struct my_regex *re, int action)
2573{
2574 struct http_hdr_ctx ctx;
2575 struct buffer *output = get_trash_chunk();
2576
2577 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2578 ctx.blk = NULL;
2579 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2580 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2581 continue;
2582
2583 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2584 if (output->data == -1)
2585 return -1;
2586 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2587 return -1;
2588 }
2589 return 0;
2590}
2591
2592static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2593 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2594{
2595 struct buffer *replace;
2596 int ret = -1;
2597
2598 replace = alloc_trash_chunk();
2599 if (!replace)
2600 goto leave;
2601
2602 replace->data = build_logline(s, replace->area, replace->size, fmt);
2603 if (replace->data >= replace->size - 1)
2604 goto leave;
2605
2606 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2607
2608 leave:
2609 free_trash_chunk(replace);
2610 return ret;
2611}
2612
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002613
2614/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2615 * on success and -1 on error. The response channel is updated accordingly.
2616 */
2617static int htx_reply_103_early_hints(struct channel *res)
2618{
2619 struct htx *htx = htx_from_buf(&res->buf);
2620 size_t data;
2621
2622 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2623 /* If an error occurred during an Early-hint rule,
2624 * remove the incomplete HTTP 103 response from the
2625 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002626 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002627 return -1;
2628 }
2629
2630 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002631 c_adv(res, data);
2632 res->total += data;
2633 return 0;
2634}
2635
Christopher Faulet6eb92892018-11-15 16:39:29 +01002636/*
2637 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2638 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002639 * If <early_hints> is 0, it is starts a new response by adding the start
2640 * line. If an error occurred -1 is returned. On success 0 is returned. The
2641 * channel is not updated here. It must be done calling the function
2642 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002643 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002644static 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 +01002645{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646 struct channel *res = &s->res;
2647 struct htx *htx = htx_from_buf(&res->buf);
2648 struct buffer *value = alloc_trash_chunk();
2649
Christopher Faulet6eb92892018-11-15 16:39:29 +01002650 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002651 struct htx_sl *sl;
2652 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2653 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2654
2655 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2656 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2657 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002658 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002659 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002660 }
2661
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002662 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2663 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002664 goto fail;
2665
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002666 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002667 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002668
2669 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002670 /* If an error occurred during an Early-hint rule, remove the incomplete
2671 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002672 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002673 free_trash_chunk(value);
2674 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002675}
2676
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002677/* This function executes one of the set-{method,path,query,uri} actions. It
2678 * takes the string from the variable 'replace' with length 'len', then modifies
2679 * the relevant part of the request line accordingly. Then it updates various
2680 * pointers to the next elements which were moved, and the total buffer length.
2681 * It finds the action to be performed in p[2], previously filled by function
2682 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2683 * error, though this can be revisited when this code is finally exploited.
2684 *
2685 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2686 * query string and 3 to replace uri.
2687 *
2688 * In query string case, the mark question '?' must be set at the start of the
2689 * string by the caller, event if the replacement query string is empty.
2690 */
2691int htx_req_replace_stline(int action, const char *replace, int len,
2692 struct proxy *px, struct stream *s)
2693{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002694 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002695
2696 switch (action) {
2697 case 0: // method
2698 if (!http_replace_req_meth(htx, ist2(replace, len)))
2699 return -1;
2700 break;
2701
2702 case 1: // path
2703 if (!http_replace_req_path(htx, ist2(replace, len)))
2704 return -1;
2705 break;
2706
2707 case 2: // query
2708 if (!http_replace_req_query(htx, ist2(replace, len)))
2709 return -1;
2710 break;
2711
2712 case 3: // uri
2713 if (!http_replace_req_uri(htx, ist2(replace, len)))
2714 return -1;
2715 break;
2716
2717 default:
2718 return -1;
2719 }
2720 return 0;
2721}
2722
2723/* This function replace the HTTP status code and the associated message. The
2724 * variable <status> contains the new status code. This function never fails.
2725 */
2726void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2727{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002728 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002729 char *res;
2730
2731 chunk_reset(&trash);
2732 res = ultoa_o(status, trash.area, trash.size);
2733 trash.data = res - trash.area;
2734
2735 /* Do we have a custom reason format string? */
2736 if (reason == NULL)
2737 reason = http_get_reason(status);
2738
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002739 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002740 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2741}
2742
Christopher Faulet3e964192018-10-24 11:39:23 +02002743/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2744 * transaction <txn>. Returns the verdict of the first rule that prevents
2745 * further processing of the request (auth, deny, ...), and defaults to
2746 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2747 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2748 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2749 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2750 * status.
2751 */
2752static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2753 struct stream *s, int *deny_status)
2754{
2755 struct session *sess = strm_sess(s);
2756 struct http_txn *txn = s->txn;
2757 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002758 struct act_rule *rule;
2759 struct http_hdr_ctx ctx;
2760 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002761 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2762 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002763 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002764
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002765 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002766
2767 /* If "the current_rule_list" match the executed rule list, we are in
2768 * resume condition. If a resume is needed it is always in the action
2769 * and never in the ACL or converters. In this case, we initialise the
2770 * current rule, and go to the action execution point.
2771 */
2772 if (s->current_rule) {
2773 rule = s->current_rule;
2774 s->current_rule = NULL;
2775 if (s->current_rule_list == rules)
2776 goto resume_execution;
2777 }
2778 s->current_rule_list = rules;
2779
2780 list_for_each_entry(rule, rules, list) {
2781 /* check optional condition */
2782 if (rule->cond) {
2783 int ret;
2784
2785 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2786 ret = acl_pass(ret);
2787
2788 if (rule->cond->pol == ACL_COND_UNLESS)
2789 ret = !ret;
2790
2791 if (!ret) /* condition not matched */
2792 continue;
2793 }
2794
2795 act_flags |= ACT_FLAG_FIRST;
2796 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002797 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2798 early_hints = 0;
2799 if (htx_reply_103_early_hints(&s->res) == -1) {
2800 rule_ret = HTTP_RULE_RES_BADREQ;
2801 goto end;
2802 }
2803 }
2804
Christopher Faulet3e964192018-10-24 11:39:23 +02002805 switch (rule->action) {
2806 case ACT_ACTION_ALLOW:
2807 rule_ret = HTTP_RULE_RES_STOP;
2808 goto end;
2809
2810 case ACT_ACTION_DENY:
2811 if (deny_status)
2812 *deny_status = rule->deny_status;
2813 rule_ret = HTTP_RULE_RES_DENY;
2814 goto end;
2815
2816 case ACT_HTTP_REQ_TARPIT:
2817 txn->flags |= TX_CLTARPIT;
2818 if (deny_status)
2819 *deny_status = rule->deny_status;
2820 rule_ret = HTTP_RULE_RES_DENY;
2821 goto end;
2822
2823 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002824 /* Auth might be performed on regular http-req rules as well as on stats */
2825 auth_realm = rule->arg.auth.realm;
2826 if (!auth_realm) {
2827 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2828 auth_realm = STATS_DEFAULT_REALM;
2829 else
2830 auth_realm = px->id;
2831 }
2832 /* send 401/407 depending on whether we use a proxy or not. We still
2833 * count one error, because normal browsing won't significantly
2834 * increase the counter but brute force attempts will.
2835 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002836 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002837 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2838 rule_ret = HTTP_RULE_RES_BADREQ;
2839 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002840 goto end;
2841
2842 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002843 rule_ret = HTTP_RULE_RES_DONE;
2844 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2845 rule_ret = HTTP_RULE_RES_BADREQ;
2846 goto end;
2847
2848 case ACT_HTTP_SET_NICE:
2849 s->task->nice = rule->arg.nice;
2850 break;
2851
2852 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002853 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002854 break;
2855
2856 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002857 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002858 break;
2859
2860 case ACT_HTTP_SET_LOGL:
2861 s->logs.level = rule->arg.loglevel;
2862 break;
2863
2864 case ACT_HTTP_REPLACE_HDR:
2865 case ACT_HTTP_REPLACE_VAL:
2866 if (htx_transform_header(s, &s->req, htx,
2867 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2868 &rule->arg.hdr_add.fmt,
2869 &rule->arg.hdr_add.re, rule->action)) {
2870 rule_ret = HTTP_RULE_RES_BADREQ;
2871 goto end;
2872 }
2873 break;
2874
2875 case ACT_HTTP_DEL_HDR:
2876 /* remove all occurrences of the header */
2877 ctx.blk = NULL;
2878 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2879 http_remove_header(htx, &ctx);
2880 break;
2881
2882 case ACT_HTTP_SET_HDR:
2883 case ACT_HTTP_ADD_HDR: {
2884 /* The scope of the trash buffer must be limited to this function. The
2885 * build_logline() function can execute a lot of other function which
2886 * can use the trash buffer. So for limiting the scope of this global
2887 * buffer, we build first the header value using build_logline, and
2888 * after we store the header name.
2889 */
2890 struct buffer *replace;
2891 struct ist n, v;
2892
2893 replace = alloc_trash_chunk();
2894 if (!replace) {
2895 rule_ret = HTTP_RULE_RES_BADREQ;
2896 goto end;
2897 }
2898
2899 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2900 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2901 v = ist2(replace->area, replace->data);
2902
2903 if (rule->action == ACT_HTTP_SET_HDR) {
2904 /* remove all occurrences of the header */
2905 ctx.blk = NULL;
2906 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2907 http_remove_header(htx, &ctx);
2908 }
2909
2910 if (!http_add_header(htx, n, v)) {
2911 static unsigned char rate_limit = 0;
2912
2913 if ((rate_limit++ & 255) == 0) {
2914 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);
2915 }
2916
2917 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
2918 if (sess->fe != s->be)
2919 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
2920 if (sess->listener->counters)
2921 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
2922 }
2923 free_trash_chunk(replace);
2924 break;
2925 }
2926
2927 case ACT_HTTP_DEL_ACL:
2928 case ACT_HTTP_DEL_MAP: {
2929 struct pat_ref *ref;
2930 struct buffer *key;
2931
2932 /* collect reference */
2933 ref = pat_ref_lookup(rule->arg.map.ref);
2934 if (!ref)
2935 continue;
2936
2937 /* allocate key */
2938 key = alloc_trash_chunk();
2939 if (!key) {
2940 rule_ret = HTTP_RULE_RES_BADREQ;
2941 goto end;
2942 }
2943
2944 /* collect key */
2945 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2946 key->area[key->data] = '\0';
2947
2948 /* perform update */
2949 /* returned code: 1=ok, 0=ko */
2950 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2951 pat_ref_delete(ref, key->area);
2952 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2953
2954 free_trash_chunk(key);
2955 break;
2956 }
2957
2958 case ACT_HTTP_ADD_ACL: {
2959 struct pat_ref *ref;
2960 struct buffer *key;
2961
2962 /* collect reference */
2963 ref = pat_ref_lookup(rule->arg.map.ref);
2964 if (!ref)
2965 continue;
2966
2967 /* allocate key */
2968 key = alloc_trash_chunk();
2969 if (!key) {
2970 rule_ret = HTTP_RULE_RES_BADREQ;
2971 goto end;
2972 }
2973
2974 /* collect key */
2975 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2976 key->area[key->data] = '\0';
2977
2978 /* perform update */
2979 /* add entry only if it does not already exist */
2980 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2981 if (pat_ref_find_elt(ref, key->area) == NULL)
2982 pat_ref_add(ref, key->area, NULL, NULL);
2983 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2984
2985 free_trash_chunk(key);
2986 break;
2987 }
2988
2989 case ACT_HTTP_SET_MAP: {
2990 struct pat_ref *ref;
2991 struct buffer *key, *value;
2992
2993 /* collect reference */
2994 ref = pat_ref_lookup(rule->arg.map.ref);
2995 if (!ref)
2996 continue;
2997
2998 /* allocate key */
2999 key = alloc_trash_chunk();
3000 if (!key) {
3001 rule_ret = HTTP_RULE_RES_BADREQ;
3002 goto end;
3003 }
3004
3005 /* allocate value */
3006 value = alloc_trash_chunk();
3007 if (!value) {
3008 free_trash_chunk(key);
3009 rule_ret = HTTP_RULE_RES_BADREQ;
3010 goto end;
3011 }
3012
3013 /* collect key */
3014 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3015 key->area[key->data] = '\0';
3016
3017 /* collect value */
3018 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3019 value->area[value->data] = '\0';
3020
3021 /* perform update */
3022 if (pat_ref_find_elt(ref, key->area) != NULL)
3023 /* update entry if it exists */
3024 pat_ref_set(ref, key->area, value->area, NULL);
3025 else
3026 /* insert a new entry */
3027 pat_ref_add(ref, key->area, value->area, NULL);
3028
3029 free_trash_chunk(key);
3030 free_trash_chunk(value);
3031 break;
3032 }
3033
3034 case ACT_HTTP_EARLY_HINT:
3035 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3036 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003037 early_hints = htx_add_early_hint_header(s, early_hints,
3038 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003039 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003040 if (early_hints == -1) {
3041 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003042 goto end;
3043 }
3044 break;
3045
3046 case ACT_CUSTOM:
3047 if ((s->req.flags & CF_READ_ERROR) ||
3048 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3049 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3050 (px->options & PR_O_ABRT_CLOSE)))
3051 act_flags |= ACT_FLAG_FINAL;
3052
3053 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3054 case ACT_RET_ERR:
3055 case ACT_RET_CONT:
3056 break;
3057 case ACT_RET_STOP:
3058 rule_ret = HTTP_RULE_RES_DONE;
3059 goto end;
3060 case ACT_RET_YIELD:
3061 s->current_rule = rule;
3062 rule_ret = HTTP_RULE_RES_YIELD;
3063 goto end;
3064 }
3065 break;
3066
3067 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3068 /* Note: only the first valid tracking parameter of each
3069 * applies.
3070 */
3071
3072 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3073 struct stktable *t;
3074 struct stksess *ts;
3075 struct stktable_key *key;
3076 void *ptr1, *ptr2;
3077
3078 t = rule->arg.trk_ctr.table.t;
3079 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3080 rule->arg.trk_ctr.expr, NULL);
3081
3082 if (key && (ts = stktable_get_entry(t, key))) {
3083 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3084
3085 /* let's count a new HTTP request as it's the first time we do it */
3086 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3087 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3088 if (ptr1 || ptr2) {
3089 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3090
3091 if (ptr1)
3092 stktable_data_cast(ptr1, http_req_cnt)++;
3093
3094 if (ptr2)
3095 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3096 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3097
3098 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3099
3100 /* If data was modified, we need to touch to re-schedule sync */
3101 stktable_touch_local(t, ts, 0);
3102 }
3103
3104 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3105 if (sess->fe != s->be)
3106 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3107 }
3108 }
3109 break;
3110
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003111 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003112 default:
3113 break;
3114 }
3115 }
3116
3117 end:
3118 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003119 if (htx_reply_103_early_hints(&s->res) == -1)
3120 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003121 }
3122
3123 /* we reached the end of the rules, nothing to report */
3124 return rule_ret;
3125}
3126
3127/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3128 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3129 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3130 * is returned, the process can continue the evaluation of next rule list. If
3131 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3132 * is returned, it means the operation could not be processed and a server error
3133 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3134 * deny rule. If *YIELD is returned, the caller must call again the function
3135 * with the same context.
3136 */
3137static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3138 struct stream *s)
3139{
3140 struct session *sess = strm_sess(s);
3141 struct http_txn *txn = s->txn;
3142 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003143 struct act_rule *rule;
3144 struct http_hdr_ctx ctx;
3145 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3146 int act_flags = 0;
3147
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003148 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003149
3150 /* If "the current_rule_list" match the executed rule list, we are in
3151 * resume condition. If a resume is needed it is always in the action
3152 * and never in the ACL or converters. In this case, we initialise the
3153 * current rule, and go to the action execution point.
3154 */
3155 if (s->current_rule) {
3156 rule = s->current_rule;
3157 s->current_rule = NULL;
3158 if (s->current_rule_list == rules)
3159 goto resume_execution;
3160 }
3161 s->current_rule_list = rules;
3162
3163 list_for_each_entry(rule, rules, list) {
3164 /* check optional condition */
3165 if (rule->cond) {
3166 int ret;
3167
3168 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3169 ret = acl_pass(ret);
3170
3171 if (rule->cond->pol == ACL_COND_UNLESS)
3172 ret = !ret;
3173
3174 if (!ret) /* condition not matched */
3175 continue;
3176 }
3177
3178 act_flags |= ACT_FLAG_FIRST;
3179resume_execution:
3180 switch (rule->action) {
3181 case ACT_ACTION_ALLOW:
3182 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3183 goto end;
3184
3185 case ACT_ACTION_DENY:
3186 txn->flags |= TX_SVDENY;
3187 rule_ret = HTTP_RULE_RES_STOP;
3188 goto end;
3189
3190 case ACT_HTTP_SET_NICE:
3191 s->task->nice = rule->arg.nice;
3192 break;
3193
3194 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003195 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003196 break;
3197
3198 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003199 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003200 break;
3201
3202 case ACT_HTTP_SET_LOGL:
3203 s->logs.level = rule->arg.loglevel;
3204 break;
3205
3206 case ACT_HTTP_REPLACE_HDR:
3207 case ACT_HTTP_REPLACE_VAL:
3208 if (htx_transform_header(s, &s->res, htx,
3209 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3210 &rule->arg.hdr_add.fmt,
3211 &rule->arg.hdr_add.re, rule->action)) {
3212 rule_ret = HTTP_RULE_RES_BADREQ;
3213 goto end;
3214 }
3215 break;
3216
3217 case ACT_HTTP_DEL_HDR:
3218 /* remove all occurrences of the header */
3219 ctx.blk = NULL;
3220 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3221 http_remove_header(htx, &ctx);
3222 break;
3223
3224 case ACT_HTTP_SET_HDR:
3225 case ACT_HTTP_ADD_HDR: {
3226 struct buffer *replace;
3227 struct ist n, v;
3228
3229 replace = alloc_trash_chunk();
3230 if (!replace) {
3231 rule_ret = HTTP_RULE_RES_BADREQ;
3232 goto end;
3233 }
3234
3235 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3236 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3237 v = ist2(replace->area, replace->data);
3238
3239 if (rule->action == ACT_HTTP_SET_HDR) {
3240 /* remove all occurrences of the header */
3241 ctx.blk = NULL;
3242 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3243 http_remove_header(htx, &ctx);
3244 }
3245
3246 if (!http_add_header(htx, n, v)) {
3247 static unsigned char rate_limit = 0;
3248
3249 if ((rate_limit++ & 255) == 0) {
3250 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);
3251 }
3252
3253 HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
3254 if (sess->fe != s->be)
3255 HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
3256 if (sess->listener->counters)
3257 HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
3258 if (objt_server(s->target))
3259 HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
3260 }
3261 free_trash_chunk(replace);
3262 break;
3263 }
3264
3265 case ACT_HTTP_DEL_ACL:
3266 case ACT_HTTP_DEL_MAP: {
3267 struct pat_ref *ref;
3268 struct buffer *key;
3269
3270 /* collect reference */
3271 ref = pat_ref_lookup(rule->arg.map.ref);
3272 if (!ref)
3273 continue;
3274
3275 /* allocate key */
3276 key = alloc_trash_chunk();
3277 if (!key) {
3278 rule_ret = HTTP_RULE_RES_BADREQ;
3279 goto end;
3280 }
3281
3282 /* collect key */
3283 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3284 key->area[key->data] = '\0';
3285
3286 /* perform update */
3287 /* returned code: 1=ok, 0=ko */
3288 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3289 pat_ref_delete(ref, key->area);
3290 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3291
3292 free_trash_chunk(key);
3293 break;
3294 }
3295
3296 case ACT_HTTP_ADD_ACL: {
3297 struct pat_ref *ref;
3298 struct buffer *key;
3299
3300 /* collect reference */
3301 ref = pat_ref_lookup(rule->arg.map.ref);
3302 if (!ref)
3303 continue;
3304
3305 /* allocate key */
3306 key = alloc_trash_chunk();
3307 if (!key) {
3308 rule_ret = HTTP_RULE_RES_BADREQ;
3309 goto end;
3310 }
3311
3312 /* collect key */
3313 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3314 key->area[key->data] = '\0';
3315
3316 /* perform update */
3317 /* check if the entry already exists */
3318 if (pat_ref_find_elt(ref, key->area) == NULL)
3319 pat_ref_add(ref, key->area, NULL, NULL);
3320
3321 free_trash_chunk(key);
3322 break;
3323 }
3324
3325 case ACT_HTTP_SET_MAP: {
3326 struct pat_ref *ref;
3327 struct buffer *key, *value;
3328
3329 /* collect reference */
3330 ref = pat_ref_lookup(rule->arg.map.ref);
3331 if (!ref)
3332 continue;
3333
3334 /* allocate key */
3335 key = alloc_trash_chunk();
3336 if (!key) {
3337 rule_ret = HTTP_RULE_RES_BADREQ;
3338 goto end;
3339 }
3340
3341 /* allocate value */
3342 value = alloc_trash_chunk();
3343 if (!value) {
3344 free_trash_chunk(key);
3345 rule_ret = HTTP_RULE_RES_BADREQ;
3346 goto end;
3347 }
3348
3349 /* collect key */
3350 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3351 key->area[key->data] = '\0';
3352
3353 /* collect value */
3354 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3355 value->area[value->data] = '\0';
3356
3357 /* perform update */
3358 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3359 if (pat_ref_find_elt(ref, key->area) != NULL)
3360 /* update entry if it exists */
3361 pat_ref_set(ref, key->area, value->area, NULL);
3362 else
3363 /* insert a new entry */
3364 pat_ref_add(ref, key->area, value->area, NULL);
3365 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3366 free_trash_chunk(key);
3367 free_trash_chunk(value);
3368 break;
3369 }
3370
3371 case ACT_HTTP_REDIR:
3372 rule_ret = HTTP_RULE_RES_DONE;
3373 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3374 rule_ret = HTTP_RULE_RES_BADREQ;
3375 goto end;
3376
3377 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3378 /* Note: only the first valid tracking parameter of each
3379 * applies.
3380 */
3381 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3382 struct stktable *t;
3383 struct stksess *ts;
3384 struct stktable_key *key;
3385 void *ptr;
3386
3387 t = rule->arg.trk_ctr.table.t;
3388 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3389 rule->arg.trk_ctr.expr, NULL);
3390
3391 if (key && (ts = stktable_get_entry(t, key))) {
3392 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3393
3394 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3395
3396 /* let's count a new HTTP request as it's the first time we do it */
3397 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3398 if (ptr)
3399 stktable_data_cast(ptr, http_req_cnt)++;
3400
3401 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3402 if (ptr)
3403 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3404 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3405
3406 /* When the client triggers a 4xx from the server, it's most often due
3407 * to a missing object or permission. These events should be tracked
3408 * because if they happen often, it may indicate a brute force or a
3409 * vulnerability scan. Normally this is done when receiving the response
3410 * but here we're tracking after this ought to have been done so we have
3411 * to do it on purpose.
3412 */
3413 if ((unsigned)(txn->status - 400) < 100) {
3414 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3415 if (ptr)
3416 stktable_data_cast(ptr, http_err_cnt)++;
3417
3418 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3419 if (ptr)
3420 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3421 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3422 }
3423
3424 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3425
3426 /* If data was modified, we need to touch to re-schedule sync */
3427 stktable_touch_local(t, ts, 0);
3428
3429 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3430 if (sess->fe != s->be)
3431 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3432 }
3433 }
3434 break;
3435
3436 case ACT_CUSTOM:
3437 if ((s->req.flags & CF_READ_ERROR) ||
3438 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3439 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3440 (px->options & PR_O_ABRT_CLOSE)))
3441 act_flags |= ACT_FLAG_FINAL;
3442
3443 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3444 case ACT_RET_ERR:
3445 case ACT_RET_CONT:
3446 break;
3447 case ACT_RET_STOP:
3448 rule_ret = HTTP_RULE_RES_STOP;
3449 goto end;
3450 case ACT_RET_YIELD:
3451 s->current_rule = rule;
3452 rule_ret = HTTP_RULE_RES_YIELD;
3453 goto end;
3454 }
3455 break;
3456
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003457 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003458 default:
3459 break;
3460 }
3461 }
3462
3463 end:
3464 /* we reached the end of the rules, nothing to report */
3465 return rule_ret;
3466}
3467
Christopher Faulet33640082018-10-24 11:53:01 +02003468/* Iterate the same filter through all request headers.
3469 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3470 * Since it can manage the switch to another backend, it updates the per-proxy
3471 * DENY stats.
3472 */
3473static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3474{
3475 struct http_txn *txn = s->txn;
3476 struct htx *htx;
3477 struct buffer *hdr = get_trash_chunk();
3478 int32_t pos;
3479
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003480 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003481
3482 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3483 struct htx_blk *blk = htx_get_blk(htx, pos);
3484 enum htx_blk_type type;
3485 struct ist n, v;
3486
3487 next_hdr:
3488 type = htx_get_blk_type(blk);
3489 if (type == HTX_BLK_EOH)
3490 break;
3491 if (type != HTX_BLK_HDR)
3492 continue;
3493
3494 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3495 return 1;
3496 else if (unlikely(txn->flags & TX_CLALLOW) &&
3497 (exp->action == ACT_ALLOW ||
3498 exp->action == ACT_DENY ||
3499 exp->action == ACT_TARPIT))
3500 return 0;
3501
3502 n = htx_get_blk_name(htx, blk);
3503 v = htx_get_blk_value(htx, blk);
3504
Christopher Faulet02e771a2019-02-26 15:36:05 +01003505 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003506 hdr->area[hdr->data++] = ':';
3507 hdr->area[hdr->data++] = ' ';
3508 chunk_memcat(hdr, v.ptr, v.len);
3509
3510 /* Now we have one header in <hdr> */
3511
3512 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3513 struct http_hdr_ctx ctx;
3514 int len;
3515
3516 switch (exp->action) {
3517 case ACT_ALLOW:
3518 txn->flags |= TX_CLALLOW;
3519 goto end;
3520
3521 case ACT_DENY:
3522 txn->flags |= TX_CLDENY;
3523 goto end;
3524
3525 case ACT_TARPIT:
3526 txn->flags |= TX_CLTARPIT;
3527 goto end;
3528
3529 case ACT_REPLACE:
3530 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3531 if (len < 0)
3532 return -1;
3533
3534 http_parse_header(ist2(trash.area, len), &n, &v);
3535 ctx.blk = blk;
3536 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003537 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003538 if (!http_replace_header(htx, &ctx, n, v))
3539 return -1;
3540 if (!ctx.blk)
3541 goto end;
3542 pos = htx_get_blk_pos(htx, blk);
3543 break;
3544
3545 case ACT_REMOVE:
3546 ctx.blk = blk;
3547 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003548 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003549 if (!http_remove_header(htx, &ctx))
3550 return -1;
3551 if (!ctx.blk)
3552 goto end;
3553 pos = htx_get_blk_pos(htx, blk);
3554 goto next_hdr;
3555
3556 }
3557 }
3558 }
3559 end:
3560 return 0;
3561}
3562
3563/* Apply the filter to the request line.
3564 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3565 * or -1 if a replacement resulted in an invalid request line.
3566 * Since it can manage the switch to another backend, it updates the per-proxy
3567 * DENY stats.
3568 */
3569static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3570{
3571 struct http_txn *txn = s->txn;
3572 struct htx *htx;
3573 struct buffer *reqline = get_trash_chunk();
3574 int done;
3575
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003576 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003577
3578 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3579 return 1;
3580 else if (unlikely(txn->flags & TX_CLALLOW) &&
3581 (exp->action == ACT_ALLOW ||
3582 exp->action == ACT_DENY ||
3583 exp->action == ACT_TARPIT))
3584 return 0;
3585 else if (exp->action == ACT_REMOVE)
3586 return 0;
3587
3588 done = 0;
3589
3590 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3591
3592 /* Now we have the request line between cur_ptr and cur_end */
3593 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003594 struct htx_sl *sl = http_find_stline(htx);
3595 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003596 int len;
3597
3598 switch (exp->action) {
3599 case ACT_ALLOW:
3600 txn->flags |= TX_CLALLOW;
3601 done = 1;
3602 break;
3603
3604 case ACT_DENY:
3605 txn->flags |= TX_CLDENY;
3606 done = 1;
3607 break;
3608
3609 case ACT_TARPIT:
3610 txn->flags |= TX_CLTARPIT;
3611 done = 1;
3612 break;
3613
3614 case ACT_REPLACE:
3615 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3616 if (len < 0)
3617 return -1;
3618
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003619 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3620 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3621 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003622 return -1;
3623 done = 1;
3624 break;
3625 }
3626 }
3627 return done;
3628}
3629
3630/*
3631 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3632 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3633 * unparsable request. Since it can manage the switch to another backend, it
3634 * updates the per-proxy DENY stats.
3635 */
3636static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3637{
3638 struct session *sess = s->sess;
3639 struct http_txn *txn = s->txn;
3640 struct hdr_exp *exp;
3641
3642 for (exp = px->req_exp; exp; exp = exp->next) {
3643 int ret;
3644
3645 /*
3646 * The interleaving of transformations and verdicts
3647 * makes it difficult to decide to continue or stop
3648 * the evaluation.
3649 */
3650
3651 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3652 break;
3653
3654 if ((txn->flags & TX_CLALLOW) &&
3655 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3656 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3657 continue;
3658
3659 /* if this filter had a condition, evaluate it now and skip to
3660 * next filter if the condition does not match.
3661 */
3662 if (exp->cond) {
3663 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3664 ret = acl_pass(ret);
3665 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3666 ret = !ret;
3667
3668 if (!ret)
3669 continue;
3670 }
3671
3672 /* Apply the filter to the request line. */
3673 ret = htx_apply_filter_to_req_line(s, req, exp);
3674 if (unlikely(ret < 0))
3675 return -1;
3676
3677 if (likely(ret == 0)) {
3678 /* The filter did not match the request, it can be
3679 * iterated through all headers.
3680 */
3681 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3682 return -1;
3683 }
3684 }
3685 return 0;
3686}
3687
3688/* Iterate the same filter through all response headers contained in <res>.
3689 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3690 */
3691static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3692{
3693 struct http_txn *txn = s->txn;
3694 struct htx *htx;
3695 struct buffer *hdr = get_trash_chunk();
3696 int32_t pos;
3697
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003698 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003699
3700 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3701 struct htx_blk *blk = htx_get_blk(htx, pos);
3702 enum htx_blk_type type;
3703 struct ist n, v;
3704
3705 next_hdr:
3706 type = htx_get_blk_type(blk);
3707 if (type == HTX_BLK_EOH)
3708 break;
3709 if (type != HTX_BLK_HDR)
3710 continue;
3711
3712 if (unlikely(txn->flags & TX_SVDENY))
3713 return 1;
3714 else if (unlikely(txn->flags & TX_SVALLOW) &&
3715 (exp->action == ACT_ALLOW ||
3716 exp->action == ACT_DENY))
3717 return 0;
3718
3719 n = htx_get_blk_name(htx, blk);
3720 v = htx_get_blk_value(htx, blk);
3721
Christopher Faulet02e771a2019-02-26 15:36:05 +01003722 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003723 hdr->area[hdr->data++] = ':';
3724 hdr->area[hdr->data++] = ' ';
3725 chunk_memcat(hdr, v.ptr, v.len);
3726
3727 /* Now we have one header in <hdr> */
3728
3729 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3730 struct http_hdr_ctx ctx;
3731 int len;
3732
3733 switch (exp->action) {
3734 case ACT_ALLOW:
3735 txn->flags |= TX_SVALLOW;
3736 goto end;
3737 break;
3738
3739 case ACT_DENY:
3740 txn->flags |= TX_SVDENY;
3741 goto end;
3742 break;
3743
3744 case ACT_REPLACE:
3745 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3746 if (len < 0)
3747 return -1;
3748
3749 http_parse_header(ist2(trash.area, len), &n, &v);
3750 ctx.blk = blk;
3751 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003752 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003753 if (!http_replace_header(htx, &ctx, n, v))
3754 return -1;
3755 if (!ctx.blk)
3756 goto end;
3757 pos = htx_get_blk_pos(htx, blk);
3758 break;
3759
3760 case ACT_REMOVE:
3761 ctx.blk = blk;
3762 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003763 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003764 if (!http_remove_header(htx, &ctx))
3765 return -1;
3766 if (!ctx.blk)
3767 goto end;
3768 pos = htx_get_blk_pos(htx, blk);
3769 goto next_hdr;
3770 }
3771 }
3772
3773 }
3774 end:
3775 return 0;
3776}
3777
3778/* Apply the filter to the status line in the response buffer <res>.
3779 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3780 * or -1 if a replacement resulted in an invalid status line.
3781 */
3782static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3783{
3784 struct http_txn *txn = s->txn;
3785 struct htx *htx;
3786 struct buffer *resline = get_trash_chunk();
3787 int done;
3788
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003789 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003790
3791 if (unlikely(txn->flags & TX_SVDENY))
3792 return 1;
3793 else if (unlikely(txn->flags & TX_SVALLOW) &&
3794 (exp->action == ACT_ALLOW ||
3795 exp->action == ACT_DENY))
3796 return 0;
3797 else if (exp->action == ACT_REMOVE)
3798 return 0;
3799
3800 done = 0;
3801 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3802
3803 /* Now we have the status line between cur_ptr and cur_end */
3804 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003805 struct htx_sl *sl = http_find_stline(htx);
3806 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003807 int len;
3808
3809 switch (exp->action) {
3810 case ACT_ALLOW:
3811 txn->flags |= TX_SVALLOW;
3812 done = 1;
3813 break;
3814
3815 case ACT_DENY:
3816 txn->flags |= TX_SVDENY;
3817 done = 1;
3818 break;
3819
3820 case ACT_REPLACE:
3821 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3822 if (len < 0)
3823 return -1;
3824
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003825 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3826 sl->info.res.status = strl2ui(code.ptr, code.len);
3827 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003828 return -1;
3829
3830 done = 1;
3831 return 1;
3832 }
3833 }
3834 return done;
3835}
3836
3837/*
3838 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3839 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3840 * unparsable response.
3841 */
3842static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3843{
3844 struct session *sess = s->sess;
3845 struct http_txn *txn = s->txn;
3846 struct hdr_exp *exp;
3847
3848 for (exp = px->rsp_exp; exp; exp = exp->next) {
3849 int ret;
3850
3851 /*
3852 * The interleaving of transformations and verdicts
3853 * makes it difficult to decide to continue or stop
3854 * the evaluation.
3855 */
3856
3857 if (txn->flags & TX_SVDENY)
3858 break;
3859
3860 if ((txn->flags & TX_SVALLOW) &&
3861 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3862 exp->action == ACT_PASS)) {
3863 exp = exp->next;
3864 continue;
3865 }
3866
3867 /* if this filter had a condition, evaluate it now and skip to
3868 * next filter if the condition does not match.
3869 */
3870 if (exp->cond) {
3871 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3872 ret = acl_pass(ret);
3873 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3874 ret = !ret;
3875 if (!ret)
3876 continue;
3877 }
3878
3879 /* Apply the filter to the status line. */
3880 ret = htx_apply_filter_to_sts_line(s, res, exp);
3881 if (unlikely(ret < 0))
3882 return -1;
3883
3884 if (likely(ret == 0)) {
3885 /* The filter did not match the response, it can be
3886 * iterated through all headers.
3887 */
3888 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3889 return -1;
3890 }
3891 }
3892 return 0;
3893}
3894
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003895/*
3896 * Manage client-side cookie. It can impact performance by about 2% so it is
3897 * desirable to call it only when needed. This code is quite complex because
3898 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3899 * highly recommended not to touch this part without a good reason !
3900 */
3901static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3902{
3903 struct session *sess = s->sess;
3904 struct http_txn *txn = s->txn;
3905 struct htx *htx;
3906 struct http_hdr_ctx ctx;
3907 char *hdr_beg, *hdr_end, *del_from;
3908 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3909 int preserve_hdr;
3910
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003911 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003912 ctx.blk = NULL;
3913 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3914 del_from = NULL; /* nothing to be deleted */
3915 preserve_hdr = 0; /* assume we may kill the whole header */
3916
3917 /* Now look for cookies. Conforming to RFC2109, we have to support
3918 * attributes whose name begin with a '$', and associate them with
3919 * the right cookie, if we want to delete this cookie.
3920 * So there are 3 cases for each cookie read :
3921 * 1) it's a special attribute, beginning with a '$' : ignore it.
3922 * 2) it's a server id cookie that we *MAY* want to delete : save
3923 * some pointers on it (last semi-colon, beginning of cookie...)
3924 * 3) it's an application cookie : we *MAY* have to delete a previous
3925 * "special" cookie.
3926 * At the end of loop, if a "special" cookie remains, we may have to
3927 * remove it. If no application cookie persists in the header, we
3928 * *MUST* delete it.
3929 *
3930 * Note: RFC2965 is unclear about the processing of spaces around
3931 * the equal sign in the ATTR=VALUE form. A careful inspection of
3932 * the RFC explicitly allows spaces before it, and not within the
3933 * tokens (attrs or values). An inspection of RFC2109 allows that
3934 * too but section 10.1.3 lets one think that spaces may be allowed
3935 * after the equal sign too, resulting in some (rare) buggy
3936 * implementations trying to do that. So let's do what servers do.
3937 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3938 * allowed quoted strings in values, with any possible character
3939 * after a backslash, including control chars and delimitors, which
3940 * causes parsing to become ambiguous. Browsers also allow spaces
3941 * within values even without quotes.
3942 *
3943 * We have to keep multiple pointers in order to support cookie
3944 * removal at the beginning, middle or end of header without
3945 * corrupting the header. All of these headers are valid :
3946 *
3947 * hdr_beg hdr_end
3948 * | |
3949 * v |
3950 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3951 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3952 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3953 * | | | | | | |
3954 * | | | | | | |
3955 * | | | | | | +--> next
3956 * | | | | | +----> val_end
3957 * | | | | +-----------> val_beg
3958 * | | | +--------------> equal
3959 * | | +----------------> att_end
3960 * | +---------------------> att_beg
3961 * +--------------------------> prev
3962 *
3963 */
3964 hdr_beg = ctx.value.ptr;
3965 hdr_end = hdr_beg + ctx.value.len;
3966 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3967 /* Iterate through all cookies on this line */
3968
3969 /* find att_beg */
3970 att_beg = prev;
3971 if (prev > hdr_beg)
3972 att_beg++;
3973
3974 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3975 att_beg++;
3976
3977 /* find att_end : this is the first character after the last non
3978 * space before the equal. It may be equal to hdr_end.
3979 */
3980 equal = att_end = att_beg;
3981 while (equal < hdr_end) {
3982 if (*equal == '=' || *equal == ',' || *equal == ';')
3983 break;
3984 if (HTTP_IS_SPHT(*equal++))
3985 continue;
3986 att_end = equal;
3987 }
3988
3989 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3990 * is between <att_beg> and <equal>, both may be identical.
3991 */
3992 /* look for end of cookie if there is an equal sign */
3993 if (equal < hdr_end && *equal == '=') {
3994 /* look for the beginning of the value */
3995 val_beg = equal + 1;
3996 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3997 val_beg++;
3998
3999 /* find the end of the value, respecting quotes */
4000 next = http_find_cookie_value_end(val_beg, hdr_end);
4001
4002 /* make val_end point to the first white space or delimitor after the value */
4003 val_end = next;
4004 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4005 val_end--;
4006 }
4007 else
4008 val_beg = val_end = next = equal;
4009
4010 /* We have nothing to do with attributes beginning with
4011 * '$'. However, they will automatically be removed if a
4012 * header before them is removed, since they're supposed
4013 * to be linked together.
4014 */
4015 if (*att_beg == '$')
4016 continue;
4017
4018 /* Ignore cookies with no equal sign */
4019 if (equal == next) {
4020 /* This is not our cookie, so we must preserve it. But if we already
4021 * scheduled another cookie for removal, we cannot remove the
4022 * complete header, but we can remove the previous block itself.
4023 */
4024 preserve_hdr = 1;
4025 if (del_from != NULL) {
4026 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4027 val_end += delta;
4028 next += delta;
4029 hdr_end += delta;
4030 prev = del_from;
4031 del_from = NULL;
4032 }
4033 continue;
4034 }
4035
4036 /* if there are spaces around the equal sign, we need to
4037 * strip them otherwise we'll get trouble for cookie captures,
4038 * or even for rewrites. Since this happens extremely rarely,
4039 * it does not hurt performance.
4040 */
4041 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4042 int stripped_before = 0;
4043 int stripped_after = 0;
4044
4045 if (att_end != equal) {
4046 memmove(att_end, equal, hdr_end - equal);
4047 stripped_before = (att_end - equal);
4048 equal += stripped_before;
4049 val_beg += stripped_before;
4050 }
4051
4052 if (val_beg > equal + 1) {
4053 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4054 stripped_after = (equal + 1) - val_beg;
4055 val_beg += stripped_after;
4056 stripped_before += stripped_after;
4057 }
4058
4059 val_end += stripped_before;
4060 next += stripped_before;
4061 hdr_end += stripped_before;
4062 }
4063 /* now everything is as on the diagram above */
4064
4065 /* First, let's see if we want to capture this cookie. We check
4066 * that we don't already have a client side cookie, because we
4067 * can only capture one. Also as an optimisation, we ignore
4068 * cookies shorter than the declared name.
4069 */
4070 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4071 (val_end - att_beg >= sess->fe->capture_namelen) &&
4072 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4073 int log_len = val_end - att_beg;
4074
4075 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4076 ha_alert("HTTP logging : out of memory.\n");
4077 } else {
4078 if (log_len > sess->fe->capture_len)
4079 log_len = sess->fe->capture_len;
4080 memcpy(txn->cli_cookie, att_beg, log_len);
4081 txn->cli_cookie[log_len] = 0;
4082 }
4083 }
4084
4085 /* Persistence cookies in passive, rewrite or insert mode have the
4086 * following form :
4087 *
4088 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4089 *
4090 * For cookies in prefix mode, the form is :
4091 *
4092 * Cookie: NAME=SRV~VALUE
4093 */
4094 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4095 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4096 struct server *srv = s->be->srv;
4097 char *delim;
4098
4099 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4100 * have the server ID between val_beg and delim, and the original cookie between
4101 * delim+1 and val_end. Otherwise, delim==val_end :
4102 *
4103 * hdr_beg
4104 * |
4105 * v
4106 * NAME=SRV; # in all but prefix modes
4107 * NAME=SRV~OPAQUE ; # in prefix mode
4108 * || || | |+-> next
4109 * || || | +--> val_end
4110 * || || +---------> delim
4111 * || |+------------> val_beg
4112 * || +-------------> att_end = equal
4113 * |+-----------------> att_beg
4114 * +------------------> prev
4115 *
4116 */
4117 if (s->be->ck_opts & PR_CK_PFX) {
4118 for (delim = val_beg; delim < val_end; delim++)
4119 if (*delim == COOKIE_DELIM)
4120 break;
4121 }
4122 else {
4123 char *vbar1;
4124 delim = val_end;
4125 /* Now check if the cookie contains a date field, which would
4126 * appear after a vertical bar ('|') just after the server name
4127 * and before the delimiter.
4128 */
4129 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4130 if (vbar1) {
4131 /* OK, so left of the bar is the server's cookie and
4132 * right is the last seen date. It is a base64 encoded
4133 * 30-bit value representing the UNIX date since the
4134 * epoch in 4-second quantities.
4135 */
4136 int val;
4137 delim = vbar1++;
4138 if (val_end - vbar1 >= 5) {
4139 val = b64tos30(vbar1);
4140 if (val > 0)
4141 txn->cookie_last_date = val << 2;
4142 }
4143 /* look for a second vertical bar */
4144 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4145 if (vbar1 && (val_end - vbar1 > 5)) {
4146 val = b64tos30(vbar1 + 1);
4147 if (val > 0)
4148 txn->cookie_first_date = val << 2;
4149 }
4150 }
4151 }
4152
4153 /* if the cookie has an expiration date and the proxy wants to check
4154 * it, then we do that now. We first check if the cookie is too old,
4155 * then only if it has expired. We detect strict overflow because the
4156 * time resolution here is not great (4 seconds). Cookies with dates
4157 * in the future are ignored if their offset is beyond one day. This
4158 * allows an admin to fix timezone issues without expiring everyone
4159 * and at the same time avoids keeping unwanted side effects for too
4160 * long.
4161 */
4162 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4163 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4164 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4165 txn->flags &= ~TX_CK_MASK;
4166 txn->flags |= TX_CK_OLD;
4167 delim = val_beg; // let's pretend we have not found the cookie
4168 txn->cookie_first_date = 0;
4169 txn->cookie_last_date = 0;
4170 }
4171 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4172 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4173 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4174 txn->flags &= ~TX_CK_MASK;
4175 txn->flags |= TX_CK_EXPIRED;
4176 delim = val_beg; // let's pretend we have not found the cookie
4177 txn->cookie_first_date = 0;
4178 txn->cookie_last_date = 0;
4179 }
4180
4181 /* Here, we'll look for the first running server which supports the cookie.
4182 * This allows to share a same cookie between several servers, for example
4183 * to dedicate backup servers to specific servers only.
4184 * However, to prevent clients from sticking to cookie-less backup server
4185 * when they have incidentely learned an empty cookie, we simply ignore
4186 * empty cookies and mark them as invalid.
4187 * The same behaviour is applied when persistence must be ignored.
4188 */
4189 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4190 srv = NULL;
4191
4192 while (srv) {
4193 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4194 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4195 if ((srv->cur_state != SRV_ST_STOPPED) ||
4196 (s->be->options & PR_O_PERSIST) ||
4197 (s->flags & SF_FORCE_PRST)) {
4198 /* we found the server and we can use it */
4199 txn->flags &= ~TX_CK_MASK;
4200 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4201 s->flags |= SF_DIRECT | SF_ASSIGNED;
4202 s->target = &srv->obj_type;
4203 break;
4204 } else {
4205 /* we found a server, but it's down,
4206 * mark it as such and go on in case
4207 * another one is available.
4208 */
4209 txn->flags &= ~TX_CK_MASK;
4210 txn->flags |= TX_CK_DOWN;
4211 }
4212 }
4213 srv = srv->next;
4214 }
4215
4216 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4217 /* no server matched this cookie or we deliberately skipped it */
4218 txn->flags &= ~TX_CK_MASK;
4219 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4220 txn->flags |= TX_CK_UNUSED;
4221 else
4222 txn->flags |= TX_CK_INVALID;
4223 }
4224
4225 /* depending on the cookie mode, we may have to either :
4226 * - delete the complete cookie if we're in insert+indirect mode, so that
4227 * the server never sees it ;
4228 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004229 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004230 * if we're in cookie prefix mode
4231 */
4232 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4233 int delta; /* negative */
4234
4235 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4236 delta = val_beg - (delim + 1);
4237 val_end += delta;
4238 next += delta;
4239 hdr_end += delta;
4240 del_from = NULL;
4241 preserve_hdr = 1; /* we want to keep this cookie */
4242 }
4243 else if (del_from == NULL &&
4244 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4245 del_from = prev;
4246 }
4247 }
4248 else {
4249 /* This is not our cookie, so we must preserve it. But if we already
4250 * scheduled another cookie for removal, we cannot remove the
4251 * complete header, but we can remove the previous block itself.
4252 */
4253 preserve_hdr = 1;
4254
4255 if (del_from != NULL) {
4256 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4257 if (att_beg >= del_from)
4258 att_beg += delta;
4259 if (att_end >= del_from)
4260 att_end += delta;
4261 val_beg += delta;
4262 val_end += delta;
4263 next += delta;
4264 hdr_end += delta;
4265 prev = del_from;
4266 del_from = NULL;
4267 }
4268 }
4269
4270 /* continue with next cookie on this header line */
4271 att_beg = next;
4272 } /* for each cookie */
4273
4274
4275 /* There are no more cookies on this line.
4276 * We may still have one (or several) marked for deletion at the
4277 * end of the line. We must do this now in two ways :
4278 * - if some cookies must be preserved, we only delete from the
4279 * mark to the end of line ;
4280 * - if nothing needs to be preserved, simply delete the whole header
4281 */
4282 if (del_from) {
4283 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4284 }
4285 if ((hdr_end - hdr_beg) != ctx.value.len) {
4286 if (hdr_beg != hdr_end) {
4287 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004288 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004289 }
4290 else
4291 http_remove_header(htx, &ctx);
4292 }
4293 } /* for each "Cookie header */
4294}
4295
4296/*
4297 * Manage server-side cookies. It can impact performance by about 2% so it is
4298 * desirable to call it only when needed. This function is also used when we
4299 * just need to know if there is a cookie (eg: for check-cache).
4300 */
4301static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4302{
4303 struct session *sess = s->sess;
4304 struct http_txn *txn = s->txn;
4305 struct htx *htx;
4306 struct http_hdr_ctx ctx;
4307 struct server *srv;
4308 char *hdr_beg, *hdr_end;
4309 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4310 int is_cookie2;
4311
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004312 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004313
4314 ctx.blk = NULL;
4315 while (1) {
4316 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4317 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4318 break;
4319 is_cookie2 = 1;
4320 }
4321
4322 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4323 * <prev> points to the colon.
4324 */
4325 txn->flags |= TX_SCK_PRESENT;
4326
4327 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4328 * check-cache is enabled) and we are not interested in checking
4329 * them. Warning, the cookie capture is declared in the frontend.
4330 */
4331 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4332 break;
4333
4334 /* OK so now we know we have to process this response cookie.
4335 * The format of the Set-Cookie header is slightly different
4336 * from the format of the Cookie header in that it does not
4337 * support the comma as a cookie delimiter (thus the header
4338 * cannot be folded) because the Expires attribute described in
4339 * the original Netscape's spec may contain an unquoted date
4340 * with a comma inside. We have to live with this because
4341 * many browsers don't support Max-Age and some browsers don't
4342 * support quoted strings. However the Set-Cookie2 header is
4343 * clean.
4344 *
4345 * We have to keep multiple pointers in order to support cookie
4346 * removal at the beginning, middle or end of header without
4347 * corrupting the header (in case of set-cookie2). A special
4348 * pointer, <scav> points to the beginning of the set-cookie-av
4349 * fields after the first semi-colon. The <next> pointer points
4350 * either to the end of line (set-cookie) or next unquoted comma
4351 * (set-cookie2). All of these headers are valid :
4352 *
4353 * hdr_beg hdr_end
4354 * | |
4355 * v |
4356 * NAME1 = VALUE 1 ; Secure; Path="/" |
4357 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4358 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4359 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4360 * | | | | | | | |
4361 * | | | | | | | +-> next
4362 * | | | | | | +------------> scav
4363 * | | | | | +--------------> val_end
4364 * | | | | +--------------------> val_beg
4365 * | | | +----------------------> equal
4366 * | | +------------------------> att_end
4367 * | +----------------------------> att_beg
4368 * +------------------------------> prev
4369 * -------------------------------> hdr_beg
4370 */
4371 hdr_beg = ctx.value.ptr;
4372 hdr_end = hdr_beg + ctx.value.len;
4373 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4374
4375 /* Iterate through all cookies on this line */
4376
4377 /* find att_beg */
4378 att_beg = prev;
4379 if (prev > hdr_beg)
4380 att_beg++;
4381
4382 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4383 att_beg++;
4384
4385 /* find att_end : this is the first character after the last non
4386 * space before the equal. It may be equal to hdr_end.
4387 */
4388 equal = att_end = att_beg;
4389
4390 while (equal < hdr_end) {
4391 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4392 break;
4393 if (HTTP_IS_SPHT(*equal++))
4394 continue;
4395 att_end = equal;
4396 }
4397
4398 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4399 * is between <att_beg> and <equal>, both may be identical.
4400 */
4401
4402 /* look for end of cookie if there is an equal sign */
4403 if (equal < hdr_end && *equal == '=') {
4404 /* look for the beginning of the value */
4405 val_beg = equal + 1;
4406 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4407 val_beg++;
4408
4409 /* find the end of the value, respecting quotes */
4410 next = http_find_cookie_value_end(val_beg, hdr_end);
4411
4412 /* make val_end point to the first white space or delimitor after the value */
4413 val_end = next;
4414 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4415 val_end--;
4416 }
4417 else {
4418 /* <equal> points to next comma, semi-colon or EOL */
4419 val_beg = val_end = next = equal;
4420 }
4421
4422 if (next < hdr_end) {
4423 /* Set-Cookie2 supports multiple cookies, and <next> points to
4424 * a colon or semi-colon before the end. So skip all attr-value
4425 * pairs and look for the next comma. For Set-Cookie, since
4426 * commas are permitted in values, skip to the end.
4427 */
4428 if (is_cookie2)
4429 next = http_find_hdr_value_end(next, hdr_end);
4430 else
4431 next = hdr_end;
4432 }
4433
4434 /* Now everything is as on the diagram above */
4435
4436 /* Ignore cookies with no equal sign */
4437 if (equal == val_end)
4438 continue;
4439
4440 /* If there are spaces around the equal sign, we need to
4441 * strip them otherwise we'll get trouble for cookie captures,
4442 * or even for rewrites. Since this happens extremely rarely,
4443 * it does not hurt performance.
4444 */
4445 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4446 int stripped_before = 0;
4447 int stripped_after = 0;
4448
4449 if (att_end != equal) {
4450 memmove(att_end, equal, hdr_end - equal);
4451 stripped_before = (att_end - equal);
4452 equal += stripped_before;
4453 val_beg += stripped_before;
4454 }
4455
4456 if (val_beg > equal + 1) {
4457 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4458 stripped_after = (equal + 1) - val_beg;
4459 val_beg += stripped_after;
4460 stripped_before += stripped_after;
4461 }
4462
4463 val_end += stripped_before;
4464 next += stripped_before;
4465 hdr_end += stripped_before;
4466
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004467 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4468 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004469 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004470 }
4471
4472 /* First, let's see if we want to capture this cookie. We check
4473 * that we don't already have a server side cookie, because we
4474 * can only capture one. Also as an optimisation, we ignore
4475 * cookies shorter than the declared name.
4476 */
4477 if (sess->fe->capture_name != NULL &&
4478 txn->srv_cookie == NULL &&
4479 (val_end - att_beg >= sess->fe->capture_namelen) &&
4480 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4481 int log_len = val_end - att_beg;
4482 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4483 ha_alert("HTTP logging : out of memory.\n");
4484 }
4485 else {
4486 if (log_len > sess->fe->capture_len)
4487 log_len = sess->fe->capture_len;
4488 memcpy(txn->srv_cookie, att_beg, log_len);
4489 txn->srv_cookie[log_len] = 0;
4490 }
4491 }
4492
4493 srv = objt_server(s->target);
4494 /* now check if we need to process it for persistence */
4495 if (!(s->flags & SF_IGNORE_PRST) &&
4496 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4497 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4498 /* assume passive cookie by default */
4499 txn->flags &= ~TX_SCK_MASK;
4500 txn->flags |= TX_SCK_FOUND;
4501
4502 /* If the cookie is in insert mode on a known server, we'll delete
4503 * this occurrence because we'll insert another one later.
4504 * We'll delete it too if the "indirect" option is set and we're in
4505 * a direct access.
4506 */
4507 if (s->be->ck_opts & PR_CK_PSV) {
4508 /* The "preserve" flag was set, we don't want to touch the
4509 * server's cookie.
4510 */
4511 }
4512 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4513 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4514 /* this cookie must be deleted */
4515 if (prev == hdr_beg && next == hdr_end) {
4516 /* whole header */
4517 http_remove_header(htx, &ctx);
4518 /* note: while both invalid now, <next> and <hdr_end>
4519 * are still equal, so the for() will stop as expected.
4520 */
4521 } else {
4522 /* just remove the value */
4523 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4524 next = prev;
4525 hdr_end += delta;
4526 }
4527 txn->flags &= ~TX_SCK_MASK;
4528 txn->flags |= TX_SCK_DELETED;
4529 /* and go on with next cookie */
4530 }
4531 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4532 /* replace bytes val_beg->val_end with the cookie name associated
4533 * with this server since we know it.
4534 */
4535 int sliding, delta;
4536
4537 ctx.value = ist2(val_beg, val_end - val_beg);
4538 ctx.lws_before = ctx.lws_after = 0;
4539 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4540 delta = srv->cklen - (val_end - val_beg);
4541 sliding = (ctx.value.ptr - val_beg);
4542 hdr_beg += sliding;
4543 val_beg += sliding;
4544 next += sliding + delta;
4545 hdr_end += sliding + delta;
4546
4547 txn->flags &= ~TX_SCK_MASK;
4548 txn->flags |= TX_SCK_REPLACED;
4549 }
4550 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4551 /* insert the cookie name associated with this server
4552 * before existing cookie, and insert a delimiter between them..
4553 */
4554 int sliding, delta;
4555 ctx.value = ist2(val_beg, 0);
4556 ctx.lws_before = ctx.lws_after = 0;
4557 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4558 delta = srv->cklen + 1;
4559 sliding = (ctx.value.ptr - val_beg);
4560 hdr_beg += sliding;
4561 val_beg += sliding;
4562 next += sliding + delta;
4563 hdr_end += sliding + delta;
4564
4565 val_beg[srv->cklen] = COOKIE_DELIM;
4566 txn->flags &= ~TX_SCK_MASK;
4567 txn->flags |= TX_SCK_REPLACED;
4568 }
4569 }
4570 /* that's done for this cookie, check the next one on the same
4571 * line when next != hdr_end (only if is_cookie2).
4572 */
4573 }
4574 }
4575}
4576
Christopher Faulet25a02f62018-10-24 12:00:25 +02004577/*
4578 * Parses the Cache-Control and Pragma request header fields to determine if
4579 * the request may be served from the cache and/or if it is cacheable. Updates
4580 * s->txn->flags.
4581 */
4582void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4583{
4584 struct http_txn *txn = s->txn;
4585 struct htx *htx;
4586 int32_t pos;
4587 int pragma_found, cc_found, i;
4588
4589 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4590 return; /* nothing more to do here */
4591
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004592 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004593 pragma_found = cc_found = 0;
4594 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4595 struct htx_blk *blk = htx_get_blk(htx, pos);
4596 enum htx_blk_type type = htx_get_blk_type(blk);
4597 struct ist n, v;
4598
4599 if (type == HTX_BLK_EOH)
4600 break;
4601 if (type != HTX_BLK_HDR)
4602 continue;
4603
4604 n = htx_get_blk_name(htx, blk);
4605 v = htx_get_blk_value(htx, blk);
4606
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004607 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004608 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4609 pragma_found = 1;
4610 continue;
4611 }
4612 }
4613
4614 /* Don't use the cache and don't try to store if we found the
4615 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004616 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004617 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4618 txn->flags |= TX_CACHE_IGNORE;
4619 continue;
4620 }
4621
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004622 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004623 continue;
4624
4625 /* OK, right now we know we have a cache-control header */
4626 cc_found = 1;
4627 if (!v.len) /* no info */
4628 continue;
4629
4630 i = 0;
4631 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4632 !isspace((unsigned char)*(v.ptr+i)))
4633 i++;
4634
4635 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4636 * values after max-age, max-stale nor min-fresh, we simply don't
4637 * use the cache when they're specified.
4638 */
4639 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4640 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4641 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4642 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4643 txn->flags |= TX_CACHE_IGNORE;
4644 continue;
4645 }
4646
4647 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4648 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4649 continue;
4650 }
4651 }
4652
4653 /* RFC7234#5.4:
4654 * When the Cache-Control header field is also present and
4655 * understood in a request, Pragma is ignored.
4656 * When the Cache-Control header field is not present in a
4657 * request, caches MUST consider the no-cache request
4658 * pragma-directive as having the same effect as if
4659 * "Cache-Control: no-cache" were present.
4660 */
4661 if (!cc_found && pragma_found)
4662 txn->flags |= TX_CACHE_IGNORE;
4663}
4664
4665/*
4666 * Check if response is cacheable or not. Updates s->txn->flags.
4667 */
4668void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4669{
4670 struct http_txn *txn = s->txn;
4671 struct htx *htx;
4672 int32_t pos;
4673 int i;
4674
4675 if (txn->status < 200) {
4676 /* do not try to cache interim responses! */
4677 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4678 return;
4679 }
4680
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004681 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004682 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4683 struct htx_blk *blk = htx_get_blk(htx, pos);
4684 enum htx_blk_type type = htx_get_blk_type(blk);
4685 struct ist n, v;
4686
4687 if (type == HTX_BLK_EOH)
4688 break;
4689 if (type != HTX_BLK_HDR)
4690 continue;
4691
4692 n = htx_get_blk_name(htx, blk);
4693 v = htx_get_blk_value(htx, blk);
4694
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004695 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004696 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4697 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4698 return;
4699 }
4700 }
4701
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004702 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004703 continue;
4704
4705 /* OK, right now we know we have a cache-control header */
4706 if (!v.len) /* no info */
4707 continue;
4708
4709 i = 0;
4710 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4711 !isspace((unsigned char)*(v.ptr+i)))
4712 i++;
4713
4714 /* we have a complete value between v.ptr and (v.ptr+i) */
4715 if (i < v.len && *(v.ptr + i) == '=') {
4716 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4717 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4718 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4719 continue;
4720 }
4721
4722 /* we have something of the form no-cache="set-cookie" */
4723 if ((v.len >= 21) &&
4724 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4725 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4726 txn->flags &= ~TX_CACHE_COOK;
4727 continue;
4728 }
4729
4730 /* OK, so we know that either p2 points to the end of string or to a comma */
4731 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4732 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4733 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4734 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4735 return;
4736 }
4737
4738 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4739 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4740 continue;
4741 }
4742 }
4743}
4744
Christopher Faulet64159df2018-10-24 21:15:35 +02004745/* send a server's name with an outgoing request over an established connection.
4746 * Note: this function is designed to be called once the request has been
4747 * scheduled for being forwarded. This is the reason why the number of forwarded
4748 * bytes have to be adjusted.
4749 */
4750int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4751{
4752 struct htx *htx;
4753 struct http_hdr_ctx ctx;
4754 struct ist hdr;
4755 uint32_t data;
4756
4757 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004758 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004759 data = htx->data;
4760
4761 ctx.blk = NULL;
4762 while (http_find_header(htx, hdr, &ctx, 1))
4763 http_remove_header(htx, &ctx);
4764 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4765
4766 if (co_data(&s->req)) {
4767 if (data >= htx->data)
4768 c_rew(&s->req, data - htx->data);
4769 else
4770 c_adv(&s->req, htx->data - data);
4771 }
4772 return 0;
4773}
4774
Christopher Faulet377c5a52018-10-24 21:21:30 +02004775/*
4776 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4777 * for the current backend.
4778 *
4779 * It is assumed that the request is either a HEAD, GET, or POST and that the
4780 * uri_auth field is valid.
4781 *
4782 * Returns 1 if stats should be provided, otherwise 0.
4783 */
4784static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4785{
4786 struct uri_auth *uri_auth = backend->uri_auth;
4787 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004788 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004789 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004790
4791 if (!uri_auth)
4792 return 0;
4793
4794 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4795 return 0;
4796
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004797 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004798 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004799 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004800
4801 /* check URI size */
4802 if (uri_auth->uri_len > uri.len)
4803 return 0;
4804
4805 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4806 return 0;
4807
4808 return 1;
4809}
4810
4811/* This function prepares an applet to handle the stats. It can deal with the
4812 * "100-continue" expectation, check that admin rules are met for POST requests,
4813 * and program a response message if something was unexpected. It cannot fail
4814 * and always relies on the stats applet to complete the job. It does not touch
4815 * analysers nor counters, which are left to the caller. It does not touch
4816 * s->target which is supposed to already point to the stats applet. The caller
4817 * is expected to have already assigned an appctx to the stream.
4818 */
4819static int htx_handle_stats(struct stream *s, struct channel *req)
4820{
4821 struct stats_admin_rule *stats_admin_rule;
4822 struct stream_interface *si = &s->si[1];
4823 struct session *sess = s->sess;
4824 struct http_txn *txn = s->txn;
4825 struct http_msg *msg = &txn->req;
4826 struct uri_auth *uri_auth = s->be->uri_auth;
4827 const char *h, *lookup, *end;
4828 struct appctx *appctx;
4829 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004830 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004831
4832 appctx = si_appctx(si);
4833 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4834 appctx->st1 = appctx->st2 = 0;
4835 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4836 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4837 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4838 appctx->ctx.stats.flags |= STAT_CHUNKED;
4839
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004840 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004841 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004842 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4843 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004844
4845 for (h = lookup; h <= end - 3; h++) {
4846 if (memcmp(h, ";up", 3) == 0) {
4847 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4848 break;
4849 }
4850 }
4851
4852 if (uri_auth->refresh) {
4853 for (h = lookup; h <= end - 10; h++) {
4854 if (memcmp(h, ";norefresh", 10) == 0) {
4855 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4856 break;
4857 }
4858 }
4859 }
4860
4861 for (h = lookup; h <= end - 4; h++) {
4862 if (memcmp(h, ";csv", 4) == 0) {
4863 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4864 break;
4865 }
4866 }
4867
4868 for (h = lookup; h <= end - 6; h++) {
4869 if (memcmp(h, ";typed", 6) == 0) {
4870 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4871 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4872 break;
4873 }
4874 }
4875
4876 for (h = lookup; h <= end - 8; h++) {
4877 if (memcmp(h, ";st=", 4) == 0) {
4878 int i;
4879 h += 4;
4880 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4881 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4882 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4883 appctx->ctx.stats.st_code = i;
4884 break;
4885 }
4886 }
4887 break;
4888 }
4889 }
4890
4891 appctx->ctx.stats.scope_str = 0;
4892 appctx->ctx.stats.scope_len = 0;
4893 for (h = lookup; h <= end - 8; h++) {
4894 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4895 int itx = 0;
4896 const char *h2;
4897 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4898 const char *err;
4899
4900 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4901 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004902 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4903 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004904 if (*h == ';' || *h == '&' || *h == ' ')
4905 break;
4906 itx++;
4907 h++;
4908 }
4909
4910 if (itx > STAT_SCOPE_TXT_MAXLEN)
4911 itx = STAT_SCOPE_TXT_MAXLEN;
4912 appctx->ctx.stats.scope_len = itx;
4913
4914 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4915 memcpy(scope_txt, h2, itx);
4916 scope_txt[itx] = '\0';
4917 err = invalid_char(scope_txt);
4918 if (err) {
4919 /* bad char in search text => clear scope */
4920 appctx->ctx.stats.scope_str = 0;
4921 appctx->ctx.stats.scope_len = 0;
4922 }
4923 break;
4924 }
4925 }
4926
4927 /* now check whether we have some admin rules for this request */
4928 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4929 int ret = 1;
4930
4931 if (stats_admin_rule->cond) {
4932 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4933 ret = acl_pass(ret);
4934 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4935 ret = !ret;
4936 }
4937
4938 if (ret) {
4939 /* no rule, or the rule matches */
4940 appctx->ctx.stats.flags |= STAT_ADMIN;
4941 break;
4942 }
4943 }
4944
4945 /* Was the status page requested with a POST ? */
4946 if (unlikely(txn->meth == HTTP_METH_POST)) {
4947 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4948 /* we'll need the request body, possibly after sending 100-continue */
4949 if (msg->msg_state < HTTP_MSG_DATA)
4950 req->analysers |= AN_REQ_HTTP_BODY;
4951 appctx->st0 = STAT_HTTP_POST;
4952 }
4953 else {
4954 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4955 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4956 appctx->st0 = STAT_HTTP_LAST;
4957 }
4958 }
4959 else {
4960 /* So it was another method (GET/HEAD) */
4961 appctx->st0 = STAT_HTTP_HEAD;
4962 }
4963
4964 s->task->nice = -32; /* small boost for HTTP statistics */
4965 return 1;
4966}
4967
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004968void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4969{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004970 struct channel *req = &s->req;
4971 struct channel *res = &s->res;
4972 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004973 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004974 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004975 struct ist path, location;
4976 unsigned int flags;
4977 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004978
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004979 /*
4980 * Create the location
4981 */
4982 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004983
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004984 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004985 /* special prefix "/" means don't change URL */
4986 srv = __objt_server(s->target);
4987 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4988 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4989 return;
4990 }
4991
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004992 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004993 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004994 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004995 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004996 if (!path.ptr)
4997 return;
4998
4999 if (!chunk_memcat(&trash, path.ptr, path.len))
5000 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005001 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005002
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005003 /*
5004 * Create the 302 respone
5005 */
5006 htx = htx_from_buf(&res->buf);
5007 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5008 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5009 ist("HTTP/1.1"), ist("302"), ist("Found"));
5010 if (!sl)
5011 goto fail;
5012 sl->info.res.status = 302;
5013 s->txn->status = 302;
5014
5015 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5016 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5017 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5018 !htx_add_header(htx, ist("Location"), location))
5019 goto fail;
5020
5021 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5022 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005023
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005024 /*
5025 * Send the message
5026 */
5027 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005028 c_adv(res, data);
5029 res->total += data;
5030
5031 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005032 si_shutr(si);
5033 si_shutw(si);
5034 si->err_type = SI_ET_NONE;
5035 si->state = SI_ST_CLO;
5036
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005037 channel_auto_read(req);
5038 channel_abort(req);
5039 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005040 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005041 channel_auto_read(res);
5042 channel_auto_close(res);
5043
5044 if (!(s->flags & SF_ERR_MASK))
5045 s->flags |= SF_ERR_LOCAL;
5046 if (!(s->flags & SF_FINST_MASK))
5047 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005048
5049 /* FIXME: we should increase a counter of redirects per server and per backend. */
5050 srv_inc_sess_ctr(srv);
5051 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005052 return;
5053
5054 fail:
5055 /* If an error occurred, remove the incomplete HTTP response from the
5056 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005057 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005058}
5059
Christopher Fauletf2824e62018-10-01 12:12:37 +02005060/* This function terminates the request because it was completly analyzed or
5061 * because an error was triggered during the body forwarding.
5062 */
5063static void htx_end_request(struct stream *s)
5064{
5065 struct channel *chn = &s->req;
5066 struct http_txn *txn = s->txn;
5067
5068 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5069 now_ms, __FUNCTION__, s,
5070 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5071 s->req.analysers, s->res.analysers);
5072
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005073 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5074 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005075 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005076 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005077 goto end;
5078 }
5079
5080 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5081 return;
5082
5083 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005084 /* No need to read anymore, the request was completely parsed.
5085 * We can shut the read side unless we want to abort_on_close,
5086 * or we have a POST request. The issue with POST requests is
5087 * that some browsers still send a CRLF after the request, and
5088 * this CRLF must be read so that it does not remain in the kernel
5089 * buffers, otherwise a close could cause an RST on some systems
5090 * (eg: Linux).
5091 */
5092 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5093 txn->meth != HTTP_METH_POST)
5094 channel_dont_read(chn);
5095
5096 /* if the server closes the connection, we want to immediately react
5097 * and close the socket to save packets and syscalls.
5098 */
5099 s->si[1].flags |= SI_FL_NOHALF;
5100
5101 /* In any case we've finished parsing the request so we must
5102 * disable Nagle when sending data because 1) we're not going
5103 * to shut this side, and 2) the server is waiting for us to
5104 * send pending data.
5105 */
5106 chn->flags |= CF_NEVER_WAIT;
5107
Christopher Fauletd01ce402019-01-02 17:44:13 +01005108 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5109 /* The server has not finished to respond, so we
5110 * don't want to move in order not to upset it.
5111 */
5112 return;
5113 }
5114
Christopher Fauletf2824e62018-10-01 12:12:37 +02005115 /* When we get here, it means that both the request and the
5116 * response have finished receiving. Depending on the connection
5117 * mode, we'll have to wait for the last bytes to leave in either
5118 * direction, and sometimes for a close to be effective.
5119 */
5120 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5121 /* Tunnel mode will not have any analyser so it needs to
5122 * poll for reads.
5123 */
5124 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005125 if (b_data(&chn->buf))
5126 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005127 txn->req.msg_state = HTTP_MSG_TUNNEL;
5128 }
5129 else {
5130 /* we're not expecting any new data to come for this
5131 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005132 *
5133 * However, there is an exception if the response
5134 * length is undefined. In this case, we need to wait
5135 * the close from the server. The response will be
5136 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005137 */
5138 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5139 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005140 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005141
5142 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5143 channel_shutr_now(chn);
5144 channel_shutw_now(chn);
5145 }
5146 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005147 goto check_channel_flags;
5148 }
5149
5150 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5151 http_msg_closing:
5152 /* nothing else to forward, just waiting for the output buffer
5153 * to be empty and for the shutw_now to take effect.
5154 */
5155 if (channel_is_empty(chn)) {
5156 txn->req.msg_state = HTTP_MSG_CLOSED;
5157 goto http_msg_closed;
5158 }
5159 else if (chn->flags & CF_SHUTW) {
5160 txn->req.err_state = txn->req.msg_state;
5161 txn->req.msg_state = HTTP_MSG_ERROR;
5162 goto end;
5163 }
5164 return;
5165 }
5166
5167 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5168 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005169 /* if we don't know whether the server will close, we need to hard close */
5170 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5171 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005172 /* see above in MSG_DONE why we only do this in these states */
5173 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5174 channel_dont_read(chn);
5175 goto end;
5176 }
5177
5178 check_channel_flags:
5179 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5180 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5181 /* if we've just closed an output, let's switch */
5182 txn->req.msg_state = HTTP_MSG_CLOSING;
5183 goto http_msg_closing;
5184 }
5185
5186 end:
5187 chn->analysers &= AN_REQ_FLT_END;
5188 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5189 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5190 channel_auto_close(chn);
5191 channel_auto_read(chn);
5192}
5193
5194
5195/* This function terminates the response because it was completly analyzed or
5196 * because an error was triggered during the body forwarding.
5197 */
5198static void htx_end_response(struct stream *s)
5199{
5200 struct channel *chn = &s->res;
5201 struct http_txn *txn = s->txn;
5202
5203 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5204 now_ms, __FUNCTION__, s,
5205 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5206 s->req.analysers, s->res.analysers);
5207
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005208 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5209 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005210 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005211 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005212 goto end;
5213 }
5214
5215 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5216 return;
5217
5218 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5219 /* In theory, we don't need to read anymore, but we must
5220 * still monitor the server connection for a possible close
5221 * while the request is being uploaded, so we don't disable
5222 * reading.
5223 */
5224 /* channel_dont_read(chn); */
5225
5226 if (txn->req.msg_state < HTTP_MSG_DONE) {
5227 /* The client seems to still be sending data, probably
5228 * because we got an error response during an upload.
5229 * We have the choice of either breaking the connection
5230 * or letting it pass through. Let's do the later.
5231 */
5232 return;
5233 }
5234
5235 /* When we get here, it means that both the request and the
5236 * response have finished receiving. Depending on the connection
5237 * mode, we'll have to wait for the last bytes to leave in either
5238 * direction, and sometimes for a close to be effective.
5239 */
5240 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5241 channel_auto_read(chn);
5242 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005243 if (b_data(&chn->buf))
5244 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005245 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5246 }
5247 else {
5248 /* we're not expecting any new data to come for this
5249 * transaction, so we can close it.
5250 */
5251 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5252 channel_shutr_now(chn);
5253 channel_shutw_now(chn);
5254 }
5255 }
5256 goto check_channel_flags;
5257 }
5258
5259 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5260 http_msg_closing:
5261 /* nothing else to forward, just waiting for the output buffer
5262 * to be empty and for the shutw_now to take effect.
5263 */
5264 if (channel_is_empty(chn)) {
5265 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5266 goto http_msg_closed;
5267 }
5268 else if (chn->flags & CF_SHUTW) {
5269 txn->rsp.err_state = txn->rsp.msg_state;
5270 txn->rsp.msg_state = HTTP_MSG_ERROR;
5271 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5272 if (objt_server(s->target))
5273 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5274 goto end;
5275 }
5276 return;
5277 }
5278
5279 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5280 http_msg_closed:
5281 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005282 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005283 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005284 goto end;
5285 }
5286
5287 check_channel_flags:
5288 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5289 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5290 /* if we've just closed an output, let's switch */
5291 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5292 goto http_msg_closing;
5293 }
5294
5295 end:
5296 chn->analysers &= AN_RES_FLT_END;
5297 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5298 chn->analysers |= AN_RES_FLT_XFER_DATA;
5299 channel_auto_close(chn);
5300 channel_auto_read(chn);
5301}
5302
Christopher Faulet0f226952018-10-22 09:29:56 +02005303void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5304 int finst, const struct buffer *msg)
5305{
5306 channel_auto_read(si_oc(si));
5307 channel_abort(si_oc(si));
5308 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005309 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005310 channel_auto_close(si_ic(si));
5311 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005312
5313 /* <msg> is an HTX structure. So we copy it in the response's
5314 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005315 if (msg) {
5316 struct channel *chn = si_ic(si);
5317 struct htx *htx;
5318
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005319 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005320 chn->buf.data = msg->data;
5321 memcpy(chn->buf.area, msg->area, msg->data);
5322 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005323 c_adv(chn, htx->data);
5324 chn->total += htx->data;
5325 }
5326 if (!(s->flags & SF_ERR_MASK))
5327 s->flags |= err;
5328 if (!(s->flags & SF_FINST_MASK))
5329 s->flags |= finst;
5330}
5331
5332void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5333{
5334 channel_auto_read(&s->req);
5335 channel_abort(&s->req);
5336 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005337 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5338 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005339
5340 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005341
5342 /* <msg> is an HTX structure. So we copy it in the response's
5343 * channel */
5344 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005345 if (msg) {
5346 struct channel *chn = &s->res;
5347 struct htx *htx;
5348
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005349 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005350 chn->buf.data = msg->data;
5351 memcpy(chn->buf.area, msg->area, msg->data);
5352 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005353 c_adv(chn, htx->data);
5354 chn->total += htx->data;
5355 }
5356
5357 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5358 channel_auto_read(&s->res);
5359 channel_auto_close(&s->res);
5360 channel_shutr_now(&s->res);
5361}
5362
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005363struct buffer *htx_error_message(struct stream *s)
5364{
5365 const int msgnum = http_get_status_idx(s->txn->status);
5366
5367 if (s->be->errmsg[msgnum].area)
5368 return &s->be->errmsg[msgnum];
5369 else if (strm_fe(s)->errmsg[msgnum].area)
5370 return &strm_fe(s)->errmsg[msgnum];
5371 else
5372 return &htx_err_chunks[msgnum];
5373}
5374
5375
Christopher Faulet23a3c792018-11-28 10:01:23 +01005376/* Send a 100-Continue response to the client. It returns 0 on success and -1
5377 * on error. The response channel is updated accordingly.
5378 */
5379static int htx_reply_100_continue(struct stream *s)
5380{
5381 struct channel *res = &s->res;
5382 struct htx *htx = htx_from_buf(&res->buf);
5383 struct htx_sl *sl;
5384 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5385 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5386 size_t data;
5387
5388 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5389 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5390 if (!sl)
5391 goto fail;
5392 sl->info.res.status = 100;
5393
5394 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5395 goto fail;
5396
5397 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005398 c_adv(res, data);
5399 res->total += data;
5400 return 0;
5401
5402 fail:
5403 /* If an error occurred, remove the incomplete HTTP response from the
5404 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005405 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005406 return -1;
5407}
5408
Christopher Faulet12c51e22018-11-28 15:59:42 +01005409
5410/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5411 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5412 * error. The response channel is updated accordingly.
5413 */
5414static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5415{
5416 struct channel *res = &s->res;
5417 struct htx *htx = htx_from_buf(&res->buf);
5418 struct htx_sl *sl;
5419 struct ist code, body;
5420 int status;
5421 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5422 size_t data;
5423
5424 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5425 status = 401;
5426 code = ist("401");
5427 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5428 "You need a valid user and password to access this content.\n"
5429 "</body></html>\n");
5430 }
5431 else {
5432 status = 407;
5433 code = ist("407");
5434 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5435 "You need a valid user and password to access this content.\n"
5436 "</body></html>\n");
5437 }
5438
5439 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5440 ist("HTTP/1.1"), code, ist("Unauthorized"));
5441 if (!sl)
5442 goto fail;
5443 sl->info.res.status = status;
5444 s->txn->status = status;
5445
5446 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5447 goto fail;
5448
5449 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5450 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005451 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5452 goto fail;
5453 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5454 goto fail;
5455 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005456 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005457 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5458 goto fail;
5459
5460 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005461 c_adv(res, data);
5462 res->total += data;
5463
5464 channel_auto_read(&s->req);
5465 channel_abort(&s->req);
5466 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005467 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005468
5469 res->wex = tick_add_ifset(now_ms, res->wto);
5470 channel_auto_read(res);
5471 channel_auto_close(res);
5472 channel_shutr_now(res);
5473 return 0;
5474
5475 fail:
5476 /* If an error occurred, remove the incomplete HTTP response from the
5477 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005478 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005479 return -1;
5480}
5481
Christopher Faulet0f226952018-10-22 09:29:56 +02005482/*
5483 * Capture headers from message <htx> according to header list <cap_hdr>, and
5484 * fill the <cap> pointers appropriately.
5485 */
5486static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5487{
5488 struct cap_hdr *h;
5489 int32_t pos;
5490
5491 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5492 struct htx_blk *blk = htx_get_blk(htx, pos);
5493 enum htx_blk_type type = htx_get_blk_type(blk);
5494 struct ist n, v;
5495
5496 if (type == HTX_BLK_EOH)
5497 break;
5498 if (type != HTX_BLK_HDR)
5499 continue;
5500
5501 n = htx_get_blk_name(htx, blk);
5502
5503 for (h = cap_hdr; h; h = h->next) {
5504 if (h->namelen && (h->namelen == n.len) &&
5505 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5506 if (cap[h->index] == NULL)
5507 cap[h->index] =
5508 pool_alloc(h->pool);
5509
5510 if (cap[h->index] == NULL) {
5511 ha_alert("HTTP capture : out of memory.\n");
5512 break;
5513 }
5514
5515 v = htx_get_blk_value(htx, blk);
5516 if (v.len > h->len)
5517 v.len = h->len;
5518
5519 memcpy(cap[h->index], v.ptr, v.len);
5520 cap[h->index][v.len]=0;
5521 }
5522 }
5523 }
5524}
5525
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005526/* Delete a value in a header between delimiters <from> and <next>. The header
5527 * itself is delimited by <start> and <end> pointers. The number of characters
5528 * displaced is returned, and the pointer to the first delimiter is updated if
5529 * required. The function tries as much as possible to respect the following
5530 * principles :
5531 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5532 * in which case <next> is simply removed
5533 * - set exactly one space character after the new first delimiter, unless there
5534 * are not enough characters in the block being moved to do so.
5535 * - remove unneeded spaces before the previous delimiter and after the new
5536 * one.
5537 *
5538 * It is the caller's responsibility to ensure that :
5539 * - <from> points to a valid delimiter or <start> ;
5540 * - <next> points to a valid delimiter or <end> ;
5541 * - there are non-space chars before <from>.
5542 */
5543static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5544{
5545 char *prev = *from;
5546
5547 if (prev == start) {
5548 /* We're removing the first value. eat the semicolon, if <next>
5549 * is lower than <end> */
5550 if (next < end)
5551 next++;
5552
5553 while (next < end && HTTP_IS_SPHT(*next))
5554 next++;
5555 }
5556 else {
5557 /* Remove useless spaces before the old delimiter. */
5558 while (HTTP_IS_SPHT(*(prev-1)))
5559 prev--;
5560 *from = prev;
5561
5562 /* copy the delimiter and if possible a space if we're
5563 * not at the end of the line.
5564 */
5565 if (next < end) {
5566 *prev++ = *next++;
5567 if (prev + 1 < next)
5568 *prev++ = ' ';
5569 while (next < end && HTTP_IS_SPHT(*next))
5570 next++;
5571 }
5572 }
5573 memmove(prev, next, end - next);
5574 return (prev - next);
5575}
5576
Christopher Faulet0f226952018-10-22 09:29:56 +02005577
5578/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005579 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005580 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005581static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005582{
5583 struct ist dst = ist2(str, 0);
5584
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005586 goto end;
5587 if (dst.len + 1 > len)
5588 goto end;
5589 dst.ptr[dst.len++] = ' ';
5590
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005591 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005592 goto end;
5593 if (dst.len + 1 > len)
5594 goto end;
5595 dst.ptr[dst.len++] = ' ';
5596
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005597 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005598 end:
5599 return dst.len;
5600}
5601
Christopher Fauletf0523542018-10-24 11:06:58 +02005602/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005603 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005604 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005605static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005606{
5607 struct ist dst = ist2(str, 0);
5608
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005609 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005610 goto end;
5611 if (dst.len + 1 > len)
5612 goto end;
5613 dst.ptr[dst.len++] = ' ';
5614
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005615 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005616 goto end;
5617 if (dst.len + 1 > len)
5618 goto end;
5619 dst.ptr[dst.len++] = ' ';
5620
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005621 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005622 end:
5623 return dst.len;
5624}
5625
5626
Christopher Faulet0f226952018-10-22 09:29:56 +02005627/*
5628 * Print a debug line with a start line.
5629 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005631{
5632 struct session *sess = strm_sess(s);
5633 int max;
5634
5635 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5636 dir,
5637 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5638 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5639
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005640 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005641 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005642 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005643 trash.area[trash.data++] = ' ';
5644
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005645 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005646 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005647 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005648 trash.area[trash.data++] = ' ';
5649
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005650 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005651 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005652 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005653 trash.area[trash.data++] = '\n';
5654
5655 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5656}
5657
5658/*
5659 * Print a debug line with a header.
5660 */
5661static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5662{
5663 struct session *sess = strm_sess(s);
5664 int max;
5665
5666 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5667 dir,
5668 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5669 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5670
5671 max = n.len;
5672 UBOUND(max, trash.size - trash.data - 3);
5673 chunk_memcat(&trash, n.ptr, max);
5674 trash.area[trash.data++] = ':';
5675 trash.area[trash.data++] = ' ';
5676
5677 max = v.len;
5678 UBOUND(max, trash.size - trash.data - 1);
5679 chunk_memcat(&trash, v.ptr, max);
5680 trash.area[trash.data++] = '\n';
5681
5682 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5683}
5684
5685
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005686__attribute__((constructor))
5687static void __htx_protocol_init(void)
5688{
5689}
5690
5691
5692/*
5693 * Local variables:
5694 * c-indent-level: 8
5695 * c-basic-offset: 8
5696 * End:
5697 */