blob: f5e2e73d2a74f61c4d0e700fd4fb1e4318b21985 [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
Willy Tarreau4236f032019-03-05 10:43:32 +0100100 /* Parsing errors are caught here */
101 if (htx->flags & HTX_FL_PARSING_ERROR) {
102 stream_inc_http_req_ctr(s);
103 stream_inc_http_err_ctr(s);
104 proxy_inc_fe_req_ctr(sess->fe);
105 goto return_bad_req;
106 }
107
Christopher Faulete0768eb2018-10-03 16:38:02 +0200108 /* we're speaking HTTP here, so let's speak HTTP to the client */
109 s->srv_error = http_return_srv_error;
110
111 /* If there is data available for analysis, log the end of the idle time. */
Christopher Faulet870aad92018-11-29 15:23:46 +0100112 if (c_data(req) && s->logs.t_idle == -1) {
113 const struct cs_info *csinfo = si_get_cs_info(objt_cs(s->si[0].end));
114
115 s->logs.t_idle = ((csinfo)
116 ? csinfo->t_idle
117 : tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake);
118 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200119
Christopher Faulete0768eb2018-10-03 16:38:02 +0200120 /*
121 * Now we quickly check if we have found a full valid request.
122 * If not so, we check the FD and buffer states before leaving.
123 * A full request is indicated by the fact that we have seen
124 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
125 * requests are checked first. When waiting for a second request
126 * on a keep-alive stream, if we encounter and error, close, t/o,
127 * we note the error in the stream flags but don't set any state.
128 * Since the error will be noted there, it will not be counted by
129 * process_stream() as a frontend error.
130 * Last, we may increase some tracked counters' http request errors on
131 * the cases that are deliberately the client's fault. For instance,
132 * a timeout or connection reset is not counted as an error. However
133 * a bad request is.
134 */
Christopher Faulet9768c262018-10-22 09:34:31 +0200135 if (unlikely(htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100136 /*
Willy Tarreau4236f032019-03-05 10:43:32 +0100137 * First catch invalid request because only part of headers have
138 * been transfered. Multiplexers have the responsibility to emit
139 * all headers at once.
Christopher Faulet47365272018-10-31 17:40:50 +0100140 */
Willy Tarreau4236f032019-03-05 10:43:32 +0100141 if (htx_is_not_empty(htx) || (s->si[0].flags & SI_FL_RXBLK_ROOM)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100142 stream_inc_http_req_ctr(s);
143 stream_inc_http_err_ctr(s);
144 proxy_inc_fe_req_ctr(sess->fe);
145 goto return_bad_req;
146 }
147
Christopher Faulet9768c262018-10-22 09:34:31 +0200148 /* 1: have we encountered a read error ? */
149 if (req->flags & CF_READ_ERROR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200150 if (!(s->flags & SF_ERR_MASK))
151 s->flags |= SF_ERR_CLICL;
152
153 if (txn->flags & TX_WAIT_NEXT_RQ)
154 goto failed_keep_alive;
155
156 if (sess->fe->options & PR_O_IGNORE_PRB)
157 goto failed_keep_alive;
158
Christopher Faulet9768c262018-10-22 09:34:31 +0200159 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200160 stream_inc_http_req_ctr(s);
161 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100162 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200163 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100164 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200165
Christopher Faulet9768c262018-10-22 09:34:31 +0200166 txn->status = 400;
167 msg->err_state = msg->msg_state;
168 msg->msg_state = HTTP_MSG_ERROR;
169 htx_reply_and_close(s, txn->status, NULL);
170 req->analysers &= AN_REQ_FLT_END;
171
Christopher Faulete0768eb2018-10-03 16:38:02 +0200172 if (!(s->flags & SF_FINST_MASK))
173 s->flags |= SF_FINST_R;
174 return 0;
175 }
176
Christopher Faulet9768c262018-10-22 09:34:31 +0200177 /* 2: has the read timeout expired ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200178 else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) {
179 if (!(s->flags & SF_ERR_MASK))
180 s->flags |= SF_ERR_CLITO;
181
182 if (txn->flags & TX_WAIT_NEXT_RQ)
183 goto failed_keep_alive;
184
185 if (sess->fe->options & PR_O_IGNORE_PRB)
186 goto failed_keep_alive;
187
Christopher Faulet9768c262018-10-22 09:34:31 +0200188 stream_inc_http_err_ctr(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200189 stream_inc_http_req_ctr(s);
190 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100191 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200192 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100193 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200194
Christopher Faulet9768c262018-10-22 09:34:31 +0200195 txn->status = 408;
196 msg->err_state = msg->msg_state;
197 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100198 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200199 req->analysers &= AN_REQ_FLT_END;
200
Christopher Faulete0768eb2018-10-03 16:38:02 +0200201 if (!(s->flags & SF_FINST_MASK))
202 s->flags |= SF_FINST_R;
203 return 0;
204 }
205
Christopher Faulet9768c262018-10-22 09:34:31 +0200206 /* 3: have we encountered a close ? */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200207 else if (req->flags & CF_SHUTR) {
208 if (!(s->flags & SF_ERR_MASK))
209 s->flags |= SF_ERR_CLICL;
210
211 if (txn->flags & TX_WAIT_NEXT_RQ)
212 goto failed_keep_alive;
213
214 if (sess->fe->options & PR_O_IGNORE_PRB)
215 goto failed_keep_alive;
216
Christopher Faulete0768eb2018-10-03 16:38:02 +0200217 stream_inc_http_err_ctr(s);
218 stream_inc_http_req_ctr(s);
219 proxy_inc_fe_req_ctr(sess->fe);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100220 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200221 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100222 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200223
Christopher Faulet9768c262018-10-22 09:34:31 +0200224 txn->status = 400;
225 msg->err_state = msg->msg_state;
226 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100227 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet9768c262018-10-22 09:34:31 +0200228 req->analysers &= AN_REQ_FLT_END;
229
Christopher Faulete0768eb2018-10-03 16:38:02 +0200230 if (!(s->flags & SF_FINST_MASK))
231 s->flags |= SF_FINST_R;
232 return 0;
233 }
234
235 channel_dont_connect(req);
236 req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
237 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100238
Christopher Faulet9768c262018-10-22 09:34:31 +0200239 if (sess->listener->options & LI_O_NOQUICKACK && htx_is_not_empty(htx) &&
Christopher Faulete0768eb2018-10-03 16:38:02 +0200240 objt_conn(sess->origin) && conn_ctrl_ready(__objt_conn(sess->origin))) {
241 /* We need more data, we have to re-enable quick-ack in case we
242 * previously disabled it, otherwise we might cause the client
243 * to delay next data.
244 */
Willy Tarreau1a18b542018-12-11 16:37:42 +0100245 conn_set_quickack(objt_conn(sess->origin), 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200246 }
Willy Tarreau1a18b542018-12-11 16:37:42 +0100247
Christopher Faulet47365272018-10-31 17:40:50 +0100248 if ((req->flags & CF_READ_PARTIAL) && (txn->flags & TX_WAIT_NEXT_RQ)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200249 /* If the client starts to talk, let's fall back to
250 * request timeout processing.
251 */
252 txn->flags &= ~TX_WAIT_NEXT_RQ;
253 req->analyse_exp = TICK_ETERNITY;
254 }
255
256 /* just set the request timeout once at the beginning of the request */
257 if (!tick_isset(req->analyse_exp)) {
Christopher Faulet47365272018-10-31 17:40:50 +0100258 if ((txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200259 req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka);
260 else
261 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
262 }
263
264 /* we're not ready yet */
265 return 0;
266
267 failed_keep_alive:
268 /* Here we process low-level errors for keep-alive requests. In
269 * short, if the request is not the first one and it experiences
270 * a timeout, read error or shutdown, we just silently close so
271 * that the client can try again.
272 */
273 txn->status = 0;
274 msg->msg_state = HTTP_MSG_RQBEFORE;
275 req->analysers &= AN_REQ_FLT_END;
276 s->logs.logwait = 0;
277 s->logs.level = 0;
278 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +0200279 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200280 return 0;
281 }
282
Christopher Faulet9768c262018-10-22 09:34:31 +0200283 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200284 stream_inc_http_req_ctr(s);
285 proxy_inc_fe_req_ctr(sess->fe); /* one more valid request for this FE */
286
Christopher Faulet9768c262018-10-22 09:34:31 +0200287 /* kill the pending keep-alive timeout */
288 txn->flags &= ~TX_WAIT_NEXT_RQ;
289 req->analyse_exp = TICK_ETERNITY;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200290
Christopher Faulet03599112018-11-27 11:21:21 +0100291 sl = http_find_stline(htx);
292
Christopher Faulet9768c262018-10-22 09:34:31 +0200293 /* 0: we might have to print this header in debug mode */
294 if (unlikely((global.mode & MODE_DEBUG) &&
295 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
296 int32_t pos;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200297
Christopher Faulet03599112018-11-27 11:21:21 +0100298 htx_debug_stline("clireq", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +0200299
300 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
301 struct htx_blk *blk = htx_get_blk(htx, pos);
302 enum htx_blk_type type = htx_get_blk_type(blk);
303
304 if (type == HTX_BLK_EOH)
305 break;
306 if (type != HTX_BLK_HDR)
307 continue;
308
309 htx_debug_hdr("clihdr", s,
310 htx_get_blk_name(htx, blk),
311 htx_get_blk_value(htx, blk));
312 }
313 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200314
315 /*
Christopher Faulet03599112018-11-27 11:21:21 +0100316 * 1: identify the method and the version. Also set HTTP flags
Christopher Faulete0768eb2018-10-03 16:38:02 +0200317 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100318 txn->meth = sl->info.req.meth;
Christopher Faulet03599112018-11-27 11:21:21 +0100319 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +0200320 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +0100321 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +0100322 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +0100323 if (sl->flags & HTX_SL_F_BODYLESS)
324 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200325
326 /* we can make use of server redirect on GET and HEAD */
327 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
328 s->flags |= SF_REDIRECTABLE;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100329 else if (txn->meth == HTTP_METH_OTHER && isteqi(htx_sl_req_meth(sl), ist("PRI"))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200330 /* PRI is reserved for the HTTP/2 preface */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200331 goto return_bad_req;
332 }
333
334 /*
335 * 2: check if the URI matches the monitor_uri.
336 * We have to do this for every request which gets in, because
337 * the monitor-uri is defined by the frontend.
338 */
339 if (unlikely((sess->fe->monitor_uri_len != 0) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100340 isteqi(htx_sl_req_uri(sl), ist2(sess->fe->monitor_uri, sess->fe->monitor_uri_len)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200341 /*
342 * We have found the monitor URI
343 */
344 struct acl_cond *cond;
345
346 s->flags |= SF_MONITOR;
Olivier Houcharda798bf52019-03-08 18:52:00 +0100347 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200348
349 /* Check if we want to fail this monitor request or not */
350 list_for_each_entry(cond, &sess->fe->mon_fail_cond, list) {
351 int ret = acl_exec_cond(cond, sess->fe, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
352
353 ret = acl_pass(ret);
354 if (cond->pol == ACL_COND_UNLESS)
355 ret = !ret;
356
357 if (ret) {
358 /* we fail this request, let's return 503 service unavail */
359 txn->status = 503;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100360 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200361 if (!(s->flags & SF_ERR_MASK))
362 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
363 goto return_prx_cond;
364 }
365 }
366
Joseph Herlantc42c0e92018-11-25 10:43:27 -0800367 /* nothing to fail, let's reply normally */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200368 txn->status = 200;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100369 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200370 if (!(s->flags & SF_ERR_MASK))
371 s->flags |= SF_ERR_LOCAL; /* we don't want a real error here */
372 goto return_prx_cond;
373 }
374
375 /*
376 * 3: Maybe we have to copy the original REQURI for the logs ?
377 * Note: we cannot log anymore if the request has been
378 * classified as invalid.
379 */
380 if (unlikely(s->logs.logwait & LW_REQ)) {
381 /* we have a complete HTTP request that we must log */
382 if ((txn->uri = pool_alloc(pool_head_requri)) != NULL) {
Christopher Faulet9768c262018-10-22 09:34:31 +0200383 size_t len;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200384
Christopher Faulet9768c262018-10-22 09:34:31 +0200385 len = htx_fmt_req_line(sl, txn->uri, global.tune.requri_len - 1);
386 txn->uri[len] = 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200387
388 if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT)))
389 s->do_log(s);
390 } else {
391 ha_alert("HTTP logging : out of memory.\n");
392 }
393 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200394
Christopher Faulete0768eb2018-10-03 16:38:02 +0200395 /* if the frontend has "option http-use-proxy-header", we'll check if
396 * we have what looks like a proxied connection instead of a connection,
397 * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection.
398 * Note that this is *not* RFC-compliant, however browsers and proxies
399 * happen to do that despite being non-standard :-(
400 * We consider that a request not beginning with either '/' or '*' is
401 * a proxied connection, which covers both "scheme://location" and
402 * CONNECT ip:port.
403 */
404 if ((sess->fe->options2 & PR_O2_USE_PXHDR) &&
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100405 *HTX_SL_REQ_UPTR(sl) != '/' && *HTX_SL_REQ_UPTR(sl) != '*')
Christopher Faulete0768eb2018-10-03 16:38:02 +0200406 txn->flags |= TX_USE_PX_CONN;
407
Christopher Faulete0768eb2018-10-03 16:38:02 +0200408 /* 5: we may need to capture headers */
409 if (unlikely((s->logs.logwait & LW_REQHDR) && s->req_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +0200410 htx_capture_headers(htx, s->req_cap, sess->fe->req_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200411
412 /* Until set to anything else, the connection mode is set as Keep-Alive. It will
413 * only change if both the request and the config reference something else.
414 * Option httpclose by itself sets tunnel mode where headers are mangled.
415 * However, if another mode is set, it will affect it (eg: server-close/
416 * keep-alive + httpclose = close). Note that we avoid to redo the same work
417 * if FE and BE have the same settings (common). The method consists in
418 * checking if options changed between the two calls (implying that either
419 * one is non-null, or one of them is non-null and we are there for the first
420 * time.
421 */
Christopher Fauletf2824e62018-10-01 12:12:37 +0200422 if ((sess->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))
Christopher Faulet0f226952018-10-22 09:29:56 +0200423 htx_adjust_conn_mode(s, txn);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200424
425 /* we may have to wait for the request's body */
Christopher Faulet9768c262018-10-22 09:34:31 +0200426 if (s->be->options & PR_O_WREQ_BODY)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200427 req->analysers |= AN_REQ_HTTP_BODY;
428
429 /*
430 * RFC7234#4:
431 * A cache MUST write through requests with methods
432 * that are unsafe (Section 4.2.1 of [RFC7231]) to
433 * the origin server; i.e., a cache is not allowed
434 * to generate a reply to such a request before
435 * having forwarded the request and having received
436 * a corresponding response.
437 *
438 * RFC7231#4.2.1:
439 * Of the request methods defined by this
440 * specification, the GET, HEAD, OPTIONS, and TRACE
441 * methods are defined to be safe.
442 */
443 if (likely(txn->meth == HTTP_METH_GET ||
444 txn->meth == HTTP_METH_HEAD ||
445 txn->meth == HTTP_METH_OPTIONS ||
446 txn->meth == HTTP_METH_TRACE))
447 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
448
449 /* end of job, return OK */
450 req->analysers &= ~an_bit;
451 req->analyse_exp = TICK_ETERNITY;
Christopher Faulet9768c262018-10-22 09:34:31 +0200452
Christopher Faulete0768eb2018-10-03 16:38:02 +0200453 return 1;
454
455 return_bad_req:
Christopher Faulet9768c262018-10-22 09:34:31 +0200456 txn->status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200457 txn->req.err_state = txn->req.msg_state;
458 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100459 htx_reply_and_close(s, txn->status, htx_error_message(s));
Olivier Houcharda798bf52019-03-08 18:52:00 +0100460 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200461 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100462 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200463
464 return_prx_cond:
465 if (!(s->flags & SF_ERR_MASK))
466 s->flags |= SF_ERR_PRXCOND;
467 if (!(s->flags & SF_FINST_MASK))
468 s->flags |= SF_FINST_R;
469
470 req->analysers &= AN_REQ_FLT_END;
471 req->analyse_exp = TICK_ETERNITY;
472 return 0;
473}
474
475
476/* This stream analyser runs all HTTP request processing which is common to
477 * frontends and backends, which means blocking ACLs, filters, connection-close,
478 * reqadd, stats and redirects. This is performed for the designated proxy.
479 * It returns 1 if the processing can continue on next analysers, or zero if it
480 * either needs more data or wants to immediately abort the request (eg: deny,
481 * error, ...).
482 */
483int htx_process_req_common(struct stream *s, struct channel *req, int an_bit, struct proxy *px)
484{
485 struct session *sess = s->sess;
486 struct http_txn *txn = s->txn;
487 struct http_msg *msg = &txn->req;
Christopher Fauletff2759f2018-10-24 11:13:16 +0200488 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200489 struct redirect_rule *rule;
490 struct cond_wordlist *wl;
491 enum rule_result verdict;
492 int deny_status = HTTP_ERR_403;
493 struct connection *conn = objt_conn(sess->origin);
494
495 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
496 /* we need more data */
497 goto return_prx_yield;
498 }
499
500 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
501 now_ms, __FUNCTION__,
502 s,
503 req,
504 req->rex, req->wex,
505 req->flags,
506 ci_data(req),
507 req->analysers);
508
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100509 htx = htxbuf(&req->buf);
Christopher Fauletff2759f2018-10-24 11:13:16 +0200510
Christopher Faulete0768eb2018-10-03 16:38:02 +0200511 /* just in case we have some per-backend tracking */
512 stream_inc_be_http_req_ctr(s);
513
514 /* evaluate http-request rules */
515 if (!LIST_ISEMPTY(&px->http_req_rules)) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200516 verdict = htx_req_get_intercept_rule(px, &px->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200517
518 switch (verdict) {
519 case HTTP_RULE_RES_YIELD: /* some data miss, call the function later. */
520 goto return_prx_yield;
521
522 case HTTP_RULE_RES_CONT:
523 case HTTP_RULE_RES_STOP: /* nothing to do */
524 break;
525
526 case HTTP_RULE_RES_DENY: /* deny or tarpit */
527 if (txn->flags & TX_CLTARPIT)
528 goto tarpit;
529 goto deny;
530
531 case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */
532 goto return_prx_cond;
533
534 case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */
535 goto done;
536
537 case HTTP_RULE_RES_BADREQ: /* failed with a bad request */
538 goto return_bad_req;
539 }
540 }
541
542 if (conn && (conn->flags & CO_FL_EARLY_DATA) &&
543 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE))) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200544 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200545
Christopher Fauletff2759f2018-10-24 11:13:16 +0200546 ctx.blk = NULL;
547 if (!http_find_header(htx, ist("Early-Data"), &ctx, 0)) {
548 if (unlikely(!http_add_header(htx, ist("Early-Data"), ist("1"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200549 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200550 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200551 }
552
553 /* OK at this stage, we know that the request was accepted according to
554 * the http-request rules, we can check for the stats. Note that the
555 * URI is detected *before* the req* rules in order not to be affected
556 * by a possible reqrep, while they are processed *after* so that a
557 * reqdeny can still block them. This clearly needs to change in 1.6!
558 */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200559 if (htx_stats_check_uri(s, txn, px)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200560 s->target = &http_stats_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +0100561 if (unlikely(!si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200562 txn->status = 500;
563 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100564 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200565
566 if (!(s->flags & SF_ERR_MASK))
567 s->flags |= SF_ERR_RESOURCE;
568 goto return_prx_cond;
569 }
570
571 /* parse the whole stats request and extract the relevant information */
Christopher Fauletff2759f2018-10-24 11:13:16 +0200572 htx_handle_stats(s, req);
573 verdict = htx_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, &deny_status);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200574 /* not all actions implemented: deny, allow, auth */
575
576 if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */
577 goto deny;
578
579 if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */
580 goto return_prx_cond;
581 }
582
583 /* evaluate the req* rules except reqadd */
584 if (px->req_exp != NULL) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200585 if (htx_apply_filters_to_request(s, req, px) < 0)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200586 goto return_bad_req;
587
588 if (txn->flags & TX_CLDENY)
589 goto deny;
590
591 if (txn->flags & TX_CLTARPIT) {
592 deny_status = HTTP_ERR_500;
593 goto tarpit;
594 }
595 }
596
597 /* add request headers from the rule sets in the same order */
598 list_for_each_entry(wl, &px->req_add, list) {
Christopher Fauletff2759f2018-10-24 11:13:16 +0200599 struct ist n,v;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200600 if (wl->cond) {
601 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
602 ret = acl_pass(ret);
603 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
604 ret = !ret;
605 if (!ret)
606 continue;
607 }
608
Christopher Fauletff2759f2018-10-24 11:13:16 +0200609 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
610 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200611 goto return_bad_req;
612 }
613
Christopher Faulete0768eb2018-10-03 16:38:02 +0200614 /* Proceed with the stats now. */
615 if (unlikely(objt_applet(s->target) == &http_stats_applet) ||
616 unlikely(objt_applet(s->target) == &http_cache_applet)) {
617 /* process the stats request now */
618 if (sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Olivier Houcharda798bf52019-03-08 18:52:00 +0100619 _HA_ATOMIC_ADD(&sess->fe->fe_counters.intercepted_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200620
621 if (!(s->flags & SF_ERR_MASK)) // this is not really an error but it is
622 s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
623 if (!(s->flags & SF_FINST_MASK))
624 s->flags |= SF_FINST_R;
625
626 /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */
627 req->analysers &= (AN_REQ_HTTP_BODY | AN_REQ_FLT_HTTP_HDRS | AN_REQ_FLT_END);
628 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
629 req->analysers |= AN_REQ_HTTP_XFER_BODY;
630 goto done;
631 }
632
633 /* check whether we have some ACLs set to redirect this request */
634 list_for_each_entry(rule, &px->redirect_rules, list) {
635 if (rule->cond) {
636 int ret;
637
638 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
639 ret = acl_pass(ret);
640 if (rule->cond->pol == ACL_COND_UNLESS)
641 ret = !ret;
642 if (!ret)
643 continue;
644 }
Christopher Fauletf2824e62018-10-01 12:12:37 +0200645 if (!htx_apply_redirect_rule(rule, s, txn))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200646 goto return_bad_req;
647 goto done;
648 }
649
650 /* POST requests may be accompanied with an "Expect: 100-Continue" header.
651 * If this happens, then the data will not come immediately, so we must
652 * send all what we have without waiting. Note that due to the small gain
653 * in waiting for the body of the request, it's easier to simply put the
654 * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove
655 * itself once used.
656 */
657 req->flags |= CF_SEND_DONTWAIT;
658
659 done: /* done with this analyser, continue with next ones that the calling
660 * points will have set, if any.
661 */
662 req->analyse_exp = TICK_ETERNITY;
663 done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */
664 req->analysers &= ~an_bit;
665 return 1;
666
667 tarpit:
668 /* Allow cookie logging
669 */
670 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200671 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200672
673 /* When a connection is tarpitted, we use the tarpit timeout,
674 * which may be the same as the connect timeout if unspecified.
675 * If unset, then set it to zero because we really want it to
676 * eventually expire. We build the tarpit as an analyser.
677 */
Christopher Faulet202c6ce2019-01-07 14:57:35 +0100678 channel_htx_erase(&s->req, htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200679
680 /* wipe the request out so that we can drop the connection early
681 * if the client closes first.
682 */
683 channel_dont_connect(req);
684
685 txn->status = http_err_codes[deny_status];
686
687 req->analysers &= AN_REQ_FLT_END; /* remove switching rules etc... */
688 req->analysers |= AN_REQ_HTTP_TARPIT;
689 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit);
690 if (!req->analyse_exp)
691 req->analyse_exp = tick_add(now_ms, 0);
692 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100693 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200694 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100695 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200696 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100697 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200698 goto done_without_exp;
699
700 deny: /* this request was blocked (denied) */
701
702 /* Allow cookie logging
703 */
704 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletff2759f2018-10-24 11:13:16 +0200705 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200706
707 txn->flags |= TX_CLDENY;
708 txn->status = http_err_codes[deny_status];
709 s->logs.tv_request = now;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100710 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200711 stream_inc_http_err_ctr(s);
Olivier Houcharda798bf52019-03-08 18:52:00 +0100712 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200713 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100714 _HA_ATOMIC_ADD(&s->be->be_counters.denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200715 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100716 _HA_ATOMIC_ADD(&sess->listener->counters->denied_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200717 goto return_prx_cond;
718
719 return_bad_req:
Christopher Faulete0768eb2018-10-03 16:38:02 +0200720 txn->req.err_state = txn->req.msg_state;
721 txn->req.msg_state = HTTP_MSG_ERROR;
722 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100723 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200724
Olivier Houcharda798bf52019-03-08 18:52:00 +0100725 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200726 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100727 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200728
729 return_prx_cond:
730 if (!(s->flags & SF_ERR_MASK))
731 s->flags |= SF_ERR_PRXCOND;
732 if (!(s->flags & SF_FINST_MASK))
733 s->flags |= SF_FINST_R;
734
735 req->analysers &= AN_REQ_FLT_END;
736 req->analyse_exp = TICK_ETERNITY;
737 return 0;
738
739 return_prx_yield:
740 channel_dont_connect(req);
741 return 0;
742}
743
744/* This function performs all the processing enabled for the current request.
745 * It returns 1 if the processing can continue on next analysers, or zero if it
746 * needs more data, encounters an error, or wants to immediately abort the
747 * request. It relies on buffers flags, and updates s->req.analysers.
748 */
749int htx_process_request(struct stream *s, struct channel *req, int an_bit)
750{
751 struct session *sess = s->sess;
752 struct http_txn *txn = s->txn;
753 struct http_msg *msg = &txn->req;
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200754 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200755 struct connection *cli_conn = objt_conn(strm_sess(s)->origin);
756
757 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) {
758 /* we need more data */
759 channel_dont_connect(req);
760 return 0;
761 }
762
763 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
764 now_ms, __FUNCTION__,
765 s,
766 req,
767 req->rex, req->wex,
768 req->flags,
769 ci_data(req),
770 req->analysers);
771
772 /*
773 * Right now, we know that we have processed the entire headers
774 * and that unwanted requests have been filtered out. We can do
775 * whatever we want with the remaining request. Also, now we
776 * may have separate values for ->fe, ->be.
777 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +0100778 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200779
780 /*
781 * If HTTP PROXY is set we simply get remote server address parsing
782 * incoming request. Note that this requires that a connection is
783 * allocated on the server side.
784 */
785 if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SF_ADDR_SET)) {
786 struct connection *conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100787 struct htx_sl *sl;
788 struct ist uri, path;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200789
790 /* Note that for now we don't reuse existing proxy connections */
791 if (unlikely((conn = cs_conn(si_alloc_cs(&s->si[1], NULL))) == NULL)) {
792 txn->req.err_state = txn->req.msg_state;
793 txn->req.msg_state = HTTP_MSG_ERROR;
794 txn->status = 500;
795 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100796 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200797
798 if (!(s->flags & SF_ERR_MASK))
799 s->flags |= SF_ERR_RESOURCE;
800 if (!(s->flags & SF_FINST_MASK))
801 s->flags |= SF_FINST_R;
802
803 return 0;
804 }
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200805 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100806 uri = htx_sl_req_uri(sl);
807 path = http_get_path(uri);
808 if (url2sa(uri.ptr, uri.len - path.len, &conn->addr.to, NULL) == -1)
Christopher Faulete0768eb2018-10-03 16:38:02 +0200809 goto return_bad_req;
810
811 /* if the path was found, we have to remove everything between
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200812 * uri.ptr and path.ptr (excluded). If it was not found, we need
813 * to replace from all the uri by a single "/".
814 *
815 * Instead of rewritting the whole start line, we just update
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100816 * the star-line URI. Some space will be lost but it should be
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200817 * insignificant.
Christopher Faulete0768eb2018-10-03 16:38:02 +0200818 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +0100819 istcpy(&uri, (path.len ? path : ist("/")), uri.len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200820 }
821
822 /*
823 * 7: Now we can work with the cookies.
824 * Note that doing so might move headers in the request, but
825 * the fields will stay coherent and the URI will not move.
826 * This should only be performed in the backend.
827 */
828 if (s->be->cookie_name || sess->fe->capture_name)
Christopher Fauletb6aadbd2018-12-18 16:41:31 +0100829 htx_manage_client_side_cookies(s, req);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200830
831 /* add unique-id if "header-unique-id" is specified */
832
833 if (!LIST_ISEMPTY(&sess->fe->format_unique_id) && !s->unique_id) {
834 if ((s->unique_id = pool_alloc(pool_head_uniqueid)) == NULL)
835 goto return_bad_req;
836 s->unique_id[0] = '\0';
837 build_logline(s, s->unique_id, UNIQUEID_LEN, &sess->fe->format_unique_id);
838 }
839
840 if (sess->fe->header_unique_id && s->unique_id) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200841 struct ist n = ist2(sess->fe->header_unique_id, strlen(sess->fe->header_unique_id));
842 struct ist v = ist2(s->unique_id, strlen(s->unique_id));
843
844 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200845 goto return_bad_req;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200846 }
847
848 /*
849 * 9: add X-Forwarded-For if either the frontend or the backend
850 * asks for it.
851 */
852 if ((sess->fe->options | s->be->options) & PR_O_FWDFOR) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200853 struct http_hdr_ctx ctx = { .blk = NULL };
854 struct ist hdr = ist2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : sess->fe->fwdfor_hdr_name,
855 s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : sess->fe->fwdfor_hdr_len);
856
Christopher Faulete0768eb2018-10-03 16:38:02 +0200857 if (!((sess->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200858 http_find_header(htx, hdr, &ctx, 0)) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200859 /* The header is set to be added only if none is present
860 * and we found it, so don't do anything.
861 */
862 }
863 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
864 /* Add an X-Forwarded-For header unless the source IP is
865 * in the 'except' network range.
866 */
867 if ((!sess->fe->except_mask.s_addr ||
868 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & sess->fe->except_mask.s_addr)
869 != sess->fe->except_net.s_addr) &&
870 (!s->be->except_mask.s_addr ||
871 (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)
872 != s->be->except_net.s_addr)) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200873 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200874
875 /* Note: we rely on the backend to get the header name to be used for
876 * x-forwarded-for, because the header is really meant for the backends.
877 * However, if the backend did not specify any option, we have to rely
878 * on the frontend's header name.
879 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200880 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
881 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200882 goto return_bad_req;
883 }
884 }
885 else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {
886 /* FIXME: for the sake of completeness, we should also support
887 * 'except' here, although it is mostly useless in this case.
888 */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200889 char pn[INET6_ADDRSTRLEN];
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200890
Christopher Faulete0768eb2018-10-03 16:38:02 +0200891 inet_ntop(AF_INET6,
892 (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,
893 pn, sizeof(pn));
894
895 /* Note: we rely on the backend to get the header name to be used for
896 * x-forwarded-for, because the header is really meant for the backends.
897 * However, if the backend did not specify any option, we have to rely
898 * on the frontend's header name.
899 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200900 chunk_printf(&trash, "%s", pn);
901 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200902 goto return_bad_req;
903 }
904 }
905
906 /*
907 * 10: add X-Original-To if either the frontend or the backend
908 * asks for it.
909 */
910 if ((sess->fe->options | s->be->options) & PR_O_ORGTO) {
911
912 /* FIXME: don't know if IPv6 can handle that case too. */
913 if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {
914 /* Add an X-Original-To header unless the destination IP is
915 * in the 'except' network range.
916 */
917 conn_get_to_addr(cli_conn);
918
919 if (cli_conn->addr.to.ss_family == AF_INET &&
920 ((!sess->fe->except_mask_to.s_addr ||
921 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & sess->fe->except_mask_to.s_addr)
922 != sess->fe->except_to.s_addr) &&
923 (!s->be->except_mask_to.s_addr ||
924 (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)
925 != s->be->except_to.s_addr))) {
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200926 struct ist hdr;
927 unsigned char *pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;
Christopher Faulete0768eb2018-10-03 16:38:02 +0200928
929 /* Note: we rely on the backend to get the header name to be used for
930 * x-original-to, because the header is really meant for the backends.
931 * However, if the backend did not specify any option, we have to rely
932 * on the frontend's header name.
933 */
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200934 if (s->be->orgto_hdr_len)
935 hdr = ist2(s->be->orgto_hdr_name, s->be->orgto_hdr_len);
936 else
937 hdr = ist2(sess->fe->orgto_hdr_name, sess->fe->orgto_hdr_len);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200938
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200939 chunk_printf(&trash, "%d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]);
940 if (unlikely(!http_add_header(htx, hdr, ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +0200941 goto return_bad_req;
942 }
943 }
Christopher Faulete0768eb2018-10-03 16:38:02 +0200944 }
945
Christopher Faulete0768eb2018-10-03 16:38:02 +0200946 /* If we have no server assigned yet and we're balancing on url_param
947 * with a POST request, we may be interested in checking the body for
948 * that parameter. This will be done in another analyser.
949 */
950 if (!(s->flags & (SF_ASSIGNED|SF_DIRECT)) &&
Willy Tarreau089eaa02019-01-14 15:17:46 +0100951 s->txn->meth == HTTP_METH_POST &&
952 (s->be->lbprm.algo & BE_LB_ALGO) == BE_LB_ALGO_PH) {
Christopher Faulete0768eb2018-10-03 16:38:02 +0200953 channel_dont_connect(req);
954 req->analysers |= AN_REQ_HTTP_BODY;
955 }
956
957 req->analysers &= ~AN_REQ_FLT_XFER_DATA;
958 req->analysers |= AN_REQ_HTTP_XFER_BODY;
Willy Tarreau1a18b542018-12-11 16:37:42 +0100959
Christopher Faulete0768eb2018-10-03 16:38:02 +0200960 /* We expect some data from the client. Unless we know for sure
961 * we already have a full request, we have to re-enable quick-ack
962 * in case we previously disabled it, otherwise we might cause
963 * the client to delay further data.
964 */
965 if ((sess->listener->options & LI_O_NOQUICKACK) &&
Christopher Fauletd7bdfb12018-10-24 11:14:34 +0200966 (htx_get_tail_type(htx) != HTX_BLK_EOM))
Willy Tarreau1a18b542018-12-11 16:37:42 +0100967 conn_set_quickack(cli_conn, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200968
969 /*************************************************************
970 * OK, that's finished for the headers. We have done what we *
971 * could. Let's switch to the DATA state. *
972 ************************************************************/
973 req->analyse_exp = TICK_ETERNITY;
974 req->analysers &= ~an_bit;
975
976 s->logs.tv_request = now;
977 /* OK let's go on with the BODY now */
978 return 1;
979
980 return_bad_req: /* let's centralize all bad requests */
Christopher Faulete0768eb2018-10-03 16:38:02 +0200981 txn->req.err_state = txn->req.msg_state;
982 txn->req.msg_state = HTTP_MSG_ERROR;
983 txn->status = 400;
984 req->analysers &= AN_REQ_FLT_END;
Christopher Fauleta7b677c2018-11-29 16:48:49 +0100985 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +0200986
Olivier Houcharda798bf52019-03-08 18:52:00 +0100987 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200988 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +0100989 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +0200990
991 if (!(s->flags & SF_ERR_MASK))
992 s->flags |= SF_ERR_PRXCOND;
993 if (!(s->flags & SF_FINST_MASK))
994 s->flags |= SF_FINST_R;
995 return 0;
996}
997
998/* This function is an analyser which processes the HTTP tarpit. It always
999 * returns zero, at the beginning because it prevents any other processing
1000 * from occurring, and at the end because it terminates the request.
1001 */
1002int htx_process_tarpit(struct stream *s, struct channel *req, int an_bit)
1003{
1004 struct http_txn *txn = s->txn;
1005
1006 /* This connection is being tarpitted. The CLIENT side has
1007 * already set the connect expiration date to the right
1008 * timeout. We just have to check that the client is still
1009 * there and that the timeout has not expired.
1010 */
1011 channel_dont_connect(req);
1012 if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 &&
1013 !tick_is_expired(req->analyse_exp, now_ms))
1014 return 0;
1015
1016 /* We will set the queue timer to the time spent, just for
1017 * logging purposes. We fake a 500 server error, so that the
1018 * attacker will not suspect his connection has been tarpitted.
1019 * It will not cause trouble to the logs because we can exclude
1020 * the tarpitted connections by filtering on the 'PT' status flags.
1021 */
1022 s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now);
1023
1024 if (!(req->flags & CF_READ_ERROR))
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001025 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001026
1027 req->analysers &= AN_REQ_FLT_END;
1028 req->analyse_exp = TICK_ETERNITY;
1029
1030 if (!(s->flags & SF_ERR_MASK))
1031 s->flags |= SF_ERR_PRXCOND;
1032 if (!(s->flags & SF_FINST_MASK))
1033 s->flags |= SF_FINST_T;
1034 return 0;
1035}
1036
1037/* This function is an analyser which waits for the HTTP request body. It waits
1038 * for either the buffer to be full, or the full advertised contents to have
1039 * reached the buffer. It must only be called after the standard HTTP request
1040 * processing has occurred, because it expects the request to be parsed and will
1041 * look for the Expect header. It may send a 100-Continue interim response. It
1042 * takes in input any state starting from HTTP_MSG_BODY and leaves with one of
1043 * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it
1044 * needs to read more data, or 1 once it has completed its analysis.
1045 */
1046int htx_wait_for_request_body(struct stream *s, struct channel *req, int an_bit)
1047{
1048 struct session *sess = s->sess;
1049 struct http_txn *txn = s->txn;
1050 struct http_msg *msg = &s->txn->req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001051 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001052
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001053
1054 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1055 now_ms, __FUNCTION__,
1056 s,
1057 req,
1058 req->rex, req->wex,
1059 req->flags,
1060 ci_data(req),
1061 req->analysers);
1062
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001063 htx = htxbuf(&req->buf);
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001064
Willy Tarreau4236f032019-03-05 10:43:32 +01001065 if (htx->flags & HTX_FL_PARSING_ERROR)
1066 goto return_bad_req;
1067
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001068 if (msg->msg_state < HTTP_MSG_BODY)
1069 goto missing_data;
Christopher Faulet9768c262018-10-22 09:34:31 +02001070
Christopher Faulete0768eb2018-10-03 16:38:02 +02001071 /* We have to parse the HTTP request body to find any required data.
1072 * "balance url_param check_post" should have been the only way to get
1073 * into this. We were brought here after HTTP header analysis, so all
1074 * related structures are ready.
1075 */
1076
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001077 if (msg->msg_state < HTTP_MSG_DATA) {
1078 /* If we have HTTP/1.1 and Expect: 100-continue, then we must
1079 * send an HTTP/1.1 100 Continue intermediate response.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001080 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001081 if (msg->flags & HTTP_MSGF_VER_11) {
1082 struct ist hdr = { .ptr = "Expect", .len = 6 };
1083 struct http_hdr_ctx ctx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001084
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001085 ctx.blk = NULL;
1086 /* Expect is allowed in 1.1, look for it */
1087 if (http_find_header(htx, hdr, &ctx, 0) &&
1088 unlikely(isteqi(ctx.value, ist2("100-continue", 12)))) {
Christopher Faulet23a3c792018-11-28 10:01:23 +01001089 if (htx_reply_100_continue(s) == -1)
1090 goto return_bad_req;
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001091 http_remove_header(htx, &ctx);
1092 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001093 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001094 }
1095
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001096 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001097
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001098 /* Now we're in HTTP_MSG_DATA. We just need to know if all data have
1099 * been received or if the buffer is full.
Christopher Faulete0768eb2018-10-03 16:38:02 +02001100 */
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001101 if (htx_get_tail_type(htx) >= HTX_BLK_EOD ||
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001102 channel_htx_full(req, htx, global.tune.maxrewrite))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001103 goto http_end;
1104
Christopher Fauletf76ebe82018-10-24 11:16:22 +02001105 missing_data:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001106 if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) {
1107 txn->status = 408;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001108 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001109
1110 if (!(s->flags & SF_ERR_MASK))
1111 s->flags |= SF_ERR_CLITO;
1112 if (!(s->flags & SF_FINST_MASK))
1113 s->flags |= SF_FINST_D;
1114 goto return_err_msg;
1115 }
1116
1117 /* we get here if we need to wait for more data */
1118 if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) {
1119 /* Not enough data. We'll re-use the http-request
1120 * timeout here. Ideally, we should set the timeout
1121 * relative to the accept() date. We just set the
1122 * request timeout once at the beginning of the
1123 * request.
1124 */
1125 channel_dont_connect(req);
1126 if (!tick_isset(req->analyse_exp))
1127 req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq);
1128 return 0;
1129 }
1130
1131 http_end:
1132 /* The situation will not evolve, so let's give up on the analysis. */
1133 s->logs.tv_request = now; /* update the request timer to reflect full request */
1134 req->analysers &= ~an_bit;
1135 req->analyse_exp = TICK_ETERNITY;
1136 return 1;
1137
1138 return_bad_req: /* let's centralize all bad requests */
1139 txn->req.err_state = txn->req.msg_state;
1140 txn->req.msg_state = HTTP_MSG_ERROR;
1141 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001142 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001143
1144 if (!(s->flags & SF_ERR_MASK))
1145 s->flags |= SF_ERR_PRXCOND;
1146 if (!(s->flags & SF_FINST_MASK))
1147 s->flags |= SF_FINST_R;
1148
1149 return_err_msg:
1150 req->analysers &= AN_REQ_FLT_END;
Olivier Houcharda798bf52019-03-08 18:52:00 +01001151 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001152 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001153 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001154 return 0;
1155}
1156
1157/* This function is an analyser which forwards request body (including chunk
1158 * sizes if any). It is called as soon as we must forward, even if we forward
1159 * zero byte. The only situation where it must not be called is when we're in
1160 * tunnel mode and we want to forward till the close. It's used both to forward
1161 * remaining data and to resync after end of body. It expects the msg_state to
1162 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
1163 * read more data, or 1 once we can go on with next request or end the stream.
1164 * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len
1165 * bytes of pending data + the headers if not already done.
1166 */
1167int htx_request_forward_body(struct stream *s, struct channel *req, int an_bit)
1168{
1169 struct session *sess = s->sess;
1170 struct http_txn *txn = s->txn;
Christopher Faulet9768c262018-10-22 09:34:31 +02001171 struct http_msg *msg = &txn->req;
1172 struct htx *htx;
Christopher Faulet93e02d82019-03-08 14:18:50 +01001173 short status = 0;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001174 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001175
1176 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1177 now_ms, __FUNCTION__,
1178 s,
1179 req,
1180 req->rex, req->wex,
1181 req->flags,
1182 ci_data(req),
1183 req->analysers);
1184
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001185 htx = htxbuf(&req->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001186
1187 if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
1188 ((req->flags & CF_SHUTW) && (req->to_forward || co_data(req)))) {
1189 /* Output closed while we were sending data. We must abort and
1190 * wake the other side up.
1191 */
1192 msg->err_state = msg->msg_state;
1193 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001194 htx_end_request(s);
1195 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001196 return 1;
1197 }
1198
1199 /* Note that we don't have to send 100-continue back because we don't
1200 * need the data to complete our job, and it's up to the server to
1201 * decide whether to return 100, 417 or anything else in return of
1202 * an "Expect: 100-continue" header.
1203 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001204 if (msg->msg_state == HTTP_MSG_BODY)
1205 msg->msg_state = HTTP_MSG_DATA;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001206
1207 /* Some post-connect processing might want us to refrain from starting to
1208 * forward data. Currently, the only reason for this is "balance url_param"
1209 * whichs need to parse/process the request after we've enabled forwarding.
1210 */
1211 if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
1212 if (!(s->res.flags & CF_READ_ATTACHED)) {
1213 channel_auto_connect(req);
1214 req->flags |= CF_WAKE_CONNECT;
1215 channel_dont_close(req); /* don't fail on early shutr */
1216 goto waiting;
1217 }
1218 msg->flags &= ~HTTP_MSGF_WAIT_CONN;
1219 }
1220
1221 /* in most states, we should abort in case of early close */
1222 channel_auto_close(req);
1223
1224 if (req->to_forward) {
1225 /* We can't process the buffer's contents yet */
1226 req->flags |= CF_WAKE_WRITE;
1227 goto missing_data_or_waiting;
1228 }
1229
Christopher Faulet9768c262018-10-22 09:34:31 +02001230 if (msg->msg_state >= HTTP_MSG_DONE)
1231 goto done;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001232 /* Forward input data. We get it by removing all outgoing data not
1233 * forwarded yet from HTX data size. If there are some data filters, we
1234 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02001235 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001236 if (HAS_REQ_DATA_FILTERS(s)) {
1237 ret = flt_http_payload(s, msg, htx->data);
1238 if (ret < 0)
1239 goto return_bad_req;
1240 c_adv(req, ret);
1241 if (htx->data != co_data(req) || htx->extra)
1242 goto missing_data_or_waiting;
1243 }
1244 else {
1245 c_adv(req, htx->data - co_data(req));
Christopher Faulet9768c262018-10-22 09:34:31 +02001246
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001247 /* To let the function channel_forward work as expected we must update
1248 * the channel's buffer to pretend there is no more input data. The
1249 * right length is then restored. We must do that, because when an HTX
1250 * message is stored into a buffer, it appears as full.
1251 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01001252 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
1253 htx->extra -= channel_htx_forward(req, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001254 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001255
Christopher Faulet9768c262018-10-22 09:34:31 +02001256 /* Check if the end-of-message is reached and if so, switch the message
1257 * in HTTP_MSG_DONE state.
1258 */
1259 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
1260 goto missing_data_or_waiting;
1261
1262 msg->msg_state = HTTP_MSG_DONE;
1263
1264 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001265 /* other states, DONE...TUNNEL */
1266 /* we don't want to forward closes on DONE except in tunnel mode. */
1267 if ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN)
1268 channel_dont_close(req);
1269
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001270 if (HAS_REQ_DATA_FILTERS(s)) {
1271 ret = flt_http_end(s, msg);
1272 if (ret <= 0) {
1273 if (!ret)
1274 goto missing_data_or_waiting;
1275 goto return_bad_req;
1276 }
1277 }
1278
Christopher Fauletf2824e62018-10-01 12:12:37 +02001279 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001280 if (!(req->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02001281 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001282 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
1283 if (req->flags & CF_SHUTW) {
1284 /* request errors are most likely due to the
1285 * server aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001286 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001287 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02001288 goto return_bad_req;
1289 }
1290 return 1;
1291 }
1292
1293 /* If "option abortonclose" is set on the backend, we want to monitor
1294 * the client's connection and forward any shutdown notification to the
1295 * server, which will decide whether to close or to go on processing the
1296 * request. We only do that in tunnel mode, and not in other modes since
1297 * it can be abused to exhaust source ports. */
1298 if ((s->be->options & PR_O_ABRT_CLOSE) && !(s->si[0].flags & SI_FL_CLEAN_ABRT)) {
1299 channel_auto_read(req);
1300 if ((req->flags & (CF_SHUTR|CF_READ_NULL)) &&
1301 ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN))
1302 s->si[1].flags |= SI_FL_NOLINGER;
1303 channel_auto_close(req);
1304 }
1305 else if (s->txn->meth == HTTP_METH_POST) {
1306 /* POST requests may require to read extra CRLF sent by broken
1307 * browsers and which could cause an RST to be sent upon close
1308 * on some systems (eg: Linux). */
1309 channel_auto_read(req);
1310 }
1311 return 0;
1312
1313 missing_data_or_waiting:
1314 /* stop waiting for data if the input is closed before the end */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001315 if (msg->msg_state < HTTP_MSG_DONE && req->flags & CF_SHUTR)
1316 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001317
1318 waiting:
1319 /* waiting for the last bits to leave the buffer */
1320 if (req->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01001321 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001322
Christopher Faulet47365272018-10-31 17:40:50 +01001323 if (htx->flags & HTX_FL_PARSING_ERROR)
1324 goto return_bad_req;
Christopher Faulet9768c262018-10-22 09:34:31 +02001325
Christopher Faulete0768eb2018-10-03 16:38:02 +02001326 /* When TE: chunked is used, we need to get there again to parse remaining
1327 * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
1328 * And when content-length is used, we never want to let the possible
1329 * shutdown be forwarded to the other side, as the state machine will
1330 * take care of it once the client responds. It's also important to
1331 * prevent TIME_WAITs from accumulating on the backend side, and for
1332 * HTTP/2 where the last frame comes with a shutdown.
1333 */
Christopher Faulet9768c262018-10-22 09:34:31 +02001334 if (msg->flags & HTTP_MSGF_XFER_LEN)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001335 channel_dont_close(req);
1336
1337 /* We know that more data are expected, but we couldn't send more that
1338 * what we did. So we always set the CF_EXPECT_MORE flag so that the
1339 * system knows it must not set a PUSH on this first part. Interactive
1340 * modes are already handled by the stream sock layer. We must not do
1341 * this in content-length mode because it could present the MSG_MORE
1342 * flag with the last block of forwarded data, which would cause an
1343 * additional delay to be observed by the receiver.
1344 */
1345 if (msg->flags & HTTP_MSGF_TE_CHNK)
1346 req->flags |= CF_EXPECT_MORE;
1347
1348 return 0;
1349
Christopher Faulet93e02d82019-03-08 14:18:50 +01001350 return_cli_abort:
1351 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1352 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
1353 if (objt_server(s->target))
1354 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
1355 if (!(s->flags & SF_ERR_MASK))
1356 s->flags |= SF_ERR_CLICL;
1357 status = 400;
1358 goto return_error;
1359
1360 return_srv_abort:
1361 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
1362 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
1363 if (objt_server(s->target))
1364 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
1365 if (!(s->flags & SF_ERR_MASK))
1366 s->flags |= SF_ERR_SRVCL;
1367 status = 502;
1368 goto return_error;
1369
1370 return_bad_req:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001371 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001372 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001373 _HA_ATOMIC_ADD(&sess->listener->counters->failed_req, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001374 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01001375 s->flags |= SF_ERR_CLICL;
1376 status = 400;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001377
Christopher Faulet93e02d82019-03-08 14:18:50 +01001378 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001379 txn->req.err_state = txn->req.msg_state;
1380 txn->req.msg_state = HTTP_MSG_ERROR;
Christopher Faulet9768c262018-10-22 09:34:31 +02001381 if (txn->status > 0) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02001382 /* Note: we don't send any error if some data were already sent */
Christopher Faulet9768c262018-10-22 09:34:31 +02001383 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001384 } else {
Christopher Faulet93e02d82019-03-08 14:18:50 +01001385 txn->status = status;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001386 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001387 }
1388 req->analysers &= AN_REQ_FLT_END;
1389 s->res.analysers &= AN_RES_FLT_END; /* we're in data phase, we want to abort both directions */
Christopher Faulet93e02d82019-03-08 14:18:50 +01001390 if (!(s->flags & SF_FINST_MASK))
1391 s->flags |= ((txn->rsp.msg_state < HTTP_MSG_ERROR) ? SF_FINST_H : SF_FINST_D);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001392 return 0;
1393}
1394
1395/* This stream analyser waits for a complete HTTP response. It returns 1 if the
1396 * processing can continue on next analysers, or zero if it either needs more
1397 * data or wants to immediately abort the response (eg: timeout, error, ...). It
1398 * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->res.analysers
1399 * when it has nothing left to do, and may remove any analyser when it wants to
1400 * abort.
1401 */
1402int htx_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
1403{
Christopher Faulet9768c262018-10-22 09:34:31 +02001404 /*
1405 * We will analyze a complete HTTP response to check the its syntax.
1406 *
1407 * Once the start line and all headers are received, we may perform a
1408 * capture of the error (if any), and we will set a few fields. We also
1409 * logging and finally headers capture.
1410 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001411 struct session *sess = s->sess;
1412 struct http_txn *txn = s->txn;
1413 struct http_msg *msg = &txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02001414 struct htx *htx;
Christopher Faulet61608322018-11-23 16:23:45 +01001415 struct connection *srv_conn;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001416 struct htx_sl *sl;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001417 int n;
1418
1419 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1420 now_ms, __FUNCTION__,
1421 s,
1422 rep,
1423 rep->rex, rep->wex,
1424 rep->flags,
1425 ci_data(rep),
1426 rep->analysers);
1427
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001428 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001429
Willy Tarreau4236f032019-03-05 10:43:32 +01001430 /* Parsing errors are caught here */
1431 if (htx->flags & HTX_FL_PARSING_ERROR)
1432 goto return_bad_res;
1433
Christopher Faulete0768eb2018-10-03 16:38:02 +02001434 /*
1435 * Now we quickly check if we have found a full valid response.
1436 * If not so, we check the FD and buffer states before leaving.
1437 * A full response is indicated by the fact that we have seen
1438 * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid
1439 * responses are checked first.
1440 *
1441 * Depending on whether the client is still there or not, we
1442 * may send an error response back or not. Note that normally
1443 * we should only check for HTTP status there, and check I/O
1444 * errors somewhere else.
1445 */
Christopher Faulet72b62732018-11-28 16:44:44 +01001446 if (unlikely(co_data(rep) || htx_is_empty(htx) || htx_get_tail_type(htx) < HTX_BLK_EOH)) {
Christopher Faulet47365272018-10-31 17:40:50 +01001447 /*
Christopher Fauletdcd8c5e2019-01-21 11:24:38 +01001448 * First catch invalid response because of a parsing error or
1449 * because only part of headers have been transfered.
1450 * Multiplexers have the responsibility to emit all headers at
1451 * once. We must be sure to have forwarded all outgoing data
1452 * first.
Christopher Faulet47365272018-10-31 17:40:50 +01001453 */
Willy Tarreau4236f032019-03-05 10:43:32 +01001454 if (!co_data(rep) && (htx_is_not_empty(htx) || (s->si[1].flags & SI_FL_RXBLK_ROOM)))
Christopher Faulet47365272018-10-31 17:40:50 +01001455 goto return_bad_res;
1456
Christopher Faulet9768c262018-10-22 09:34:31 +02001457 /* 1: have we encountered a read error ? */
1458 if (rep->flags & CF_READ_ERROR) {
1459 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001460 goto abort_keep_alive;
1461
Olivier Houcharda798bf52019-03-08 18:52:00 +01001462 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001463 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001464 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001465 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001466 }
1467
Christopher Faulete0768eb2018-10-03 16:38:02 +02001468 rep->analysers &= AN_RES_FLT_END;
1469 txn->status = 502;
1470
1471 /* Check to see if the server refused the early data.
1472 * If so, just send a 425
1473 */
1474 if (objt_cs(s->si[1].end)) {
1475 struct connection *conn = objt_cs(s->si[1].end)->conn;
1476
1477 if (conn->err_code == CO_ER_SSL_EARLY_FAILED)
1478 txn->status = 425;
1479 }
1480
1481 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001482 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001483
1484 if (!(s->flags & SF_ERR_MASK))
1485 s->flags |= SF_ERR_SRVCL;
1486 if (!(s->flags & SF_FINST_MASK))
1487 s->flags |= SF_FINST_H;
1488 return 0;
1489 }
1490
Christopher Faulet9768c262018-10-22 09:34:31 +02001491 /* 2: read timeout : return a 504 to the client. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001492 else if (rep->flags & CF_READ_TIMEOUT) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001493 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001494 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001495 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001496 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001497 }
1498
Christopher Faulete0768eb2018-10-03 16:38:02 +02001499 rep->analysers &= AN_RES_FLT_END;
1500 txn->status = 504;
1501 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001502 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001503
1504 if (!(s->flags & SF_ERR_MASK))
1505 s->flags |= SF_ERR_SRVTO;
1506 if (!(s->flags & SF_FINST_MASK))
1507 s->flags |= SF_FINST_H;
1508 return 0;
1509 }
1510
Christopher Faulet9768c262018-10-22 09:34:31 +02001511 /* 3: client abort with an abortonclose */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001512 else if ((rep->flags & CF_SHUTR) && ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001513 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
1514 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001515 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001516 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001517
1518 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001519 txn->status = 400;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001520 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001521
1522 if (!(s->flags & SF_ERR_MASK))
1523 s->flags |= SF_ERR_CLICL;
1524 if (!(s->flags & SF_FINST_MASK))
1525 s->flags |= SF_FINST_H;
1526
1527 /* process_stream() will take care of the error */
1528 return 0;
1529 }
1530
Christopher Faulet9768c262018-10-22 09:34:31 +02001531 /* 4: close from server, capture the response if the server has started to respond */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001532 else if (rep->flags & CF_SHUTR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001533 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001534 goto abort_keep_alive;
1535
Olivier Houcharda798bf52019-03-08 18:52:00 +01001536 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001537 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001538 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001539 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001540 }
1541
Christopher Faulete0768eb2018-10-03 16:38:02 +02001542 rep->analysers &= AN_RES_FLT_END;
1543 txn->status = 502;
1544 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001545 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulete0768eb2018-10-03 16:38:02 +02001546
1547 if (!(s->flags & SF_ERR_MASK))
1548 s->flags |= SF_ERR_SRVCL;
1549 if (!(s->flags & SF_FINST_MASK))
1550 s->flags |= SF_FINST_H;
1551 return 0;
1552 }
1553
Christopher Faulet9768c262018-10-22 09:34:31 +02001554 /* 5: write error to client (we don't send any message then) */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001555 else if (rep->flags & CF_WRITE_ERROR) {
Christopher Faulet9768c262018-10-22 09:34:31 +02001556 if (txn->flags & TX_NOT_FIRST)
Christopher Faulete0768eb2018-10-03 16:38:02 +02001557 goto abort_keep_alive;
1558
Olivier Houcharda798bf52019-03-08 18:52:00 +01001559 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001560 rep->analysers &= AN_RES_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001561
1562 if (!(s->flags & SF_ERR_MASK))
1563 s->flags |= SF_ERR_CLICL;
1564 if (!(s->flags & SF_FINST_MASK))
1565 s->flags |= SF_FINST_H;
1566
1567 /* process_stream() will take care of the error */
1568 return 0;
1569 }
1570
1571 channel_dont_close(rep);
1572 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
1573 return 0;
1574 }
1575
1576 /* More interesting part now : we know that we have a complete
1577 * response which at least looks like HTTP. We have an indicator
1578 * of each header's length, so we can parse them quickly.
1579 */
1580
Christopher Faulet9768c262018-10-22 09:34:31 +02001581 msg->msg_state = HTTP_MSG_BODY;
Christopher Faulet03599112018-11-27 11:21:21 +01001582 sl = http_find_stline(htx);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001583
Christopher Faulet9768c262018-10-22 09:34:31 +02001584 /* 0: we might have to print this header in debug mode */
1585 if (unlikely((global.mode & MODE_DEBUG) &&
1586 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) {
1587 int32_t pos;
1588
Christopher Faulet03599112018-11-27 11:21:21 +01001589 htx_debug_stline("srvrep", s, sl);
Christopher Faulet9768c262018-10-22 09:34:31 +02001590
1591 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1592 struct htx_blk *blk = htx_get_blk(htx, pos);
1593 enum htx_blk_type type = htx_get_blk_type(blk);
1594
1595 if (type == HTX_BLK_EOH)
1596 break;
1597 if (type != HTX_BLK_HDR)
1598 continue;
1599
1600 htx_debug_hdr("srvhdr", s,
1601 htx_get_blk_name(htx, blk),
1602 htx_get_blk_value(htx, blk));
1603 }
1604 }
1605
Christopher Faulet03599112018-11-27 11:21:21 +01001606 /* 1: get the status code and the version. Also set HTTP flags */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01001607 txn->status = sl->info.res.status;
Christopher Faulet03599112018-11-27 11:21:21 +01001608 if (sl->flags & HTX_SL_F_VER_11)
Christopher Faulet9768c262018-10-22 09:34:31 +02001609 msg->flags |= HTTP_MSGF_VER_11;
Christopher Faulet03599112018-11-27 11:21:21 +01001610 if (sl->flags & HTX_SL_F_XFER_LEN) {
1611 msg->flags |= HTTP_MSGF_XFER_LEN;
Christopher Faulet834eee72019-02-18 11:35:02 +01001612 msg->flags |= ((sl->flags & HTX_SL_F_CLEN) ? HTTP_MSGF_CNT_LEN : HTTP_MSGF_TE_CHNK);
Christopher Fauletb2db4fa2018-11-27 16:51:09 +01001613 if (sl->flags & HTX_SL_F_BODYLESS)
1614 msg->flags |= HTTP_MSGF_BODYLESS;
Christopher Faulet03599112018-11-27 11:21:21 +01001615 }
Christopher Faulet9768c262018-10-22 09:34:31 +02001616
1617 n = txn->status / 100;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001618 if (n < 1 || n > 5)
1619 n = 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001620
Christopher Faulete0768eb2018-10-03 16:38:02 +02001621 /* when the client triggers a 4xx from the server, it's most often due
1622 * to a missing object or permission. These events should be tracked
1623 * because if they happen often, it may indicate a brute force or a
1624 * vulnerability scan.
1625 */
1626 if (n == 4)
1627 stream_inc_http_err_ctr(s);
1628
1629 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001630 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.p.http.rsp[n], 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001631
Christopher Faulete0768eb2018-10-03 16:38:02 +02001632 /* Adjust server's health based on status code. Note: status codes 501
1633 * and 505 are triggered on demand by client request, so we must not
1634 * count them as server failures.
1635 */
1636 if (objt_server(s->target)) {
1637 if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505))
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001638 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_OK);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001639 else
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001640 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_STS);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001641 }
1642
1643 /*
1644 * We may be facing a 100-continue response, or any other informational
1645 * 1xx response which is non-final, in which case this is not the right
1646 * response, and we're waiting for the next one. Let's allow this response
1647 * to go to the client and wait for the next one. There's an exception for
1648 * 101 which is used later in the code to switch protocols.
1649 */
1650 if (txn->status < 200 &&
1651 (txn->status == 100 || txn->status >= 102)) {
Christopher Fauletaed82cf2018-11-30 22:22:32 +01001652 FLT_STRM_CB(s, flt_http_reset(s, msg));
Christopher Faulet9768c262018-10-22 09:34:31 +02001653 c_adv(rep, htx->data);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001654 msg->msg_state = HTTP_MSG_RPBEFORE;
1655 txn->status = 0;
1656 s->logs.t_data = -1; /* was not a response yet */
Christopher Faulet9768c262018-10-22 09:34:31 +02001657 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001658 }
1659
1660 /*
1661 * 2: check for cacheability.
1662 */
1663
1664 switch (txn->status) {
1665 case 200:
1666 case 203:
1667 case 204:
1668 case 206:
1669 case 300:
1670 case 301:
1671 case 404:
1672 case 405:
1673 case 410:
1674 case 414:
1675 case 501:
1676 break;
1677 default:
1678 /* RFC7231#6.1:
1679 * Responses with status codes that are defined as
1680 * cacheable by default (e.g., 200, 203, 204, 206,
1681 * 300, 301, 404, 405, 410, 414, and 501 in this
1682 * specification) can be reused by a cache with
1683 * heuristic expiration unless otherwise indicated
1684 * by the method definition or explicit cache
1685 * controls [RFC7234]; all other status codes are
1686 * not cacheable by default.
1687 */
1688 txn->flags &= ~(TX_CACHEABLE | TX_CACHE_COOK);
1689 break;
1690 }
1691
1692 /*
1693 * 3: we may need to capture headers
1694 */
1695 s->logs.logwait &= ~LW_RESP;
1696 if (unlikely((s->logs.logwait & LW_RSPHDR) && s->res_cap))
Christopher Faulet9768c262018-10-22 09:34:31 +02001697 htx_capture_headers(htx, s->res_cap, sess->fe->rsp_cap);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001698
Christopher Faulet9768c262018-10-22 09:34:31 +02001699 /* Skip parsing if no content length is possible. */
Christopher Faulete0768eb2018-10-03 16:38:02 +02001700 if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) ||
1701 txn->status == 101)) {
1702 /* Either we've established an explicit tunnel, or we're
1703 * switching the protocol. In both cases, we're very unlikely
1704 * to understand the next protocols. We have to switch to tunnel
1705 * mode, so that we transfer the request and responses then let
1706 * this protocol pass unmodified. When we later implement specific
1707 * parsers for such protocols, we'll want to check the Upgrade
1708 * header which contains information about that protocol for
1709 * responses with status 101 (eg: see RFC2817 about TLS).
1710 */
1711 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001712 }
1713
Christopher Faulet61608322018-11-23 16:23:45 +01001714 /* check for NTML authentication headers in 401 (WWW-Authenticate) and
1715 * 407 (Proxy-Authenticate) responses and set the connection to private
1716 */
1717 srv_conn = cs_conn(objt_cs(s->si[1].end));
1718 if (srv_conn) {
1719 struct ist hdr;
1720 struct http_hdr_ctx ctx;
1721
1722 if (txn->status == 401)
1723 hdr = ist("WWW-Authenticate");
1724 else if (txn->status == 407)
1725 hdr = ist("Proxy-Authenticate");
1726 else
1727 goto end;
1728
1729 ctx.blk = NULL;
1730 while (http_find_header(htx, hdr, &ctx, 0)) {
1731 if ((ctx.value.len >= 9 && word_match(ctx.value.ptr, ctx.value.len, "Negotiate", 9)) ||
1732 (ctx.value.len >= 4 && word_match(ctx.value.ptr, ctx.value.len, "NTLM", 4)))
1733 srv_conn->flags |= CO_FL_PRIVATE;
1734 }
1735 }
1736
1737 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02001738 /* we want to have the response time before we start processing it */
1739 s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now);
1740
1741 /* end of job, return OK */
1742 rep->analysers &= ~an_bit;
1743 rep->analyse_exp = TICK_ETERNITY;
1744 channel_auto_close(rep);
1745 return 1;
1746
Christopher Faulet47365272018-10-31 17:40:50 +01001747 return_bad_res:
Olivier Houcharda798bf52019-03-08 18:52:00 +01001748 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Faulet47365272018-10-31 17:40:50 +01001749 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01001750 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01001751 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_HDRRSP);
Christopher Faulet47365272018-10-31 17:40:50 +01001752 }
1753 txn->status = 502;
1754 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01001755 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Faulet47365272018-10-31 17:40:50 +01001756 rep->analysers &= AN_RES_FLT_END;
1757
1758 if (!(s->flags & SF_ERR_MASK))
1759 s->flags |= SF_ERR_PRXCOND;
1760 if (!(s->flags & SF_FINST_MASK))
1761 s->flags |= SF_FINST_H;
1762 return 0;
1763
Christopher Faulete0768eb2018-10-03 16:38:02 +02001764 abort_keep_alive:
1765 /* A keep-alive request to the server failed on a network error.
1766 * The client is required to retry. We need to close without returning
1767 * any other information so that the client retries.
1768 */
1769 txn->status = 0;
1770 rep->analysers &= AN_RES_FLT_END;
1771 s->req.analysers &= AN_REQ_FLT_END;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001772 s->logs.logwait = 0;
1773 s->logs.level = 0;
1774 s->res.flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */
Christopher Faulet9768c262018-10-22 09:34:31 +02001775 htx_reply_and_close(s, txn->status, NULL);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001776 return 0;
1777}
1778
1779/* This function performs all the processing enabled for the current response.
1780 * It normally returns 1 unless it wants to break. It relies on buffers flags,
1781 * and updates s->res.analysers. It might make sense to explode it into several
1782 * other functions. It works like process_request (see indications above).
1783 */
1784int htx_process_res_common(struct stream *s, struct channel *rep, int an_bit, struct proxy *px)
1785{
1786 struct session *sess = s->sess;
1787 struct http_txn *txn = s->txn;
1788 struct http_msg *msg = &txn->rsp;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001789 struct htx *htx;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001790 struct proxy *cur_proxy;
1791 struct cond_wordlist *wl;
1792 enum rule_result ret = HTTP_RULE_RES_CONT;
1793
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001794 if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */
1795 return 0;
Christopher Faulet9768c262018-10-22 09:34:31 +02001796
Christopher Faulete0768eb2018-10-03 16:38:02 +02001797 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
1798 now_ms, __FUNCTION__,
1799 s,
1800 rep,
1801 rep->rex, rep->wex,
1802 rep->flags,
1803 ci_data(rep),
1804 rep->analysers);
1805
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01001806 htx = htxbuf(&rep->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001807
1808 /* The stats applet needs to adjust the Connection header but we don't
1809 * apply any filter there.
1810 */
1811 if (unlikely(objt_applet(s->target) == &http_stats_applet)) {
1812 rep->analysers &= ~an_bit;
1813 rep->analyse_exp = TICK_ETERNITY;
Christopher Fauletf2824e62018-10-01 12:12:37 +02001814 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001815 }
1816
1817 /*
1818 * We will have to evaluate the filters.
1819 * As opposed to version 1.2, now they will be evaluated in the
1820 * filters order and not in the header order. This means that
1821 * each filter has to be validated among all headers.
1822 *
1823 * Filters are tried with ->be first, then with ->fe if it is
1824 * different from ->be.
1825 *
1826 * Maybe we are in resume condiion. In this case I choose the
1827 * "struct proxy" which contains the rule list matching the resume
1828 * pointer. If none of theses "struct proxy" match, I initialise
1829 * the process with the first one.
1830 *
1831 * In fact, I check only correspondance betwwen the current list
1832 * pointer and the ->fe rule list. If it doesn't match, I initialize
1833 * the loop with the ->be.
1834 */
1835 if (s->current_rule_list == &sess->fe->http_res_rules)
1836 cur_proxy = sess->fe;
1837 else
1838 cur_proxy = s->be;
1839 while (1) {
1840 struct proxy *rule_set = cur_proxy;
1841
1842 /* evaluate http-response rules */
1843 if (ret == HTTP_RULE_RES_CONT) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001844 ret = htx_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001845
1846 if (ret == HTTP_RULE_RES_BADREQ)
1847 goto return_srv_prx_502;
1848
1849 if (ret == HTTP_RULE_RES_DONE) {
1850 rep->analysers &= ~an_bit;
1851 rep->analyse_exp = TICK_ETERNITY;
1852 return 1;
1853 }
1854 }
1855
1856 /* we need to be called again. */
1857 if (ret == HTTP_RULE_RES_YIELD) {
1858 channel_dont_close(rep);
1859 return 0;
1860 }
1861
1862 /* try headers filters */
1863 if (rule_set->rsp_exp != NULL) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001864 if (htx_apply_filters_to_response(s, rep, rule_set) < 0)
1865 goto return_bad_resp;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001866 }
1867
1868 /* has the response been denied ? */
1869 if (txn->flags & TX_SVDENY) {
1870 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01001871 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001872
Olivier Houcharda798bf52019-03-08 18:52:00 +01001873 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
1874 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001875 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01001876 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001877 goto return_srv_prx_502;
1878 }
1879
1880 /* add response headers from the rule sets in the same order */
1881 list_for_each_entry(wl, &rule_set->rsp_add, list) {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001882 struct ist n, v;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001883 if (txn->status < 200 && txn->status != 101)
1884 break;
1885 if (wl->cond) {
1886 int ret = acl_exec_cond(wl->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
1887 ret = acl_pass(ret);
1888 if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS)
1889 ret = !ret;
1890 if (!ret)
1891 continue;
1892 }
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001893
1894 http_parse_header(ist2(wl->s, strlen(wl->s)), &n, &v);
1895 if (unlikely(!http_add_header(htx, n, v)))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001896 goto return_bad_resp;
1897 }
1898
1899 /* check whether we're already working on the frontend */
1900 if (cur_proxy == sess->fe)
1901 break;
1902 cur_proxy = sess->fe;
1903 }
1904
1905 /* After this point, this anayzer can't return yield, so we can
1906 * remove the bit corresponding to this analyzer from the list.
1907 *
1908 * Note that the intermediate returns and goto found previously
1909 * reset the analyzers.
1910 */
1911 rep->analysers &= ~an_bit;
1912 rep->analyse_exp = TICK_ETERNITY;
1913
1914 /* OK that's all we can do for 1xx responses */
1915 if (unlikely(txn->status < 200 && txn->status != 101))
Christopher Fauletf2824e62018-10-01 12:12:37 +02001916 goto end;
Christopher Faulete0768eb2018-10-03 16:38:02 +02001917
1918 /*
1919 * Now check for a server cookie.
1920 */
1921 if (s->be->cookie_name || sess->fe->capture_name || (s->be->options & PR_O_CHK_CACHE))
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001922 htx_manage_server_side_cookies(s, rep);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001923
1924 /*
1925 * Check for cache-control or pragma headers if required.
1926 */
1927 if ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))
1928 check_response_for_cacheability(s, rep);
1929
1930 /*
1931 * Add server cookie in the response if needed
1932 */
1933 if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) &&
1934 !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) &&
1935 (!(s->flags & SF_DIRECT) ||
1936 ((s->be->cookie_maxidle || txn->cookie_last_date) &&
1937 (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) ||
1938 (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date
1939 (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date
1940 (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) &&
1941 !(s->flags & SF_IGNORE_PRST)) {
1942 /* the server is known, it's not the one the client requested, or the
1943 * cookie's last seen date needs to be refreshed. We have to
1944 * insert a set-cookie here, except if we want to insert only on POST
1945 * requests and this one isn't. Note that servers which don't have cookies
1946 * (eg: some backup servers) will return a full cookie removal request.
1947 */
1948 if (!objt_server(s->target)->cookie) {
1949 chunk_printf(&trash,
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001950 "%s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/",
Christopher Faulete0768eb2018-10-03 16:38:02 +02001951 s->be->cookie_name);
1952 }
1953 else {
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001954 chunk_printf(&trash, "%s=%s", s->be->cookie_name, objt_server(s->target)->cookie);
Christopher Faulete0768eb2018-10-03 16:38:02 +02001955
1956 if (s->be->cookie_maxidle || s->be->cookie_maxlife) {
1957 /* emit last_date, which is mandatory */
1958 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1959 s30tob64((date.tv_sec+3) >> 2,
1960 trash.area + trash.data);
1961 trash.data += 5;
1962
1963 if (s->be->cookie_maxlife) {
1964 /* emit first_date, which is either the original one or
1965 * the current date.
1966 */
1967 trash.area[trash.data++] = COOKIE_DELIM_DATE;
1968 s30tob64(txn->cookie_first_date ?
1969 txn->cookie_first_date >> 2 :
1970 (date.tv_sec+3) >> 2,
1971 trash.area + trash.data);
1972 trash.data += 5;
1973 }
1974 }
1975 chunk_appendf(&trash, "; path=/");
1976 }
1977
1978 if (s->be->cookie_domain)
1979 chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain);
1980
1981 if (s->be->ck_opts & PR_CK_HTTPONLY)
1982 chunk_appendf(&trash, "; HttpOnly");
1983
1984 if (s->be->ck_opts & PR_CK_SECURE)
1985 chunk_appendf(&trash, "; Secure");
1986
Christopher Fauletfec7bd12018-10-24 11:17:50 +02001987 if (unlikely(!http_add_header(htx, ist("Set-Cookie"), ist2(trash.area, trash.data))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02001988 goto return_bad_resp;
1989
1990 txn->flags &= ~TX_SCK_MASK;
1991 if (__objt_server(s->target)->cookie && (s->flags & SF_DIRECT))
1992 /* the server did not change, only the date was updated */
1993 txn->flags |= TX_SCK_UPDATED;
1994 else
1995 txn->flags |= TX_SCK_INSERTED;
1996
1997 /* Here, we will tell an eventual cache on the client side that we don't
1998 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
1999 * Some caches understand the correct form: 'no-cache="set-cookie"', but
2000 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
2001 */
2002 if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) {
2003
2004 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
2005
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002006 if (unlikely(!http_add_header(htx, ist("Cache-control"), ist("private"))))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002007 goto return_bad_resp;
2008 }
2009 }
2010
2011 /*
2012 * Check if result will be cacheable with a cookie.
2013 * We'll block the response if security checks have caught
2014 * nasty things such as a cacheable cookie.
2015 */
2016 if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) ==
2017 (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) &&
2018 (s->be->options & PR_O_CHK_CACHE)) {
2019 /* we're in presence of a cacheable response containing
2020 * a set-cookie header. We'll block it as requested by
2021 * the 'checkcache' option, and send an alert.
2022 */
2023 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01002024 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_secu, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002025
Olivier Houcharda798bf52019-03-08 18:52:00 +01002026 _HA_ATOMIC_ADD(&s->be->be_counters.denied_resp, 1);
2027 _HA_ATOMIC_ADD(&sess->fe->fe_counters.denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002028 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002029 _HA_ATOMIC_ADD(&sess->listener->counters->denied_resp, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002030
2031 ha_alert("Blocking cacheable cookie in response from instance %s, server %s.\n",
2032 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2033 send_log(s->be, LOG_ALERT,
2034 "Blocking cacheable cookie in response from instance %s, server %s.\n",
2035 s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>");
2036 goto return_srv_prx_502;
2037 }
2038
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002039 end:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002040 /* Always enter in the body analyzer */
2041 rep->analysers &= ~AN_RES_FLT_XFER_DATA;
2042 rep->analysers |= AN_RES_HTTP_XFER_BODY;
2043
2044 /* if the user wants to log as soon as possible, without counting
2045 * bytes from the server, then this is the right moment. We have
2046 * to temporarily assign bytes_out to log what we currently have.
2047 */
2048 if (!LIST_ISEMPTY(&sess->fe->logformat) && !(s->logs.logwait & LW_BYTES)) {
2049 s->logs.t_close = s->logs.t_data; /* to get a valid end date */
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002050 s->logs.bytes_out = htx->data;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002051 s->do_log(s);
2052 s->logs.bytes_out = 0;
2053 }
2054 return 1;
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002055
2056 return_bad_resp:
2057 if (objt_server(s->target)) {
Olivier Houcharda798bf52019-03-08 18:52:00 +01002058 _HA_ATOMIC_ADD(&__objt_server(s->target)->counters.failed_resp, 1);
Willy Tarreaub54c40a2018-12-02 19:28:41 +01002059 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002060 }
Olivier Houcharda798bf52019-03-08 18:52:00 +01002061 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002062
2063 return_srv_prx_502:
2064 rep->analysers &= AN_RES_FLT_END;
2065 txn->status = 502;
2066 s->logs.t_data = -1; /* was not a valid response */
2067 s->si[1].flags |= SI_FL_NOLINGER;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01002068 htx_reply_and_close(s, txn->status, htx_error_message(s));
Christopher Fauletfec7bd12018-10-24 11:17:50 +02002069 if (!(s->flags & SF_ERR_MASK))
2070 s->flags |= SF_ERR_PRXCOND;
2071 if (!(s->flags & SF_FINST_MASK))
2072 s->flags |= SF_FINST_H;
2073 return 0;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002074}
2075
2076/* This function is an analyser which forwards response body (including chunk
2077 * sizes if any). It is called as soon as we must forward, even if we forward
2078 * zero byte. The only situation where it must not be called is when we're in
2079 * tunnel mode and we want to forward till the close. It's used both to forward
2080 * remaining data and to resync after end of body. It expects the msg_state to
2081 * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to
2082 * read more data, or 1 once we can go on with next request or end the stream.
2083 *
2084 * It is capable of compressing response data both in content-length mode and
2085 * in chunked mode. The state machines follows different flows depending on
2086 * whether content-length and chunked modes are used, since there are no
2087 * trailers in content-length :
2088 *
2089 * chk-mode cl-mode
2090 * ,----- BODY -----.
2091 * / \
2092 * V size > 0 V chk-mode
2093 * .--> SIZE -------------> DATA -------------> CRLF
2094 * | | size == 0 | last byte |
2095 * | v final crlf v inspected |
2096 * | TRAILERS -----------> DONE |
2097 * | |
2098 * `----------------------------------------------'
2099 *
2100 * Compression only happens in the DATA state, and must be flushed in final
2101 * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding
2102 * is performed at once on final states for all bytes parsed, or when leaving
2103 * on missing data.
2104 */
2105int htx_response_forward_body(struct stream *s, struct channel *res, int an_bit)
2106{
2107 struct session *sess = s->sess;
2108 struct http_txn *txn = s->txn;
2109 struct http_msg *msg = &s->txn->rsp;
Christopher Faulet9768c262018-10-22 09:34:31 +02002110 struct htx *htx;
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002111 int ret;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002112
2113 DPRINTF(stderr,"[%u] %s: stream=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%lu analysers=%02x\n",
2114 now_ms, __FUNCTION__,
2115 s,
2116 res,
2117 res->rex, res->wex,
2118 res->flags,
2119 ci_data(res),
2120 res->analysers);
2121
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002122 htx = htxbuf(&res->buf);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002123
2124 if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
Christopher Fauletf2824e62018-10-01 12:12:37 +02002125 ((res->flags & CF_SHUTW) && (res->to_forward || co_data(res)))) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002126 /* Output closed while we were sending data. We must abort and
2127 * wake the other side up.
2128 */
2129 msg->err_state = msg->msg_state;
2130 msg->msg_state = HTTP_MSG_ERROR;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002131 htx_end_response(s);
2132 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002133 return 1;
2134 }
2135
Christopher Faulet9768c262018-10-22 09:34:31 +02002136 if (msg->msg_state == HTTP_MSG_BODY)
2137 msg->msg_state = HTTP_MSG_DATA;
2138
Christopher Faulete0768eb2018-10-03 16:38:02 +02002139 /* in most states, we should abort in case of early close */
2140 channel_auto_close(res);
2141
Christopher Faulete0768eb2018-10-03 16:38:02 +02002142 if (res->to_forward) {
2143 /* We can't process the buffer's contents yet */
2144 res->flags |= CF_WAKE_WRITE;
2145 goto missing_data_or_waiting;
2146 }
2147
Christopher Faulet9768c262018-10-22 09:34:31 +02002148 if (msg->msg_state >= HTTP_MSG_DONE)
2149 goto done;
2150
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002151 /* Forward input data. We get it by removing all outgoing data not
2152 * forwarded yet from HTX data size. If there are some data filters, we
2153 * let them decide the amount of data to forward.
Christopher Faulet9768c262018-10-22 09:34:31 +02002154 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002155 if (HAS_RSP_DATA_FILTERS(s)) {
2156 ret = flt_http_payload(s, msg, htx->data);
2157 if (ret < 0)
2158 goto return_bad_res;
2159 c_adv(res, ret);
2160 if (htx->data != co_data(res) || htx->extra)
2161 goto missing_data_or_waiting;
2162 }
2163 else {
2164 c_adv(res, htx->data - co_data(res));
Christopher Faulet9768c262018-10-22 09:34:31 +02002165
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002166 /* To let the function channel_forward work as expected we must update
2167 * the channel's buffer to pretend there is no more input data. The
2168 * right length is then restored. We must do that, because when an HTX
2169 * message is stored into a buffer, it appears as full.
2170 */
Christopher Fauletb2aedea2018-12-05 11:56:15 +01002171 if ((msg->flags & HTTP_MSGF_XFER_LEN) && htx->extra)
2172 htx->extra -= channel_htx_forward(res, htx, htx->extra);
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002173 }
Christopher Faulet9768c262018-10-22 09:34:31 +02002174
2175 if (!(msg->flags & HTTP_MSGF_XFER_LEN)) {
2176 /* The server still sending data that should be filtered */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002177 if (res->flags & CF_SHUTR || !HAS_RSP_DATA_FILTERS(s)) {
Christopher Faulet9768c262018-10-22 09:34:31 +02002178 msg->msg_state = HTTP_MSG_TUNNEL;
2179 goto done;
2180 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002181 }
2182
Christopher Faulet9768c262018-10-22 09:34:31 +02002183 /* Check if the end-of-message is reached and if so, switch the message
2184 * in HTTP_MSG_DONE state.
2185 */
2186 if (htx_get_tail_type(htx) != HTX_BLK_EOM)
2187 goto missing_data_or_waiting;
2188
2189 msg->msg_state = HTTP_MSG_DONE;
2190
2191 done:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002192 /* other states, DONE...TUNNEL */
Christopher Faulet9768c262018-10-22 09:34:31 +02002193 channel_dont_close(res);
2194
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002195 if (HAS_RSP_DATA_FILTERS(s)) {
2196 ret = flt_http_end(s, msg);
2197 if (ret <= 0) {
2198 if (!ret)
2199 goto missing_data_or_waiting;
2200 goto return_bad_res;
2201 }
2202 }
2203
Christopher Fauletf2824e62018-10-01 12:12:37 +02002204 htx_end_response(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002205 if (!(res->analysers & an_bit)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02002206 htx_end_request(s);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002207 if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
2208 if (res->flags & CF_SHUTW) {
2209 /* response errors are most likely due to the
2210 * client aborting the transfer. */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002211 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002212 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002213 goto return_bad_res;
2214 }
2215 return 1;
2216 }
2217 return 0;
2218
2219 missing_data_or_waiting:
2220 if (res->flags & CF_SHUTW)
Christopher Faulet93e02d82019-03-08 14:18:50 +01002221 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002222
Christopher Faulet47365272018-10-31 17:40:50 +01002223 if (htx->flags & HTX_FL_PARSING_ERROR)
2224 goto return_bad_res;
2225
Christopher Faulete0768eb2018-10-03 16:38:02 +02002226 /* stop waiting for data if the input is closed before the end. If the
2227 * client side was already closed, it means that the client has aborted,
2228 * so we don't want to count this as a server abort. Otherwise it's a
2229 * server abort.
2230 */
Christopher Faulet9768c262018-10-22 09:34:31 +02002231 if (msg->msg_state < HTTP_MSG_DONE && res->flags & CF_SHUTR) {
Christopher Faulete0768eb2018-10-03 16:38:02 +02002232 if ((s->req.flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002233 goto return_cli_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002234 /* If we have some pending data, we continue the processing */
Christopher Faulet93e02d82019-03-08 14:18:50 +01002235 if (htx_is_empty(htx))
2236 goto return_srv_abort;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002237 }
2238
Christopher Faulete0768eb2018-10-03 16:38:02 +02002239 /* When TE: chunked is used, we need to get there again to parse
2240 * remaining chunks even if the server has closed, so we don't want to
Christopher Faulet9768c262018-10-22 09:34:31 +02002241 * set CF_DONTCLOSE. Similarly when there is a content-leng or if there
2242 * are filters registered on the stream, we don't want to forward a
2243 * close
Christopher Faulete0768eb2018-10-03 16:38:02 +02002244 */
Christopher Fauletaed82cf2018-11-30 22:22:32 +01002245 if ((msg->flags & HTTP_MSGF_XFER_LEN) || HAS_RSP_DATA_FILTERS(s))
Christopher Faulete0768eb2018-10-03 16:38:02 +02002246 channel_dont_close(res);
2247
2248 /* We know that more data are expected, but we couldn't send more that
2249 * what we did. So we always set the CF_EXPECT_MORE flag so that the
2250 * system knows it must not set a PUSH on this first part. Interactive
2251 * modes are already handled by the stream sock layer. We must not do
2252 * this in content-length mode because it could present the MSG_MORE
2253 * flag with the last block of forwarded data, which would cause an
2254 * additional delay to be observed by the receiver.
2255 */
2256 if ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->flags & HTTP_MSGF_COMPRESSING))
2257 res->flags |= CF_EXPECT_MORE;
2258
2259 /* the stream handler will take care of timeouts and errors */
2260 return 0;
2261
Christopher Faulet93e02d82019-03-08 14:18:50 +01002262 return_srv_abort:
2263 _HA_ATOMIC_ADD(&sess->fe->fe_counters.srv_aborts, 1);
2264 _HA_ATOMIC_ADD(&s->be->be_counters.srv_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002265 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002266 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.srv_aborts, 1);
2267 if (!(s->flags & SF_ERR_MASK))
2268 s->flags |= SF_ERR_SRVCL;
2269 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002270
Christopher Faulet93e02d82019-03-08 14:18:50 +01002271 return_cli_abort:
2272 _HA_ATOMIC_ADD(&sess->fe->fe_counters.cli_aborts, 1);
2273 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Faulete0768eb2018-10-03 16:38:02 +02002274 if (objt_server(s->target))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002275 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
2276 if (!(s->flags & SF_ERR_MASK))
2277 s->flags |= SF_ERR_CLICL;
2278 goto return_error;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002279
Christopher Faulet93e02d82019-03-08 14:18:50 +01002280 return_bad_res:
2281 _HA_ATOMIC_ADD(&s->be->be_counters.failed_resp, 1);
2282 if (objt_server(s->target)) {
2283 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_resp, 1);
2284 health_adjust(__objt_server(s->target), HANA_STATUS_HTTP_RSP);
2285 }
Christopher Faulete0768eb2018-10-03 16:38:02 +02002286 if (!(s->flags & SF_ERR_MASK))
Christopher Faulet93e02d82019-03-08 14:18:50 +01002287 s->flags |= SF_ERR_SRVCL;
Christopher Faulete0768eb2018-10-03 16:38:02 +02002288
Christopher Faulet93e02d82019-03-08 14:18:50 +01002289 return_error:
Christopher Faulete0768eb2018-10-03 16:38:02 +02002290 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 */
Christopher Faulete0768eb2018-10-03 16:38:02 +02002296 if (!(s->flags & SF_FINST_MASK))
2297 s->flags |= SF_FINST_D;
2298 return 0;
2299}
2300
Christopher Faulet0f226952018-10-22 09:29:56 +02002301void htx_adjust_conn_mode(struct stream *s, struct http_txn *txn)
Christopher Fauletf2824e62018-10-01 12:12:37 +02002302{
2303 struct proxy *fe = strm_fe(s);
2304 int tmp = TX_CON_WANT_CLO;
2305
2306 if ((fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN)
2307 tmp = TX_CON_WANT_TUN;
2308
2309 if ((txn->flags & TX_CON_WANT_MSK) < tmp)
Christopher Faulet0f226952018-10-22 09:29:56 +02002310 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002311}
2312
2313/* Perform an HTTP redirect based on the information in <rule>. The function
Christopher Faulet99daf282018-11-28 22:58:13 +01002314 * returns zero on success, or zero in case of a, irrecoverable error such
Christopher Fauletf2824e62018-10-01 12:12:37 +02002315 * as too large a request to build a valid response.
2316 */
2317int htx_apply_redirect_rule(struct redirect_rule *rule, struct stream *s, struct http_txn *txn)
2318{
Christopher Faulet99daf282018-11-28 22:58:13 +01002319 struct channel *req = &s->req;
2320 struct channel *res = &s->res;
2321 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01002322 struct htx_sl *sl;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002323 struct buffer *chunk;
Christopher Faulet99daf282018-11-28 22:58:13 +01002324 struct ist status, reason, location;
2325 unsigned int flags;
2326 size_t data;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002327
2328 chunk = alloc_trash_chunk();
2329 if (!chunk)
Christopher Faulet99daf282018-11-28 22:58:13 +01002330 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002331
Christopher Faulet99daf282018-11-28 22:58:13 +01002332 /*
2333 * Create the location
2334 */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002335 htx = htxbuf(&req->buf);
Christopher Fauletf2824e62018-10-01 12:12:37 +02002336 switch(rule->type) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002337 case REDIRECT_TYPE_SCHEME: {
2338 struct http_hdr_ctx ctx;
2339 struct ist path, host;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002340
Christopher Faulet99daf282018-11-28 22:58:13 +01002341 host = ist("");
2342 ctx.blk = NULL;
2343 if (http_find_header(htx, ist("Host"), &ctx, 0))
2344 host = ctx.value;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002345
Christopher Faulet99daf282018-11-28 22:58:13 +01002346 sl = http_find_stline(htx);
2347 path = http_get_path(htx_sl_req_uri(sl));
2348 /* build message using path */
2349 if (path.ptr) {
2350 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2351 int qs = 0;
2352 while (qs < path.len) {
2353 if (*(path.ptr + qs) == '?') {
2354 path.len = qs;
2355 break;
2356 }
2357 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002358 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002359 }
2360 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002361 else
2362 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002363
Christopher Faulet99daf282018-11-28 22:58:13 +01002364 if (rule->rdr_str) { /* this is an old "redirect" rule */
2365 /* add scheme */
2366 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2367 goto fail;
2368 }
2369 else {
2370 /* add scheme with executing log format */
2371 chunk->data += build_logline(s, chunk->area + chunk->data,
2372 chunk->size - chunk->data,
2373 &rule->rdr_fmt);
2374 }
2375 /* add "://" + host + path */
2376 if (!chunk_memcat(chunk, "://", 3) ||
2377 !chunk_memcat(chunk, host.ptr, host.len) ||
2378 !chunk_memcat(chunk, path.ptr, path.len))
2379 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002380
Christopher Faulet99daf282018-11-28 22:58:13 +01002381 /* append a slash at the end of the location if needed and missing */
2382 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2383 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2384 if (chunk->data + 1 >= chunk->size)
2385 goto fail;
2386 chunk->area[chunk->data++] = '/';
2387 }
2388 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002389 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002390
Christopher Faulet99daf282018-11-28 22:58:13 +01002391 case REDIRECT_TYPE_PREFIX: {
2392 struct ist path;
2393
2394 sl = http_find_stline(htx);
2395 path = http_get_path(htx_sl_req_uri(sl));
2396 /* build message using path */
2397 if (path.ptr) {
2398 if (rule->flags & REDIRECT_FLAG_DROP_QS) {
2399 int qs = 0;
2400 while (qs < path.len) {
2401 if (*(path.ptr + qs) == '?') {
2402 path.len = qs;
2403 break;
2404 }
2405 qs++;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002406 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002407 }
2408 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002409 else
2410 path = ist("/");
Christopher Fauletf2824e62018-10-01 12:12:37 +02002411
Christopher Faulet99daf282018-11-28 22:58:13 +01002412 if (rule->rdr_str) { /* this is an old "redirect" rule */
2413 /* add prefix. Note that if prefix == "/", we don't want to
2414 * add anything, otherwise it makes it hard for the user to
2415 * configure a self-redirection.
2416 */
2417 if (rule->rdr_len != 1 || *rule->rdr_str != '/') {
2418 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2419 goto fail;
2420 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002421 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002422 else {
2423 /* add prefix with executing log format */
2424 chunk->data += build_logline(s, chunk->area + chunk->data,
2425 chunk->size - chunk->data,
2426 &rule->rdr_fmt);
2427 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02002428
Christopher Faulet99daf282018-11-28 22:58:13 +01002429 /* add path */
2430 if (!chunk_memcat(chunk, path.ptr, path.len))
2431 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002432
Christopher Faulet99daf282018-11-28 22:58:13 +01002433 /* append a slash at the end of the location if needed and missing */
2434 if (chunk->data && chunk->area[chunk->data - 1] != '/' &&
2435 (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) {
2436 if (chunk->data + 1 >= chunk->size)
2437 goto fail;
2438 chunk->area[chunk->data++] = '/';
2439 }
2440 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002441 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002442 case REDIRECT_TYPE_LOCATION:
2443 default:
2444 if (rule->rdr_str) { /* this is an old "redirect" rule */
2445 /* add location */
2446 if (!chunk_memcat(chunk, rule->rdr_str, rule->rdr_len))
2447 goto fail;
2448 }
2449 else {
2450 /* add location with executing log format */
2451 chunk->data += build_logline(s, chunk->area + chunk->data,
2452 chunk->size - chunk->data,
2453 &rule->rdr_fmt);
2454 }
2455 break;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002456 }
Christopher Faulet99daf282018-11-28 22:58:13 +01002457 location = ist2(chunk->area, chunk->data);
2458
2459 /*
2460 * Create the 30x response
2461 */
2462 switch (rule->code) {
2463 case 308:
2464 status = ist("308");
2465 reason = ist("Permanent Redirect");
2466 break;
2467 case 307:
2468 status = ist("307");
2469 reason = ist("Temporary Redirect");
2470 break;
2471 case 303:
2472 status = ist("303");
2473 reason = ist("See Other");
2474 break;
2475 case 301:
2476 status = ist("301");
2477 reason = ist("Moved Permanently");
2478 break;
2479 case 302:
2480 default:
2481 status = ist("302");
2482 reason = ist("Found");
2483 break;
2484 }
2485
2486 htx = htx_from_buf(&res->buf);
2487 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2488 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), status, reason);
2489 if (!sl)
2490 goto fail;
2491 sl->info.res.status = rule->code;
2492 s->txn->status = rule->code;
2493
2494 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
2495 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
2496 !htx_add_header(htx, ist("Location"), location))
2497 goto fail;
2498
2499 if (rule->code == 302 || rule->code == 303 || rule->code == 307) {
2500 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")))
2501 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002502 }
2503
2504 if (rule->cookie_len) {
Christopher Faulet99daf282018-11-28 22:58:13 +01002505 if (!htx_add_header(htx, ist("Set-Cookie"), ist2(rule->cookie_str, rule->cookie_len)))
2506 goto fail;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002507 }
2508
Christopher Faulet99daf282018-11-28 22:58:13 +01002509 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
2510 goto fail;
2511
Christopher Fauletf2824e62018-10-01 12:12:37 +02002512 /* let's log the request time */
2513 s->logs.tv_request = now;
2514
Christopher Faulet99daf282018-11-28 22:58:13 +01002515 data = htx->data - co_data(res);
Christopher Faulet99daf282018-11-28 22:58:13 +01002516 c_adv(res, data);
2517 res->total += data;
2518
2519 channel_auto_read(req);
2520 channel_abort(req);
2521 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002522 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet99daf282018-11-28 22:58:13 +01002523
2524 res->wex = tick_add_ifset(now_ms, res->wto);
2525 channel_auto_read(res);
2526 channel_auto_close(res);
2527 channel_shutr_now(res);
2528
2529 req->analysers &= AN_REQ_FLT_END;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002530
2531 if (!(s->flags & SF_ERR_MASK))
2532 s->flags |= SF_ERR_LOCAL;
2533 if (!(s->flags & SF_FINST_MASK))
2534 s->flags |= SF_FINST_R;
2535
Christopher Faulet99daf282018-11-28 22:58:13 +01002536 free_trash_chunk(chunk);
2537 return 1;
2538
2539 fail:
2540 /* If an error occurred, remove the incomplete HTTP response from the
2541 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002542 channel_htx_truncate(res, htxbuf(&res->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02002543 free_trash_chunk(chunk);
Christopher Faulet99daf282018-11-28 22:58:13 +01002544 return 0;
Christopher Fauletf2824e62018-10-01 12:12:37 +02002545}
2546
Christopher Faulet72333522018-10-24 11:25:02 +02002547int htx_transform_header_str(struct stream* s, struct channel *chn, struct htx *htx,
2548 struct ist name, const char *str, struct my_regex *re, int action)
2549{
2550 struct http_hdr_ctx ctx;
2551 struct buffer *output = get_trash_chunk();
2552
2553 /* find full header is action is ACT_HTTP_REPLACE_HDR */
2554 ctx.blk = NULL;
2555 while (http_find_header(htx, name, &ctx, (action == ACT_HTTP_REPLACE_HDR))) {
2556 if (!regex_exec_match2(re, ctx.value.ptr, ctx.value.len, MAX_MATCH, pmatch, 0))
2557 continue;
2558
2559 output->data = exp_replace(output->area, output->size, ctx.value.ptr, str, pmatch);
2560 if (output->data == -1)
2561 return -1;
2562 if (!http_replace_header_value(htx, &ctx, ist2(output->area, output->data)))
2563 return -1;
2564 }
2565 return 0;
2566}
2567
2568static int htx_transform_header(struct stream* s, struct channel *chn, struct htx *htx,
2569 const struct ist name, struct list *fmt, struct my_regex *re, int action)
2570{
2571 struct buffer *replace;
2572 int ret = -1;
2573
2574 replace = alloc_trash_chunk();
2575 if (!replace)
2576 goto leave;
2577
2578 replace->data = build_logline(s, replace->area, replace->size, fmt);
2579 if (replace->data >= replace->size - 1)
2580 goto leave;
2581
2582 ret = htx_transform_header_str(s, chn, htx, name, replace->area, re, action);
2583
2584 leave:
2585 free_trash_chunk(replace);
2586 return ret;
2587}
2588
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002589
2590/* Terminate a 103-Erly-hints response and send it to the client. It returns 0
2591 * on success and -1 on error. The response channel is updated accordingly.
2592 */
2593static int htx_reply_103_early_hints(struct channel *res)
2594{
2595 struct htx *htx = htx_from_buf(&res->buf);
2596 size_t data;
2597
2598 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM)) {
2599 /* If an error occurred during an Early-hint rule,
2600 * remove the incomplete HTTP 103 response from the
2601 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002602 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002603 return -1;
2604 }
2605
2606 data = htx->data - co_data(res);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002607 c_adv(res, data);
2608 res->total += data;
2609 return 0;
2610}
2611
Christopher Faulet6eb92892018-11-15 16:39:29 +01002612/*
2613 * Build an HTTP Early Hint HTTP 103 response header with <name> as name and with a value
2614 * built according to <fmt> log line format.
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002615 * If <early_hints> is 0, it is starts a new response by adding the start
2616 * line. If an error occurred -1 is returned. On success 0 is returned. The
2617 * channel is not updated here. It must be done calling the function
2618 * htx_reply_103_early_hints().
Christopher Faulet6eb92892018-11-15 16:39:29 +01002619 */
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002620static 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 +01002621{
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002622 struct channel *res = &s->res;
2623 struct htx *htx = htx_from_buf(&res->buf);
2624 struct buffer *value = alloc_trash_chunk();
2625
Christopher Faulet6eb92892018-11-15 16:39:29 +01002626 if (!early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002627 struct htx_sl *sl;
2628 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
2629 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
2630
2631 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
2632 ist("HTTP/1.1"), ist("103"), ist("Early Hints"));
2633 if (!sl)
Christopher Faulet6eb92892018-11-15 16:39:29 +01002634 goto fail;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002635 sl->info.res.status = 103;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002636 }
2637
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002638 value->data = build_logline(s, b_tail(value), b_room(value), fmt);
2639 if (!htx_add_header(htx, name, ist2(b_head(value), b_data(value))))
Christopher Faulet6eb92892018-11-15 16:39:29 +01002640 goto fail;
2641
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002642 free_trash_chunk(value);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002643 return 1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002644
2645 fail:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002646 /* If an error occurred during an Early-hint rule, remove the incomplete
2647 * HTTP 103 response from the buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01002648 channel_htx_truncate(res, htx);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002649 free_trash_chunk(value);
2650 return -1;
Christopher Faulet6eb92892018-11-15 16:39:29 +01002651}
2652
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002653/* This function executes one of the set-{method,path,query,uri} actions. It
2654 * takes the string from the variable 'replace' with length 'len', then modifies
2655 * the relevant part of the request line accordingly. Then it updates various
2656 * pointers to the next elements which were moved, and the total buffer length.
2657 * It finds the action to be performed in p[2], previously filled by function
2658 * parse_set_req_line(). It returns 0 in case of success, -1 in case of internal
2659 * error, though this can be revisited when this code is finally exploited.
2660 *
2661 * 'action' can be '0' to replace method, '1' to replace path, '2' to replace
2662 * query string and 3 to replace uri.
2663 *
2664 * In query string case, the mark question '?' must be set at the start of the
2665 * string by the caller, event if the replacement query string is empty.
2666 */
2667int htx_req_replace_stline(int action, const char *replace, int len,
2668 struct proxy *px, struct stream *s)
2669{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002670 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002671
2672 switch (action) {
2673 case 0: // method
2674 if (!http_replace_req_meth(htx, ist2(replace, len)))
2675 return -1;
2676 break;
2677
2678 case 1: // path
2679 if (!http_replace_req_path(htx, ist2(replace, len)))
2680 return -1;
2681 break;
2682
2683 case 2: // query
2684 if (!http_replace_req_query(htx, ist2(replace, len)))
2685 return -1;
2686 break;
2687
2688 case 3: // uri
2689 if (!http_replace_req_uri(htx, ist2(replace, len)))
2690 return -1;
2691 break;
2692
2693 default:
2694 return -1;
2695 }
2696 return 0;
2697}
2698
2699/* This function replace the HTTP status code and the associated message. The
2700 * variable <status> contains the new status code. This function never fails.
2701 */
2702void htx_res_set_status(unsigned int status, const char *reason, struct stream *s)
2703{
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002704 struct htx *htx = htxbuf(&s->res.buf);
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002705 char *res;
2706
2707 chunk_reset(&trash);
2708 res = ultoa_o(status, trash.area, trash.size);
2709 trash.data = res - trash.area;
2710
2711 /* Do we have a custom reason format string? */
2712 if (reason == NULL)
2713 reason = http_get_reason(status);
2714
Christopher Faulet87a2c0d2018-12-13 21:58:18 +01002715 if (http_replace_res_status(htx, ist2(trash.area, trash.data)))
Christopher Faulet8d8ac192018-10-24 11:27:39 +02002716 http_replace_res_reason(htx, ist2(reason, strlen(reason)));
2717}
2718
Christopher Faulet3e964192018-10-24 11:39:23 +02002719/* Executes the http-request rules <rules> for stream <s>, proxy <px> and
2720 * transaction <txn>. Returns the verdict of the first rule that prevents
2721 * further processing of the request (auth, deny, ...), and defaults to
2722 * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or
2723 * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT
2724 * on txn->flags if it encounters a tarpit rule. If <deny_status> is not NULL
2725 * and a deny/tarpit rule is matched, it will be filled with this rule's deny
2726 * status.
2727 */
2728static enum rule_result htx_req_get_intercept_rule(struct proxy *px, struct list *rules,
2729 struct stream *s, int *deny_status)
2730{
2731 struct session *sess = strm_sess(s);
2732 struct http_txn *txn = s->txn;
2733 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02002734 struct act_rule *rule;
2735 struct http_hdr_ctx ctx;
2736 const char *auth_realm;
Christopher Faulet3e964192018-10-24 11:39:23 +02002737 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
2738 int act_flags = 0;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002739 int early_hints = 0;
Christopher Faulet3e964192018-10-24 11:39:23 +02002740
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01002741 htx = htxbuf(&s->req.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02002742
2743 /* If "the current_rule_list" match the executed rule list, we are in
2744 * resume condition. If a resume is needed it is always in the action
2745 * and never in the ACL or converters. In this case, we initialise the
2746 * current rule, and go to the action execution point.
2747 */
2748 if (s->current_rule) {
2749 rule = s->current_rule;
2750 s->current_rule = NULL;
2751 if (s->current_rule_list == rules)
2752 goto resume_execution;
2753 }
2754 s->current_rule_list = rules;
2755
2756 list_for_each_entry(rule, rules, list) {
2757 /* check optional condition */
2758 if (rule->cond) {
2759 int ret;
2760
2761 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
2762 ret = acl_pass(ret);
2763
2764 if (rule->cond->pol == ACL_COND_UNLESS)
2765 ret = !ret;
2766
2767 if (!ret) /* condition not matched */
2768 continue;
2769 }
2770
2771 act_flags |= ACT_FLAG_FIRST;
2772 resume_execution:
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01002773 if (early_hints && rule->action != ACT_HTTP_EARLY_HINT) {
2774 early_hints = 0;
2775 if (htx_reply_103_early_hints(&s->res) == -1) {
2776 rule_ret = HTTP_RULE_RES_BADREQ;
2777 goto end;
2778 }
2779 }
2780
Christopher Faulet3e964192018-10-24 11:39:23 +02002781 switch (rule->action) {
2782 case ACT_ACTION_ALLOW:
2783 rule_ret = HTTP_RULE_RES_STOP;
2784 goto end;
2785
2786 case ACT_ACTION_DENY:
2787 if (deny_status)
2788 *deny_status = rule->deny_status;
2789 rule_ret = HTTP_RULE_RES_DENY;
2790 goto end;
2791
2792 case ACT_HTTP_REQ_TARPIT:
2793 txn->flags |= TX_CLTARPIT;
2794 if (deny_status)
2795 *deny_status = rule->deny_status;
2796 rule_ret = HTTP_RULE_RES_DENY;
2797 goto end;
2798
2799 case ACT_HTTP_REQ_AUTH:
Christopher Faulet3e964192018-10-24 11:39:23 +02002800 /* Auth might be performed on regular http-req rules as well as on stats */
2801 auth_realm = rule->arg.auth.realm;
2802 if (!auth_realm) {
2803 if (px->uri_auth && rules == &px->uri_auth->http_req_rules)
2804 auth_realm = STATS_DEFAULT_REALM;
2805 else
2806 auth_realm = px->id;
2807 }
2808 /* send 401/407 depending on whether we use a proxy or not. We still
2809 * count one error, because normal browsing won't significantly
2810 * increase the counter but brute force attempts will.
2811 */
Christopher Faulet3e964192018-10-24 11:39:23 +02002812 rule_ret = HTTP_RULE_RES_ABRT;
Christopher Faulet12c51e22018-11-28 15:59:42 +01002813 if (htx_reply_40x_unauthorized(s, auth_realm) == -1)
2814 rule_ret = HTTP_RULE_RES_BADREQ;
2815 stream_inc_http_err_ctr(s);
Christopher Faulet3e964192018-10-24 11:39:23 +02002816 goto end;
2817
2818 case ACT_HTTP_REDIR:
Christopher Faulet3e964192018-10-24 11:39:23 +02002819 rule_ret = HTTP_RULE_RES_DONE;
2820 if (!htx_apply_redirect_rule(rule->arg.redir, s, txn))
2821 rule_ret = HTTP_RULE_RES_BADREQ;
2822 goto end;
2823
2824 case ACT_HTTP_SET_NICE:
2825 s->task->nice = rule->arg.nice;
2826 break;
2827
2828 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002829 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02002830 break;
2831
2832 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01002833 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02002834 break;
2835
2836 case ACT_HTTP_SET_LOGL:
2837 s->logs.level = rule->arg.loglevel;
2838 break;
2839
2840 case ACT_HTTP_REPLACE_HDR:
2841 case ACT_HTTP_REPLACE_VAL:
2842 if (htx_transform_header(s, &s->req, htx,
2843 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
2844 &rule->arg.hdr_add.fmt,
2845 &rule->arg.hdr_add.re, rule->action)) {
2846 rule_ret = HTTP_RULE_RES_BADREQ;
2847 goto end;
2848 }
2849 break;
2850
2851 case ACT_HTTP_DEL_HDR:
2852 /* remove all occurrences of the header */
2853 ctx.blk = NULL;
2854 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2855 http_remove_header(htx, &ctx);
2856 break;
2857
2858 case ACT_HTTP_SET_HDR:
2859 case ACT_HTTP_ADD_HDR: {
2860 /* The scope of the trash buffer must be limited to this function. The
2861 * build_logline() function can execute a lot of other function which
2862 * can use the trash buffer. So for limiting the scope of this global
2863 * buffer, we build first the header value using build_logline, and
2864 * after we store the header name.
2865 */
2866 struct buffer *replace;
2867 struct ist n, v;
2868
2869 replace = alloc_trash_chunk();
2870 if (!replace) {
2871 rule_ret = HTTP_RULE_RES_BADREQ;
2872 goto end;
2873 }
2874
2875 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
2876 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
2877 v = ist2(replace->area, replace->data);
2878
2879 if (rule->action == ACT_HTTP_SET_HDR) {
2880 /* remove all occurrences of the header */
2881 ctx.blk = NULL;
2882 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
2883 http_remove_header(htx, &ctx);
2884 }
2885
2886 if (!http_add_header(htx, n, v)) {
2887 static unsigned char rate_limit = 0;
2888
2889 if ((rate_limit++ & 255) == 0) {
2890 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);
2891 }
2892
Olivier Houcharda798bf52019-03-08 18:52:00 +01002893 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002894 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002895 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002896 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01002897 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02002898 }
2899 free_trash_chunk(replace);
2900 break;
2901 }
2902
2903 case ACT_HTTP_DEL_ACL:
2904 case ACT_HTTP_DEL_MAP: {
2905 struct pat_ref *ref;
2906 struct buffer *key;
2907
2908 /* collect reference */
2909 ref = pat_ref_lookup(rule->arg.map.ref);
2910 if (!ref)
2911 continue;
2912
2913 /* allocate key */
2914 key = alloc_trash_chunk();
2915 if (!key) {
2916 rule_ret = HTTP_RULE_RES_BADREQ;
2917 goto end;
2918 }
2919
2920 /* collect key */
2921 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2922 key->area[key->data] = '\0';
2923
2924 /* perform update */
2925 /* returned code: 1=ok, 0=ko */
2926 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2927 pat_ref_delete(ref, key->area);
2928 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2929
2930 free_trash_chunk(key);
2931 break;
2932 }
2933
2934 case ACT_HTTP_ADD_ACL: {
2935 struct pat_ref *ref;
2936 struct buffer *key;
2937
2938 /* collect reference */
2939 ref = pat_ref_lookup(rule->arg.map.ref);
2940 if (!ref)
2941 continue;
2942
2943 /* allocate key */
2944 key = alloc_trash_chunk();
2945 if (!key) {
2946 rule_ret = HTTP_RULE_RES_BADREQ;
2947 goto end;
2948 }
2949
2950 /* collect key */
2951 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2952 key->area[key->data] = '\0';
2953
2954 /* perform update */
2955 /* add entry only if it does not already exist */
2956 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
2957 if (pat_ref_find_elt(ref, key->area) == NULL)
2958 pat_ref_add(ref, key->area, NULL, NULL);
2959 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
2960
2961 free_trash_chunk(key);
2962 break;
2963 }
2964
2965 case ACT_HTTP_SET_MAP: {
2966 struct pat_ref *ref;
2967 struct buffer *key, *value;
2968
2969 /* collect reference */
2970 ref = pat_ref_lookup(rule->arg.map.ref);
2971 if (!ref)
2972 continue;
2973
2974 /* allocate key */
2975 key = alloc_trash_chunk();
2976 if (!key) {
2977 rule_ret = HTTP_RULE_RES_BADREQ;
2978 goto end;
2979 }
2980
2981 /* allocate value */
2982 value = alloc_trash_chunk();
2983 if (!value) {
2984 free_trash_chunk(key);
2985 rule_ret = HTTP_RULE_RES_BADREQ;
2986 goto end;
2987 }
2988
2989 /* collect key */
2990 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
2991 key->area[key->data] = '\0';
2992
2993 /* collect value */
2994 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
2995 value->area[value->data] = '\0';
2996
2997 /* perform update */
2998 if (pat_ref_find_elt(ref, key->area) != NULL)
2999 /* update entry if it exists */
3000 pat_ref_set(ref, key->area, value->area, NULL);
3001 else
3002 /* insert a new entry */
3003 pat_ref_add(ref, key->area, value->area, NULL);
3004
3005 free_trash_chunk(key);
3006 free_trash_chunk(value);
3007 break;
3008 }
3009
3010 case ACT_HTTP_EARLY_HINT:
3011 if (!(txn->req.flags & HTTP_MSGF_VER_11))
3012 break;
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003013 early_hints = htx_add_early_hint_header(s, early_hints,
3014 ist2(rule->arg.early_hint.name, rule->arg.early_hint.name_len),
Christopher Faulet3e964192018-10-24 11:39:23 +02003015 &rule->arg.early_hint.fmt);
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003016 if (early_hints == -1) {
3017 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003018 goto end;
3019 }
3020 break;
3021
3022 case ACT_CUSTOM:
3023 if ((s->req.flags & CF_READ_ERROR) ||
3024 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3025 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3026 (px->options & PR_O_ABRT_CLOSE)))
3027 act_flags |= ACT_FLAG_FINAL;
3028
3029 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3030 case ACT_RET_ERR:
3031 case ACT_RET_CONT:
3032 break;
3033 case ACT_RET_STOP:
3034 rule_ret = HTTP_RULE_RES_DONE;
3035 goto end;
3036 case ACT_RET_YIELD:
3037 s->current_rule = rule;
3038 rule_ret = HTTP_RULE_RES_YIELD;
3039 goto end;
3040 }
3041 break;
3042
3043 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3044 /* Note: only the first valid tracking parameter of each
3045 * applies.
3046 */
3047
3048 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3049 struct stktable *t;
3050 struct stksess *ts;
3051 struct stktable_key *key;
3052 void *ptr1, *ptr2;
3053
3054 t = rule->arg.trk_ctr.table.t;
3055 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
3056 rule->arg.trk_ctr.expr, NULL);
3057
3058 if (key && (ts = stktable_get_entry(t, key))) {
3059 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3060
3061 /* let's count a new HTTP request as it's the first time we do it */
3062 ptr1 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3063 ptr2 = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3064 if (ptr1 || ptr2) {
3065 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3066
3067 if (ptr1)
3068 stktable_data_cast(ptr1, http_req_cnt)++;
3069
3070 if (ptr2)
3071 update_freq_ctr_period(&stktable_data_cast(ptr2, http_req_rate),
3072 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3073
3074 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3075
3076 /* If data was modified, we need to touch to re-schedule sync */
3077 stktable_touch_local(t, ts, 0);
3078 }
3079
3080 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3081 if (sess->fe != s->be)
3082 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3083 }
3084 }
3085 break;
3086
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003087 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003088 default:
3089 break;
3090 }
3091 }
3092
3093 end:
3094 if (early_hints) {
Christopher Fauletee9b5bf2018-11-28 13:55:14 +01003095 if (htx_reply_103_early_hints(&s->res) == -1)
3096 rule_ret = HTTP_RULE_RES_BADREQ;
Christopher Faulet3e964192018-10-24 11:39:23 +02003097 }
3098
3099 /* we reached the end of the rules, nothing to report */
3100 return rule_ret;
3101}
3102
3103/* Executes the http-response rules <rules> for stream <s> and proxy <px>. It
3104 * returns one of 5 possible statuses: HTTP_RULE_RES_CONT, HTTP_RULE_RES_STOP,
3105 * HTTP_RULE_RES_DONE, HTTP_RULE_RES_YIELD, or HTTP_RULE_RES_BADREQ. If *CONT
3106 * is returned, the process can continue the evaluation of next rule list. If
3107 * *STOP or *DONE is returned, the process must stop the evaluation. If *BADREQ
3108 * is returned, it means the operation could not be processed and a server error
3109 * must be returned. It may set the TX_SVDENY on txn->flags if it encounters a
3110 * deny rule. If *YIELD is returned, the caller must call again the function
3111 * with the same context.
3112 */
3113static enum rule_result htx_res_get_intercept_rule(struct proxy *px, struct list *rules,
3114 struct stream *s)
3115{
3116 struct session *sess = strm_sess(s);
3117 struct http_txn *txn = s->txn;
3118 struct htx *htx;
Christopher Faulet3e964192018-10-24 11:39:23 +02003119 struct act_rule *rule;
3120 struct http_hdr_ctx ctx;
3121 enum rule_result rule_ret = HTTP_RULE_RES_CONT;
3122 int act_flags = 0;
3123
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003124 htx = htxbuf(&s->res.buf);
Christopher Faulet3e964192018-10-24 11:39:23 +02003125
3126 /* If "the current_rule_list" match the executed rule list, we are in
3127 * resume condition. If a resume is needed it is always in the action
3128 * and never in the ACL or converters. In this case, we initialise the
3129 * current rule, and go to the action execution point.
3130 */
3131 if (s->current_rule) {
3132 rule = s->current_rule;
3133 s->current_rule = NULL;
3134 if (s->current_rule_list == rules)
3135 goto resume_execution;
3136 }
3137 s->current_rule_list = rules;
3138
3139 list_for_each_entry(rule, rules, list) {
3140 /* check optional condition */
3141 if (rule->cond) {
3142 int ret;
3143
3144 ret = acl_exec_cond(rule->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3145 ret = acl_pass(ret);
3146
3147 if (rule->cond->pol == ACL_COND_UNLESS)
3148 ret = !ret;
3149
3150 if (!ret) /* condition not matched */
3151 continue;
3152 }
3153
3154 act_flags |= ACT_FLAG_FIRST;
3155resume_execution:
3156 switch (rule->action) {
3157 case ACT_ACTION_ALLOW:
3158 rule_ret = HTTP_RULE_RES_STOP; /* "allow" rules are OK */
3159 goto end;
3160
3161 case ACT_ACTION_DENY:
3162 txn->flags |= TX_SVDENY;
3163 rule_ret = HTTP_RULE_RES_STOP;
3164 goto end;
3165
3166 case ACT_HTTP_SET_NICE:
3167 s->task->nice = rule->arg.nice;
3168 break;
3169
3170 case ACT_HTTP_SET_TOS:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003171 conn_set_tos(objt_conn(sess->origin), rule->arg.tos);
Christopher Faulet3e964192018-10-24 11:39:23 +02003172 break;
3173
3174 case ACT_HTTP_SET_MARK:
Willy Tarreau1a18b542018-12-11 16:37:42 +01003175 conn_set_mark(objt_conn(sess->origin), rule->arg.mark);
Christopher Faulet3e964192018-10-24 11:39:23 +02003176 break;
3177
3178 case ACT_HTTP_SET_LOGL:
3179 s->logs.level = rule->arg.loglevel;
3180 break;
3181
3182 case ACT_HTTP_REPLACE_HDR:
3183 case ACT_HTTP_REPLACE_VAL:
3184 if (htx_transform_header(s, &s->res, htx,
3185 ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len),
3186 &rule->arg.hdr_add.fmt,
3187 &rule->arg.hdr_add.re, rule->action)) {
3188 rule_ret = HTTP_RULE_RES_BADREQ;
3189 goto end;
3190 }
3191 break;
3192
3193 case ACT_HTTP_DEL_HDR:
3194 /* remove all occurrences of the header */
3195 ctx.blk = NULL;
3196 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3197 http_remove_header(htx, &ctx);
3198 break;
3199
3200 case ACT_HTTP_SET_HDR:
3201 case ACT_HTTP_ADD_HDR: {
3202 struct buffer *replace;
3203 struct ist n, v;
3204
3205 replace = alloc_trash_chunk();
3206 if (!replace) {
3207 rule_ret = HTTP_RULE_RES_BADREQ;
3208 goto end;
3209 }
3210
3211 replace->data = build_logline(s, replace->area, replace->size, &rule->arg.hdr_add.fmt);
3212 n = ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len);
3213 v = ist2(replace->area, replace->data);
3214
3215 if (rule->action == ACT_HTTP_SET_HDR) {
3216 /* remove all occurrences of the header */
3217 ctx.blk = NULL;
3218 while (http_find_header(htx, ist2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len), &ctx, 1))
3219 http_remove_header(htx, &ctx);
3220 }
3221
3222 if (!http_add_header(htx, n, v)) {
3223 static unsigned char rate_limit = 0;
3224
3225 if ((rate_limit++ & 255) == 0) {
3226 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);
3227 }
3228
Olivier Houcharda798bf52019-03-08 18:52:00 +01003229 _HA_ATOMIC_ADD(&sess->fe->fe_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003230 if (sess->fe != s->be)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003231 _HA_ATOMIC_ADD(&s->be->be_counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003232 if (sess->listener->counters)
Olivier Houcharda798bf52019-03-08 18:52:00 +01003233 _HA_ATOMIC_ADD(&sess->listener->counters->failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003234 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01003235 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.failed_rewrites, 1);
Christopher Faulet3e964192018-10-24 11:39:23 +02003236 }
3237 free_trash_chunk(replace);
3238 break;
3239 }
3240
3241 case ACT_HTTP_DEL_ACL:
3242 case ACT_HTTP_DEL_MAP: {
3243 struct pat_ref *ref;
3244 struct buffer *key;
3245
3246 /* collect reference */
3247 ref = pat_ref_lookup(rule->arg.map.ref);
3248 if (!ref)
3249 continue;
3250
3251 /* allocate key */
3252 key = alloc_trash_chunk();
3253 if (!key) {
3254 rule_ret = HTTP_RULE_RES_BADREQ;
3255 goto end;
3256 }
3257
3258 /* collect key */
3259 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3260 key->area[key->data] = '\0';
3261
3262 /* perform update */
3263 /* returned code: 1=ok, 0=ko */
3264 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3265 pat_ref_delete(ref, key->area);
3266 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3267
3268 free_trash_chunk(key);
3269 break;
3270 }
3271
3272 case ACT_HTTP_ADD_ACL: {
3273 struct pat_ref *ref;
3274 struct buffer *key;
3275
3276 /* collect reference */
3277 ref = pat_ref_lookup(rule->arg.map.ref);
3278 if (!ref)
3279 continue;
3280
3281 /* allocate key */
3282 key = alloc_trash_chunk();
3283 if (!key) {
3284 rule_ret = HTTP_RULE_RES_BADREQ;
3285 goto end;
3286 }
3287
3288 /* collect key */
3289 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3290 key->area[key->data] = '\0';
3291
3292 /* perform update */
3293 /* check if the entry already exists */
3294 if (pat_ref_find_elt(ref, key->area) == NULL)
3295 pat_ref_add(ref, key->area, NULL, NULL);
3296
3297 free_trash_chunk(key);
3298 break;
3299 }
3300
3301 case ACT_HTTP_SET_MAP: {
3302 struct pat_ref *ref;
3303 struct buffer *key, *value;
3304
3305 /* collect reference */
3306 ref = pat_ref_lookup(rule->arg.map.ref);
3307 if (!ref)
3308 continue;
3309
3310 /* allocate key */
3311 key = alloc_trash_chunk();
3312 if (!key) {
3313 rule_ret = HTTP_RULE_RES_BADREQ;
3314 goto end;
3315 }
3316
3317 /* allocate value */
3318 value = alloc_trash_chunk();
3319 if (!value) {
3320 free_trash_chunk(key);
3321 rule_ret = HTTP_RULE_RES_BADREQ;
3322 goto end;
3323 }
3324
3325 /* collect key */
3326 key->data = build_logline(s, key->area, key->size, &rule->arg.map.key);
3327 key->area[key->data] = '\0';
3328
3329 /* collect value */
3330 value->data = build_logline(s, value->area, value->size, &rule->arg.map.value);
3331 value->area[value->data] = '\0';
3332
3333 /* perform update */
3334 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
3335 if (pat_ref_find_elt(ref, key->area) != NULL)
3336 /* update entry if it exists */
3337 pat_ref_set(ref, key->area, value->area, NULL);
3338 else
3339 /* insert a new entry */
3340 pat_ref_add(ref, key->area, value->area, NULL);
3341 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
3342 free_trash_chunk(key);
3343 free_trash_chunk(value);
3344 break;
3345 }
3346
3347 case ACT_HTTP_REDIR:
3348 rule_ret = HTTP_RULE_RES_DONE;
3349 if (!http_apply_redirect_rule(rule->arg.redir, s, txn))
3350 rule_ret = HTTP_RULE_RES_BADREQ;
3351 goto end;
3352
3353 case ACT_ACTION_TRK_SC0 ... ACT_ACTION_TRK_SCMAX:
3354 /* Note: only the first valid tracking parameter of each
3355 * applies.
3356 */
3357 if (stkctr_entry(&s->stkctr[trk_idx(rule->action)]) == NULL) {
3358 struct stktable *t;
3359 struct stksess *ts;
3360 struct stktable_key *key;
3361 void *ptr;
3362
3363 t = rule->arg.trk_ctr.table.t;
3364 key = stktable_fetch_key(t, s->be, sess, s, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
3365 rule->arg.trk_ctr.expr, NULL);
3366
3367 if (key && (ts = stktable_get_entry(t, key))) {
3368 stream_track_stkctr(&s->stkctr[trk_idx(rule->action)], t, ts);
3369
3370 HA_RWLOCK_WRLOCK(STK_SESS_LOCK, &ts->lock);
3371
3372 /* let's count a new HTTP request as it's the first time we do it */
3373 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_CNT);
3374 if (ptr)
3375 stktable_data_cast(ptr, http_req_cnt)++;
3376
3377 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_REQ_RATE);
3378 if (ptr)
3379 update_freq_ctr_period(&stktable_data_cast(ptr, http_req_rate),
3380 t->data_arg[STKTABLE_DT_HTTP_REQ_RATE].u, 1);
3381
3382 /* When the client triggers a 4xx from the server, it's most often due
3383 * to a missing object or permission. These events should be tracked
3384 * because if they happen often, it may indicate a brute force or a
3385 * vulnerability scan. Normally this is done when receiving the response
3386 * but here we're tracking after this ought to have been done so we have
3387 * to do it on purpose.
3388 */
3389 if ((unsigned)(txn->status - 400) < 100) {
3390 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_CNT);
3391 if (ptr)
3392 stktable_data_cast(ptr, http_err_cnt)++;
3393
3394 ptr = stktable_data_ptr(t, ts, STKTABLE_DT_HTTP_ERR_RATE);
3395 if (ptr)
3396 update_freq_ctr_period(&stktable_data_cast(ptr, http_err_rate),
3397 t->data_arg[STKTABLE_DT_HTTP_ERR_RATE].u, 1);
3398 }
3399
3400 HA_RWLOCK_WRUNLOCK(STK_SESS_LOCK, &ts->lock);
3401
3402 /* If data was modified, we need to touch to re-schedule sync */
3403 stktable_touch_local(t, ts, 0);
3404
3405 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_CONTENT);
3406 if (sess->fe != s->be)
3407 stkctr_set_flags(&s->stkctr[trk_idx(rule->action)], STKCTR_TRACK_BACKEND);
3408 }
3409 }
3410 break;
3411
3412 case ACT_CUSTOM:
3413 if ((s->req.flags & CF_READ_ERROR) ||
3414 ((s->req.flags & (CF_SHUTR|CF_READ_NULL)) &&
3415 !(s->si[0].flags & SI_FL_CLEAN_ABRT) &&
3416 (px->options & PR_O_ABRT_CLOSE)))
3417 act_flags |= ACT_FLAG_FINAL;
3418
3419 switch (rule->action_ptr(rule, px, s->sess, s, act_flags)) {
3420 case ACT_RET_ERR:
3421 case ACT_RET_CONT:
3422 break;
3423 case ACT_RET_STOP:
3424 rule_ret = HTTP_RULE_RES_STOP;
3425 goto end;
3426 case ACT_RET_YIELD:
3427 s->current_rule = rule;
3428 rule_ret = HTTP_RULE_RES_YIELD;
3429 goto end;
3430 }
3431 break;
3432
Joseph Herlantc42c0e92018-11-25 10:43:27 -08003433 /* other flags exists, but normally, they never be matched. */
Christopher Faulet3e964192018-10-24 11:39:23 +02003434 default:
3435 break;
3436 }
3437 }
3438
3439 end:
3440 /* we reached the end of the rules, nothing to report */
3441 return rule_ret;
3442}
3443
Christopher Faulet33640082018-10-24 11:53:01 +02003444/* Iterate the same filter through all request headers.
3445 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3446 * Since it can manage the switch to another backend, it updates the per-proxy
3447 * DENY stats.
3448 */
3449static int htx_apply_filter_to_req_headers(struct stream *s, struct channel *req, struct hdr_exp *exp)
3450{
3451 struct http_txn *txn = s->txn;
3452 struct htx *htx;
3453 struct buffer *hdr = get_trash_chunk();
3454 int32_t pos;
3455
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003456 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003457
3458 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3459 struct htx_blk *blk = htx_get_blk(htx, pos);
3460 enum htx_blk_type type;
3461 struct ist n, v;
3462
3463 next_hdr:
3464 type = htx_get_blk_type(blk);
3465 if (type == HTX_BLK_EOH)
3466 break;
3467 if (type != HTX_BLK_HDR)
3468 continue;
3469
3470 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3471 return 1;
3472 else if (unlikely(txn->flags & TX_CLALLOW) &&
3473 (exp->action == ACT_ALLOW ||
3474 exp->action == ACT_DENY ||
3475 exp->action == ACT_TARPIT))
3476 return 0;
3477
3478 n = htx_get_blk_name(htx, blk);
3479 v = htx_get_blk_value(htx, blk);
3480
Christopher Faulet02e771a2019-02-26 15:36:05 +01003481 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003482 hdr->area[hdr->data++] = ':';
3483 hdr->area[hdr->data++] = ' ';
3484 chunk_memcat(hdr, v.ptr, v.len);
3485
3486 /* Now we have one header in <hdr> */
3487
3488 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3489 struct http_hdr_ctx ctx;
3490 int len;
3491
3492 switch (exp->action) {
3493 case ACT_ALLOW:
3494 txn->flags |= TX_CLALLOW;
3495 goto end;
3496
3497 case ACT_DENY:
3498 txn->flags |= TX_CLDENY;
3499 goto end;
3500
3501 case ACT_TARPIT:
3502 txn->flags |= TX_CLTARPIT;
3503 goto end;
3504
3505 case ACT_REPLACE:
3506 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3507 if (len < 0)
3508 return -1;
3509
3510 http_parse_header(ist2(trash.area, len), &n, &v);
3511 ctx.blk = blk;
3512 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003513 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003514 if (!http_replace_header(htx, &ctx, n, v))
3515 return -1;
3516 if (!ctx.blk)
3517 goto end;
3518 pos = htx_get_blk_pos(htx, blk);
3519 break;
3520
3521 case ACT_REMOVE:
3522 ctx.blk = blk;
3523 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003524 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003525 if (!http_remove_header(htx, &ctx))
3526 return -1;
3527 if (!ctx.blk)
3528 goto end;
3529 pos = htx_get_blk_pos(htx, blk);
3530 goto next_hdr;
3531
3532 }
3533 }
3534 }
3535 end:
3536 return 0;
3537}
3538
3539/* Apply the filter to the request line.
3540 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3541 * or -1 if a replacement resulted in an invalid request line.
3542 * Since it can manage the switch to another backend, it updates the per-proxy
3543 * DENY stats.
3544 */
3545static int htx_apply_filter_to_req_line(struct stream *s, struct channel *req, struct hdr_exp *exp)
3546{
3547 struct http_txn *txn = s->txn;
3548 struct htx *htx;
3549 struct buffer *reqline = get_trash_chunk();
3550 int done;
3551
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003552 htx = htxbuf(&req->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003553
3554 if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT)))
3555 return 1;
3556 else if (unlikely(txn->flags & TX_CLALLOW) &&
3557 (exp->action == ACT_ALLOW ||
3558 exp->action == ACT_DENY ||
3559 exp->action == ACT_TARPIT))
3560 return 0;
3561 else if (exp->action == ACT_REMOVE)
3562 return 0;
3563
3564 done = 0;
3565
3566 reqline->data = htx_fmt_req_line(http_find_stline(htx), reqline->area, reqline->size);
3567
3568 /* Now we have the request line between cur_ptr and cur_end */
3569 if (regex_exec_match2(exp->preg, reqline->area, reqline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003570 struct htx_sl *sl = http_find_stline(htx);
3571 struct ist meth, uri, vsn;
Christopher Faulet33640082018-10-24 11:53:01 +02003572 int len;
3573
3574 switch (exp->action) {
3575 case ACT_ALLOW:
3576 txn->flags |= TX_CLALLOW;
3577 done = 1;
3578 break;
3579
3580 case ACT_DENY:
3581 txn->flags |= TX_CLDENY;
3582 done = 1;
3583 break;
3584
3585 case ACT_TARPIT:
3586 txn->flags |= TX_CLTARPIT;
3587 done = 1;
3588 break;
3589
3590 case ACT_REPLACE:
3591 len = exp_replace(trash.area, trash.size, reqline->area, exp->replace, pmatch);
3592 if (len < 0)
3593 return -1;
3594
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003595 http_parse_stline(ist2(trash.area, len), &meth, &uri, &vsn);
3596 sl->info.req.meth = find_http_meth(meth.ptr, meth.len);
3597 if (!http_replace_stline(htx, meth, uri, vsn))
Christopher Faulet33640082018-10-24 11:53:01 +02003598 return -1;
3599 done = 1;
3600 break;
3601 }
3602 }
3603 return done;
3604}
3605
3606/*
3607 * Apply all the req filters of proxy <px> to all headers in buffer <req> of stream <s>.
3608 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3609 * unparsable request. Since it can manage the switch to another backend, it
3610 * updates the per-proxy DENY stats.
3611 */
3612static int htx_apply_filters_to_request(struct stream *s, struct channel *req, struct proxy *px)
3613{
3614 struct session *sess = s->sess;
3615 struct http_txn *txn = s->txn;
3616 struct hdr_exp *exp;
3617
3618 for (exp = px->req_exp; exp; exp = exp->next) {
3619 int ret;
3620
3621 /*
3622 * The interleaving of transformations and verdicts
3623 * makes it difficult to decide to continue or stop
3624 * the evaluation.
3625 */
3626
3627 if (txn->flags & (TX_CLDENY|TX_CLTARPIT))
3628 break;
3629
3630 if ((txn->flags & TX_CLALLOW) &&
3631 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3632 exp->action == ACT_TARPIT || exp->action == ACT_PASS))
3633 continue;
3634
3635 /* if this filter had a condition, evaluate it now and skip to
3636 * next filter if the condition does not match.
3637 */
3638 if (exp->cond) {
3639 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
3640 ret = acl_pass(ret);
3641 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3642 ret = !ret;
3643
3644 if (!ret)
3645 continue;
3646 }
3647
3648 /* Apply the filter to the request line. */
3649 ret = htx_apply_filter_to_req_line(s, req, exp);
3650 if (unlikely(ret < 0))
3651 return -1;
3652
3653 if (likely(ret == 0)) {
3654 /* The filter did not match the request, it can be
3655 * iterated through all headers.
3656 */
3657 if (unlikely(htx_apply_filter_to_req_headers(s, req, exp) < 0))
3658 return -1;
3659 }
3660 }
3661 return 0;
3662}
3663
3664/* Iterate the same filter through all response headers contained in <res>.
3665 * Returns 1 if this filter can be stopped upon return, otherwise 0.
3666 */
3667static int htx_apply_filter_to_resp_headers(struct stream *s, struct channel *res, struct hdr_exp *exp)
3668{
3669 struct http_txn *txn = s->txn;
3670 struct htx *htx;
3671 struct buffer *hdr = get_trash_chunk();
3672 int32_t pos;
3673
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003674 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003675
3676 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3677 struct htx_blk *blk = htx_get_blk(htx, pos);
3678 enum htx_blk_type type;
3679 struct ist n, v;
3680
3681 next_hdr:
3682 type = htx_get_blk_type(blk);
3683 if (type == HTX_BLK_EOH)
3684 break;
3685 if (type != HTX_BLK_HDR)
3686 continue;
3687
3688 if (unlikely(txn->flags & TX_SVDENY))
3689 return 1;
3690 else if (unlikely(txn->flags & TX_SVALLOW) &&
3691 (exp->action == ACT_ALLOW ||
3692 exp->action == ACT_DENY))
3693 return 0;
3694
3695 n = htx_get_blk_name(htx, blk);
3696 v = htx_get_blk_value(htx, blk);
3697
Christopher Faulet02e771a2019-02-26 15:36:05 +01003698 chunk_memcpy(hdr, n.ptr, n.len);
Christopher Faulet33640082018-10-24 11:53:01 +02003699 hdr->area[hdr->data++] = ':';
3700 hdr->area[hdr->data++] = ' ';
3701 chunk_memcat(hdr, v.ptr, v.len);
3702
3703 /* Now we have one header in <hdr> */
3704
3705 if (regex_exec_match2(exp->preg, hdr->area, hdr->data, MAX_MATCH, pmatch, 0)) {
3706 struct http_hdr_ctx ctx;
3707 int len;
3708
3709 switch (exp->action) {
3710 case ACT_ALLOW:
3711 txn->flags |= TX_SVALLOW;
3712 goto end;
3713 break;
3714
3715 case ACT_DENY:
3716 txn->flags |= TX_SVDENY;
3717 goto end;
3718 break;
3719
3720 case ACT_REPLACE:
3721 len = exp_replace(trash.area, trash.size, hdr->area, exp->replace, pmatch);
3722 if (len < 0)
3723 return -1;
3724
3725 http_parse_header(ist2(trash.area, len), &n, &v);
3726 ctx.blk = blk;
3727 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003728 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003729 if (!http_replace_header(htx, &ctx, n, v))
3730 return -1;
3731 if (!ctx.blk)
3732 goto end;
3733 pos = htx_get_blk_pos(htx, blk);
3734 break;
3735
3736 case ACT_REMOVE:
3737 ctx.blk = blk;
3738 ctx.value = v;
Christopher Faulet02e771a2019-02-26 15:36:05 +01003739 ctx.lws_before = ctx.lws_after = 0;
Christopher Faulet33640082018-10-24 11:53:01 +02003740 if (!http_remove_header(htx, &ctx))
3741 return -1;
3742 if (!ctx.blk)
3743 goto end;
3744 pos = htx_get_blk_pos(htx, blk);
3745 goto next_hdr;
3746 }
3747 }
3748
3749 }
3750 end:
3751 return 0;
3752}
3753
3754/* Apply the filter to the status line in the response buffer <res>.
3755 * Returns 0 if nothing has been done, 1 if the filter has been applied,
3756 * or -1 if a replacement resulted in an invalid status line.
3757 */
3758static int htx_apply_filter_to_sts_line(struct stream *s, struct channel *res, struct hdr_exp *exp)
3759{
3760 struct http_txn *txn = s->txn;
3761 struct htx *htx;
3762 struct buffer *resline = get_trash_chunk();
3763 int done;
3764
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003765 htx = htxbuf(&res->buf);
Christopher Faulet33640082018-10-24 11:53:01 +02003766
3767 if (unlikely(txn->flags & TX_SVDENY))
3768 return 1;
3769 else if (unlikely(txn->flags & TX_SVALLOW) &&
3770 (exp->action == ACT_ALLOW ||
3771 exp->action == ACT_DENY))
3772 return 0;
3773 else if (exp->action == ACT_REMOVE)
3774 return 0;
3775
3776 done = 0;
3777 resline->data = htx_fmt_res_line(http_find_stline(htx), resline->area, resline->size);
3778
3779 /* Now we have the status line between cur_ptr and cur_end */
3780 if (regex_exec_match2(exp->preg, resline->area, resline->data, MAX_MATCH, pmatch, 0)) {
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003781 struct htx_sl *sl = http_find_stline(htx);
3782 struct ist vsn, code, reason;
Christopher Faulet33640082018-10-24 11:53:01 +02003783 int len;
3784
3785 switch (exp->action) {
3786 case ACT_ALLOW:
3787 txn->flags |= TX_SVALLOW;
3788 done = 1;
3789 break;
3790
3791 case ACT_DENY:
3792 txn->flags |= TX_SVDENY;
3793 done = 1;
3794 break;
3795
3796 case ACT_REPLACE:
3797 len = exp_replace(trash.area, trash.size, resline->area, exp->replace, pmatch);
3798 if (len < 0)
3799 return -1;
3800
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01003801 http_parse_stline(ist2(trash.area, len), &vsn, &code, &reason);
3802 sl->info.res.status = strl2ui(code.ptr, code.len);
3803 if (!http_replace_stline(htx, vsn, code, reason))
Christopher Faulet33640082018-10-24 11:53:01 +02003804 return -1;
3805
3806 done = 1;
3807 return 1;
3808 }
3809 }
3810 return done;
3811}
3812
3813/*
3814 * Apply all the resp filters of proxy <px> to all headers in buffer <res> of stream <s>.
3815 * Returns 0 if everything is alright, or -1 in case a replacement lead to an
3816 * unparsable response.
3817 */
3818static int htx_apply_filters_to_response(struct stream *s, struct channel *res, struct proxy *px)
3819{
3820 struct session *sess = s->sess;
3821 struct http_txn *txn = s->txn;
3822 struct hdr_exp *exp;
3823
3824 for (exp = px->rsp_exp; exp; exp = exp->next) {
3825 int ret;
3826
3827 /*
3828 * The interleaving of transformations and verdicts
3829 * makes it difficult to decide to continue or stop
3830 * the evaluation.
3831 */
3832
3833 if (txn->flags & TX_SVDENY)
3834 break;
3835
3836 if ((txn->flags & TX_SVALLOW) &&
3837 (exp->action == ACT_ALLOW || exp->action == ACT_DENY ||
3838 exp->action == ACT_PASS)) {
3839 exp = exp->next;
3840 continue;
3841 }
3842
3843 /* if this filter had a condition, evaluate it now and skip to
3844 * next filter if the condition does not match.
3845 */
3846 if (exp->cond) {
3847 ret = acl_exec_cond(exp->cond, px, sess, s, SMP_OPT_DIR_RES|SMP_OPT_FINAL);
3848 ret = acl_pass(ret);
3849 if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS)
3850 ret = !ret;
3851 if (!ret)
3852 continue;
3853 }
3854
3855 /* Apply the filter to the status line. */
3856 ret = htx_apply_filter_to_sts_line(s, res, exp);
3857 if (unlikely(ret < 0))
3858 return -1;
3859
3860 if (likely(ret == 0)) {
3861 /* The filter did not match the response, it can be
3862 * iterated through all headers.
3863 */
3864 if (unlikely(htx_apply_filter_to_resp_headers(s, res, exp) < 0))
3865 return -1;
3866 }
3867 }
3868 return 0;
3869}
3870
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003871/*
3872 * Manage client-side cookie. It can impact performance by about 2% so it is
3873 * desirable to call it only when needed. This code is quite complex because
3874 * of the multiple very crappy and ambiguous syntaxes we have to support. it
3875 * highly recommended not to touch this part without a good reason !
3876 */
3877static void htx_manage_client_side_cookies(struct stream *s, struct channel *req)
3878{
3879 struct session *sess = s->sess;
3880 struct http_txn *txn = s->txn;
3881 struct htx *htx;
3882 struct http_hdr_ctx ctx;
3883 char *hdr_beg, *hdr_end, *del_from;
3884 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
3885 int preserve_hdr;
3886
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01003887 htx = htxbuf(&req->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02003888 ctx.blk = NULL;
3889 while (http_find_header(htx, ist("Cookie"), &ctx, 1)) {
3890 del_from = NULL; /* nothing to be deleted */
3891 preserve_hdr = 0; /* assume we may kill the whole header */
3892
3893 /* Now look for cookies. Conforming to RFC2109, we have to support
3894 * attributes whose name begin with a '$', and associate them with
3895 * the right cookie, if we want to delete this cookie.
3896 * So there are 3 cases for each cookie read :
3897 * 1) it's a special attribute, beginning with a '$' : ignore it.
3898 * 2) it's a server id cookie that we *MAY* want to delete : save
3899 * some pointers on it (last semi-colon, beginning of cookie...)
3900 * 3) it's an application cookie : we *MAY* have to delete a previous
3901 * "special" cookie.
3902 * At the end of loop, if a "special" cookie remains, we may have to
3903 * remove it. If no application cookie persists in the header, we
3904 * *MUST* delete it.
3905 *
3906 * Note: RFC2965 is unclear about the processing of spaces around
3907 * the equal sign in the ATTR=VALUE form. A careful inspection of
3908 * the RFC explicitly allows spaces before it, and not within the
3909 * tokens (attrs or values). An inspection of RFC2109 allows that
3910 * too but section 10.1.3 lets one think that spaces may be allowed
3911 * after the equal sign too, resulting in some (rare) buggy
3912 * implementations trying to do that. So let's do what servers do.
3913 * Latest ietf draft forbids spaces all around. Also, earlier RFCs
3914 * allowed quoted strings in values, with any possible character
3915 * after a backslash, including control chars and delimitors, which
3916 * causes parsing to become ambiguous. Browsers also allow spaces
3917 * within values even without quotes.
3918 *
3919 * We have to keep multiple pointers in order to support cookie
3920 * removal at the beginning, middle or end of header without
3921 * corrupting the header. All of these headers are valid :
3922 *
3923 * hdr_beg hdr_end
3924 * | |
3925 * v |
3926 * NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3 |
3927 * NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3 v
3928 * NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3
3929 * | | | | | | |
3930 * | | | | | | |
3931 * | | | | | | +--> next
3932 * | | | | | +----> val_end
3933 * | | | | +-----------> val_beg
3934 * | | | +--------------> equal
3935 * | | +----------------> att_end
3936 * | +---------------------> att_beg
3937 * +--------------------------> prev
3938 *
3939 */
3940 hdr_beg = ctx.value.ptr;
3941 hdr_end = hdr_beg + ctx.value.len;
3942 for (prev = hdr_beg; prev < hdr_end; prev = next) {
3943 /* Iterate through all cookies on this line */
3944
3945 /* find att_beg */
3946 att_beg = prev;
3947 if (prev > hdr_beg)
3948 att_beg++;
3949
3950 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
3951 att_beg++;
3952
3953 /* find att_end : this is the first character after the last non
3954 * space before the equal. It may be equal to hdr_end.
3955 */
3956 equal = att_end = att_beg;
3957 while (equal < hdr_end) {
3958 if (*equal == '=' || *equal == ',' || *equal == ';')
3959 break;
3960 if (HTTP_IS_SPHT(*equal++))
3961 continue;
3962 att_end = equal;
3963 }
3964
3965 /* here, <equal> points to '=', a delimitor or the end. <att_end>
3966 * is between <att_beg> and <equal>, both may be identical.
3967 */
3968 /* look for end of cookie if there is an equal sign */
3969 if (equal < hdr_end && *equal == '=') {
3970 /* look for the beginning of the value */
3971 val_beg = equal + 1;
3972 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
3973 val_beg++;
3974
3975 /* find the end of the value, respecting quotes */
3976 next = http_find_cookie_value_end(val_beg, hdr_end);
3977
3978 /* make val_end point to the first white space or delimitor after the value */
3979 val_end = next;
3980 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
3981 val_end--;
3982 }
3983 else
3984 val_beg = val_end = next = equal;
3985
3986 /* We have nothing to do with attributes beginning with
3987 * '$'. However, they will automatically be removed if a
3988 * header before them is removed, since they're supposed
3989 * to be linked together.
3990 */
3991 if (*att_beg == '$')
3992 continue;
3993
3994 /* Ignore cookies with no equal sign */
3995 if (equal == next) {
3996 /* This is not our cookie, so we must preserve it. But if we already
3997 * scheduled another cookie for removal, we cannot remove the
3998 * complete header, but we can remove the previous block itself.
3999 */
4000 preserve_hdr = 1;
4001 if (del_from != NULL) {
4002 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4003 val_end += delta;
4004 next += delta;
4005 hdr_end += delta;
4006 prev = del_from;
4007 del_from = NULL;
4008 }
4009 continue;
4010 }
4011
4012 /* if there are spaces around the equal sign, we need to
4013 * strip them otherwise we'll get trouble for cookie captures,
4014 * or even for rewrites. Since this happens extremely rarely,
4015 * it does not hurt performance.
4016 */
4017 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4018 int stripped_before = 0;
4019 int stripped_after = 0;
4020
4021 if (att_end != equal) {
4022 memmove(att_end, equal, hdr_end - equal);
4023 stripped_before = (att_end - equal);
4024 equal += stripped_before;
4025 val_beg += stripped_before;
4026 }
4027
4028 if (val_beg > equal + 1) {
4029 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4030 stripped_after = (equal + 1) - val_beg;
4031 val_beg += stripped_after;
4032 stripped_before += stripped_after;
4033 }
4034
4035 val_end += stripped_before;
4036 next += stripped_before;
4037 hdr_end += stripped_before;
4038 }
4039 /* now everything is as on the diagram above */
4040
4041 /* First, let's see if we want to capture this cookie. We check
4042 * that we don't already have a client side cookie, because we
4043 * can only capture one. Also as an optimisation, we ignore
4044 * cookies shorter than the declared name.
4045 */
4046 if (sess->fe->capture_name != NULL && txn->cli_cookie == NULL &&
4047 (val_end - att_beg >= sess->fe->capture_namelen) &&
4048 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4049 int log_len = val_end - att_beg;
4050
4051 if ((txn->cli_cookie = pool_alloc(pool_head_capture)) == NULL) {
4052 ha_alert("HTTP logging : out of memory.\n");
4053 } else {
4054 if (log_len > sess->fe->capture_len)
4055 log_len = sess->fe->capture_len;
4056 memcpy(txn->cli_cookie, att_beg, log_len);
4057 txn->cli_cookie[log_len] = 0;
4058 }
4059 }
4060
4061 /* Persistence cookies in passive, rewrite or insert mode have the
4062 * following form :
4063 *
4064 * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]]
4065 *
4066 * For cookies in prefix mode, the form is :
4067 *
4068 * Cookie: NAME=SRV~VALUE
4069 */
4070 if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4071 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4072 struct server *srv = s->be->srv;
4073 char *delim;
4074
4075 /* if we're in cookie prefix mode, we'll search the delimitor so that we
4076 * have the server ID between val_beg and delim, and the original cookie between
4077 * delim+1 and val_end. Otherwise, delim==val_end :
4078 *
4079 * hdr_beg
4080 * |
4081 * v
4082 * NAME=SRV; # in all but prefix modes
4083 * NAME=SRV~OPAQUE ; # in prefix mode
4084 * || || | |+-> next
4085 * || || | +--> val_end
4086 * || || +---------> delim
4087 * || |+------------> val_beg
4088 * || +-------------> att_end = equal
4089 * |+-----------------> att_beg
4090 * +------------------> prev
4091 *
4092 */
4093 if (s->be->ck_opts & PR_CK_PFX) {
4094 for (delim = val_beg; delim < val_end; delim++)
4095 if (*delim == COOKIE_DELIM)
4096 break;
4097 }
4098 else {
4099 char *vbar1;
4100 delim = val_end;
4101 /* Now check if the cookie contains a date field, which would
4102 * appear after a vertical bar ('|') just after the server name
4103 * and before the delimiter.
4104 */
4105 vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg);
4106 if (vbar1) {
4107 /* OK, so left of the bar is the server's cookie and
4108 * right is the last seen date. It is a base64 encoded
4109 * 30-bit value representing the UNIX date since the
4110 * epoch in 4-second quantities.
4111 */
4112 int val;
4113 delim = vbar1++;
4114 if (val_end - vbar1 >= 5) {
4115 val = b64tos30(vbar1);
4116 if (val > 0)
4117 txn->cookie_last_date = val << 2;
4118 }
4119 /* look for a second vertical bar */
4120 vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1);
4121 if (vbar1 && (val_end - vbar1 > 5)) {
4122 val = b64tos30(vbar1 + 1);
4123 if (val > 0)
4124 txn->cookie_first_date = val << 2;
4125 }
4126 }
4127 }
4128
4129 /* if the cookie has an expiration date and the proxy wants to check
4130 * it, then we do that now. We first check if the cookie is too old,
4131 * then only if it has expired. We detect strict overflow because the
4132 * time resolution here is not great (4 seconds). Cookies with dates
4133 * in the future are ignored if their offset is beyond one day. This
4134 * allows an admin to fix timezone issues without expiring everyone
4135 * and at the same time avoids keeping unwanted side effects for too
4136 * long.
4137 */
4138 if (txn->cookie_first_date && s->be->cookie_maxlife &&
4139 (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) ||
4140 ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) {
4141 txn->flags &= ~TX_CK_MASK;
4142 txn->flags |= TX_CK_OLD;
4143 delim = val_beg; // let's pretend we have not found the cookie
4144 txn->cookie_first_date = 0;
4145 txn->cookie_last_date = 0;
4146 }
4147 else if (txn->cookie_last_date && s->be->cookie_maxidle &&
4148 (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) ||
4149 ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) {
4150 txn->flags &= ~TX_CK_MASK;
4151 txn->flags |= TX_CK_EXPIRED;
4152 delim = val_beg; // let's pretend we have not found the cookie
4153 txn->cookie_first_date = 0;
4154 txn->cookie_last_date = 0;
4155 }
4156
4157 /* Here, we'll look for the first running server which supports the cookie.
4158 * This allows to share a same cookie between several servers, for example
4159 * to dedicate backup servers to specific servers only.
4160 * However, to prevent clients from sticking to cookie-less backup server
4161 * when they have incidentely learned an empty cookie, we simply ignore
4162 * empty cookies and mark them as invalid.
4163 * The same behaviour is applied when persistence must be ignored.
4164 */
4165 if ((delim == val_beg) || (s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4166 srv = NULL;
4167
4168 while (srv) {
4169 if (srv->cookie && (srv->cklen == delim - val_beg) &&
4170 !memcmp(val_beg, srv->cookie, delim - val_beg)) {
4171 if ((srv->cur_state != SRV_ST_STOPPED) ||
4172 (s->be->options & PR_O_PERSIST) ||
4173 (s->flags & SF_FORCE_PRST)) {
4174 /* we found the server and we can use it */
4175 txn->flags &= ~TX_CK_MASK;
4176 txn->flags |= (srv->cur_state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN;
4177 s->flags |= SF_DIRECT | SF_ASSIGNED;
4178 s->target = &srv->obj_type;
4179 break;
4180 } else {
4181 /* we found a server, but it's down,
4182 * mark it as such and go on in case
4183 * another one is available.
4184 */
4185 txn->flags &= ~TX_CK_MASK;
4186 txn->flags |= TX_CK_DOWN;
4187 }
4188 }
4189 srv = srv->next;
4190 }
4191
4192 if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) {
4193 /* no server matched this cookie or we deliberately skipped it */
4194 txn->flags &= ~TX_CK_MASK;
4195 if ((s->flags & (SF_IGNORE_PRST | SF_ASSIGNED)))
4196 txn->flags |= TX_CK_UNUSED;
4197 else
4198 txn->flags |= TX_CK_INVALID;
4199 }
4200
4201 /* depending on the cookie mode, we may have to either :
4202 * - delete the complete cookie if we're in insert+indirect mode, so that
4203 * the server never sees it ;
4204 * - remove the server id from the cookie value, and tag the cookie as an
Joseph Herlante9d5c722018-11-25 11:00:25 -08004205 * application cookie so that it does not get accidentally removed later,
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004206 * if we're in cookie prefix mode
4207 */
4208 if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) {
4209 int delta; /* negative */
4210
4211 memmove(val_beg, delim + 1, hdr_end - (delim + 1));
4212 delta = val_beg - (delim + 1);
4213 val_end += delta;
4214 next += delta;
4215 hdr_end += delta;
4216 del_from = NULL;
4217 preserve_hdr = 1; /* we want to keep this cookie */
4218 }
4219 else if (del_from == NULL &&
4220 (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) {
4221 del_from = prev;
4222 }
4223 }
4224 else {
4225 /* This is not our cookie, so we must preserve it. But if we already
4226 * scheduled another cookie for removal, we cannot remove the
4227 * complete header, but we can remove the previous block itself.
4228 */
4229 preserve_hdr = 1;
4230
4231 if (del_from != NULL) {
4232 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &del_from, prev);
4233 if (att_beg >= del_from)
4234 att_beg += delta;
4235 if (att_end >= del_from)
4236 att_end += delta;
4237 val_beg += delta;
4238 val_end += delta;
4239 next += delta;
4240 hdr_end += delta;
4241 prev = del_from;
4242 del_from = NULL;
4243 }
4244 }
4245
4246 /* continue with next cookie on this header line */
4247 att_beg = next;
4248 } /* for each cookie */
4249
4250
4251 /* There are no more cookies on this line.
4252 * We may still have one (or several) marked for deletion at the
4253 * end of the line. We must do this now in two ways :
4254 * - if some cookies must be preserved, we only delete from the
4255 * mark to the end of line ;
4256 * - if nothing needs to be preserved, simply delete the whole header
4257 */
4258 if (del_from) {
4259 hdr_end = (preserve_hdr ? del_from : hdr_beg);
4260 }
4261 if ((hdr_end - hdr_beg) != ctx.value.len) {
4262 if (hdr_beg != hdr_end) {
4263 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004264 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004265 }
4266 else
4267 http_remove_header(htx, &ctx);
4268 }
4269 } /* for each "Cookie header */
4270}
4271
4272/*
4273 * Manage server-side cookies. It can impact performance by about 2% so it is
4274 * desirable to call it only when needed. This function is also used when we
4275 * just need to know if there is a cookie (eg: for check-cache).
4276 */
4277static void htx_manage_server_side_cookies(struct stream *s, struct channel *res)
4278{
4279 struct session *sess = s->sess;
4280 struct http_txn *txn = s->txn;
4281 struct htx *htx;
4282 struct http_hdr_ctx ctx;
4283 struct server *srv;
4284 char *hdr_beg, *hdr_end;
4285 char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next;
4286 int is_cookie2;
4287
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004288 htx = htxbuf(&res->buf);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004289
4290 ctx.blk = NULL;
4291 while (1) {
4292 if (!http_find_header(htx, ist("Set-Cookie"), &ctx, 1)) {
4293 if (!http_find_header(htx, ist("Set-Cookie2"), &ctx, 1))
4294 break;
4295 is_cookie2 = 1;
4296 }
4297
4298 /* OK, right now we know we have a Set-Cookie* at hdr_beg, and
4299 * <prev> points to the colon.
4300 */
4301 txn->flags |= TX_SCK_PRESENT;
4302
4303 /* Maybe we only wanted to see if there was a Set-Cookie (eg:
4304 * check-cache is enabled) and we are not interested in checking
4305 * them. Warning, the cookie capture is declared in the frontend.
4306 */
4307 if (s->be->cookie_name == NULL && sess->fe->capture_name == NULL)
4308 break;
4309
4310 /* OK so now we know we have to process this response cookie.
4311 * The format of the Set-Cookie header is slightly different
4312 * from the format of the Cookie header in that it does not
4313 * support the comma as a cookie delimiter (thus the header
4314 * cannot be folded) because the Expires attribute described in
4315 * the original Netscape's spec may contain an unquoted date
4316 * with a comma inside. We have to live with this because
4317 * many browsers don't support Max-Age and some browsers don't
4318 * support quoted strings. However the Set-Cookie2 header is
4319 * clean.
4320 *
4321 * We have to keep multiple pointers in order to support cookie
4322 * removal at the beginning, middle or end of header without
4323 * corrupting the header (in case of set-cookie2). A special
4324 * pointer, <scav> points to the beginning of the set-cookie-av
4325 * fields after the first semi-colon. The <next> pointer points
4326 * either to the end of line (set-cookie) or next unquoted comma
4327 * (set-cookie2). All of these headers are valid :
4328 *
4329 * hdr_beg hdr_end
4330 * | |
4331 * v |
4332 * NAME1 = VALUE 1 ; Secure; Path="/" |
4333 * NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT v
4334 * NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT
4335 * NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard
4336 * | | | | | | | |
4337 * | | | | | | | +-> next
4338 * | | | | | | +------------> scav
4339 * | | | | | +--------------> val_end
4340 * | | | | +--------------------> val_beg
4341 * | | | +----------------------> equal
4342 * | | +------------------------> att_end
4343 * | +----------------------------> att_beg
4344 * +------------------------------> prev
4345 * -------------------------------> hdr_beg
4346 */
4347 hdr_beg = ctx.value.ptr;
4348 hdr_end = hdr_beg + ctx.value.len;
4349 for (prev = hdr_beg; prev < hdr_end; prev = next) {
4350
4351 /* Iterate through all cookies on this line */
4352
4353 /* find att_beg */
4354 att_beg = prev;
4355 if (prev > hdr_beg)
4356 att_beg++;
4357
4358 while (att_beg < hdr_end && HTTP_IS_SPHT(*att_beg))
4359 att_beg++;
4360
4361 /* find att_end : this is the first character after the last non
4362 * space before the equal. It may be equal to hdr_end.
4363 */
4364 equal = att_end = att_beg;
4365
4366 while (equal < hdr_end) {
4367 if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ','))
4368 break;
4369 if (HTTP_IS_SPHT(*equal++))
4370 continue;
4371 att_end = equal;
4372 }
4373
4374 /* here, <equal> points to '=', a delimitor or the end. <att_end>
4375 * is between <att_beg> and <equal>, both may be identical.
4376 */
4377
4378 /* look for end of cookie if there is an equal sign */
4379 if (equal < hdr_end && *equal == '=') {
4380 /* look for the beginning of the value */
4381 val_beg = equal + 1;
4382 while (val_beg < hdr_end && HTTP_IS_SPHT(*val_beg))
4383 val_beg++;
4384
4385 /* find the end of the value, respecting quotes */
4386 next = http_find_cookie_value_end(val_beg, hdr_end);
4387
4388 /* make val_end point to the first white space or delimitor after the value */
4389 val_end = next;
4390 while (val_end > val_beg && HTTP_IS_SPHT(*(val_end - 1)))
4391 val_end--;
4392 }
4393 else {
4394 /* <equal> points to next comma, semi-colon or EOL */
4395 val_beg = val_end = next = equal;
4396 }
4397
4398 if (next < hdr_end) {
4399 /* Set-Cookie2 supports multiple cookies, and <next> points to
4400 * a colon or semi-colon before the end. So skip all attr-value
4401 * pairs and look for the next comma. For Set-Cookie, since
4402 * commas are permitted in values, skip to the end.
4403 */
4404 if (is_cookie2)
4405 next = http_find_hdr_value_end(next, hdr_end);
4406 else
4407 next = hdr_end;
4408 }
4409
4410 /* Now everything is as on the diagram above */
4411
4412 /* Ignore cookies with no equal sign */
4413 if (equal == val_end)
4414 continue;
4415
4416 /* If there are spaces around the equal sign, we need to
4417 * strip them otherwise we'll get trouble for cookie captures,
4418 * or even for rewrites. Since this happens extremely rarely,
4419 * it does not hurt performance.
4420 */
4421 if (unlikely(att_end != equal || val_beg > equal + 1)) {
4422 int stripped_before = 0;
4423 int stripped_after = 0;
4424
4425 if (att_end != equal) {
4426 memmove(att_end, equal, hdr_end - equal);
4427 stripped_before = (att_end - equal);
4428 equal += stripped_before;
4429 val_beg += stripped_before;
4430 }
4431
4432 if (val_beg > equal + 1) {
4433 memmove(equal + 1, val_beg, hdr_end + stripped_before - val_beg);
4434 stripped_after = (equal + 1) - val_beg;
4435 val_beg += stripped_after;
4436 stripped_before += stripped_after;
4437 }
4438
4439 val_end += stripped_before;
4440 next += stripped_before;
4441 hdr_end += stripped_before;
4442
Christopher Faulet6cdaf2a2019-02-12 14:29:57 +01004443 htx_set_blk_value_len(ctx.blk, hdr_end - hdr_beg);
4444 htx->data -= ctx.value.len - (hdr_end - hdr_beg);
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004445 ctx.value.len = hdr_end - hdr_beg;
Christopher Fauletfcda7c62018-10-24 11:56:22 +02004446 }
4447
4448 /* First, let's see if we want to capture this cookie. We check
4449 * that we don't already have a server side cookie, because we
4450 * can only capture one. Also as an optimisation, we ignore
4451 * cookies shorter than the declared name.
4452 */
4453 if (sess->fe->capture_name != NULL &&
4454 txn->srv_cookie == NULL &&
4455 (val_end - att_beg >= sess->fe->capture_namelen) &&
4456 memcmp(att_beg, sess->fe->capture_name, sess->fe->capture_namelen) == 0) {
4457 int log_len = val_end - att_beg;
4458 if ((txn->srv_cookie = pool_alloc(pool_head_capture)) == NULL) {
4459 ha_alert("HTTP logging : out of memory.\n");
4460 }
4461 else {
4462 if (log_len > sess->fe->capture_len)
4463 log_len = sess->fe->capture_len;
4464 memcpy(txn->srv_cookie, att_beg, log_len);
4465 txn->srv_cookie[log_len] = 0;
4466 }
4467 }
4468
4469 srv = objt_server(s->target);
4470 /* now check if we need to process it for persistence */
4471 if (!(s->flags & SF_IGNORE_PRST) &&
4472 (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) &&
4473 (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) {
4474 /* assume passive cookie by default */
4475 txn->flags &= ~TX_SCK_MASK;
4476 txn->flags |= TX_SCK_FOUND;
4477
4478 /* If the cookie is in insert mode on a known server, we'll delete
4479 * this occurrence because we'll insert another one later.
4480 * We'll delete it too if the "indirect" option is set and we're in
4481 * a direct access.
4482 */
4483 if (s->be->ck_opts & PR_CK_PSV) {
4484 /* The "preserve" flag was set, we don't want to touch the
4485 * server's cookie.
4486 */
4487 }
4488 else if ((srv && (s->be->ck_opts & PR_CK_INS)) ||
4489 ((s->flags & SF_DIRECT) && (s->be->ck_opts & PR_CK_IND))) {
4490 /* this cookie must be deleted */
4491 if (prev == hdr_beg && next == hdr_end) {
4492 /* whole header */
4493 http_remove_header(htx, &ctx);
4494 /* note: while both invalid now, <next> and <hdr_end>
4495 * are still equal, so the for() will stop as expected.
4496 */
4497 } else {
4498 /* just remove the value */
4499 int delta = htx_del_hdr_value(hdr_beg, hdr_end, &prev, next);
4500 next = prev;
4501 hdr_end += delta;
4502 }
4503 txn->flags &= ~TX_SCK_MASK;
4504 txn->flags |= TX_SCK_DELETED;
4505 /* and go on with next cookie */
4506 }
4507 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) {
4508 /* replace bytes val_beg->val_end with the cookie name associated
4509 * with this server since we know it.
4510 */
4511 int sliding, delta;
4512
4513 ctx.value = ist2(val_beg, val_end - val_beg);
4514 ctx.lws_before = ctx.lws_after = 0;
4515 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen));
4516 delta = srv->cklen - (val_end - val_beg);
4517 sliding = (ctx.value.ptr - val_beg);
4518 hdr_beg += sliding;
4519 val_beg += sliding;
4520 next += sliding + delta;
4521 hdr_end += sliding + delta;
4522
4523 txn->flags &= ~TX_SCK_MASK;
4524 txn->flags |= TX_SCK_REPLACED;
4525 }
4526 else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) {
4527 /* insert the cookie name associated with this server
4528 * before existing cookie, and insert a delimiter between them..
4529 */
4530 int sliding, delta;
4531 ctx.value = ist2(val_beg, 0);
4532 ctx.lws_before = ctx.lws_after = 0;
4533 http_replace_header_value(htx, &ctx, ist2(srv->cookie, srv->cklen + 1));
4534 delta = srv->cklen + 1;
4535 sliding = (ctx.value.ptr - val_beg);
4536 hdr_beg += sliding;
4537 val_beg += sliding;
4538 next += sliding + delta;
4539 hdr_end += sliding + delta;
4540
4541 val_beg[srv->cklen] = COOKIE_DELIM;
4542 txn->flags &= ~TX_SCK_MASK;
4543 txn->flags |= TX_SCK_REPLACED;
4544 }
4545 }
4546 /* that's done for this cookie, check the next one on the same
4547 * line when next != hdr_end (only if is_cookie2).
4548 */
4549 }
4550 }
4551}
4552
Christopher Faulet25a02f62018-10-24 12:00:25 +02004553/*
4554 * Parses the Cache-Control and Pragma request header fields to determine if
4555 * the request may be served from the cache and/or if it is cacheable. Updates
4556 * s->txn->flags.
4557 */
4558void htx_check_request_for_cacheability(struct stream *s, struct channel *req)
4559{
4560 struct http_txn *txn = s->txn;
4561 struct htx *htx;
4562 int32_t pos;
4563 int pragma_found, cc_found, i;
4564
4565 if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
4566 return; /* nothing more to do here */
4567
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004568 htx = htxbuf(&req->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004569 pragma_found = cc_found = 0;
4570 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4571 struct htx_blk *blk = htx_get_blk(htx, pos);
4572 enum htx_blk_type type = htx_get_blk_type(blk);
4573 struct ist n, v;
4574
4575 if (type == HTX_BLK_EOH)
4576 break;
4577 if (type != HTX_BLK_HDR)
4578 continue;
4579
4580 n = htx_get_blk_name(htx, blk);
4581 v = htx_get_blk_value(htx, blk);
4582
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004583 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004584 if (v.len >= 8 && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4585 pragma_found = 1;
4586 continue;
4587 }
4588 }
4589
4590 /* Don't use the cache and don't try to store if we found the
4591 * Authorization header */
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004592 if (isteq(n, ist("authorization"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004593 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4594 txn->flags |= TX_CACHE_IGNORE;
4595 continue;
4596 }
4597
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004598 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004599 continue;
4600
4601 /* OK, right now we know we have a cache-control header */
4602 cc_found = 1;
4603 if (!v.len) /* no info */
4604 continue;
4605
4606 i = 0;
4607 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4608 !isspace((unsigned char)*(v.ptr+i)))
4609 i++;
4610
4611 /* we have a complete value between v.ptr and (v.ptr+i). We don't check the
4612 * values after max-age, max-stale nor min-fresh, we simply don't
4613 * use the cache when they're specified.
4614 */
4615 if (((i == 7) && strncasecmp(v.ptr, "max-age", 7) == 0) ||
4616 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4617 ((i == 9) && strncasecmp(v.ptr, "max-stale", 9) == 0) ||
4618 ((i == 9) && strncasecmp(v.ptr, "min-fresh", 9) == 0)) {
4619 txn->flags |= TX_CACHE_IGNORE;
4620 continue;
4621 }
4622
4623 if ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0) {
4624 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4625 continue;
4626 }
4627 }
4628
4629 /* RFC7234#5.4:
4630 * When the Cache-Control header field is also present and
4631 * understood in a request, Pragma is ignored.
4632 * When the Cache-Control header field is not present in a
4633 * request, caches MUST consider the no-cache request
4634 * pragma-directive as having the same effect as if
4635 * "Cache-Control: no-cache" were present.
4636 */
4637 if (!cc_found && pragma_found)
4638 txn->flags |= TX_CACHE_IGNORE;
4639}
4640
4641/*
4642 * Check if response is cacheable or not. Updates s->txn->flags.
4643 */
4644void htx_check_response_for_cacheability(struct stream *s, struct channel *res)
4645{
4646 struct http_txn *txn = s->txn;
4647 struct htx *htx;
4648 int32_t pos;
4649 int i;
4650
4651 if (txn->status < 200) {
4652 /* do not try to cache interim responses! */
4653 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4654 return;
4655 }
4656
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004657 htx = htxbuf(&res->buf);
Christopher Faulet25a02f62018-10-24 12:00:25 +02004658 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4659 struct htx_blk *blk = htx_get_blk(htx, pos);
4660 enum htx_blk_type type = htx_get_blk_type(blk);
4661 struct ist n, v;
4662
4663 if (type == HTX_BLK_EOH)
4664 break;
4665 if (type != HTX_BLK_HDR)
4666 continue;
4667
4668 n = htx_get_blk_name(htx, blk);
4669 v = htx_get_blk_value(htx, blk);
4670
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004671 if (isteq(n, ist("pragma"))) {
Christopher Faulet25a02f62018-10-24 12:00:25 +02004672 if ((v.len >= 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) {
4673 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4674 return;
4675 }
4676 }
4677
Willy Tarreau2e754bf2018-12-07 11:38:03 +01004678 if (!isteq(n, ist("cache-control")))
Christopher Faulet25a02f62018-10-24 12:00:25 +02004679 continue;
4680
4681 /* OK, right now we know we have a cache-control header */
4682 if (!v.len) /* no info */
4683 continue;
4684
4685 i = 0;
4686 while (i < v.len && *(v.ptr+i) != '=' && *(v.ptr+i) != ',' &&
4687 !isspace((unsigned char)*(v.ptr+i)))
4688 i++;
4689
4690 /* we have a complete value between v.ptr and (v.ptr+i) */
4691 if (i < v.len && *(v.ptr + i) == '=') {
4692 if (((v.len - i) > 1 && (i == 7) && strncasecmp(v.ptr, "max-age=0", 9) == 0) ||
4693 ((v.len - i) > 1 && (i == 8) && strncasecmp(v.ptr, "s-maxage=0", 10) == 0)) {
4694 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4695 continue;
4696 }
4697
4698 /* we have something of the form no-cache="set-cookie" */
4699 if ((v.len >= 21) &&
4700 strncasecmp(v.ptr, "no-cache=\"set-cookie", 20) == 0
4701 && (*(v.ptr + 20) == '"' || *(v.ptr + 20 ) == ','))
4702 txn->flags &= ~TX_CACHE_COOK;
4703 continue;
4704 }
4705
4706 /* OK, so we know that either p2 points to the end of string or to a comma */
4707 if (((i == 7) && strncasecmp(v.ptr, "private", 7) == 0) ||
4708 ((i == 8) && strncasecmp(v.ptr, "no-cache", 8) == 0) ||
4709 ((i == 8) && strncasecmp(v.ptr, "no-store", 8) == 0)) {
4710 txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
4711 return;
4712 }
4713
4714 if ((i == 6) && strncasecmp(v.ptr, "public", 6) == 0) {
4715 txn->flags |= TX_CACHEABLE | TX_CACHE_COOK;
4716 continue;
4717 }
4718 }
4719}
4720
Christopher Faulet64159df2018-10-24 21:15:35 +02004721/* send a server's name with an outgoing request over an established connection.
4722 * Note: this function is designed to be called once the request has been
4723 * scheduled for being forwarded. This is the reason why the number of forwarded
4724 * bytes have to be adjusted.
4725 */
4726int htx_send_name_header(struct stream *s, struct proxy *be, const char *srv_name)
4727{
4728 struct htx *htx;
4729 struct http_hdr_ctx ctx;
4730 struct ist hdr;
4731 uint32_t data;
4732
4733 hdr = ist2(be->server_id_hdr_name, be->server_id_hdr_len);
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004734 htx = htxbuf(&s->req.buf);
Christopher Faulet64159df2018-10-24 21:15:35 +02004735 data = htx->data;
4736
4737 ctx.blk = NULL;
4738 while (http_find_header(htx, hdr, &ctx, 1))
4739 http_remove_header(htx, &ctx);
4740 http_add_header(htx, hdr, ist2(srv_name, strlen(srv_name)));
4741
4742 if (co_data(&s->req)) {
4743 if (data >= htx->data)
4744 c_rew(&s->req, data - htx->data);
4745 else
4746 c_adv(&s->req, htx->data - data);
4747 }
4748 return 0;
4749}
4750
Christopher Faulet377c5a52018-10-24 21:21:30 +02004751/*
4752 * In a GET, HEAD or POST request, check if the requested URI matches the stats uri
4753 * for the current backend.
4754 *
4755 * It is assumed that the request is either a HEAD, GET, or POST and that the
4756 * uri_auth field is valid.
4757 *
4758 * Returns 1 if stats should be provided, otherwise 0.
4759 */
4760static int htx_stats_check_uri(struct stream *s, struct http_txn *txn, struct proxy *backend)
4761{
4762 struct uri_auth *uri_auth = backend->uri_auth;
4763 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004764 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004765 struct ist uri;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004766
4767 if (!uri_auth)
4768 return 0;
4769
4770 if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST)
4771 return 0;
4772
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004773 htx = htxbuf(&s->req.buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004774 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004775 uri = htx_sl_req_uri(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004776
4777 /* check URI size */
4778 if (uri_auth->uri_len > uri.len)
4779 return 0;
4780
4781 if (memcmp(uri.ptr, uri_auth->uri_prefix, uri_auth->uri_len) != 0)
4782 return 0;
4783
4784 return 1;
4785}
4786
4787/* This function prepares an applet to handle the stats. It can deal with the
4788 * "100-continue" expectation, check that admin rules are met for POST requests,
4789 * and program a response message if something was unexpected. It cannot fail
4790 * and always relies on the stats applet to complete the job. It does not touch
4791 * analysers nor counters, which are left to the caller. It does not touch
4792 * s->target which is supposed to already point to the stats applet. The caller
4793 * is expected to have already assigned an appctx to the stream.
4794 */
4795static int htx_handle_stats(struct stream *s, struct channel *req)
4796{
4797 struct stats_admin_rule *stats_admin_rule;
4798 struct stream_interface *si = &s->si[1];
4799 struct session *sess = s->sess;
4800 struct http_txn *txn = s->txn;
4801 struct http_msg *msg = &txn->req;
4802 struct uri_auth *uri_auth = s->be->uri_auth;
4803 const char *h, *lookup, *end;
4804 struct appctx *appctx;
4805 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004806 struct htx_sl *sl;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004807
4808 appctx = si_appctx(si);
4809 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
4810 appctx->st1 = appctx->st2 = 0;
4811 appctx->ctx.stats.st_code = STAT_STATUS_INIT;
4812 appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */
4813 if ((msg->flags & HTTP_MSGF_VER_11) && (txn->meth != HTTP_METH_HEAD))
4814 appctx->ctx.stats.flags |= STAT_CHUNKED;
4815
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004816 htx = htxbuf(&req->buf);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004817 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004818 lookup = HTX_SL_REQ_UPTR(sl) + uri_auth->uri_len;
4819 end = HTX_SL_REQ_UPTR(sl) + HTX_SL_REQ_ULEN(sl);
Christopher Faulet377c5a52018-10-24 21:21:30 +02004820
4821 for (h = lookup; h <= end - 3; h++) {
4822 if (memcmp(h, ";up", 3) == 0) {
4823 appctx->ctx.stats.flags |= STAT_HIDE_DOWN;
4824 break;
4825 }
4826 }
4827
4828 if (uri_auth->refresh) {
4829 for (h = lookup; h <= end - 10; h++) {
4830 if (memcmp(h, ";norefresh", 10) == 0) {
4831 appctx->ctx.stats.flags |= STAT_NO_REFRESH;
4832 break;
4833 }
4834 }
4835 }
4836
4837 for (h = lookup; h <= end - 4; h++) {
4838 if (memcmp(h, ";csv", 4) == 0) {
4839 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4840 break;
4841 }
4842 }
4843
4844 for (h = lookup; h <= end - 6; h++) {
4845 if (memcmp(h, ";typed", 6) == 0) {
4846 appctx->ctx.stats.flags &= ~STAT_FMT_HTML;
4847 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
4848 break;
4849 }
4850 }
4851
4852 for (h = lookup; h <= end - 8; h++) {
4853 if (memcmp(h, ";st=", 4) == 0) {
4854 int i;
4855 h += 4;
4856 appctx->ctx.stats.st_code = STAT_STATUS_UNKN;
4857 for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) {
4858 if (strncmp(stat_status_codes[i], h, 4) == 0) {
4859 appctx->ctx.stats.st_code = i;
4860 break;
4861 }
4862 }
4863 break;
4864 }
4865 }
4866
4867 appctx->ctx.stats.scope_str = 0;
4868 appctx->ctx.stats.scope_len = 0;
4869 for (h = lookup; h <= end - 8; h++) {
4870 if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) {
4871 int itx = 0;
4872 const char *h2;
4873 char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1];
4874 const char *err;
4875
4876 h += strlen(STAT_SCOPE_INPUT_NAME) + 1;
4877 h2 = h;
Christopher Fauleted7a0662019-01-14 11:07:34 +01004878 appctx->ctx.stats.scope_str = h2 - HTX_SL_REQ_UPTR(sl);
4879 while (h < end) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004880 if (*h == ';' || *h == '&' || *h == ' ')
4881 break;
4882 itx++;
4883 h++;
4884 }
4885
4886 if (itx > STAT_SCOPE_TXT_MAXLEN)
4887 itx = STAT_SCOPE_TXT_MAXLEN;
4888 appctx->ctx.stats.scope_len = itx;
4889
4890 /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */
4891 memcpy(scope_txt, h2, itx);
4892 scope_txt[itx] = '\0';
4893 err = invalid_char(scope_txt);
4894 if (err) {
4895 /* bad char in search text => clear scope */
4896 appctx->ctx.stats.scope_str = 0;
4897 appctx->ctx.stats.scope_len = 0;
4898 }
4899 break;
4900 }
4901 }
4902
4903 /* now check whether we have some admin rules for this request */
4904 list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) {
4905 int ret = 1;
4906
4907 if (stats_admin_rule->cond) {
4908 ret = acl_exec_cond(stats_admin_rule->cond, s->be, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL);
4909 ret = acl_pass(ret);
4910 if (stats_admin_rule->cond->pol == ACL_COND_UNLESS)
4911 ret = !ret;
4912 }
4913
4914 if (ret) {
4915 /* no rule, or the rule matches */
4916 appctx->ctx.stats.flags |= STAT_ADMIN;
4917 break;
4918 }
4919 }
4920
Christopher Faulet5d45e382019-02-27 15:15:23 +01004921 if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD)
4922 appctx->st0 = STAT_HTTP_HEAD;
4923 else if (txn->meth == HTTP_METH_POST) {
Christopher Faulet377c5a52018-10-24 21:21:30 +02004924 if (appctx->ctx.stats.flags & STAT_ADMIN) {
4925 /* we'll need the request body, possibly after sending 100-continue */
4926 if (msg->msg_state < HTTP_MSG_DATA)
4927 req->analysers |= AN_REQ_HTTP_BODY;
4928 appctx->st0 = STAT_HTTP_POST;
4929 }
4930 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004931 /* POST without admin level */
Christopher Faulet377c5a52018-10-24 21:21:30 +02004932 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4933 appctx->ctx.stats.st_code = STAT_STATUS_DENY;
4934 appctx->st0 = STAT_HTTP_LAST;
4935 }
4936 }
4937 else {
Christopher Faulet5d45e382019-02-27 15:15:23 +01004938 /* Unsupported method */
4939 appctx->ctx.stats.flags &= ~STAT_CHUNKED;
4940 appctx->ctx.stats.st_code = STAT_STATUS_IVAL;
4941 appctx->st0 = STAT_HTTP_LAST;
Christopher Faulet377c5a52018-10-24 21:21:30 +02004942 }
4943
4944 s->task->nice = -32; /* small boost for HTTP statistics */
4945 return 1;
4946}
4947
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004948void htx_perform_server_redirect(struct stream *s, struct stream_interface *si)
4949{
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004950 struct channel *req = &s->req;
4951 struct channel *res = &s->res;
4952 struct server *srv;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004953 struct htx *htx;
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004954 struct htx_sl *sl;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004955 struct ist path, location;
4956 unsigned int flags;
4957 size_t data;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004958
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004959 /*
4960 * Create the location
4961 */
4962 chunk_reset(&trash);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004963
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004964 /* 1: add the server's prefix */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004965 /* special prefix "/" means don't change URL */
4966 srv = __objt_server(s->target);
4967 if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') {
4968 if (!chunk_memcat(&trash, srv->rdr_pfx, srv->rdr_len))
4969 return;
4970 }
4971
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004972 /* 2: add the request Path */
Christopher Faulet27ba2dc2018-12-05 11:53:24 +01004973 htx = htxbuf(&req->buf);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004974 sl = http_find_stline(htx);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01004975 path = http_get_path(htx_sl_req_uri(sl));
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004976 if (!path.ptr)
4977 return;
4978
4979 if (!chunk_memcat(&trash, path.ptr, path.len))
4980 return;
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004981 location = ist2(trash.area, trash.data);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02004982
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01004983 /*
4984 * Create the 302 respone
4985 */
4986 htx = htx_from_buf(&res->buf);
4987 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4988 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4989 ist("HTTP/1.1"), ist("302"), ist("Found"));
4990 if (!sl)
4991 goto fail;
4992 sl->info.res.status = 302;
4993 s->txn->status = 302;
4994
4995 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
4996 !htx_add_header(htx, ist("Connection"), ist("close")) ||
4997 !htx_add_header(htx, ist("Content-length"), ist("0")) ||
4998 !htx_add_header(htx, ist("Location"), location))
4999 goto fail;
5000
5001 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5002 goto fail;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005003
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005004 /*
5005 * Send the message
5006 */
5007 data = htx->data - co_data(res);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005008 c_adv(res, data);
5009 res->total += data;
5010
5011 /* return without error. */
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005012 si_shutr(si);
5013 si_shutw(si);
5014 si->err_type = SI_ET_NONE;
5015 si->state = SI_ST_CLO;
5016
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005017 channel_auto_read(req);
5018 channel_abort(req);
5019 channel_auto_close(req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005020 channel_htx_erase(req, htxbuf(&req->buf));
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005021 channel_auto_read(res);
5022 channel_auto_close(res);
5023
5024 if (!(s->flags & SF_ERR_MASK))
5025 s->flags |= SF_ERR_LOCAL;
5026 if (!(s->flags & SF_FINST_MASK))
5027 s->flags |= SF_FINST_C;
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005028
5029 /* FIXME: we should increase a counter of redirects per server and per backend. */
5030 srv_inc_sess_ctr(srv);
5031 srv_set_sess_last(srv);
Christopher Faulet0eaed6b2018-11-28 17:46:40 +01005032 return;
5033
5034 fail:
5035 /* If an error occurred, remove the incomplete HTTP response from the
5036 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005037 channel_htx_truncate(res, htx);
Christopher Fauletfefc73d2018-10-24 21:18:04 +02005038}
5039
Christopher Fauletf2824e62018-10-01 12:12:37 +02005040/* This function terminates the request because it was completly analyzed or
5041 * because an error was triggered during the body forwarding.
5042 */
5043static void htx_end_request(struct stream *s)
5044{
5045 struct channel *chn = &s->req;
5046 struct http_txn *txn = s->txn;
5047
5048 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5049 now_ms, __FUNCTION__, s,
5050 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5051 s->req.analysers, s->res.analysers);
5052
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005053 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5054 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005055 channel_abort(chn);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005056 channel_htx_truncate(chn, htxbuf(&chn->buf));
Christopher Fauletf2824e62018-10-01 12:12:37 +02005057 goto end;
5058 }
5059
5060 if (unlikely(txn->req.msg_state < HTTP_MSG_DONE))
5061 return;
5062
5063 if (txn->req.msg_state == HTTP_MSG_DONE) {
Christopher Fauletf2824e62018-10-01 12:12:37 +02005064 /* No need to read anymore, the request was completely parsed.
5065 * We can shut the read side unless we want to abort_on_close,
5066 * or we have a POST request. The issue with POST requests is
5067 * that some browsers still send a CRLF after the request, and
5068 * this CRLF must be read so that it does not remain in the kernel
5069 * buffers, otherwise a close could cause an RST on some systems
5070 * (eg: Linux).
5071 */
5072 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)) &&
5073 txn->meth != HTTP_METH_POST)
5074 channel_dont_read(chn);
5075
5076 /* if the server closes the connection, we want to immediately react
5077 * and close the socket to save packets and syscalls.
5078 */
5079 s->si[1].flags |= SI_FL_NOHALF;
5080
5081 /* In any case we've finished parsing the request so we must
5082 * disable Nagle when sending data because 1) we're not going
5083 * to shut this side, and 2) the server is waiting for us to
5084 * send pending data.
5085 */
5086 chn->flags |= CF_NEVER_WAIT;
5087
Christopher Fauletd01ce402019-01-02 17:44:13 +01005088 if (txn->rsp.msg_state < HTTP_MSG_DONE) {
5089 /* The server has not finished to respond, so we
5090 * don't want to move in order not to upset it.
5091 */
5092 return;
5093 }
5094
Christopher Fauletf2824e62018-10-01 12:12:37 +02005095 /* When we get here, it means that both the request and the
5096 * response have finished receiving. Depending on the connection
5097 * mode, we'll have to wait for the last bytes to leave in either
5098 * direction, and sometimes for a close to be effective.
5099 */
5100 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5101 /* Tunnel mode will not have any analyser so it needs to
5102 * poll for reads.
5103 */
5104 channel_auto_read(chn);
Christopher Faulet9768c262018-10-22 09:34:31 +02005105 if (b_data(&chn->buf))
5106 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005107 txn->req.msg_state = HTTP_MSG_TUNNEL;
5108 }
5109 else {
5110 /* we're not expecting any new data to come for this
5111 * transaction, so we can close it.
Christopher Faulet9768c262018-10-22 09:34:31 +02005112 *
5113 * However, there is an exception if the response
5114 * length is undefined. In this case, we need to wait
5115 * the close from the server. The response will be
5116 * switched in TUNNEL mode until the end.
Christopher Fauletf2824e62018-10-01 12:12:37 +02005117 */
5118 if (!(txn->rsp.flags & HTTP_MSGF_XFER_LEN) &&
5119 txn->rsp.msg_state != HTTP_MSG_CLOSED)
Christopher Faulet9768c262018-10-22 09:34:31 +02005120 goto check_channel_flags;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005121
5122 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5123 channel_shutr_now(chn);
5124 channel_shutw_now(chn);
5125 }
5126 }
Christopher Fauletf2824e62018-10-01 12:12:37 +02005127 goto check_channel_flags;
5128 }
5129
5130 if (txn->req.msg_state == HTTP_MSG_CLOSING) {
5131 http_msg_closing:
5132 /* nothing else to forward, just waiting for the output buffer
5133 * to be empty and for the shutw_now to take effect.
5134 */
5135 if (channel_is_empty(chn)) {
5136 txn->req.msg_state = HTTP_MSG_CLOSED;
5137 goto http_msg_closed;
5138 }
5139 else if (chn->flags & CF_SHUTW) {
5140 txn->req.err_state = txn->req.msg_state;
5141 txn->req.msg_state = HTTP_MSG_ERROR;
5142 goto end;
5143 }
5144 return;
5145 }
5146
5147 if (txn->req.msg_state == HTTP_MSG_CLOSED) {
5148 http_msg_closed:
Christopher Fauletf2824e62018-10-01 12:12:37 +02005149 /* if we don't know whether the server will close, we need to hard close */
5150 if (txn->rsp.flags & HTTP_MSGF_XFER_LEN)
5151 s->si[1].flags |= SI_FL_NOLINGER; /* we want to close ASAP */
Christopher Fauletf2824e62018-10-01 12:12:37 +02005152 /* see above in MSG_DONE why we only do this in these states */
5153 if ((!(s->be->options & PR_O_ABRT_CLOSE) || (s->si[0].flags & SI_FL_CLEAN_ABRT)))
5154 channel_dont_read(chn);
5155 goto end;
5156 }
5157
5158 check_channel_flags:
5159 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5160 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5161 /* if we've just closed an output, let's switch */
5162 txn->req.msg_state = HTTP_MSG_CLOSING;
5163 goto http_msg_closing;
5164 }
5165
5166 end:
5167 chn->analysers &= AN_REQ_FLT_END;
5168 if (txn->req.msg_state == HTTP_MSG_TUNNEL && HAS_REQ_DATA_FILTERS(s))
5169 chn->analysers |= AN_REQ_FLT_XFER_DATA;
5170 channel_auto_close(chn);
5171 channel_auto_read(chn);
5172}
5173
5174
5175/* This function terminates the response because it was completly analyzed or
5176 * because an error was triggered during the body forwarding.
5177 */
5178static void htx_end_response(struct stream *s)
5179{
5180 struct channel *chn = &s->res;
5181 struct http_txn *txn = s->txn;
5182
5183 DPRINTF(stderr,"[%u] %s: stream=%p states=%s,%s req->analysers=0x%08x res->analysers=0x%08x\n",
5184 now_ms, __FUNCTION__, s,
5185 h1_msg_state_str(txn->req.msg_state), h1_msg_state_str(txn->rsp.msg_state),
5186 s->req.analysers, s->res.analysers);
5187
Christopher Fauletb42a8b62018-11-19 21:59:00 +01005188 if (unlikely(txn->req.msg_state == HTTP_MSG_ERROR ||
5189 txn->rsp.msg_state == HTTP_MSG_ERROR)) {
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005190 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005191 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005192 goto end;
5193 }
5194
5195 if (unlikely(txn->rsp.msg_state < HTTP_MSG_DONE))
5196 return;
5197
5198 if (txn->rsp.msg_state == HTTP_MSG_DONE) {
5199 /* In theory, we don't need to read anymore, but we must
5200 * still monitor the server connection for a possible close
5201 * while the request is being uploaded, so we don't disable
5202 * reading.
5203 */
5204 /* channel_dont_read(chn); */
5205
5206 if (txn->req.msg_state < HTTP_MSG_DONE) {
5207 /* The client seems to still be sending data, probably
5208 * because we got an error response during an upload.
5209 * We have the choice of either breaking the connection
5210 * or letting it pass through. Let's do the later.
5211 */
5212 return;
5213 }
5214
5215 /* When we get here, it means that both the request and the
5216 * response have finished receiving. Depending on the connection
5217 * mode, we'll have to wait for the last bytes to leave in either
5218 * direction, and sometimes for a close to be effective.
5219 */
5220 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) {
5221 channel_auto_read(chn);
5222 chn->flags |= CF_NEVER_WAIT;
Christopher Faulet9768c262018-10-22 09:34:31 +02005223 if (b_data(&chn->buf))
5224 return;
Christopher Fauletf2824e62018-10-01 12:12:37 +02005225 txn->rsp.msg_state = HTTP_MSG_TUNNEL;
5226 }
5227 else {
5228 /* we're not expecting any new data to come for this
5229 * transaction, so we can close it.
5230 */
5231 if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) {
5232 channel_shutr_now(chn);
5233 channel_shutw_now(chn);
5234 }
5235 }
5236 goto check_channel_flags;
5237 }
5238
5239 if (txn->rsp.msg_state == HTTP_MSG_CLOSING) {
5240 http_msg_closing:
5241 /* nothing else to forward, just waiting for the output buffer
5242 * to be empty and for the shutw_now to take effect.
5243 */
5244 if (channel_is_empty(chn)) {
5245 txn->rsp.msg_state = HTTP_MSG_CLOSED;
5246 goto http_msg_closed;
5247 }
5248 else if (chn->flags & CF_SHUTW) {
5249 txn->rsp.err_state = txn->rsp.msg_state;
5250 txn->rsp.msg_state = HTTP_MSG_ERROR;
Olivier Houcharda798bf52019-03-08 18:52:00 +01005251 _HA_ATOMIC_ADD(&s->be->be_counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005252 if (objt_server(s->target))
Olivier Houcharda798bf52019-03-08 18:52:00 +01005253 _HA_ATOMIC_ADD(&objt_server(s->target)->counters.cli_aborts, 1);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005254 goto end;
5255 }
5256 return;
5257 }
5258
5259 if (txn->rsp.msg_state == HTTP_MSG_CLOSED) {
5260 http_msg_closed:
5261 /* drop any pending data */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005262 channel_htx_truncate(&s->req, htxbuf(&s->req.buf));
Christopher Faulet9768c262018-10-22 09:34:31 +02005263 channel_abort(&s->req);
Christopher Fauletf2824e62018-10-01 12:12:37 +02005264 goto end;
5265 }
5266
5267 check_channel_flags:
5268 /* Here, we are in HTTP_MSG_DONE or HTTP_MSG_TUNNEL */
5269 if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
5270 /* if we've just closed an output, let's switch */
5271 txn->rsp.msg_state = HTTP_MSG_CLOSING;
5272 goto http_msg_closing;
5273 }
5274
5275 end:
5276 chn->analysers &= AN_RES_FLT_END;
5277 if (txn->rsp.msg_state == HTTP_MSG_TUNNEL && HAS_RSP_DATA_FILTERS(s))
5278 chn->analysers |= AN_RES_FLT_XFER_DATA;
5279 channel_auto_close(chn);
5280 channel_auto_read(chn);
5281}
5282
Christopher Faulet0f226952018-10-22 09:29:56 +02005283void htx_server_error(struct stream *s, struct stream_interface *si, int err,
5284 int finst, const struct buffer *msg)
5285{
5286 channel_auto_read(si_oc(si));
5287 channel_abort(si_oc(si));
5288 channel_auto_close(si_oc(si));
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005289 channel_htx_erase(si_oc(si), htxbuf(&(si_oc(si))->buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005290 channel_auto_close(si_ic(si));
5291 channel_auto_read(si_ic(si));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005292
5293 /* <msg> is an HTX structure. So we copy it in the response's
5294 * channel */
Christopher Faulet0f226952018-10-22 09:29:56 +02005295 if (msg) {
5296 struct channel *chn = si_ic(si);
5297 struct htx *htx;
5298
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005299 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005300 chn->buf.data = msg->data;
5301 memcpy(chn->buf.area, msg->area, msg->data);
5302 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005303 c_adv(chn, htx->data);
5304 chn->total += htx->data;
5305 }
5306 if (!(s->flags & SF_ERR_MASK))
5307 s->flags |= err;
5308 if (!(s->flags & SF_FINST_MASK))
5309 s->flags |= finst;
5310}
5311
5312void htx_reply_and_close(struct stream *s, short status, struct buffer *msg)
5313{
5314 channel_auto_read(&s->req);
5315 channel_abort(&s->req);
5316 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005317 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
5318 channel_htx_truncate(&s->res, htxbuf(&s->res.buf));
Christopher Faulet0f226952018-10-22 09:29:56 +02005319
5320 s->txn->flags &= ~TX_WAIT_NEXT_RQ;
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005321
5322 /* <msg> is an HTX structure. So we copy it in the response's
5323 * channel */
5324 /* FIXME: It is a problem for now if there is some outgoing data */
Christopher Faulet0f226952018-10-22 09:29:56 +02005325 if (msg) {
5326 struct channel *chn = &s->res;
5327 struct htx *htx;
5328
Christopher Fauletaed82cf2018-11-30 22:22:32 +01005329 FLT_STRM_CB(s, flt_http_reply(s, s->txn->status, msg));
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005330 chn->buf.data = msg->data;
5331 memcpy(chn->buf.area, msg->area, msg->data);
5332 htx = htx_from_buf(&chn->buf);
Christopher Faulet0f226952018-10-22 09:29:56 +02005333 c_adv(chn, htx->data);
5334 chn->total += htx->data;
5335 }
5336
5337 s->res.wex = tick_add_ifset(now_ms, s->res.wto);
5338 channel_auto_read(&s->res);
5339 channel_auto_close(&s->res);
5340 channel_shutr_now(&s->res);
5341}
5342
Christopher Fauleta7b677c2018-11-29 16:48:49 +01005343struct buffer *htx_error_message(struct stream *s)
5344{
5345 const int msgnum = http_get_status_idx(s->txn->status);
5346
5347 if (s->be->errmsg[msgnum].area)
5348 return &s->be->errmsg[msgnum];
5349 else if (strm_fe(s)->errmsg[msgnum].area)
5350 return &strm_fe(s)->errmsg[msgnum];
5351 else
5352 return &htx_err_chunks[msgnum];
5353}
5354
5355
Christopher Faulet23a3c792018-11-28 10:01:23 +01005356/* Send a 100-Continue response to the client. It returns 0 on success and -1
5357 * on error. The response channel is updated accordingly.
5358 */
5359static int htx_reply_100_continue(struct stream *s)
5360{
5361 struct channel *res = &s->res;
5362 struct htx *htx = htx_from_buf(&res->buf);
5363 struct htx_sl *sl;
5364 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
5365 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
5366 size_t data;
5367
5368 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5369 ist("HTTP/1.1"), ist("100"), ist("Continue"));
5370 if (!sl)
5371 goto fail;
5372 sl->info.res.status = 100;
5373
5374 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
5375 goto fail;
5376
5377 data = htx->data - co_data(res);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005378 c_adv(res, data);
5379 res->total += data;
5380 return 0;
5381
5382 fail:
5383 /* If an error occurred, remove the incomplete HTTP response from the
5384 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005385 channel_htx_truncate(res, htx);
Christopher Faulet23a3c792018-11-28 10:01:23 +01005386 return -1;
5387}
5388
Christopher Faulet12c51e22018-11-28 15:59:42 +01005389
5390/* Send a 401-Unauthorized or 407-Unauthorized response to the client, depending
5391 * ont whether we use a proxy or not. It returns 0 on success and -1 on
5392 * error. The response channel is updated accordingly.
5393 */
5394static int htx_reply_40x_unauthorized(struct stream *s, const char *auth_realm)
5395{
5396 struct channel *res = &s->res;
5397 struct htx *htx = htx_from_buf(&res->buf);
5398 struct htx_sl *sl;
5399 struct ist code, body;
5400 int status;
5401 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5402 size_t data;
5403
5404 if (!(s->txn->flags & TX_USE_PX_CONN)) {
5405 status = 401;
5406 code = ist("401");
5407 body = ist("<html><body><h1>401 Unauthorized</h1>\n"
5408 "You need a valid user and password to access this content.\n"
5409 "</body></html>\n");
5410 }
5411 else {
5412 status = 407;
5413 code = ist("407");
5414 body = ist("<html><body><h1>407 Unauthorized</h1>\n"
5415 "You need a valid user and password to access this content.\n"
5416 "</body></html>\n");
5417 }
5418
5419 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
5420 ist("HTTP/1.1"), code, ist("Unauthorized"));
5421 if (!sl)
5422 goto fail;
5423 sl->info.res.status = status;
5424 s->txn->status = status;
5425
5426 if (chunk_printf(&trash, "Basic realm=\"%s\"", auth_realm) == -1)
5427 goto fail;
5428
5429 if (!htx_add_header(htx, ist("Cache-Control"), ist("no-cache")) ||
5430 !htx_add_header(htx, ist("Connection"), ist("close")) ||
Jérôme Magnin86cef232018-12-28 14:49:08 +01005431 !htx_add_header(htx, ist("Content-Type"), ist("text/html")))
5432 goto fail;
5433 if (status == 401 && !htx_add_header(htx, ist("WWW-Authenticate"), ist2(trash.area, trash.data)))
5434 goto fail;
5435 if (status == 407 && !htx_add_header(htx, ist("Proxy-Authenticate"), ist2(trash.area, trash.data)))
Christopher Faulet12c51e22018-11-28 15:59:42 +01005436 goto fail;
Christopher Faulet12c51e22018-11-28 15:59:42 +01005437 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_data(htx, body) || !htx_add_endof(htx, HTX_BLK_EOM))
5438 goto fail;
5439
5440 data = htx->data - co_data(res);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005441 c_adv(res, data);
5442 res->total += data;
5443
5444 channel_auto_read(&s->req);
5445 channel_abort(&s->req);
5446 channel_auto_close(&s->req);
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005447 channel_htx_erase(&s->req, htxbuf(&s->req.buf));
Christopher Faulet12c51e22018-11-28 15:59:42 +01005448
5449 res->wex = tick_add_ifset(now_ms, res->wto);
5450 channel_auto_read(res);
5451 channel_auto_close(res);
5452 channel_shutr_now(res);
5453 return 0;
5454
5455 fail:
5456 /* If an error occurred, remove the incomplete HTTP response from the
5457 * buffer */
Christopher Faulet202c6ce2019-01-07 14:57:35 +01005458 channel_htx_truncate(res, htx);
Christopher Faulet12c51e22018-11-28 15:59:42 +01005459 return -1;
5460}
5461
Christopher Faulet0f226952018-10-22 09:29:56 +02005462/*
5463 * Capture headers from message <htx> according to header list <cap_hdr>, and
5464 * fill the <cap> pointers appropriately.
5465 */
5466static void htx_capture_headers(struct htx *htx, char **cap, struct cap_hdr *cap_hdr)
5467{
5468 struct cap_hdr *h;
5469 int32_t pos;
5470
5471 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5472 struct htx_blk *blk = htx_get_blk(htx, pos);
5473 enum htx_blk_type type = htx_get_blk_type(blk);
5474 struct ist n, v;
5475
5476 if (type == HTX_BLK_EOH)
5477 break;
5478 if (type != HTX_BLK_HDR)
5479 continue;
5480
5481 n = htx_get_blk_name(htx, blk);
5482
5483 for (h = cap_hdr; h; h = h->next) {
5484 if (h->namelen && (h->namelen == n.len) &&
5485 (strncasecmp(n.ptr, h->name, h->namelen) == 0)) {
5486 if (cap[h->index] == NULL)
5487 cap[h->index] =
5488 pool_alloc(h->pool);
5489
5490 if (cap[h->index] == NULL) {
5491 ha_alert("HTTP capture : out of memory.\n");
5492 break;
5493 }
5494
5495 v = htx_get_blk_value(htx, blk);
5496 if (v.len > h->len)
5497 v.len = h->len;
5498
5499 memcpy(cap[h->index], v.ptr, v.len);
5500 cap[h->index][v.len]=0;
5501 }
5502 }
5503 }
5504}
5505
Christopher Faulet0b6bdc52018-10-24 11:05:36 +02005506/* Delete a value in a header between delimiters <from> and <next>. The header
5507 * itself is delimited by <start> and <end> pointers. The number of characters
5508 * displaced is returned, and the pointer to the first delimiter is updated if
5509 * required. The function tries as much as possible to respect the following
5510 * principles :
5511 * - replace <from> delimiter by the <next> one unless <from> points to <start>,
5512 * in which case <next> is simply removed
5513 * - set exactly one space character after the new first delimiter, unless there
5514 * are not enough characters in the block being moved to do so.
5515 * - remove unneeded spaces before the previous delimiter and after the new
5516 * one.
5517 *
5518 * It is the caller's responsibility to ensure that :
5519 * - <from> points to a valid delimiter or <start> ;
5520 * - <next> points to a valid delimiter or <end> ;
5521 * - there are non-space chars before <from>.
5522 */
5523static int htx_del_hdr_value(char *start, char *end, char **from, char *next)
5524{
5525 char *prev = *from;
5526
5527 if (prev == start) {
5528 /* We're removing the first value. eat the semicolon, if <next>
5529 * is lower than <end> */
5530 if (next < end)
5531 next++;
5532
5533 while (next < end && HTTP_IS_SPHT(*next))
5534 next++;
5535 }
5536 else {
5537 /* Remove useless spaces before the old delimiter. */
5538 while (HTTP_IS_SPHT(*(prev-1)))
5539 prev--;
5540 *from = prev;
5541
5542 /* copy the delimiter and if possible a space if we're
5543 * not at the end of the line.
5544 */
5545 if (next < end) {
5546 *prev++ = *next++;
5547 if (prev + 1 < next)
5548 *prev++ = ' ';
5549 while (next < end && HTTP_IS_SPHT(*next))
5550 next++;
5551 }
5552 }
5553 memmove(prev, next, end - next);
5554 return (prev - next);
5555}
5556
Christopher Faulet0f226952018-10-22 09:29:56 +02005557
5558/* Formats the start line of the request (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005559 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Faulet0f226952018-10-22 09:29:56 +02005560 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005561static size_t htx_fmt_req_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Faulet0f226952018-10-22 09:29:56 +02005562{
5563 struct ist dst = ist2(str, 0);
5564
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005565 if (istcat(&dst, htx_sl_req_meth(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005566 goto end;
5567 if (dst.len + 1 > len)
5568 goto end;
5569 dst.ptr[dst.len++] = ' ';
5570
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005571 if (istcat(&dst, htx_sl_req_uri(sl), len) == -1)
Christopher Faulet0f226952018-10-22 09:29:56 +02005572 goto end;
5573 if (dst.len + 1 > len)
5574 goto end;
5575 dst.ptr[dst.len++] = ' ';
5576
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005577 istcat(&dst, htx_sl_req_vsn(sl), len);
Christopher Faulet0f226952018-10-22 09:29:56 +02005578 end:
5579 return dst.len;
5580}
5581
Christopher Fauletf0523542018-10-24 11:06:58 +02005582/* Formats the start line of the response (without CRLF) and puts it in <str> and
Joseph Herlantc42c0e92018-11-25 10:43:27 -08005583 * return the written length. The line can be truncated if it exceeds <len>.
Christopher Fauletf0523542018-10-24 11:06:58 +02005584 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005585static size_t htx_fmt_res_line(const struct htx_sl *sl, char *str, size_t len)
Christopher Fauletf0523542018-10-24 11:06:58 +02005586{
5587 struct ist dst = ist2(str, 0);
5588
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005589 if (istcat(&dst, htx_sl_res_vsn(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005590 goto end;
5591 if (dst.len + 1 > len)
5592 goto end;
5593 dst.ptr[dst.len++] = ' ';
5594
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005595 if (istcat(&dst, htx_sl_res_code(sl), len) == -1)
Christopher Fauletf0523542018-10-24 11:06:58 +02005596 goto end;
5597 if (dst.len + 1 > len)
5598 goto end;
5599 dst.ptr[dst.len++] = ' ';
5600
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005601 istcat(&dst, htx_sl_res_reason(sl), len);
Christopher Fauletf0523542018-10-24 11:06:58 +02005602 end:
5603 return dst.len;
5604}
5605
5606
Christopher Faulet0f226952018-10-22 09:29:56 +02005607/*
5608 * Print a debug line with a start line.
5609 */
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005610static void htx_debug_stline(const char *dir, struct stream *s, const struct htx_sl *sl)
Christopher Faulet0f226952018-10-22 09:29:56 +02005611{
5612 struct session *sess = strm_sess(s);
5613 int max;
5614
5615 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5616 dir,
5617 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5618 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5619
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005620 max = HTX_SL_P1_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005621 UBOUND(max, trash.size - trash.data - 3);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005622 chunk_memcat(&trash, HTX_SL_P1_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005623 trash.area[trash.data++] = ' ';
5624
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005625 max = HTX_SL_P2_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005626 UBOUND(max, trash.size - trash.data - 2);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005627 chunk_memcat(&trash, HTX_SL_P2_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005628 trash.area[trash.data++] = ' ';
5629
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005630 max = HTX_SL_P3_LEN(sl);
Christopher Faulet0f226952018-10-22 09:29:56 +02005631 UBOUND(max, trash.size - trash.data - 1);
Christopher Fauletf1ba18d2018-11-26 21:37:08 +01005632 chunk_memcat(&trash, HTX_SL_P3_PTR(sl), max);
Christopher Faulet0f226952018-10-22 09:29:56 +02005633 trash.area[trash.data++] = '\n';
5634
5635 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5636}
5637
5638/*
5639 * Print a debug line with a header.
5640 */
5641static void htx_debug_hdr(const char *dir, struct stream *s, const struct ist n, const struct ist v)
5642{
5643 struct session *sess = strm_sess(s);
5644 int max;
5645
5646 chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id,
5647 dir,
5648 objt_conn(sess->origin) ? (unsigned short)objt_conn(sess->origin)->handle.fd : -1,
5649 objt_cs(s->si[1].end) ? (unsigned short)objt_cs(s->si[1].end)->conn->handle.fd : -1);
5650
5651 max = n.len;
5652 UBOUND(max, trash.size - trash.data - 3);
5653 chunk_memcat(&trash, n.ptr, max);
5654 trash.area[trash.data++] = ':';
5655 trash.area[trash.data++] = ' ';
5656
5657 max = v.len;
5658 UBOUND(max, trash.size - trash.data - 1);
5659 chunk_memcat(&trash, v.ptr, max);
5660 trash.area[trash.data++] = '\n';
5661
5662 shut_your_big_mouth_gcc(write(1, trash.area, trash.data));
5663}
5664
5665
Christopher Fauletf4eb75d2018-10-11 15:55:07 +02005666__attribute__((constructor))
5667static void __htx_protocol_init(void)
5668{
5669}
5670
5671
5672/*
5673 * Local variables:
5674 * c-indent-level: 8
5675 * c-basic-offset: 8
5676 * End:
5677 */