blob: 59b7cb2738355f486cfeda3f8d438eb98355610b [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;
315 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
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;
1628 msg->flags |= ((sl->flags & HTX_SL_F_CHNK) ? HTTP_MSGF_TE_CHNK : HTTP_MSGF_CNT_LEN);
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
3505 chunk_memcat(hdr, n.ptr, n.len);
3506 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;
3537 if (!http_replace_header(htx, &ctx, n, v))
3538 return -1;
3539 if (!ctx.blk)
3540 goto end;
3541 pos = htx_get_blk_pos(htx, blk);
3542 break;
3543
3544 case ACT_REMOVE:
3545 ctx.blk = blk;
3546 ctx.value = v;
3547 if (!http_remove_header(htx, &ctx))
3548 return -1;
3549 if (!ctx.blk)
3550 goto end;
3551 pos = htx_get_blk_pos(htx, blk);
3552 goto next_hdr;
3553
3554 }
3555 }
3556 }
3557 end:
3558 return 0;
3559}
3560
3561/* Apply the filter to the request line.
3562 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3563 * or -1 if a replacement resulted in an invalid request line.
3564 * Since it can manage the switch to another backend, it updates the per-proxy
3565 * DENY stats.
3566 */
3567static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3568{
3569 struct http_txn *txn = s->txn;
3570 struct htx *htx;
3571 struct buffer *reqline = get_trash_chunk();
3572 int done;
3573
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003574 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003575
3576 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3577 return 1;
3578 else if (unlikely(txn->flags & TX_CLALLOW) &&
3579 (exp->action == ACT_ALLOW ||
3580 exp->action == ACT_DENY ||
3581 exp->action == ACT_TARPIT))
3582 return 0;
3583 else if (exp->action == ACT_REMOVE)
3584 return 0;
3585
3586 done = 0;
3587
3588 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3589
3590 /* Now we have the request line between cur_ptr and cur_end */
3591 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003592 struct htx_sl *sl = http_find_stline(htx);
3593 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003594 int len;
3595
3596 switch (exp->action) {
3597 case ACT_ALLOW:
3598 txn->flags |= TX_CLALLOW;
3599 done = 1;
3600 break;
3601
3602 case ACT_DENY:
3603 txn->flags |= TX_CLDENY;
3604 done = 1;
3605 break;
3606
3607 case ACT_TARPIT:
3608 txn->flags |= TX_CLTARPIT;
3609 done = 1;
3610 break;
3611
3612 case ACT_REPLACE:
3613 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3614 if (len < 0)
3615 return -1;
3616
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003617 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3618 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3619 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003620 return -1;
3621 done = 1;
3622 break;
3623 }
3624 }
3625 return done;
3626}
3627
3628/*
3629 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3630 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3631 * unparsable request. Since it can manage the switch to another backend, it
3632 * updates the per-proxy DENY stats.
3633 */
3634static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3635{
3636 struct session *sess = s->sess;
3637 struct http_txn *txn = s->txn;
3638 struct hdr_exp *exp;
3639
3640 for (exp = px->req_exp; exp; exp = exp->next) {
3641 int ret;
3642
3643 /*
3644 * The interleaving of transformations and verdicts
3645 * makes it difficult to decide to continue or stop
3646 * the evaluation.
3647 */
3648
3649 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3650 break;
3651
3652 if ((txn->flags & TX_CLALLOW) &&
3653 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3654 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3655 continue;
3656
3657 /* if this filter had a condition, evaluate it now and skip to
3658 * next filter if the condition does not match.
3659 */
3660 if (exp->cond) {
3661 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3662 ret = acl_pass(ret);
3663 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3664 ret = !ret;
3665
3666 if (!ret)
3667 continue;
3668 }
3669
3670 /* Apply the filter to the request line. */
3671 ret = htx_apply_filter_to_req_line(s, req, exp);
3672 if (unlikely(ret < 0))
3673 return -1;
3674
3675 if (likely(ret == 0)) {
3676 /* The filter did not match the request, it can be
3677 * iterated through all headers.
3678 */
3679 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3680 return -1;
3681 }
3682 }
3683 return 0;
3684}
3685
3686/* Iterate the same filter through all response headers contained in <res>.
3687 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3688 */
3689static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3690{
3691 struct http_txn *txn = s->txn;
3692 struct htx *htx;
3693 struct buffer *hdr = get_trash_chunk();
3694 int32_t pos;
3695
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003696 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003697
3698 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3699 struct htx_blk *blk = htx_get_blk(htx, pos);
3700 enum htx_blk_type type;
3701 struct ist n, v;
3702
3703 next_hdr:
3704 type = htx_get_blk_type(blk);
3705 if (type == HTX_BLK_EOH)
3706 break;
3707 if (type != HTX_BLK_HDR)
3708 continue;
3709
3710 if (unlikely(txn->flags & TX_SVDENY))
3711 return 1;
3712 else if (unlikely(txn->flags & TX_SVALLOW) &&
3713 (exp->action == ACT_ALLOW ||
3714 exp->action == ACT_DENY))
3715 return 0;
3716
3717 n = htx_get_blk_name(htx, blk);
3718 v = htx_get_blk_value(htx, blk);
3719
3720 chunk_memcat(hdr, n.ptr, n.len);
3721 hdr->area[hdr->data++] = ':';
3722 hdr->area[hdr->data++] = ' ';
3723 chunk_memcat(hdr, v.ptr, v.len);
3724
3725 /* Now we have one header in <hdr> */
3726
3727 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3728 struct http_hdr_ctx ctx;
3729 int len;
3730
3731 switch (exp->action) {
3732 case ACT_ALLOW:
3733 txn->flags |= TX_SVALLOW;
3734 goto end;
3735 break;
3736
3737 case ACT_DENY:
3738 txn->flags |= TX_SVDENY;
3739 goto end;
3740 break;
3741
3742 case ACT_REPLACE:
3743 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3744 if (len < 0)
3745 return -1;
3746
3747 http_parse_header(ist2(trash.area, len), &n, &v);
3748 ctx.blk = blk;
3749 ctx.value = v;
3750 if (!http_replace_header(htx, &ctx, n, v))
3751 return -1;
3752 if (!ctx.blk)
3753 goto end;
3754 pos = htx_get_blk_pos(htx, blk);
3755 break;
3756
3757 case ACT_REMOVE:
3758 ctx.blk = blk;
3759 ctx.value = v;
3760 if (!http_remove_header(htx, &ctx))
3761 return -1;
3762 if (!ctx.blk)
3763 goto end;
3764 pos = htx_get_blk_pos(htx, blk);
3765 goto next_hdr;
3766 }
3767 }
3768
3769 }
3770 end:
3771 return 0;
3772}
3773
3774/* Apply the filter to the status line in the response buffer <res>.
3775 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3776 * or -1 if a replacement resulted in an invalid status line.
3777 */
3778static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3779{
3780 struct http_txn *txn = s->txn;
3781 struct htx *htx;
3782 struct buffer *resline = get_trash_chunk();
3783 int done;
3784
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003785 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003786
3787 if (unlikely(txn->flags & TX_SVDENY))
3788 return 1;
3789 else if (unlikely(txn->flags & TX_SVALLOW) &&
3790 (exp->action == ACT_ALLOW ||
3791 exp->action == ACT_DENY))
3792 return 0;
3793 else if (exp->action == ACT_REMOVE)
3794 return 0;
3795
3796 done = 0;
3797 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3798
3799 /* Now we have the status line between cur_ptr and cur_end */
3800 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003801 struct htx_sl *sl = http_find_stline(htx);
3802 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003803 int len;
3804
3805 switch (exp->action) {
3806 case ACT_ALLOW:
3807 txn->flags |= TX_SVALLOW;
3808 done = 1;
3809 break;
3810
3811 case ACT_DENY:
3812 txn->flags |= TX_SVDENY;
3813 done = 1;
3814 break;
3815
3816 case ACT_REPLACE:
3817 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3818 if (len < 0)
3819 return -1;
3820
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003821 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3822 sl->info.res.status = strl2ui(code.ptr, code.len);
3823 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003824 return -1;
3825
3826 done = 1;
3827 return 1;
3828 }
3829 }
3830 return done;
3831}
3832
3833/*
3834 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3835 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3836 * unparsable response.
3837 */
3838static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3839{
3840 struct session *sess = s->sess;
3841 struct http_txn *txn = s->txn;
3842 struct hdr_exp *exp;
3843
3844 for (exp = px->rsp_exp; exp; exp = exp->next) {
3845 int ret;
3846
3847 /*
3848 * The interleaving of transformations and verdicts
3849 * makes it difficult to decide to continue or stop
3850 * the evaluation.
3851 */
3852
3853 if (txn->flags & TX_SVDENY)
3854 break;
3855
3856 if ((txn->flags & TX_SVALLOW) &&
3857 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3858 exp->action == ACT_PASS)) {
3859 exp = exp->next;
3860 continue;
3861 }
3862
3863 /* if this filter had a condition, evaluate it now and skip to
3864 * next filter if the condition does not match.
3865 */
3866 if (exp->cond) {
3867 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3868 ret = acl_pass(ret);
3869 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3870 ret = !ret;
3871 if (!ret)
3872 continue;
3873 }
3874
3875 /* Apply the filter to the status line. */
3876 ret = htx_apply_filter_to_sts_line(s, res, exp);
3877 if (unlikely(ret < 0))
3878 return -1;
3879
3880 if (likely(ret == 0)) {
3881 /* The filter did not match the response, it can be
3882 * iterated through all headers.
3883 */
3884 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3885 return -1;
3886 }
3887 }
3888 return 0;
3889}
3890
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003891/*
3892 * Manage client-side cookie. It can impact performance by about 2% so it is
3893 * desirable to call it only when needed. This code is quite complex because
3894 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3895 * highly recommended not to touch this part without a good reason !
3896 */
3897static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3898{
3899 struct session *sess = s->sess;
3900 struct http_txn *txn = s->txn;
3901 struct htx *htx;
3902 struct http_hdr_ctx ctx;
3903 char *hdr_beg, *hdr_end, *del_from;
3904 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3905 int preserve_hdr;
3906
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003907 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003908 ctx.blk = NULL;
3909 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3910 del_from = NULL; /* nothing to be deleted */
3911 preserve_hdr = 0; /* assume we may kill the whole header */
3912
3913 /* Now look for cookies. Conforming to RFC2109, we have to support
3914 * attributes whose name begin with a '$', and associate them with
3915 * the right cookie, if we want to delete this cookie.
3916 * So there are 3 cases for each cookie read :
3917 * 1) it's a special attribute, beginning with a '$' : ignore it.
3918 * 2) it's a server id cookie that we *MAY* want to delete : save
3919 * some pointers on it (last semi-colon, beginning of cookie...)
3920 * 3) it's an application cookie : we *MAY* have to delete a previous
3921 * "special" cookie.
3922 * At the end of loop, if a "special" cookie remains, we may have to
3923 * remove it. If no application cookie persists in the header, we
3924 * *MUST* delete it.
3925 *
3926 * Note: RFC2965 is unclear about the processing of spaces around
3927 * the equal sign in the ATTR=VALUE form. A careful inspection of
3928 * the RFC explicitly allows spaces before it, and not within the
3929 * tokens (attrs or values). An inspection of RFC2109 allows that
3930 * too but section 10.1.3 lets one think that spaces may be allowed
3931 * after the equal sign too, resulting in some (rare) buggy
3932 * implementations trying to do that. So let's do what servers do.
3933 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3934 * allowed quoted strings in values, with any possible character
3935 * after a backslash, including control chars and delimitors, which
3936 * causes parsing to become ambiguous. Browsers also allow spaces
3937 * within values even without quotes.
3938 *
3939 * We have to keep multiple pointers in order to support cookie
3940 * removal at the beginning, middle or end of header without
3941 * corrupting the header. All of these headers are valid :
3942 *
3943 * hdr_beg hdr_end
3944 * | |
3945 * v |
3946 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3947 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3948 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3949 * | | | | | | |
3950 * | | | | | | |
3951 * | | | | | | +--> next
3952 * | | | | | +----> val_end
3953 * | | | | +-----------> val_beg
3954 * | | | +--------------> equal
3955 * | | +----------------> att_end
3956 * | +---------------------> att_beg
3957 * +--------------------------> prev
3958 *
3959 */
3960 hdr_beg = ctx.value.ptr;
3961 hdr_end = hdr_beg + ctx.value.len;
3962 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3963 /* Iterate through all cookies on this line */
3964
3965 /* find att_beg */
3966 att_beg = prev;
3967 if (prev > hdr_beg)
3968 att_beg++;
3969
3970 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3971 att_beg++;
3972
3973 /* find att_end : this is the first character after the last non
3974 * space before the equal. It may be equal to hdr_end.
3975 */
3976 equal = att_end = att_beg;
3977 while (equal < hdr_end) {
3978 if (*equal == '=' || *equal == ',' || *equal == ';')
3979 break;
3980 if (HTTP_IS_SPHT(*equal++))
3981 continue;
3982 att_end = equal;
3983 }
3984
3985 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3986 * is between <att_beg> and <equal>, both may be identical.
3987 */
3988 /* look for end of cookie if there is an equal sign */
3989 if (equal < hdr_end && *equal == '=') {
3990 /* look for the beginning of the value */
3991 val_beg = equal + 1;
3992 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3993 val_beg++;
3994
3995 /* find the end of the value, respecting quotes */
3996 next = http_find_cookie_value_end(val_beg, hdr_end);
3997
3998 /* make val_end point to the first white space or delimitor after the value */
3999 val_end = next;
4000 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4001 val_end--;
4002 }
4003 else
4004 val_beg = val_end = next = equal;
4005
4006 /* We have nothing to do with attributes beginning with
4007 * '$'. However, they will automatically be removed if a
4008 * header before them is removed, since they're supposed
4009 * to be linked together.
4010 */
4011 if (*att_beg == '$')
4012 continue;
4013
4014 /* Ignore cookies with no equal sign */
4015 if (equal == next) {
4016 /* This is not our cookie, so we must preserve it. But if we already
4017 * scheduled another cookie for removal, we cannot remove the
4018 * complete header, but we can remove the previous block itself.
4019 */
4020 preserve_hdr = 1;
4021 if (del_from != NULL) {
4022 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4023 val_end += delta;
4024 next += delta;
4025 hdr_end += delta;
4026 prev = del_from;
4027 del_from = NULL;
4028 }
4029 continue;
4030 }
4031
4032 /* if there are spaces around the equal sign, we need to
4033 * strip them otherwise we'll get trouble for cookie captures,
4034 * or even for rewrites. Since this happens extremely rarely,
4035 * it does not hurt performance.
4036 */
4037 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4038 int stripped_before = 0;
4039 int stripped_after = 0;
4040
4041 if (att_end != equal) {
4042 memmove(att_end, equal, hdr_end - equal);
4043 stripped_before = (att_end - equal);
4044 equal += stripped_before;
4045 val_beg += stripped_before;
4046 }
4047
4048 if (val_beg > equal + 1) {
4049 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4050 stripped_after = (equal + 1) - val_beg;
4051 val_beg += stripped_after;
4052 stripped_before += stripped_after;
4053 }
4054
4055 val_end += stripped_before;
4056 next += stripped_before;
4057 hdr_end += stripped_before;
4058 }
4059 /* now everything is as on the diagram above */
4060
4061 /* First, let's see if we want to capture this cookie. We check
4062 * that we don't already have a client side cookie, because we
4063 * can only capture one. Also as an optimisation, we ignore
4064 * cookies shorter than the declared name.
4065 */
4066 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4067 (val_end - att_beg >= sess->fe->capture_namelen) &&
4068 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4069 int log_len = val_end - att_beg;
4070
4071 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4072 ha_alert("HTTP logging : out of memory.\n");
4073 } else {
4074 if (log_len > sess->fe->capture_len)
4075 log_len = sess->fe->capture_len;
4076 memcpy(txn->cli_cookie, att_beg, log_len);
4077 txn->cli_cookie[log_len] = 0;
4078 }
4079 }
4080
4081 /* Persistence cookies in passive, rewrite or insert mode have the
4082 * following form :
4083 *
4084 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4085 *
4086 * For cookies in prefix mode, the form is :
4087 *
4088 * Cookie: NAME=SRV~VALUE
4089 */
4090 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4091 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4092 struct server *srv = s->be->srv;
4093 char *delim;
4094
4095 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4096 * have the server ID between val_beg and delim, and the original cookie between
4097 * delim+1 and val_end. Otherwise, delim==val_end :
4098 *
4099 * hdr_beg
4100 * |
4101 * v
4102 * NAME=SRV; # in all but prefix modes
4103 * NAME=SRV~OPAQUE ; # in prefix mode
4104 * || || | |+-> next
4105 * || || | +--> val_end
4106 * || || +---------> delim
4107 * || |+------------> val_beg
4108 * || +-------------> att_end = equal
4109 * |+-----------------> att_beg
4110 * +------------------> prev
4111 *
4112 */
4113 if (s->be->ck_opts & PR_CK_PFX) {
4114 for (delim = val_beg; delim < val_end; delim++)
4115 if (*delim == COOKIE_DELIM)
4116 break;
4117 }
4118 else {
4119 char *vbar1;
4120 delim = val_end;
4121 /* Now check if the cookie contains a date field, which would
4122 * appear after a vertical bar ('|') just after the server name
4123 * and before the delimiter.
4124 */
4125 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4126 if (vbar1) {
4127 /* OK, so left of the bar is the server's cookie and
4128 * right is the last seen date. It is a base64 encoded
4129 * 30-bit value representing the UNIX date since the
4130 * epoch in 4-second quantities.
4131 */
4132 int val;
4133 delim = vbar1++;
4134 if (val_end - vbar1 >= 5) {
4135 val = b64tos30(vbar1);
4136 if (val > 0)
4137 txn->cookie_last_date = val << 2;
4138 }
4139 /* look for a second vertical bar */
4140 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4141 if (vbar1 && (val_end - vbar1 > 5)) {
4142 val = b64tos30(vbar1 + 1);
4143 if (val > 0)
4144 txn->cookie_first_date = val << 2;
4145 }
4146 }
4147 }
4148
4149 /* if the cookie has an expiration date and the proxy wants to check
4150 * it, then we do that now. We first check if the cookie is too old,
4151 * then only if it has expired. We detect strict overflow because the
4152 * time resolution here is not great (4 seconds). Cookies with dates
4153 * in the future are ignored if their offset is beyond one day. This
4154 * allows an admin to fix timezone issues without expiring everyone
4155 * and at the same time avoids keeping unwanted side effects for too
4156 * long.
4157 */
4158 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4159 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4160 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4161 txn->flags &= ~TX_CK_MASK;
4162 txn->flags |= TX_CK_OLD;
4163 delim = val_beg; // let's pretend we have not found the cookie
4164 txn->cookie_first_date = 0;
4165 txn->cookie_last_date = 0;
4166 }
4167 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4168 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4169 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4170 txn->flags &= ~TX_CK_MASK;
4171 txn->flags |= TX_CK_EXPIRED;
4172 delim = val_beg; // let's pretend we have not found the cookie
4173 txn->cookie_first_date = 0;
4174 txn->cookie_last_date = 0;
4175 }
4176
4177 /* Here, we'll look for the first running server which supports the cookie.
4178 * This allows to share a same cookie between several servers, for example
4179 * to dedicate backup servers to specific servers only.
4180 * However, to prevent clients from sticking to cookie-less backup server
4181 * when they have incidentely learned an empty cookie, we simply ignore
4182 * empty cookies and mark them as invalid.
4183 * The same behaviour is applied when persistence must be ignored.
4184 */
4185 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4186 srv = NULL;
4187
4188 while (srv) {
4189 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4190 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4191 if ((srv->cur_state != SRV_ST_STOPPED) ||
4192 (s->be->options & PR_O_PERSIST) ||
4193 (s->flags & SF_FORCE_PRST)) {
4194 /* we found the server and we can use it */
4195 txn->flags &= ~TX_CK_MASK;
4196 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4197 s->flags |= SF_DIRECT | SF_ASSIGNED;
4198 s->target = &srv->obj_type;
4199 break;
4200 } else {
4201 /* we found a server, but it's down,
4202 * mark it as such and go on in case
4203 * another one is available.
4204 */
4205 txn->flags &= ~TX_CK_MASK;
4206 txn->flags |= TX_CK_DOWN;
4207 }
4208 }
4209 srv = srv->next;
4210 }
4211
4212 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4213 /* no server matched this cookie or we deliberately skipped it */
4214 txn->flags &= ~TX_CK_MASK;
4215 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4216 txn->flags |= TX_CK_UNUSED;
4217 else
4218 txn->flags |= TX_CK_INVALID;
4219 }
4220
4221 /* depending on the cookie mode, we may have to either :
4222 * - delete the complete cookie if we're in insert+indirect mode, so that
4223 * the server never sees it ;
4224 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004225 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004226 * if we're in cookie prefix mode
4227 */
4228 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4229 int delta; /* negative */
4230
4231 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4232 delta = val_beg - (delim + 1);
4233 val_end += delta;
4234 next += delta;
4235 hdr_end += delta;
4236 del_from = NULL;
4237 preserve_hdr = 1; /* we want to keep this cookie */
4238 }
4239 else if (del_from == NULL &&
4240 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4241 del_from = prev;
4242 }
4243 }
4244 else {
4245 /* This is not our cookie, so we must preserve it. But if we already
4246 * scheduled another cookie for removal, we cannot remove the
4247 * complete header, but we can remove the previous block itself.
4248 */
4249 preserve_hdr = 1;
4250
4251 if (del_from != NULL) {
4252 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4253 if (att_beg >= del_from)
4254 att_beg += delta;
4255 if (att_end >= del_from)
4256 att_end += delta;
4257 val_beg += delta;
4258 val_end += delta;
4259 next += delta;
4260 hdr_end += delta;
4261 prev = del_from;
4262 del_from = NULL;
4263 }
4264 }
4265
4266 /* continue with next cookie on this header line */
4267 att_beg = next;
4268 } /* for each cookie */
4269
4270
4271 /* There are no more cookies on this line.
4272 * We may still have one (or several) marked for deletion at the
4273 * end of the line. We must do this now in two ways :
4274 * - if some cookies must be preserved, we only delete from the
4275 * mark to the end of line ;
4276 * - if nothing needs to be preserved, simply delete the whole header
4277 */
4278 if (del_from) {
4279 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4280 }
4281 if ((hdr_end - hdr_beg) != ctx.value.len) {
4282 if (hdr_beg != hdr_end) {
4283 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004284 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004285 }
4286 else
4287 http_remove_header(htx, &ctx);
4288 }
4289 } /* for each "Cookie header */
4290}
4291
4292/*
4293 * Manage server-side cookies. It can impact performance by about 2% so it is
4294 * desirable to call it only when needed. This function is also used when we
4295 * just need to know if there is a cookie (eg: for check-cache).
4296 */
4297static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4298{
4299 struct session *sess = s->sess;
4300 struct http_txn *txn = s->txn;
4301 struct htx *htx;
4302 struct http_hdr_ctx ctx;
4303 struct server *srv;
4304 char *hdr_beg, *hdr_end;
4305 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4306 int is_cookie2;
4307
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004308 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004309
4310 ctx.blk = NULL;
4311 while (1) {
4312 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4313 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4314 break;
4315 is_cookie2 = 1;
4316 }
4317
4318 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4319 * <prev> points to the colon.
4320 */
4321 txn->flags |= TX_SCK_PRESENT;
4322
4323 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4324 * check-cache is enabled) and we are not interested in checking
4325 * them. Warning, the cookie capture is declared in the frontend.
4326 */
4327 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4328 break;
4329
4330 /* OK so now we know we have to process this response cookie.
4331 * The format of the Set-Cookie header is slightly different
4332 * from the format of the Cookie header in that it does not
4333 * support the comma as a cookie delimiter (thus the header
4334 * cannot be folded) because the Expires attribute described in
4335 * the original Netscape's spec may contain an unquoted date
4336 * with a comma inside. We have to live with this because
4337 * many browsers don't support Max-Age and some browsers don't
4338 * support quoted strings. However the Set-Cookie2 header is
4339 * clean.
4340 *
4341 * We have to keep multiple pointers in order to support cookie
4342 * removal at the beginning, middle or end of header without
4343 * corrupting the header (in case of set-cookie2). A special
4344 * pointer, <scav> points to the beginning of the set-cookie-av
4345 * fields after the first semi-colon. The <next> pointer points
4346 * either to the end of line (set-cookie) or next unquoted comma
4347 * (set-cookie2). All of these headers are valid :
4348 *
4349 * hdr_beg hdr_end
4350 * | |
4351 * v |
4352 * NAME1 = VALUE 1 ; Secure; Path="/" |
4353 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4354 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4355 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4356 * | | | | | | | |
4357 * | | | | | | | +-> next
4358 * | | | | | | +------------> scav
4359 * | | | | | +--------------> val_end
4360 * | | | | +--------------------> val_beg
4361 * | | | +----------------------> equal
4362 * | | +------------------------> att_end
4363 * | +----------------------------> att_beg
4364 * +------------------------------> prev
4365 * -------------------------------> hdr_beg
4366 */
4367 hdr_beg = ctx.value.ptr;
4368 hdr_end = hdr_beg + ctx.value.len;
4369 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4370
4371 /* Iterate through all cookies on this line */
4372
4373 /* find att_beg */
4374 att_beg = prev;
4375 if (prev > hdr_beg)
4376 att_beg++;
4377
4378 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4379 att_beg++;
4380
4381 /* find att_end : this is the first character after the last non
4382 * space before the equal. It may be equal to hdr_end.
4383 */
4384 equal = att_end = att_beg;
4385
4386 while (equal < hdr_end) {
4387 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4388 break;
4389 if (HTTP_IS_SPHT(*equal++))
4390 continue;
4391 att_end = equal;
4392 }
4393
4394 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4395 * is between <att_beg> and <equal>, both may be identical.
4396 */
4397
4398 /* look for end of cookie if there is an equal sign */
4399 if (equal < hdr_end && *equal == '=') {
4400 /* look for the beginning of the value */
4401 val_beg = equal + 1;
4402 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4403 val_beg++;
4404
4405 /* find the end of the value, respecting quotes */
4406 next = http_find_cookie_value_end(val_beg, hdr_end);
4407
4408 /* make val_end point to the first white space or delimitor after the value */
4409 val_end = next;
4410 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4411 val_end--;
4412 }
4413 else {
4414 /* <equal> points to next comma, semi-colon or EOL */
4415 val_beg = val_end = next = equal;
4416 }
4417
4418 if (next < hdr_end) {
4419 /* Set-Cookie2 supports multiple cookies, and <next> points to
4420 * a colon or semi-colon before the end. So skip all attr-value
4421 * pairs and look for the next comma. For Set-Cookie, since
4422 * commas are permitted in values, skip to the end.
4423 */
4424 if (is_cookie2)
4425 next = http_find_hdr_value_end(next, hdr_end);
4426 else
4427 next = hdr_end;
4428 }
4429
4430 /* Now everything is as on the diagram above */
4431
4432 /* Ignore cookies with no equal sign */
4433 if (equal == val_end)
4434 continue;
4435
4436 /* If there are spaces around the equal sign, we need to
4437 * strip them otherwise we'll get trouble for cookie captures,
4438 * or even for rewrites. Since this happens extremely rarely,
4439 * it does not hurt performance.
4440 */
4441 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4442 int stripped_before = 0;
4443 int stripped_after = 0;
4444
4445 if (att_end != equal) {
4446 memmove(att_end, equal, hdr_end - equal);
4447 stripped_before = (att_end - equal);
4448 equal += stripped_before;
4449 val_beg += stripped_before;
4450 }
4451
4452 if (val_beg > equal + 1) {
4453 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4454 stripped_after = (equal + 1) - val_beg;
4455 val_beg += stripped_after;
4456 stripped_before += stripped_after;
4457 }
4458
4459 val_end += stripped_before;
4460 next += stripped_before;
4461 hdr_end += stripped_before;
4462
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004463 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4464 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004465 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004466 }
4467
4468 /* First, let's see if we want to capture this cookie. We check
4469 * that we don't already have a server side cookie, because we
4470 * can only capture one. Also as an optimisation, we ignore
4471 * cookies shorter than the declared name.
4472 */
4473 if (sess->fe->capture_name != NULL &&
4474 txn->srv_cookie == NULL &&
4475 (val_end - att_beg >= sess->fe->capture_namelen) &&
4476 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4477 int log_len = val_end - att_beg;
4478 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4479 ha_alert("HTTP logging : out of memory.\n");
4480 }
4481 else {
4482 if (log_len > sess->fe->capture_len)
4483 log_len = sess->fe->capture_len;
4484 memcpy(txn->srv_cookie, att_beg, log_len);
4485 txn->srv_cookie[log_len] = 0;
4486 }
4487 }
4488
4489 srv = objt_server(s->target);
4490 /* now check if we need to process it for persistence */
4491 if (!(s->flags & SF_IGNORE_PRST) &&
4492 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4493 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4494 /* assume passive cookie by default */
4495 txn->flags &= ~TX_SCK_MASK;
4496 txn->flags |= TX_SCK_FOUND;
4497
4498 /* If the cookie is in insert mode on a known server, we'll delete
4499 * this occurrence because we'll insert another one later.
4500 * We'll delete it too if the "indirect" option is set and we're in
4501 * a direct access.
4502 */
4503 if (s->be->ck_opts & PR_CK_PSV) {
4504 /* The "preserve" flag was set, we don't want to touch the
4505 * server's cookie.
4506 */
4507 }
4508 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4509 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4510 /* this cookie must be deleted */
4511 if (prev == hdr_beg && next == hdr_end) {
4512 /* whole header */
4513 http_remove_header(htx, &ctx);
4514 /* note: while both invalid now, <next> and <hdr_end>
4515 * are still equal, so the for() will stop as expected.
4516 */
4517 } else {
4518 /* just remove the value */
4519 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4520 next = prev;
4521 hdr_end += delta;
4522 }
4523 txn->flags &= ~TX_SCK_MASK;
4524 txn->flags |= TX_SCK_DELETED;
4525 /* and go on with next cookie */
4526 }
4527 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4528 /* replace bytes val_beg->val_end with the cookie name associated
4529 * with this server since we know it.
4530 */
4531 int sliding, delta;
4532
4533 ctx.value = ist2(val_beg, val_end - val_beg);
4534 ctx.lws_before = ctx.lws_after = 0;
4535 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4536 delta = srv->cklen - (val_end - val_beg);
4537 sliding = (ctx.value.ptr - val_beg);
4538 hdr_beg += sliding;
4539 val_beg += sliding;
4540 next += sliding + delta;
4541 hdr_end += sliding + delta;
4542
4543 txn->flags &= ~TX_SCK_MASK;
4544 txn->flags |= TX_SCK_REPLACED;
4545 }
4546 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4547 /* insert the cookie name associated with this server
4548 * before existing cookie, and insert a delimiter between them..
4549 */
4550 int sliding, delta;
4551 ctx.value = ist2(val_beg, 0);
4552 ctx.lws_before = ctx.lws_after = 0;
4553 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4554 delta = srv->cklen + 1;
4555 sliding = (ctx.value.ptr - val_beg);
4556 hdr_beg += sliding;
4557 val_beg += sliding;
4558 next += sliding + delta;
4559 hdr_end += sliding + delta;
4560
4561 val_beg[srv->cklen] = COOKIE_DELIM;
4562 txn->flags &= ~TX_SCK_MASK;
4563 txn->flags |= TX_SCK_REPLACED;
4564 }
4565 }
4566 /* that's done for this cookie, check the next one on the same
4567 * line when next != hdr_end (only if is_cookie2).
4568 */
4569 }
4570 }
4571}
4572
Christopher Faulet25a02f62018-10-24 12:00:25 +02004573/*
4574 * Parses the Cache-Control and Pragma request header fields to determine if
4575 * the request may be served from the cache and/or if it is cacheable. Updates
4576 * s->txn->flags.
4577 */
4578void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4579{
4580 struct http_txn *txn = s->txn;
4581 struct htx *htx;
4582 int32_t pos;
4583 int pragma_found, cc_found, i;
4584
4585 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4586 return; /* nothing more to do here */
4587
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004588 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004589 pragma_found = cc_found = 0;
4590 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4591 struct htx_blk *blk = htx_get_blk(htx, pos);
4592 enum htx_blk_type type = htx_get_blk_type(blk);
4593 struct ist n, v;
4594
4595 if (type == HTX_BLK_EOH)
4596 break;
4597 if (type != HTX_BLK_HDR)
4598 continue;
4599
4600 n = htx_get_blk_name(htx, blk);
4601 v = htx_get_blk_value(htx, blk);
4602
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004603 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004604 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4605 pragma_found = 1;
4606 continue;
4607 }
4608 }
4609
4610 /* Don't use the cache and don't try to store if we found the
4611 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004612 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004613 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4614 txn->flags |= TX_CACHE_IGNORE;
4615 continue;
4616 }
4617
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004618 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004619 continue;
4620
4621 /* OK, right now we know we have a cache-control header */
4622 cc_found = 1;
4623 if (!v.len) /* no info */
4624 continue;
4625
4626 i = 0;
4627 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4628 !isspace((unsigned char)*(v.ptr+i)))
4629 i++;
4630
4631 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4632 * values after max-age, max-stale nor min-fresh, we simply don't
4633 * use the cache when they're specified.
4634 */
4635 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4636 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4637 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4638 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4639 txn->flags |= TX_CACHE_IGNORE;
4640 continue;
4641 }
4642
4643 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4644 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4645 continue;
4646 }
4647 }
4648
4649 /* RFC7234#5.4:
4650 * When the Cache-Control header field is also present and
4651 * understood in a request, Pragma is ignored.
4652 * When the Cache-Control header field is not present in a
4653 * request, caches MUST consider the no-cache request
4654 * pragma-directive as having the same effect as if
4655 * "Cache-Control: no-cache" were present.
4656 */
4657 if (!cc_found && pragma_found)
4658 txn->flags |= TX_CACHE_IGNORE;
4659}
4660
4661/*
4662 * Check if response is cacheable or not. Updates s->txn->flags.
4663 */
4664void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4665{
4666 struct http_txn *txn = s->txn;
4667 struct htx *htx;
4668 int32_t pos;
4669 int i;
4670
4671 if (txn->status < 200) {
4672 /* do not try to cache interim responses! */
4673 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4674 return;
4675 }
4676
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004677 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004678 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4679 struct htx_blk *blk = htx_get_blk(htx, pos);
4680 enum htx_blk_type type = htx_get_blk_type(blk);
4681 struct ist n, v;
4682
4683 if (type == HTX_BLK_EOH)
4684 break;
4685 if (type != HTX_BLK_HDR)
4686 continue;
4687
4688 n = htx_get_blk_name(htx, blk);
4689 v = htx_get_blk_value(htx, blk);
4690
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004691 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004692 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4693 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4694 return;
4695 }
4696 }
4697
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004698 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004699 continue;
4700
4701 /* OK, right now we know we have a cache-control header */
4702 if (!v.len) /* no info */
4703 continue;
4704
4705 i = 0;
4706 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4707 !isspace((unsigned char)*(v.ptr+i)))
4708 i++;
4709
4710 /* we have a complete value between v.ptr and (v.ptr+i) */
4711 if (i < v.len && *(v.ptr + i) == '=') {
4712 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4713 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4714 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4715 continue;
4716 }
4717
4718 /* we have something of the form no-cache="set-cookie" */
4719 if ((v.len >= 21) &&
4720 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4721 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4722 txn->flags &= ~TX_CACHE_COOK;
4723 continue;
4724 }
4725
4726 /* OK, so we know that either p2 points to the end of string or to a comma */
4727 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4728 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4729 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4730 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4731 return;
4732 }
4733
4734 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4735 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4736 continue;
4737 }
4738 }
4739}
4740
Christopher Faulet64159df2018-10-24 21:15:35 +02004741/* send a server's name with an outgoing request over an established connection.
4742 * Note: this function is designed to be called once the request has been
4743 * scheduled for being forwarded. This is the reason why the number of forwarded
4744 * bytes have to be adjusted.
4745 */
4746int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4747{
4748 struct htx *htx;
4749 struct http_hdr_ctx ctx;
4750 struct ist hdr;
4751 uint32_t data;
4752
4753 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004754 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004755 data = htx->data;
4756
4757 ctx.blk = NULL;
4758 while (http_find_header(htx, hdr, &ctx, 1))
4759 http_remove_header(htx, &ctx);
4760 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4761
4762 if (co_data(&s->req)) {
4763 if (data >= htx->data)
4764 c_rew(&s->req, data - htx->data);
4765 else
4766 c_adv(&s->req, htx->data - data);
4767 }
4768 return 0;
4769}
4770
Christopher Faulet377c5a52018-10-24 21:21:30 +02004771/*
4772 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4773 * for the current backend.
4774 *
4775 * It is assumed that the request is either a HEAD, GET, or POST and that the
4776 * uri_auth field is valid.
4777 *
4778 * Returns 1 if stats should be provided, otherwise 0.
4779 */
4780static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4781{
4782 struct uri_auth *uri_auth = backend->uri_auth;
4783 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004784 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004785 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004786
4787 if (!uri_auth)
4788 return 0;
4789
4790 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4791 return 0;
4792
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004793 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004794 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004795 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004796
4797 /* check URI size */
4798 if (uri_auth->uri_len > uri.len)
4799 return 0;
4800
4801 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4802 return 0;
4803
4804 return 1;
4805}
4806
4807/* This function prepares an applet to handle the stats. It can deal with the
4808 * "100-continue" expectation, check that admin rules are met for POST requests,
4809 * and program a response message if something was unexpected. It cannot fail
4810 * and always relies on the stats applet to complete the job. It does not touch
4811 * analysers nor counters, which are left to the caller. It does not touch
4812 * s->target which is supposed to already point to the stats applet. The caller
4813 * is expected to have already assigned an appctx to the stream.
4814 */
4815static int htx_handle_stats(struct stream *s, struct channel *req)
4816{
4817 struct stats_admin_rule *stats_admin_rule;
4818 struct stream_interface *si = &s->si[1];
4819 struct session *sess = s->sess;
4820 struct http_txn *txn = s->txn;
4821 struct http_msg *msg = &txn->req;
4822 struct uri_auth *uri_auth = s->be->uri_auth;
4823 const char *h, *lookup, *end;
4824 struct appctx *appctx;
4825 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004826 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004827
4828 appctx = si_appctx(si);
4829 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4830 appctx->st1 = appctx->st2 = 0;
4831 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4832 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4833 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4834 appctx->ctx.stats.flags |= STAT_CHUNKED;
4835
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004836 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004837 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004838 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4839 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004840
4841 for (h = lookup; h <= end - 3; h++) {
4842 if (memcmp(h, ";up", 3) == 0) {
4843 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4844 break;
4845 }
4846 }
4847
4848 if (uri_auth->refresh) {
4849 for (h = lookup; h <= end - 10; h++) {
4850 if (memcmp(h, ";norefresh", 10) == 0) {
4851 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4852 break;
4853 }
4854 }
4855 }
4856
4857 for (h = lookup; h <= end - 4; h++) {
4858 if (memcmp(h, ";csv", 4) == 0) {
4859 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4860 break;
4861 }
4862 }
4863
4864 for (h = lookup; h <= end - 6; h++) {
4865 if (memcmp(h, ";typed", 6) == 0) {
4866 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4867 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4868 break;
4869 }
4870 }
4871
4872 for (h = lookup; h <= end - 8; h++) {
4873 if (memcmp(h, ";st=", 4) == 0) {
4874 int i;
4875 h += 4;
4876 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4877 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4878 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4879 appctx->ctx.stats.st_code = i;
4880 break;
4881 }
4882 }
4883 break;
4884 }
4885 }
4886
4887 appctx->ctx.stats.scope_str = 0;
4888 appctx->ctx.stats.scope_len = 0;
4889 for (h = lookup; h <= end - 8; h++) {
4890 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4891 int itx = 0;
4892 const char *h2;
4893 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4894 const char *err;
4895
4896 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4897 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004898 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4899 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004900 if (*h == ';' || *h == '&' || *h == ' ')
4901 break;
4902 itx++;
4903 h++;
4904 }
4905
4906 if (itx > STAT_SCOPE_TXT_MAXLEN)
4907 itx = STAT_SCOPE_TXT_MAXLEN;
4908 appctx->ctx.stats.scope_len = itx;
4909
4910 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4911 memcpy(scope_txt, h2, itx);
4912 scope_txt[itx] = '\0';
4913 err = invalid_char(scope_txt);
4914 if (err) {
4915 /* bad char in search text => clear scope */
4916 appctx->ctx.stats.scope_str = 0;
4917 appctx->ctx.stats.scope_len = 0;
4918 }
4919 break;
4920 }
4921 }
4922
4923 /* now check whether we have some admin rules for this request */
4924 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4925 int ret = 1;
4926
4927 if (stats_admin_rule->cond) {
4928 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4929 ret = acl_pass(ret);
4930 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4931 ret = !ret;
4932 }
4933
4934 if (ret) {
4935 /* no rule, or the rule matches */
4936 appctx->ctx.stats.flags |= STAT_ADMIN;
4937 break;
4938 }
4939 }
4940
4941 /* Was the status page requested with a POST ? */
4942 if (unlikely(txn->meth == HTTP_METH_POST)) {
4943 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4944 /* we'll need the request body, possibly after sending 100-continue */
4945 if (msg->msg_state < HTTP_MSG_DATA)
4946 req->analysers |= AN_REQ_HTTP_BODY;
4947 appctx->st0 = STAT_HTTP_POST;
4948 }
4949 else {
4950 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4951 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4952 appctx->st0 = STAT_HTTP_LAST;
4953 }
4954 }
4955 else {
4956 /* So it was another method (GET/HEAD) */
4957 appctx->st0 = STAT_HTTP_HEAD;
4958 }
4959
4960 s->task->nice = -32; /* small boost for HTTP statistics */
4961 return 1;
4962}
4963
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004964void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4965{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004966 struct channel *req = &s->req;
4967 struct channel *res = &s->res;
4968 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004969 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004970 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004971 struct ist path, location;
4972 unsigned int flags;
4973 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004974
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004975 /*
4976 * Create the location
4977 */
4978 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004979
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004980 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004981 /* special prefix "/" means don't change URL */
4982 srv = __objt_server(s->target);
4983 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4984 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4985 return;
4986 }
4987
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004988 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004989 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004990 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004991 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004992 if (!path.ptr)
4993 return;
4994
4995 if (!chunk_memcat(&trash, path.ptr, path.len))
4996 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004997 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004998
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004999 /*
5000 * Create the 302 respone
5001 */
5002 htx = htx_from_buf(&res->buf);
5003 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5004 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5005 ist("HTTP/1.1"), ist("302"), ist("Found"));
5006 if (!sl)
5007 goto fail;
5008 sl->info.res.status = 302;
5009 s->txn->status = 302;
5010
5011 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5012 !htx_add_header(htx, ist("Connection"), ist("close")) ||
5013 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
5014 !htx_add_header(htx, ist("Location"), location))
5015 goto fail;
5016
5017 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5018 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005019
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005020 /*
5021 * Send the message
5022 */
5023 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005024 c_adv(res, data);
5025 res->total += data;
5026
5027 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028 si_shutr(si);
5029 si_shutw(si);
5030 si->err_type = SI_ET_NONE;
5031 si->state = SI_ST_CLO;
5032
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005033 channel_auto_read(req);
5034 channel_abort(req);
5035 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005036 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005037 channel_auto_read(res);
5038 channel_auto_close(res);
5039
5040 if (!(s->flags & SF_ERR_MASK))
5041 s->flags |= SF_ERR_LOCAL;
5042 if (!(s->flags & SF_FINST_MASK))
5043 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005044
5045 /* FIXME: we should increase a counter of redirects per server and per backend. */
5046 srv_inc_sess_ctr(srv);
5047 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005048 return;
5049
5050 fail:
5051 /* If an error occurred, remove the incomplete HTTP response from the
5052 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005053 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005054}
5055
Christopher Fauletf2824e62018-10-01 12:12:37 +02005056/* This function terminates the request because it was completly analyzed or
5057 * because an error was triggered during the body forwarding.
5058 */
5059static void htx_end_request(struct stream *s)
5060{
5061 struct channel *chn = &s->req;
5062 struct http_txn *txn = s->txn;
5063
5064 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5065 now_ms, __FUNCTION__, s,
5066 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5067 s->req.analysers, s->res.analysers);
5068
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005069 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5070 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005071 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005072 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005073 goto end;
5074 }
5075
5076 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5077 return;
5078
5079 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005080 /* No need to read anymore, the request was completely parsed.
5081 * We can shut the read side unless we want to abort_on_close,
5082 * or we have a POST request. The issue with POST requests is
5083 * that some browsers still send a CRLF after the request, and
5084 * this CRLF must be read so that it does not remain in the kernel
5085 * buffers, otherwise a close could cause an RST on some systems
5086 * (eg: Linux).
5087 */
5088 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5089 txn->meth != HTTP_METH_POST)
5090 channel_dont_read(chn);
5091
5092 /* if the server closes the connection, we want to immediately react
5093 * and close the socket to save packets and syscalls.
5094 */
5095 s->si[1].flags |= SI_FL_NOHALF;
5096
5097 /* In any case we've finished parsing the request so we must
5098 * disable Nagle when sending data because 1) we're not going
5099 * to shut this side, and 2) the server is waiting for us to
5100 * send pending data.
5101 */
5102 chn->flags |= CF_NEVER_WAIT;
5103
Christopher Fauletd01ce402019-01-02 17:44:13 +01005104 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5105 /* The server has not finished to respond, so we
5106 * don't want to move in order not to upset it.
5107 */
5108 return;
5109 }
5110
Christopher Fauletf2824e62018-10-01 12:12:37 +02005111 /* When we get here, it means that both the request and the
5112 * response have finished receiving. Depending on the connection
5113 * mode, we'll have to wait for the last bytes to leave in either
5114 * direction, and sometimes for a close to be effective.
5115 */
5116 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5117 /* Tunnel mode will not have any analyser so it needs to
5118 * poll for reads.
5119 */
5120 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005121 if (b_data(&chn->buf))
5122 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005123 txn->req.msg_state = HTTP_MSG_TUNNEL;
5124 }
5125 else {
5126 /* we're not expecting any new data to come for this
5127 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005128 *
5129 * However, there is an exception if the response
5130 * length is undefined. In this case, we need to wait
5131 * the close from the server. The response will be
5132 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005133 */
5134 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5135 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005136 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005137
5138 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5139 channel_shutr_now(chn);
5140 channel_shutw_now(chn);
5141 }
5142 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005143 goto check_channel_flags;
5144 }
5145
5146 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5147 http_msg_closing:
5148 /* nothing else to forward, just waiting for the output buffer
5149 * to be empty and for the shutw_now to take effect.
5150 */
5151 if (channel_is_empty(chn)) {
5152 txn->req.msg_state = HTTP_MSG_CLOSED;
5153 goto http_msg_closed;
5154 }
5155 else if (chn->flags & CF_SHUTW) {
5156 txn->req.err_state = txn->req.msg_state;
5157 txn->req.msg_state = HTTP_MSG_ERROR;
5158 goto end;
5159 }
5160 return;
5161 }
5162
5163 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5164 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005165 /* if we don't know whether the server will close, we need to hard close */
5166 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5167 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005168 /* see above in MSG_DONE why we only do this in these states */
5169 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5170 channel_dont_read(chn);
5171 goto end;
5172 }
5173
5174 check_channel_flags:
5175 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5176 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5177 /* if we've just closed an output, let's switch */
5178 txn->req.msg_state = HTTP_MSG_CLOSING;
5179 goto http_msg_closing;
5180 }
5181
5182 end:
5183 chn->analysers &= AN_REQ_FLT_END;
5184 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5185 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5186 channel_auto_close(chn);
5187 channel_auto_read(chn);
5188}
5189
5190
5191/* This function terminates the response because it was completly analyzed or
5192 * because an error was triggered during the body forwarding.
5193 */
5194static void htx_end_response(struct stream *s)
5195{
5196 struct channel *chn = &s->res;
5197 struct http_txn *txn = s->txn;
5198
5199 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5200 now_ms, __FUNCTION__, s,
5201 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5202 s->req.analysers, s->res.analysers);
5203
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005204 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5205 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005206 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005207 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005208 goto end;
5209 }
5210
5211 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5212 return;
5213
5214 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5215 /* In theory, we don't need to read anymore, but we must
5216 * still monitor the server connection for a possible close
5217 * while the request is being uploaded, so we don't disable
5218 * reading.
5219 */
5220 /* channel_dont_read(chn); */
5221
5222 if (txn->req.msg_state < HTTP_MSG_DONE) {
5223 /* The client seems to still be sending data, probably
5224 * because we got an error response during an upload.
5225 * We have the choice of either breaking the connection
5226 * or letting it pass through. Let's do the later.
5227 */
5228 return;
5229 }
5230
5231 /* When we get here, it means that both the request and the
5232 * response have finished receiving. Depending on the connection
5233 * mode, we'll have to wait for the last bytes to leave in either
5234 * direction, and sometimes for a close to be effective.
5235 */
5236 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5237 channel_auto_read(chn);
5238 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005239 if (b_data(&chn->buf))
5240 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005241 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5242 }
5243 else {
5244 /* we're not expecting any new data to come for this
5245 * transaction, so we can close it.
5246 */
5247 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5248 channel_shutr_now(chn);
5249 channel_shutw_now(chn);
5250 }
5251 }
5252 goto check_channel_flags;
5253 }
5254
5255 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5256 http_msg_closing:
5257 /* nothing else to forward, just waiting for the output buffer
5258 * to be empty and for the shutw_now to take effect.
5259 */
5260 if (channel_is_empty(chn)) {
5261 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5262 goto http_msg_closed;
5263 }
5264 else if (chn->flags & CF_SHUTW) {
5265 txn->rsp.err_state = txn->rsp.msg_state;
5266 txn->rsp.msg_state = HTTP_MSG_ERROR;
5267 HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
5268 if (objt_server(s->target))
5269 HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
5270 goto end;
5271 }
5272 return;
5273 }
5274
5275 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5276 http_msg_closed:
5277 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005278 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005279 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005280 goto end;
5281 }
5282
5283 check_channel_flags:
5284 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5285 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5286 /* if we've just closed an output, let's switch */
5287 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5288 goto http_msg_closing;
5289 }
5290
5291 end:
5292 chn->analysers &= AN_RES_FLT_END;
5293 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5294 chn->analysers |= AN_RES_FLT_XFER_DATA;
5295 channel_auto_close(chn);
5296 channel_auto_read(chn);
5297}
5298
Christopher Faulet0f226952018-10-22 09:29:56 +02005299void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5300 int finst, const struct buffer *msg)
5301{
5302 channel_auto_read(si_oc(si));
5303 channel_abort(si_oc(si));
5304 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005305 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005306 channel_auto_close(si_ic(si));
5307 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005308
5309 /* <msg> is an HTX structure. So we copy it in the response's
5310 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005311 if (msg) {
5312 struct channel *chn = si_ic(si);
5313 struct htx *htx;
5314
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005315 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005316 chn->buf.data = msg->data;
5317 memcpy(chn->buf.area, msg->area, msg->data);
5318 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005319 c_adv(chn, htx->data);
5320 chn->total += htx->data;
5321 }
5322 if (!(s->flags & SF_ERR_MASK))
5323 s->flags |= err;
5324 if (!(s->flags & SF_FINST_MASK))
5325 s->flags |= finst;
5326}
5327
5328void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5329{
5330 channel_auto_read(&s->req);
5331 channel_abort(&s->req);
5332 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005333 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5334 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005335
5336 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005337
5338 /* <msg> is an HTX structure. So we copy it in the response's
5339 * channel */
5340 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005341 if (msg) {
5342 struct channel *chn = &s->res;
5343 struct htx *htx;
5344
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005345 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005346 chn->buf.data = msg->data;
5347 memcpy(chn->buf.area, msg->area, msg->data);
5348 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005349 c_adv(chn, htx->data);
5350 chn->total += htx->data;
5351 }
5352
5353 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5354 channel_auto_read(&s->res);
5355 channel_auto_close(&s->res);
5356 channel_shutr_now(&s->res);
5357}
5358
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005359struct buffer *htx_error_message(struct stream *s)
5360{
5361 const int msgnum = http_get_status_idx(s->txn->status);
5362
5363 if (s->be->errmsg[msgnum].area)
5364 return &s->be->errmsg[msgnum];
5365 else if (strm_fe(s)->errmsg[msgnum].area)
5366 return &strm_fe(s)->errmsg[msgnum];
5367 else
5368 return &htx_err_chunks[msgnum];
5369}
5370
5371
Christopher Faulet23a3c792018-11-28 10:01:23 +01005372/* Send a 100-Continue response to the client. It returns 0 on success and -1
5373 * on error. The response channel is updated accordingly.
5374 */
5375static int htx_reply_100_continue(struct stream *s)
5376{
5377 struct channel *res = &s->res;
5378 struct htx *htx = htx_from_buf(&res->buf);
5379 struct htx_sl *sl;
5380 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5381 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5382 size_t data;
5383
5384 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5385 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5386 if (!sl)
5387 goto fail;
5388 sl->info.res.status = 100;
5389
5390 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5391 goto fail;
5392
5393 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005394 c_adv(res, data);
5395 res->total += data;
5396 return 0;
5397
5398 fail:
5399 /* If an error occurred, remove the incomplete HTTP response from the
5400 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005401 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005402 return -1;
5403}
5404
Christopher Faulet12c51e22018-11-28 15:59:42 +01005405
5406/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5407 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5408 * error. The response channel is updated accordingly.
5409 */
5410static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5411{
5412 struct channel *res = &s->res;
5413 struct htx *htx = htx_from_buf(&res->buf);
5414 struct htx_sl *sl;
5415 struct ist code, body;
5416 int status;
5417 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5418 size_t data;
5419
5420 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5421 status = 401;
5422 code = ist("401");
5423 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5424 "You need a valid user and password to access this content.\n"
5425 "</body></html>\n");
5426 }
5427 else {
5428 status = 407;
5429 code = ist("407");
5430 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5431 "You need a valid user and password to access this content.\n"
5432 "</body></html>\n");
5433 }
5434
5435 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5436 ist("HTTP/1.1"), code, ist("Unauthorized"));
5437 if (!sl)
5438 goto fail;
5439 sl->info.res.status = status;
5440 s->txn->status = status;
5441
5442 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5443 goto fail;
5444
5445 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5446 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005447 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5448 goto fail;
5449 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5450 goto fail;
5451 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005452 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005453 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5454 goto fail;
5455
5456 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005457 c_adv(res, data);
5458 res->total += data;
5459
5460 channel_auto_read(&s->req);
5461 channel_abort(&s->req);
5462 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005463 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005464
5465 res->wex = tick_add_ifset(now_ms, res->wto);
5466 channel_auto_read(res);
5467 channel_auto_close(res);
5468 channel_shutr_now(res);
5469 return 0;
5470
5471 fail:
5472 /* If an error occurred, remove the incomplete HTTP response from the
5473 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005474 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005475 return -1;
5476}
5477
Christopher Faulet0f226952018-10-22 09:29:56 +02005478/*
5479 * Capture headers from message <htx> according to header list <cap_hdr>, and
5480 * fill the <cap> pointers appropriately.
5481 */
5482static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5483{
5484 struct cap_hdr *h;
5485 int32_t pos;
5486
5487 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5488 struct htx_blk *blk = htx_get_blk(htx, pos);
5489 enum htx_blk_type type = htx_get_blk_type(blk);
5490 struct ist n, v;
5491
5492 if (type == HTX_BLK_EOH)
5493 break;
5494 if (type != HTX_BLK_HDR)
5495 continue;
5496
5497 n = htx_get_blk_name(htx, blk);
5498
5499 for (h = cap_hdr; h; h = h->next) {
5500 if (h->namelen && (h->namelen == n.len) &&
5501 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5502 if (cap[h->index] == NULL)
5503 cap[h->index] =
5504 pool_alloc(h->pool);
5505
5506 if (cap[h->index] == NULL) {
5507 ha_alert("HTTP capture : out of memory.\n");
5508 break;
5509 }
5510
5511 v = htx_get_blk_value(htx, blk);
5512 if (v.len > h->len)
5513 v.len = h->len;
5514
5515 memcpy(cap[h->index], v.ptr, v.len);
5516 cap[h->index][v.len]=0;
5517 }
5518 }
5519 }
5520}
5521
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005522/* Delete a value in a header between delimiters <from> and <next>. The header
5523 * itself is delimited by <start> and <end> pointers. The number of characters
5524 * displaced is returned, and the pointer to the first delimiter is updated if
5525 * required. The function tries as much as possible to respect the following
5526 * principles :
5527 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5528 * in which case <next> is simply removed
5529 * - set exactly one space character after the new first delimiter, unless there
5530 * are not enough characters in the block being moved to do so.
5531 * - remove unneeded spaces before the previous delimiter and after the new
5532 * one.
5533 *
5534 * It is the caller's responsibility to ensure that :
5535 * - <from> points to a valid delimiter or <start> ;
5536 * - <next> points to a valid delimiter or <end> ;
5537 * - there are non-space chars before <from>.
5538 */
5539static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5540{
5541 char *prev = *from;
5542
5543 if (prev == start) {
5544 /* We're removing the first value. eat the semicolon, if <next>
5545 * is lower than <end> */
5546 if (next < end)
5547 next++;
5548
5549 while (next < end && HTTP_IS_SPHT(*next))
5550 next++;
5551 }
5552 else {
5553 /* Remove useless spaces before the old delimiter. */
5554 while (HTTP_IS_SPHT(*(prev-1)))
5555 prev--;
5556 *from = prev;
5557
5558 /* copy the delimiter and if possible a space if we're
5559 * not at the end of the line.
5560 */
5561 if (next < end) {
5562 *prev++ = *next++;
5563 if (prev + 1 < next)
5564 *prev++ = ' ';
5565 while (next < end && HTTP_IS_SPHT(*next))
5566 next++;
5567 }
5568 }
5569 memmove(prev, next, end - next);
5570 return (prev - next);
5571}
5572
Christopher Faulet0f226952018-10-22 09:29:56 +02005573
5574/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005575 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005576 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005577static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005578{
5579 struct ist dst = ist2(str, 0);
5580
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005581 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005582 goto end;
5583 if (dst.len + 1 > len)
5584 goto end;
5585 dst.ptr[dst.len++] = ' ';
5586
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005587 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005588 goto end;
5589 if (dst.len + 1 > len)
5590 goto end;
5591 dst.ptr[dst.len++] = ' ';
5592
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005593 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005594 end:
5595 return dst.len;
5596}
5597
Christopher Fauletf0523542018-10-24 11:06:58 +02005598/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005599 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005600 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005601static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005602{
5603 struct ist dst = ist2(str, 0);
5604
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005605 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005606 goto end;
5607 if (dst.len + 1 > len)
5608 goto end;
5609 dst.ptr[dst.len++] = ' ';
5610
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005611 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005612 goto end;
5613 if (dst.len + 1 > len)
5614 goto end;
5615 dst.ptr[dst.len++] = ' ';
5616
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005617 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005618 end:
5619 return dst.len;
5620}
5621
5622
Christopher Faulet0f226952018-10-22 09:29:56 +02005623/*
5624 * Print a debug line with a start line.
5625 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005626static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005627{
5628 struct session *sess = strm_sess(s);
5629 int max;
5630
5631 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5632 dir,
5633 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5634 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5635
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005636 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005637 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005638 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005639 trash.area[trash.data++] = ' ';
5640
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005641 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005642 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005643 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005644 trash.area[trash.data++] = ' ';
5645
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005646 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005647 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005648 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005649 trash.area[trash.data++] = '\n';
5650
5651 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5652}
5653
5654/*
5655 * Print a debug line with a header.
5656 */
5657static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5658{
5659 struct session *sess = strm_sess(s);
5660 int max;
5661
5662 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5663 dir,
5664 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5665 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5666
5667 max = n.len;
5668 UBOUND(max, trash.size - trash.data - 3);
5669 chunk_memcat(&trash, n.ptr, max);
5670 trash.area[trash.data++] = ':';
5671 trash.area[trash.data++] = ' ';
5672
5673 max = v.len;
5674 UBOUND(max, trash.size - trash.data - 1);
5675 chunk_memcat(&trash, v.ptr, max);
5676 trash.area[trash.data++] = '\n';
5677
5678 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5679}
5680
5681
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005682__attribute__((constructor))
5683static void __htx_protocol_init(void)
5684{
5685}
5686
5687
5688/*
5689 * Local variables:
5690 * c-indent-level: 8
5691 * c-basic-offset: 8
5692 * End:
5693 */